Compare commits
57 commits
v0.1.0-bet
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| b42f77a3aa | |||
| 1f9474c2fd | |||
| 0d423eb708 | |||
| 624f01f745 | |||
| 6775d29249 | |||
| 940fe0a6b6 | |||
| bc3358cb07 | |||
| 5719432fe8 | |||
| bb204796ac | |||
| e2166070d0 | |||
| 70530e30e2 | |||
| 2db7d8b272 | |||
| 28e633dad1 | |||
| dfe865d8f4 | |||
| c7dcdffc30 | |||
| 82c0a8e758 | |||
| 0361a98fa4 | |||
| 59e00cde4b | |||
| 1d7f497594 | |||
| b5dc5d8666 | |||
| 8755d16735 | |||
| c70aeede74 | |||
| 328a93695a | |||
| 9729755dc9 | |||
| 8ed44c2fe4 | |||
| c3d2f4b6a7 | |||
| 4985f1dde0 | |||
| 0eb8518927 | |||
| a38db53161 | |||
| 10103d0e77 | |||
|
|
c7b391d6b4 | ||
|
|
6f92aa42cc | ||
|
|
a7aad59409 | ||
|
|
3aacb94048 | ||
|
|
1a0a5ffbee | ||
|
|
7d0803481b | ||
| a3c05e9062 | |||
| e0df581f0b | |||
| 242a1cec1b | |||
| faab5a7e69 | |||
| a1e4b084aa | |||
| d9e22dde2e | |||
| ac5048f0b2 | |||
| 97acce176b | |||
| 5b6c063ff1 | |||
| 506c69b36e | |||
| f75d4fddb8 | |||
| 9fd2b0603e | |||
| 5efcf2c5a5 | |||
| b6260f7c39 | |||
| 5dc18ff9e5 | |||
| 6be6633f64 | |||
| 5a0f2ed907 | |||
| 43c168da95 | |||
| be865fa992 | |||
| 4478d2206d | |||
| 835cdad98b |
47
.forgejo/workflows/build-installers.yml
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
name: Build Kaleido Desktop installers
|
||||||
|
# Started by hand (Actions, then this workflow, then Run). Each platform needs a runner
|
||||||
|
# with its label; without one the job would wait indefinitely, so this never runs on
|
||||||
|
# push. Releases can instead be built with scripts/build.ps1 (Windows) or
|
||||||
|
# scripts/build.sh (macOS) and published with scripts/publish-release.mjs.
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- os: windows
|
||||||
|
runner: windows-latest
|
||||||
|
# - os: macos
|
||||||
|
# runner: macos-latest
|
||||||
|
# - os: linux
|
||||||
|
# runner: ubuntu-latest
|
||||||
|
runs-on: ${{ matrix.runner }}
|
||||||
|
timeout-minutes: 90
|
||||||
|
steps:
|
||||||
|
- uses: https://data.forgejo.org/actions/checkout@v4.4.0
|
||||||
|
- name: Build (Windows)
|
||||||
|
if: matrix.os == 'windows'
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||||
|
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||||
|
run: ./scripts/build.ps1
|
||||||
|
- name: Build (macOS)
|
||||||
|
if: matrix.os == 'macos'
|
||||||
|
env:
|
||||||
|
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||||
|
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||||
|
run: sh scripts/build.sh
|
||||||
|
- name: Build (Linux)
|
||||||
|
if: matrix.os == 'linux'
|
||||||
|
run: |
|
||||||
|
sh scripts/fetch-libmpv.sh
|
||||||
|
npm ci
|
||||||
|
npx tauri build
|
||||||
|
- uses: https://data.forgejo.org/actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: kaleido-${{ matrix.os }}
|
||||||
|
path: src-tauri/target/release/bundle/
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
name: Validate and publish Kaleido Desktop
|
name: Validate Kaleido Desktop
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
|
|
@ -28,44 +28,3 @@ jobs:
|
||||||
curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal
|
curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal
|
||||||
. "$HOME/.cargo/env"
|
. "$HOME/.cargo/env"
|
||||||
mkdir -p dist && cargo check --manifest-path src-tauri/Cargo.toml
|
mkdir -p dist && cargo check --manifest-path src-tauri/Cargo.toml
|
||||||
|
|
||||||
# Signed installers per platform for version tags. Each OS needs a runner with
|
|
||||||
# its label; set the repository variable DESKTOP_RUNNERS=true once they exist.
|
|
||||||
# Until then, build with scripts/build.ps1 and attach the files to the release.
|
|
||||||
build:
|
|
||||||
if: startsWith(github.ref, 'refs/tags/v') && vars.DESKTOP_RUNNERS == 'true'
|
|
||||||
needs: validate
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- os: windows
|
|
||||||
runner: windows-latest
|
|
||||||
# - os: macos
|
|
||||||
# runner: macos-latest
|
|
||||||
# - os: linux
|
|
||||||
# runner: ubuntu-latest
|
|
||||||
runs-on: ${{ matrix.runner }}
|
|
||||||
timeout-minutes: 90
|
|
||||||
steps:
|
|
||||||
- uses: https://data.forgejo.org/actions/checkout@v4.4.0
|
|
||||||
- name: Build (Windows)
|
|
||||||
if: matrix.os == 'windows'
|
|
||||||
shell: pwsh
|
|
||||||
env:
|
|
||||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
|
||||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
|
||||||
run: ./scripts/build.ps1
|
|
||||||
- name: Build (macOS / Linux)
|
|
||||||
if: matrix.os != 'windows'
|
|
||||||
env:
|
|
||||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
|
||||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
|
||||||
run: |
|
|
||||||
sh scripts/fetch-libmpv.sh
|
|
||||||
npm ci
|
|
||||||
npx tauri build
|
|
||||||
- uses: https://data.forgejo.org/actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: kaleido-${{ matrix.os }}
|
|
||||||
path: src-tauri/target/release/bundle/
|
|
||||||
|
|
|
||||||
1
.gitignore
vendored
|
|
@ -10,5 +10,6 @@ vendor/mpv/*/
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
evidence/
|
evidence/
|
||||||
|
.DS_Store
|
||||||
*.log
|
*.log
|
||||||
.claude/
|
.claude/
|
||||||
|
|
|
||||||
17
AGENTS.md
|
|
@ -11,7 +11,7 @@
|
||||||
- Keep the interface restrained: no redundant buttons or navigation.
|
- Keep the interface restrained: no redundant buttons or navigation.
|
||||||
- `.env` (`PLEX_SERVER_URL`, `PLEX_TOKEN`) is for local testing only. Never print,
|
- `.env` (`PLEX_SERVER_URL`, `PLEX_TOKEN`) is for local testing only. Never print,
|
||||||
commit or embed credentials. `.tools/updater.key` signs updates; never commit or
|
commit or embed credentials. `.tools/updater.key` signs updates; never commit or
|
||||||
replace it.
|
replace it. `.tools/macos-signing.*` backs up the macOS signing certificate; same rules.
|
||||||
- Shared code goes in `src/` and `src-tauri/src/`; anything OS-specific goes in
|
- Shared code goes in `src/` and `src-tauri/src/`; anything OS-specific goes in
|
||||||
`src-tauri/src/platform/<os>.rs` or `tauri.<os>.conf.json`.
|
`src-tauri/src/platform/<os>.rs` or `tauri.<os>.conf.json`.
|
||||||
|
|
||||||
|
|
@ -19,9 +19,20 @@
|
||||||
|
|
||||||
- `npm run typecheck`, `npm test`, `cargo check --manifest-path src-tauri/Cargo.toml`.
|
- `npm run typecheck`, `npm test`, `cargo check --manifest-path src-tauri/Cargo.toml`.
|
||||||
- UI: `npm run dev` and a browser at http://localhost:1420 (signs in from `.env`).
|
- UI: `npm run dev` and a browser at http://localhost:1420 (signs in from `.env`).
|
||||||
- Native: `npm run tauri dev` with `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`;
|
- Native: `npm run tauri dev` (on Windows with `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`);
|
||||||
`window.__kaleido` exposes the stores in development.
|
`window.__kaleido` exposes the stores in development. On macOS the Rust toolchain is
|
||||||
|
Homebrew's keg-only `rustup` (`export PATH=/opt/homebrew/opt/rustup/bin:$PATH`).
|
||||||
- Mute before playback tests (`__kaleido.useSettings.getState().set('volume', 0)`).
|
- Mute before playback tests (`__kaleido.useSettings.getState().set('volume', 0)`).
|
||||||
Playback changes real Plex progress and track selections; restore them.
|
Playback changes real Plex progress and track selections; restore them.
|
||||||
|
|
||||||
|
## Releases
|
||||||
|
|
||||||
|
Built and published locally, Windows and macOS each on their own machine, into one
|
||||||
|
release (CI only validates). In short: bump the version in `package.json`,
|
||||||
|
`src-tauri/Cargo.toml`, `src-tauri/tauri.conf.json` (+ lockfile), add a `CHANGELOG.md`
|
||||||
|
section, commit + tag `vX.Y.Z` + push; on each OS build (`.\scripts\build.ps1` /
|
||||||
|
`sh scripts/build.sh`) and `node scripts/publish-release.mjs X.Y.Z [--prerelease]`; then
|
||||||
|
`node scripts/update-manifest.mjs X.Y.Z` and commit/push `updates/latest.json`. Full checklist: `docs/development.md` → Releases. Only push or
|
||||||
|
publish when the user asks. `FORGEJO_TOKEN` lives in the ignored `.env`.
|
||||||
|
|
||||||
See `docs/architecture.md` and `docs/development.md`.
|
See `docs/architecture.md` and `docs/development.md`.
|
||||||
|
|
|
||||||
193
CHANGELOG.md
|
|
@ -1,5 +1,198 @@
|
||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 1.0.1
|
||||||
|
|
||||||
|
A quicker start, a Stop button, and recovery when the server drops out mid-video.
|
||||||
|
|
||||||
|
- Kaleido starts faster: the opening animation is shorter, so you reach your library in about a second.
|
||||||
|
- The player has a Stop button, next to the forward controls, which closes the player completely instead of moving it to the miniplayer.
|
||||||
|
- If your Plex server goes down while you're watching, the player waits for it once the buffered video runs out, then carries on from the same spot when the server is back. Before, it treated the video as finished and Play started it again from the beginning. Pressing Play while it waits tries to reconnect straight away.
|
||||||
|
|
||||||
|
## 1.0.0
|
||||||
|
|
||||||
|
Kaleido is out of beta. This release reworks the show and season pages and smooths out watching a series.
|
||||||
|
|
||||||
|
- Season pages show their episodes as a grid of cards, each with its still, description and watched state, in place of the long episode list.
|
||||||
|
- Click the season's name under the show's logo to switch to another season.
|
||||||
|
- Show pages list seasons once, as a row of posters. A show with only one season shows its episodes directly.
|
||||||
|
- Episodes you've watched stay marked as watched when you rewatch them and stop partway through. The leftover position only shows on the episode you're up to.
|
||||||
|
- When the next episode plays, whether automatically or with Next, it starts from the beginning instead of near the end of an earlier viewing.
|
||||||
|
- Click a show's name under a Continue Watching card to go to the show.
|
||||||
|
- Continue Watching starts at the first title when something new is added, instead of scrolling it off the left edge.
|
||||||
|
- Season posters outside their show's page, such as New Seasons, are labelled with the show's name.
|
||||||
|
- Season pages show the year the season aired, and their Play button agrees with the show page about which episode is next.
|
||||||
|
- Movie and episode pages show the runtime in their details, with the time left on the Resume button.
|
||||||
|
|
||||||
|
## 0.1.0-beta.19
|
||||||
|
|
||||||
|
Up Next fixes.
|
||||||
|
|
||||||
|
- Up Next now opens every time the credits start: going back to the credits and seeking into the episode brings it back when they come round again, and it always opens when an episode reaches the end.
|
||||||
|
- The back arrow and a full-screen button are back at the top of Up Next, so you can return to browsing (playback continues in the miniplayer) or leave full screen.
|
||||||
|
- Click the show's logo to go to its page, with playback moving to the miniplayer.
|
||||||
|
- The Play next episode countdown fills smoothly.
|
||||||
|
- The episode rows are sized to fill the screen instead of leaving a gap at the bottom.
|
||||||
|
- The backdrop now shows the next episode, and its description is easier to read over bright artwork.
|
||||||
|
|
||||||
|
## 0.1.0-beta.18
|
||||||
|
|
||||||
|
A rebuilt Up Next screen that looks and works like the rest of Kaleido.
|
||||||
|
|
||||||
|
- Up Next now uses the same artwork backdrop, colour wash, buttons and cards as the title pages. The credits keep playing in the top-left corner beside the next episode, and the Play next episode button fills as the countdown runs.
|
||||||
|
- The Season and Related shows rows scroll with the side arrows, like every other row, instead of scrollbars. The season row starts at the episode you just watched.
|
||||||
|
- Click the video or press Esc to go back to the credits; at the end of an episode this no longer restarts it from the beginning.
|
||||||
|
- Up Next fits smaller windows, and the window buttons stay visible on Mac while it's open.
|
||||||
|
- Playback settings are a simple list again: Skip intros, Skip movie credits, Automatic skip delay and Autoplay next episode.
|
||||||
|
|
||||||
|
## 0.1.0-beta.17
|
||||||
|
|
||||||
|
- Fix the Up Next countdown stalling when the native video has keyboard focus instead of the webview. Count elapsed time accurately through delayed timer callbacks, and keep the countdown independent of the video's pause state, as on Android TV.
|
||||||
|
- Open Up Next at the first episode credit marker, including after seeking into credits, independently of movie-credit skip preferences. Open the screen immediately while episode context loads, and start autoplay once the next episode is known. Without markers, use the end of the episode as a fallback.
|
||||||
|
- Cancel autoplay on mouse movement, clicks, scrolling or keypresses. A stationary pointer does not cancel it; cancelled autoplay stays cancelled when delayed metadata arrives.
|
||||||
|
- Match the Android TV screen more closely: remove the extra toolbar actions, Cancel autoplay button and autoplay-status text; show only a white video outline on hover or keyboard focus. Use compact episode metadata, full runtime, landscape related shows and captions beneath the artwork.
|
||||||
|
|
||||||
|
## 0.1.0-beta.16
|
||||||
|
|
||||||
|
- Simplify playback settings: group intro, credits and skip-delay choices together, show the delay only when automatic skipping is enabled, and combine the next-episode switch and countdown into one Off / After … seconds selection. Existing preferences are preserved.
|
||||||
|
- Make Up Next readable over bright artwork with a dark backdrop across the page, brighter secondary text and larger synopsis and autoplay hints. The playing video stays at its original brightness.
|
||||||
|
|
||||||
|
## 0.1.0-beta.15
|
||||||
|
|
||||||
|
A new Up Next screen, adapted from Kaleido for Android TV for mouse and keyboard.
|
||||||
|
|
||||||
|
- Replace the corner countdown with a full Up Next screen. Credits keep playing in the top-left corner beside the next episode’s artwork, title, rating and synopsis, with the season and related shows below. The Play next episode button fills during the single countdown.
|
||||||
|
- Click the video or Return to video, or press Esc, to return to the credits. Click Play next episode to start immediately, choose any season episode, or open a related show. Tab and Shift+Tab move between controls with visible keyboard focus.
|
||||||
|
- Click, scroll or press any key to cancel autoplay while keeping Up Next open. Moving the mouse alone leaves the countdown running. The timer pauses while Kaleido is hidden, unfocused or paused, and never restarts after cancellation or returning to the credits.
|
||||||
|
- Respect the credits preference: Skip automatically opens Up Next as episode credits begin; Show button opens it when clicked; Off waits for the episode to end. Episode credits use only the Up Next countdown, independent of the intro/movie skip delay. A series finale shows More to watch without autoplay.
|
||||||
|
|
||||||
|
## 0.1.0-beta.14
|
||||||
|
|
||||||
|
Full screen stays on with the miniplayer, a smoother colour wash, and a round of playback and download fixes.
|
||||||
|
|
||||||
|
- Going back from the full-screen player to the miniplayer now keeps Kaleido in full screen, so you can browse full screen while the video plays in the corner. Press Esc to go back to a window, or on Windows use the new Exit full screen button beside the window controls. Closing the miniplayer leaves the window as it is.
|
||||||
|
- The colour wash behind the featured titles and title pages now blends into the next title's colours instead of jumping when the artwork changes. Clicking quickly through featured titles no longer blanks the background for a moment.
|
||||||
|
- Playback stays with the server it started on: progress and watched marks never go to a server you switch to later, and switching account, profile or server ends playback from the old one. Downloads report only to their own server.
|
||||||
|
- When Plex converts a video, the audio and subtitle tracks you chose (and your language preferences) are now applied, and kept when you change quality.
|
||||||
|
- Watching a download offline now saves where you stopped and marks it watched.
|
||||||
|
- Fixed: playing something offline could crash the player.
|
||||||
|
- Fixed: closing or switching titles while a video was still starting could start it anyway.
|
||||||
|
- Fixed: Home and the libraries could still show the previous account's or profile's titles after switching.
|
||||||
|
- Fixed: titles split into several files were downloaded only in part; Kaleido now picks a single-file version, or says it can't download the title.
|
||||||
|
- Fixed: episodes downloaded into the same season folder could overwrite or delete each other's artwork, and pause or remove could stop working after a download restarted.
|
||||||
|
- Library grids refresh fully when something changes, slow server responses time out properly, and the featured titles start rotating again when you scroll back to them.
|
||||||
|
|
||||||
|
## 0.1.0-beta.13
|
||||||
|
|
||||||
|
A gentler automatic intro skip, and home screens that keep up with your other Plex apps.
|
||||||
|
|
||||||
|
- "Skip automatically" for intros (and credits) now waits a moment first: the Skip button reads "Skipping intro" and fills as it counts down, then skips. Pause, seek or press any key before then to keep watching; the button stays as a regular Skip intro for the rest of the intro. Click it to skip straight away.
|
||||||
|
- Choose how long it waits in Settings → Playback → Automatic skip delay (3, 5 or 10 seconds, or straight away as before). It's 5 seconds by default.
|
||||||
|
- Jumping into the middle of an intro yourself no longer skips it automatically.
|
||||||
|
- Fixed: Continue Watching, a show's next episode, and watched marks didn't update after watching something on another device (a TV, a phone) while Kaleido stayed open. They now refresh when you switch back to Kaleido, and Continue Watching also refreshes every minute while it's on screen.
|
||||||
|
|
||||||
|
## 0.1.0-beta.12
|
||||||
|
|
||||||
|
A smoother miniplayer on Windows.
|
||||||
|
|
||||||
|
- The miniplayer is now a small window of its own, so dragging it moves the video and its controls together: the video keeps playing smoothly as you move it, with no flicker around its edges.
|
||||||
|
- Letting go snaps it to the nearest corner of the window, or the corner you flick it towards, and it remembers that corner. It stays in place as the window moves or resizes.
|
||||||
|
- Using its buttons no longer takes focus from the main window, so keyboard shortcuts keep working.
|
||||||
|
- On Mac the miniplayer is unchanged for now.
|
||||||
|
|
||||||
|
## 0.1.0-beta.11
|
||||||
|
|
||||||
|
Fixes the app freezing when leaving full screen for the miniplayer, and adds local hang and crash reports.
|
||||||
|
|
||||||
|
- Fixed: going back from the full-screen player to the miniplayer (or moving or resizing the miniplayer) could freeze the window — it turned see-through and "Not Responding" while the video kept playing. Two parts of the player were each waiting for the other when the window resized at the wrong moment.
|
||||||
|
- When the window stops responding for 5 seconds, or the app crashes, Kaleido now saves a report of what each part of the app was doing in its log folder (`%LOCALAPPDATA%\tv.kaleido.desktop\logs`), so a rare problem can be traced the first time it happens. Reports stay on your computer.
|
||||||
|
|
||||||
|
## 0.1.0-beta.10
|
||||||
|
|
||||||
|
A redesigned player control bar, previous episode, and a movable miniplayer.
|
||||||
|
|
||||||
|
- The player's controls are rearranged the way most media players lay them out: play/pause sits in the centre under the timeline, with 10-second skips either side and previous/next episode beyond those. Volume and the time are on the left; subtitles, settings and full screen stay on the right.
|
||||||
|
- New previous-episode button (and Shift+P) to go back an episode. For episodes both buttons always show, dimmed at the start or end of a show, so play/pause stays put.
|
||||||
|
- The miniplayer can be dragged anywhere in the window. It stays inside the window when it's resized, and remembers where you left it.
|
||||||
|
- Fixed: the Play now and Cancel buttons on the next-episode card during the credits couldn't be clicked (the player's title row covered them). The Skip intro/credits button had the same problem with tall show logos.
|
||||||
|
- Fixed: clicking Skip intro or Skip credits also paused the video.
|
||||||
|
- The featured titles at the top of Home, Movies and TV Shows no longer carry a "Highly rated" / "Recommended" label, and their logo has room above the details line instead of touching it.
|
||||||
|
|
||||||
|
## 0.1.0-beta.9
|
||||||
|
|
||||||
|
Fixes for the Mac version.
|
||||||
|
|
||||||
|
- Regular (SDR) video no longer looks washed out on Mac; HDR was unaffected.
|
||||||
|
- Downloaded titles show their artwork again on Mac.
|
||||||
|
|
||||||
|
## 0.1.0-beta.8
|
||||||
|
|
||||||
|
Kaleido for Mac.
|
||||||
|
|
||||||
|
- Kaleido now runs on Macs with Apple silicon (macOS 26 or later), with the same interface and features as on Windows: browsing, playback with hardware decoding, the miniplayer, downloads, server management and in-app updates. The window uses the Mac's own close, minimize and zoom buttons, which fade with the player's controls, and shortcuts use ⌘ (⌘K to search, ⌘[ to go back, ⌃⌘F for full screen).
|
||||||
|
- HDR passthrough works on Mac too: HDR titles play in the display's extended dynamic range instead of being converted to SDR.
|
||||||
|
- Each release now includes both the Windows and Mac versions.
|
||||||
|
- Updates are signed with a new key, so the Windows version needs to be reinstalled once from this release; later updates install in the app as before.
|
||||||
|
|
||||||
|
## 0.1.0-beta.7
|
||||||
|
|
||||||
|
A new startup animation and a bolder app icon.
|
||||||
|
|
||||||
|
- New startup animation: a kaleidoscope of shards turns and gathers into the Kaleido mark, then the view flies through its centre into the app. If the server is slow to answer, small shards keep circling the mark instead of the animation freezing.
|
||||||
|
- The app icon's mark is much larger, so it reads clearly on the taskbar and in the Start menu.
|
||||||
|
|
||||||
|
## 0.1.0-beta.6
|
||||||
|
|
||||||
|
RTX Video upscaling, stopped streams and a live bandwidth graph.
|
||||||
|
|
||||||
|
- When the server owner stops your stream, the player now stops and shows their message instead of playing out its buffer and waiting forever.
|
||||||
|
- The server dashboard's bandwidth graph updates every second and shows the last two minutes on a true per-second scale (it previously refreshed every six seconds and under-reported throughput).
|
||||||
|
- Fixed: a title paused and then closed made the next title start paused while the controls showed it playing.
|
||||||
|
- Upscaling tiers reworked. Balanced is now the strongest shader chain (light nlmeans denoising, FSRCNNX 16, colour reconstruction, debanding), chosen by measuring candidates against 1080p references; it works on every computer. Quality is now NVIDIA RTX Video Super Resolution, which upscales and cleans up compression artifacts on the GPU; it needs Windows and an NVIDIA RTX graphics card (it's greyed out otherwise), applies to SDR video, and its strength follows the NVIDIA App's RTX Video setting.
|
||||||
|
- The denoiser is much lighter (AN3223's light profile at reduced luma strength), so faces, fabric and fine texture no longer look smoothed over.
|
||||||
|
|
||||||
|
## 0.1.0-beta.5
|
||||||
|
|
||||||
|
A live-action Quality upscaling tier.
|
||||||
|
|
||||||
|
- The Quality tier now uses nlmeans denoising (AN3223, made for live action, and it works at any size) ahead of the larger FSRCNNX 16 upscaler, replacing ArtCNN, which is tuned for animation and looked unnatural on live action. It also compiles in seconds rather than about a minute per model.
|
||||||
|
- The "Preparing upscaling" notice only appears if a first-time shader compile takes more than a few seconds.
|
||||||
|
|
||||||
|
## 0.1.0-beta.4
|
||||||
|
|
||||||
|
A Quality upscaling tier, with checks that upscaling is really running.
|
||||||
|
|
||||||
|
- Quality upscaling tier: ArtCNN C4F32 (with its denoising model while upscaling), colour reconstruction, debanding and sharpening. Its network runs whenever the video is enlarged (Balanced from 1.3×), so 1080p in a maximized 1440p window is doubled and scaled down. The first use on a computer compiles its shaders for about a minute, with a notice in the player; compiled shaders are now kept between launches.
|
||||||
|
- Upscaling stages (debanding, sharpening, denoising) can be switched individually, B compares with enhancement off, and the panel shows what the renderer is running, its GPU time per frame and dropped frames.
|
||||||
|
- A tier whose shaders fail to load drops to the one below with a notice instead of silently showing plain scaling; tier changes are serialized; HDR is detected from the decoded video, so converted streams aren't treated as HDR.
|
||||||
|
|
||||||
|
## 0.1.0-beta.3
|
||||||
|
|
||||||
|
Upscaling in the player, and player fixes.
|
||||||
|
|
||||||
|
- Upscaling in the player (Playback options, or press U): Performance (sharp scaling, debanding, CAS sharpening) and Balanced (FSRCNNX neural upscaling, KrigBilateral colour reconstruction, debanding, sharpening). The shaders decide per video and window size whether to upscale or just clean up at native resolution.
|
||||||
|
- Click the title above the scrub bar to open its show or movie (or the episode line for that episode) while playback continues in the miniplayer.
|
||||||
|
- Fixed: starting a title while the miniplayer was showing left the app invisible apart from the corner video; it now plays full screen.
|
||||||
|
- Fixed: the scrub bar's played and buffered sections were hard to tell apart, and the preview thumbnail shrank near the end of the bar.
|
||||||
|
|
||||||
|
## 0.1.0-beta.2
|
||||||
|
|
||||||
|
Second beta: fixes and changes from testing the first.
|
||||||
|
|
||||||
|
- New startup animation: the iris opens and the view flies through the aperture, as on Kaleido for TV.
|
||||||
|
- Miniplayer: the player's back arrow (or Esc) keeps the video playing in the corner while you browse.
|
||||||
|
- Window controls stay available in the player, and its controls also hide when the pointer leaves the window.
|
||||||
|
- Playback options now include audio and subtitle tracks, audio sync, the source bitrate for Original quality, subtitle size and background, and playback details.
|
||||||
|
- Subtitle styling in Settings (size, colour, edge, background, bold, position) with a live preview.
|
||||||
|
- Categories replace Collections in Movies and TV Shows: genre tiles with artwork that open a filtered library.
|
||||||
|
- Smoother scrolling: per-card and scrolling backdrop blurs were re-rendering every frame.
|
||||||
|
- The artwork colour wash is visible again and carries down the page.
|
||||||
|
- The volume slider follows loudness (halfway is about half as loud), and theme music is much quieter and follows the player volume.
|
||||||
|
- Search keeps results on screen while you type; the A–Z rail is easier to see and magnifies under the pointer; long descriptions expand when clicked.
|
||||||
|
- Featured titles rotate faster and preload their artwork; hovering Continue Watching shows a preview.
|
||||||
|
- Downloads: Remove all (everything, a show, or all movies) and a simpler page.
|
||||||
|
- Removed: the five-star rating, the duplicate Settings entry in the profile menu and the server settings' Show advanced switch (everything is shown).
|
||||||
|
- Fixed: double focus ring in search, a stray dot under the navigation, and overlapping text on the TV Shows header.
|
||||||
|
|
||||||
## 0.1.0-beta.1
|
## 0.1.0-beta.1
|
||||||
|
|
||||||
First beta of Kaleido for Windows.
|
First beta of Kaleido for Windows.
|
||||||
|
|
|
||||||
1
CLAUDE.md
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
@AGENTS.md
|
||||||
28
README.md
|
|
@ -4,9 +4,10 @@ A cinematic Plex client for the desktop, built in the same artwork-led style as
|
||||||
[Kaleido for Android TV](https://git.elijahkuntz.com/Elijah/Kaleido), and designed for
|
[Kaleido for Android TV](https://git.elijahkuntz.com/Elijah/Kaleido), and designed for
|
||||||
mouse and keyboard.
|
mouse and keyboard.
|
||||||
|
|
||||||
Windows is supported today. The repository is structured for Windows, macOS and Linux:
|
Kaleido runs on Windows and macOS (Apple silicon) with the same interface and features;
|
||||||
the interface and nearly all of the native core are shared, and each platform's
|
each release carries both, and installed copies update themselves. The interface and
|
||||||
differences live in one place (see [Architecture](docs/architecture.md)).
|
nearly all of the native core are shared, and each platform's differences live in one
|
||||||
|
place (see [Architecture](docs/architecture.md)). Linux builds browse but don't play yet.
|
||||||
|
|
||||||
## What's in the app
|
## What's in the app
|
||||||
|
|
||||||
|
|
@ -61,18 +62,20 @@ differences live in one place (see [Architecture](docs/architecture.md)).
|
||||||
|
|
||||||
| Browsing | | Player | |
|
| Browsing | | Player | |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Ctrl+K | Search | Space / K | Play/pause |
|
| Ctrl+K (⌘K) | Search | Space / K | Play/pause |
|
||||||
| Arrow keys | Move between titles | ← / → | Seek (Shift: 1 min) |
|
| Arrow keys | Move between titles | ← / → | Seek (Shift: 1 min) |
|
||||||
| Enter / Space | Open / play | ↑ / ↓, wheel | Volume |
|
| Enter / Space | Open / play | ↑ / ↓, wheel | Volume |
|
||||||
| Menu or Shift+F10 | Title actions | F, double-click | Full screen |
|
| Menu or Shift+F10 | Title actions | F, double-click | Full screen |
|
||||||
| Alt+← / mouse back | Back | C | Next subtitle |
|
| Alt+← (⌘[) / mouse back | Back | C | Next subtitle |
|
||||||
| / | Focus search | Shift+N | Next episode |
|
| / | Focus search | Shift+P / N | Previous / next episode |
|
||||||
| F11 | Full screen | Esc | Exit full screen, then player |
|
| F11 (⌃⌘F) | Full screen | Esc | Exit full screen, then player |
|
||||||
|
|
||||||
|
Keys in brackets are the macOS equivalents.
|
||||||
|
|
||||||
## Build from source
|
## Build from source
|
||||||
|
|
||||||
Requirements: Node 22+, Rust (stable), and on Windows the Visual Studio C++ build tools
|
Requirements: Node 22+, Rust (stable); on Windows the Visual Studio C++ build tools and
|
||||||
and 7-Zip.
|
7-Zip, on macOS the Xcode command line tools and Homebrew.
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
npm ci
|
npm ci
|
||||||
|
|
@ -81,6 +84,13 @@ npm run tauri dev # development app
|
||||||
.\scripts\build.ps1 # signed release installer (NSIS)
|
.\scripts\build.ps1 # signed release installer (NSIS)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm ci
|
||||||
|
sh scripts/fetch-libmpv.sh # libmpv and its libraries into vendor/mpv/macos
|
||||||
|
npm run tauri dev # development app
|
||||||
|
sh scripts/build.sh # .app, .dmg and the signed update archive
|
||||||
|
```
|
||||||
|
|
||||||
During development the app signs in automatically from an ignored `.env` in the
|
During development the app signs in automatically from an ignored `.env` in the
|
||||||
repository root (`PLEX_SERVER_URL`, `PLEX_TOKEN`). Release builds never read it.
|
repository root (`PLEX_SERVER_URL`, `PLEX_TOKEN`). Release builds never read it.
|
||||||
`npm run dev` serves the interface alone in a browser for UI work (no playback or
|
`npm run dev` serves the interface alone in a browser for UI work (no playback or
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ src/ Shared interface (all platforms)
|
||||||
plex/ Plex client: account (plex.tv), library API, admin, playback, parsing
|
plex/ Plex client: account (plex.tv), library API, admin, playback, parsing
|
||||||
player/ Playback controller (store.ts), mpv bridge, player overlay
|
player/ Playback controller (store.ts), mpv bridge, player overlay
|
||||||
downloads/ Download catalog and actions
|
downloads/ Download catalog and actions
|
||||||
screens/ Home, Movies/TV (Discover/Library/Collections), title pages,
|
screens/ Home, Movies/TV (Discover/Library/Categories), title pages,
|
||||||
search, people, downloads, settings, dialogs
|
search, people, downloads, settings, dialogs
|
||||||
ui/ Design system: primitives, menus/dialogs/toasts, cards, hero
|
ui/ Design system: primitives, menus/dialogs/toasts, cards, hero
|
||||||
styles/ Tokens and styles (base, ui, app, screens, player)
|
styles/ Tokens and styles (base, ui, app, screens, player)
|
||||||
|
|
@ -35,21 +35,34 @@ updates/latest.json Signed update feed for every platform
|
||||||
`src-tauri/src/platform/mod.rs` selects one of `windows.rs`, `macos.rs` or `linux.rs`.
|
`src-tauri/src/platform/mod.rs` selects one of `windows.rs`, `macos.rs` or `linux.rs`.
|
||||||
Each exposes the same items:
|
Each exposes the same items:
|
||||||
|
|
||||||
| Item | Windows implementation |
|
| Item | Windows | macOS |
|
||||||
| --- | --- |
|
| --- | --- | --- |
|
||||||
| `VideoSurface` | mpv renders with `d3d11-output-mode=composition`; its swapchain (`display-swapchain`) is set as the content of a DirectComposition visual targeted at the window with `topmost = false`, i.e. behind the web view's child windows. |
|
| `VideoSurface` | mpv renders with `d3d11-output-mode=composition`; its swapchain (`display-swapchain`) is set as the content of a DirectComposition visual targeted at the window with `topmost = false`, i.e. behind the web view's child windows. For the miniplayer the visual is offset and mpv's composition size shrunk to a corner rectangle (`player_rect`). | mpv's render API (`vo=libmpv`, OpenGL) draws into a `CAOpenGLLayer` hosted by a view inserted beneath the WKWebView, whose background is turned off (`drawsBackground`). `start` creates the render context once mpv is initialized; a render thread redraws the layer whenever mpv reports a new frame. For the miniplayer the view is moved to the corner rectangle. |
|
||||||
| `MPV_LIBRARIES` | `libmpv-2.dll` |
|
| `MPV_LIBRARIES` | `libmpv-2.dll` | `libmpv.2.dylib` (in `Contents/Frameworks` with the libraries it links) |
|
||||||
| `hold_awake` | `SetThreadExecutionState` while video plays |
|
| `hold_awake` | `SetThreadExecutionState` | an IOKit `PreventUserIdleDisplaySleep` assertion |
|
||||||
|
| Window buttons | drawn by the page (`WindowControls`) | the native traffic lights (`titleBarStyle: Overlay`, placed on the top bar's centre line); `set_window_buttons` hides them with the player's controls |
|
||||||
|
| `device_name` | `COMPUTERNAME` | the computer name from Sharing settings |
|
||||||
|
|
||||||
macOS and Linux currently provide stubs for `VideoSurface` (browsing, downloads,
|
Linux provides stubs for `VideoSurface` (browsing, downloads, settings and updates
|
||||||
settings and updates work; playback reports that it is unavailable). To add playback
|
work; playback reports that it is unavailable); the macOS approach (render API beneath
|
||||||
there, render through mpv's render API into a layer beneath the web view and implement
|
the web view) applies there with an OpenGL surface under WebKitGTK. Per-OS bundling
|
||||||
the same five methods. Per-OS bundling (libmpv, targets, dependencies) lives in
|
(libmpv, targets, window style) lives in `tauri.<os>.conf.json`. Credentials use the
|
||||||
`tauri.macos.conf.json` and `tauri.linux.conf.json`. Credentials use the platform's
|
platform's keychain through the `keyring` crate with per-OS features in `Cargo.toml`;
|
||||||
keychain through the `keyring` crate with per-OS features in `Cargo.toml`.
|
macOS debug builds keep them in a private file instead, because each unsigned rebuild
|
||||||
|
would make the Keychain ask again.
|
||||||
|
|
||||||
On Windows the main window is created transparent and the page background turns
|
The page background turns transparent only while video is visible
|
||||||
transparent only while video is visible (`html.video-active`), so browsing is opaque.
|
(`html.video-active`), so browsing is opaque. The page knows its OS synchronously
|
||||||
|
(`hostOS` in `platform/native.ts`, from the web view's user agent) and tags the root
|
||||||
|
element (`html.os-macos`) for the few styles that differ, such as room for the traffic
|
||||||
|
lights.
|
||||||
|
|
||||||
|
HDR passthrough (`target-colorspace-hint`) works differently on each OS. On Windows mpv
|
||||||
|
switches its swapchain's colour space itself. On macOS the surface watches
|
||||||
|
`video-params/gamma`: for PQ or HLG video it has mpv output PQ in BT.2020
|
||||||
|
(`target-trc`, `target-prim`) into the 16-bit float framebuffer and turns on the layer's
|
||||||
|
extended dynamic range with the BT.2100 PQ colour space, so macOS maps the picture
|
||||||
|
into the display's HDR headroom; SDR video returns both to their defaults.
|
||||||
|
|
||||||
## Interface
|
## Interface
|
||||||
|
|
||||||
|
|
@ -66,7 +79,33 @@ transparent only while video is visible (`html.video-active`), so browsing is op
|
||||||
part titles are joined with an mpv EDL); other qualities request Plex HLS with
|
part titles are joined with an mpv EDL); other qualities request Plex HLS with
|
||||||
timestamps kept absolute. If direct play fails, playback retries through Plex once.
|
timestamps kept absolute. If direct play fails, playback retries through Plex once.
|
||||||
Plex streams are matched to mpv tracks by stream index; external subtitles are added
|
Plex streams are matched to mpv tracks by stream index; external subtitles are added
|
||||||
on demand. Timeline reports every 10 seconds make the session appear in Plex, and the
|
on demand. Timeline reports every 10 seconds (and when playback stalls) make the session appear in
|
||||||
title is marked watched at the configured percentage.
|
Plex; a reply carrying a termination (the server owner stopped the stream) stops
|
||||||
|
playback and shows their message. The title is marked watched at the configured percentage. The player's back arrow (or Esc)
|
||||||
|
shrinks playback into a miniplayer. On Windows it is a window of its own
|
||||||
|
(`src-tauri/src/mini.rs`, page `mini.html` → `src/mini/`): a small borderless window
|
||||||
|
owned by the main one, which the video moves into (`VideoSurface::set_host`, one
|
||||||
|
composition target per window, swapped in a single commit). Dragging moves that whole
|
||||||
|
window, so video and controls never drift apart; letting go glides it to a corner of
|
||||||
|
the main window (or the one it's flicked towards), and it follows the main window as
|
||||||
|
that moves or resizes. Its page mirrors the player from the main window and sends its
|
||||||
|
buttons back (`player/miniWindow.ts`, events `mini:state` / `mini:action`). The video
|
||||||
|
moves into it once the main page is opaque again, and back before the page turns
|
||||||
|
transparent, so neither window flashes. On macOS the miniplayer stays inside the page:
|
||||||
|
the video is drawn in a corner rectangle with a matching hole masked out of the page
|
||||||
|
(`html.player-mini`).
|
||||||
|
- **Upscaling** (`player/enhance.ts`): Performance and Balanced set mpv's scalers and
|
||||||
|
debanding and load shaders bundled from `src-tauri/shaders/` (FSRCNNX 16, nlmeans,
|
||||||
|
KrigBilateral, AMD CAS); each shader's `WHEN` condition decides whether it runs for the
|
||||||
|
current video and size. Quality is NVIDIA RTX Video Super Resolution through mpv's
|
||||||
|
`d3d11vpp` filter (`scaling-mode=nvidia`, labelled `@kaleido-vsr`), sized to the window
|
||||||
|
and re-applied when that changes; it is offered only on Windows with an NVIDIA RTX GPU
|
||||||
|
(`app_info` lists the adapters), runs Balanced for HDR or at native size, and the
|
||||||
|
driver's own setting picks its quality level. The chosen tier and the running one are
|
||||||
|
tracked separately: shader or RTX Video errors in mpv's log, missing network passes in
|
||||||
|
`vo-passes`, or RTX Video output that isn't enlarged drop to the tier below. Compiled shaders are
|
||||||
|
cached in the app cache folder (`gpu-shader-cache-dir`), so a slow first Direct3D
|
||||||
|
compile happens once per shader set, mpv version and GPU driver.
|
||||||
- **Updates**: `app/updater.ts` checks the signed feed on start; installs need the
|
- **Updates**: `app/updater.ts` checks the signed feed on start; installs need the
|
||||||
user's confirmation and then relaunch.
|
user's confirmation and then relaunch. One release carries every platform's build and
|
||||||
|
the feed lists each of them (`windows-x86_64`, `darwin-aarch64`).
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,22 @@
|
||||||
debug builds and the Vite dev server. Never commit or print it.
|
debug builds and the Vite dev server. Never commit or print it.
|
||||||
5. `npm run tauri dev`
|
5. `npm run tauri dev`
|
||||||
|
|
||||||
|
## Setup (macOS)
|
||||||
|
|
||||||
|
1. Node 22+, Rust stable (`brew install rustup && rustup default stable`), the Xcode
|
||||||
|
command line tools and Homebrew.
|
||||||
|
2. `npm ci`
|
||||||
|
3. `sh scripts/fetch-libmpv.sh` installs Homebrew's `mpv` and copies libmpv with every
|
||||||
|
library it links into `vendor/mpv/macos`, rewritten to find each other there
|
||||||
|
(`@loader_path`) and signed, so the bundle doesn't depend on Homebrew. Homebrew
|
||||||
|
builds for the macOS it runs on, so the app's minimum macOS is that of the build
|
||||||
|
machine (`scripts/build.sh` sets it from the libraries).
|
||||||
|
4. `.env` as on Windows, then `npm run tauri dev`.
|
||||||
|
|
||||||
|
Debug builds on macOS keep the Plex token in `dev-secrets.json` in the app data folder
|
||||||
|
rather than the Keychain: every rebuild is a new unsigned binary, which the Keychain
|
||||||
|
would ask about again. Release builds always use the Keychain.
|
||||||
|
|
||||||
The interface alone runs in a browser with `npm run dev` (port 1420), which is handy for
|
The interface alone runs in a browser with `npm run dev` (port 1420), which is handy for
|
||||||
layout work; playback, downloads and native dialogs need the desktop app. In development
|
layout work; playback, downloads and native dialogs need the desktop app. In development
|
||||||
builds the stores are available as `window.__kaleido` for debugging.
|
builds the stores are available as `window.__kaleido` for debugging.
|
||||||
|
|
@ -31,20 +47,107 @@ Playback tests change real Plex progress; resume an in-progress title near its s
|
||||||
position, or restore it afterwards. Selecting audio or subtitle tracks is saved to Plex
|
position, or restore it afterwards. Selecting audio or subtitle tracks is saved to Plex
|
||||||
for that file.
|
for that file.
|
||||||
|
|
||||||
|
Up Next (`player/PostPlay.tsx`) opens at an episode's first credits marker, or at the end
|
||||||
|
without markers. The video is drawn into its top-left frame (`player_rect`) behind a
|
||||||
|
matching hole in the page; check that the two line up after resizing, changing display
|
||||||
|
scale and returning to the video. In the browser, open it from the console by setting
|
||||||
|
`postPlay: true` (with `item`, `nextUp`, `episodeContextReady`) on `__kaleido.usePlayer`.
|
||||||
|
|
||||||
|
## Diagnostics
|
||||||
|
|
||||||
|
`src-tauri/src/diagnostics.rs` writes to the app's log folder
|
||||||
|
(`%LOCALAPPDATA%\tv.kaleido.desktop\logs` on Windows); nothing is uploaded.
|
||||||
|
|
||||||
|
- **Hangs**: a watchdog asks the UI thread to answer every second. After 5 seconds of
|
||||||
|
silence it writes `kaleido-hang-<time>-v<version>.dmp` with every thread's stack (once
|
||||||
|
per stall) and notes the stall and the recovery in `diagnostics.log`.
|
||||||
|
- **Crashes** (Windows): an unhandled exception writes `kaleido-crash-…dmp` and logs the
|
||||||
|
exception and faulting module, e.g. `access violation at libmpv-2.dll+0x1234`.
|
||||||
|
- **Panics** are logged with a backtrace.
|
||||||
|
|
||||||
|
The newest five dumps of each kind are kept. To read one, open it in WinDbg with the
|
||||||
|
symbols of the exact build that wrote it: `scripts/build.ps1` keeps each release's
|
||||||
|
`kaleido.exe` and `kaleido.pdb` in `.tools/symbols/<version>/` (release builds keep
|
||||||
|
function names and line tables in the `.pdb`; the installer doesn't change). In WinDbg:
|
||||||
|
`.sympath+ <that folder>`, `.reload`, then `~*k` for every thread's stack.
|
||||||
|
|
||||||
|
Development builds have two test commands: `debug_freeze_ui` (`{ seconds }`, holds the
|
||||||
|
UI thread) and `debug_crash` (an access violation); both refuse to run in release builds.
|
||||||
|
|
||||||
|
Threading rule learned the hard way: Tauri's window getters (`hwnd()`, sizes…) called
|
||||||
|
off the UI thread wait for it to answer, so never call one while holding a lock the UI
|
||||||
|
thread might wait on, and keep window-event handlers from waiting on the player's locks
|
||||||
|
(they run on the UI thread; `lib.rs` hands resize handling to a background thread).
|
||||||
|
|
||||||
|
## App icon
|
||||||
|
|
||||||
|
`src-tauri/icons/app-icon.svg` is the source. Render it to a 1024×1024 `app-icon.png`
|
||||||
|
with a transparent background, run `npx tauri icon src-tauri/icons/app-icon.png -o <temp dir>`,
|
||||||
|
and copy back only the files already in `src-tauri/icons` (the Android and iOS sets aren't used).
|
||||||
|
|
||||||
## Releases
|
## Releases
|
||||||
|
|
||||||
1. Bump the version in `package.json`, `src-tauri/Cargo.toml` and
|
Releases are built and published locally: Windows on the Windows machine, macOS on the
|
||||||
`src-tauri/tauri.conf.json`.
|
Mac. CI only validates; it never builds installers on push (there are no Windows/macOS
|
||||||
2. `.\scripts\build.ps1` builds the NSIS installer and its signed updater artifact. The
|
runners). Versions follow SemVer; betas use a prerelease suffix (`0.1.0-beta.1`) and are
|
||||||
updater key is read from `.tools/updater.key` (ignored; keep it safe — replacing it
|
published as pre-releases. **Each release carries both platforms**, and the update feed
|
||||||
breaks in-app updates for existing installs) or from `TAURI_SIGNING_PRIVATE_KEY`.
|
is written only once both are uploaded.
|
||||||
3. Create the release (tag `vX.Y.Z`) and upload the files from
|
|
||||||
`src-tauri/target/release/bundle/nsis/`.
|
|
||||||
4. `node scripts/update-manifest.mjs X.Y.Z https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/vX.Y.Z notes.md`
|
|
||||||
and commit `updates/latest.json`. Installed copies offer the update on their next
|
|
||||||
start.
|
|
||||||
|
|
||||||
For macOS and Linux, build on those systems (`scripts/fetch-libmpv.sh`, then
|
Checklist for version `X.Y.Z` (run from the repository root):
|
||||||
`npx tauri build`) and merge their bundles into the same feed with `KALEIDO_BUNDLES`.
|
|
||||||
CI (`.forgejo/workflows/release.yml`) validates every push and builds installers for
|
1. **Version** (either machine): set `X.Y.Z` in `package.json`, `src-tauri/Cargo.toml`
|
||||||
tags on runners for each enabled platform.
|
and `src-tauri/tauri.conf.json`, then `npm install --package-lock-only` to update
|
||||||
|
`package-lock.json`.
|
||||||
|
2. **Changelog**: add a `## X.Y.Z` section at the top of `CHANGELOG.md`. It becomes the
|
||||||
|
release notes and the in-app update notes.
|
||||||
|
3. **Check**: `npm run typecheck`, `npm test`, `cargo check --manifest-path src-tauri/Cargo.toml`.
|
||||||
|
4. **Commit and tag**: commit as `Release Kaleido Desktop X.Y.Z`, then
|
||||||
|
`git tag -a vX.Y.Z -m "Kaleido Desktop X.Y.Z"` and `git push origin main vX.Y.Z`
|
||||||
|
(SSH remote `origin`, already configured). Pull it on the other machine.
|
||||||
|
5. **Build and publish on Windows**: `.\scripts\build.ps1` →
|
||||||
|
`src-tauri/target/release/bundle/nsis/Kaleido_X.Y.Z_x64-setup.exe` and its `.sig`;
|
||||||
|
then `node scripts/publish-release.mjs X.Y.Z` (add `--prerelease` for betas) creates
|
||||||
|
the Forgejo release with the notes from `CHANGELOG.md` and uploads them.
|
||||||
|
6. **Build and publish on macOS**: `sh scripts/build.sh` → `bundle/dmg/Kaleido_X.Y.Z_aarch64.dmg`
|
||||||
|
(first installs) and `bundle/macos/Kaleido_X.Y.Z_aarch64.app.tar.gz` with its `.sig`
|
||||||
|
(updates); then `node scripts/publish-release.mjs X.Y.Z [--prerelease]` adds them to
|
||||||
|
the same release. The order of 5 and 6 doesn't matter.
|
||||||
|
7. **Update feed** (either machine): `node scripts/update-manifest.mjs X.Y.Z` reads the
|
||||||
|
release's assets (downloading each `.sig`) and rewrites `updates/latest.json`; commit
|
||||||
|
it (`Publish the X.Y.Z update feed`) and push. Installed copies offer the update on
|
||||||
|
their next start. The script refuses while a platform's build is missing from the
|
||||||
|
release, so neither OS is ever pointed at an older build; `--allow-missing` publishes
|
||||||
|
the feed without it (that OS then sees no update until the feed is regenerated).
|
||||||
|
8. **Verify**: download each artifact from the release and compare its SHA-256 with the
|
||||||
|
local file; `https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/raw/branch/main/updates/latest.json`
|
||||||
|
should list both platforms at the new version; CI on Actions should finish green.
|
||||||
|
|
||||||
|
Both publishing scripts read `FORGEJO_TOKEN` (repository read/write) from the
|
||||||
|
environment or the ignored `.env`, and never print it. Re-running `publish-release.mjs`
|
||||||
|
replaces that machine's assets.
|
||||||
|
|
||||||
|
**Update signing**: both build scripts sign update artifacts with the updater key from
|
||||||
|
`.tools/updater.key` (ignored; keep it safe — replacing it breaks in-app updates for
|
||||||
|
existing installs) or `TAURI_SIGNING_PRIVATE_KEY`. Both build machines need the same
|
||||||
|
key in `.tools/`; without it a build has no update archive.
|
||||||
|
|
||||||
|
**Windows** installs per user (`%LOCALAPPDATA%\Kaleido`, no admin) and is not
|
||||||
|
code-signed, so SmartScreen warns on first run. In-app updates run the installer in
|
||||||
|
passive mode and relaunch.
|
||||||
|
|
||||||
|
**macOS** builds are signed with a self-signed certificate, "Kaleido Self-Signed", in
|
||||||
|
the build Mac's login keychain (backed up, with its password, as
|
||||||
|
`.tools/macos-signing.p12` and `.tools/macos-signing.password`). A lasting signature
|
||||||
|
keeps the app's identity across updates, so the Keychain keeps trusting it with the
|
||||||
|
Plex token; ad hoc signatures change with every build and would make macOS ask again
|
||||||
|
after each update. To build on another Mac, import the backup:
|
||||||
|
`security import .tools/macos-signing.p12 -k ~/Library/Keychains/login.keychain-db -P "$(cat .tools/macos-signing.password)" -T /usr/bin/codesign`.
|
||||||
|
The app isn't notarized, so the first launch of a downloaded `.dmg` needs
|
||||||
|
System Settings → Privacy & Security → Open Anyway (or right-click → Open); in-app
|
||||||
|
updates aren't quarantined and install without that. Building runs Finder through
|
||||||
|
AppleScript to lay out the disk image window; set `CI=true` to skip that step.
|
||||||
|
|
||||||
|
Linux can be built with `sh scripts/fetch-libmpv.sh` and `npx tauri build` but isn't
|
||||||
|
published. `.forgejo/workflows/release.yml` validates every push and tag;
|
||||||
|
`.forgejo/workflows/build-installers.yml` can build installers in CI once runners exist
|
||||||
|
for each platform, and only runs when started by hand.
|
||||||
|
|
|
||||||
12
mini.html
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en" class="mini-window">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Kaleido</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/mini/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
4
package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
||||||
{
|
{
|
||||||
"name": "kaleido-desktop",
|
"name": "kaleido-desktop",
|
||||||
"version": "0.1.0-beta.1",
|
"version": "1.0.1",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "kaleido-desktop",
|
"name": "kaleido-desktop",
|
||||||
"version": "0.1.0-beta.1",
|
"version": "1.0.1",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fontsource-variable/inter": "^5.3.0",
|
"@fontsource-variable/inter": "^5.3.0",
|
||||||
"@tanstack/react-query": "^5.105.0",
|
"@tanstack/react-query": "^5.105.0",
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"name": "kaleido-desktop",
|
"name": "kaleido-desktop",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.1.0-beta.1",
|
"version": "1.0.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|
|
||||||
|
|
@ -21,10 +21,25 @@ if (-not $env:TAURI_SIGNING_PRIVATE_KEY) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not (Test-Path (Join-Path $root "node_modules"))) { npm ci }
|
if (-not (Test-Path (Join-Path $root "node_modules"))) { npm ci }
|
||||||
|
|
||||||
|
# Symbols for reading hang and crash dumps (diagnostics.rs): keep function names
|
||||||
|
# and line tables in kaleido.pdb. They stay out of the executable.
|
||||||
|
$env:CARGO_PROFILE_RELEASE_STRIP = "none"
|
||||||
|
$env:CARGO_PROFILE_RELEASE_DEBUG = "line-tables-only"
|
||||||
$buildArgs = @("tauri", "build")
|
$buildArgs = @("tauri", "build")
|
||||||
if ($Debug) { $buildArgs += "--debug" }
|
if ($Debug) { $buildArgs += "--debug" }
|
||||||
npx @buildArgs
|
npx @buildArgs
|
||||||
if ($LASTEXITCODE -ne 0) { throw "Build failed" }
|
if ($LASTEXITCODE -ne 0) { throw "Build failed" }
|
||||||
|
|
||||||
$profile = if ($Debug) { "debug" } else { "release" }
|
$profile = if ($Debug) { "debug" } else { "release" }
|
||||||
|
|
||||||
|
# Keep this version's executable and symbols: a dump can only be read with the
|
||||||
|
# exact build that wrote it (.tools/ is ignored).
|
||||||
|
if (-not $Debug) {
|
||||||
|
$version = (Get-Content (Join-Path $root "src-tauri\tauri.conf.json") -Raw | ConvertFrom-Json).version
|
||||||
|
$symbols = Join-Path $root ".tools\symbols\$version"
|
||||||
|
New-Item -ItemType Directory -Force $symbols | Out-Null
|
||||||
|
Copy-Item (Join-Path $root "src-tauri\target\release\kaleido.exe"), (Join-Path $root "src-tauri\target\release\kaleido.pdb") $symbols -Force
|
||||||
|
Write-Host "Symbols kept in $symbols"
|
||||||
|
}
|
||||||
Get-ChildItem (Join-Path $root "src-tauri\target\$profile\bundle\nsis") | Select-Object Name, Length
|
Get-ChildItem (Join-Path $root "src-tauri\target\$profile\bundle\nsis") | Select-Object Name, Length
|
||||||
|
|
|
||||||
54
scripts/build.sh
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
#!/usr/bin/env sh
|
||||||
|
# Builds Kaleido for macOS: the .app, a .dmg for first installs and the signed updater
|
||||||
|
# archive, renamed Kaleido_<version>_<arch>.app.tar.gz for the release.
|
||||||
|
# sh scripts/build.sh # release build
|
||||||
|
# sh scripts/build.sh --debug # faster unoptimized build
|
||||||
|
set -eu
|
||||||
|
root=$(cd "$(dirname "$0")/.." && pwd)
|
||||||
|
cd "$root"
|
||||||
|
profile=release
|
||||||
|
[ "${1:-}" = "--debug" ] && profile=debug
|
||||||
|
|
||||||
|
sh scripts/fetch-libmpv.sh
|
||||||
|
|
||||||
|
# The bundled libraries decide the oldest macOS Kaleido runs on (Homebrew builds them
|
||||||
|
# for the macOS of the machine that installed them).
|
||||||
|
minos=$(for f in vendor/mpv/macos/*.dylib; do otool -l "$f" | awk '/LC_BUILD_VERSION/{b=1} b&&/minos/{print $2; b=0}'; done | sort -V | tail -1)
|
||||||
|
|
||||||
|
# Signing with one lasting certificate keeps the app's identity across updates, so the
|
||||||
|
# Keychain keeps trusting it with the Plex token (ad hoc signatures change every build).
|
||||||
|
# "Kaleido Self-Signed" lives in the login keychain; .tools/macos-signing.p12 backs it up.
|
||||||
|
identity=${KALEIDO_SIGNING_IDENTITY:-Kaleido Self-Signed}
|
||||||
|
if security find-identity -p codesigning | grep -q "\"$identity\""; then
|
||||||
|
codesign --force --sign "$identity" vendor/mpv/macos/*.dylib 2>/dev/null
|
||||||
|
else
|
||||||
|
echo "warning: no \"$identity\" signing certificate; signing ad hoc (the Keychain will ask again after updates)." >&2
|
||||||
|
identity=-
|
||||||
|
fi
|
||||||
|
|
||||||
|
# The updater signing key stays outside git (.tools/), as on Windows.
|
||||||
|
updater=true
|
||||||
|
if [ -z "${TAURI_SIGNING_PRIVATE_KEY:-}" ]; then
|
||||||
|
if [ -f .tools/updater.key ]; then
|
||||||
|
TAURI_SIGNING_PRIVATE_KEY=$(cat .tools/updater.key)
|
||||||
|
TAURI_SIGNING_PRIVATE_KEY_PASSWORD=${TAURI_SIGNING_PRIVATE_KEY_PASSWORD:-}
|
||||||
|
export TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD
|
||||||
|
else
|
||||||
|
echo "warning: no updater signing key (.tools/updater.key); building without update artifacts." >&2
|
||||||
|
updater=false
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
config="{\"bundle\":{\"createUpdaterArtifacts\":$updater,\"macOS\":{\"minimumSystemVersion\":\"$minos\",\"signingIdentity\":\"$identity\"}}}"
|
||||||
|
|
||||||
|
[ -d node_modules ] || npm ci
|
||||||
|
if [ "$profile" = debug ]; then npx tauri build --debug --config "$config"; else npx tauri build --config "$config"; fi
|
||||||
|
|
||||||
|
version=$(node -p "require('./package.json').version")
|
||||||
|
arch=$(uname -m | sed 's/arm64/aarch64/; s/x86_64/x64/')
|
||||||
|
bundle="src-tauri/target/$profile/bundle"
|
||||||
|
if [ -f "$bundle/macos/Kaleido.app.tar.gz" ]; then
|
||||||
|
cp "$bundle/macos/Kaleido.app.tar.gz" "$bundle/macos/Kaleido_${version}_${arch}.app.tar.gz"
|
||||||
|
cp "$bundle/macos/Kaleido.app.tar.gz.sig" "$bundle/macos/Kaleido_${version}_${arch}.app.tar.gz.sig"
|
||||||
|
fi
|
||||||
|
echo "Built for macOS $minos or later:"
|
||||||
|
ls -l "$bundle/dmg" "$bundle/macos"
|
||||||
|
|
@ -1,14 +1,39 @@
|
||||||
#!/usr/bin/env sh
|
#!/usr/bin/env sh
|
||||||
# macOS: copies Homebrew's libmpv into vendor/mpv/macos for bundling.
|
# macOS: copies Homebrew's libmpv and every library it links (ffmpeg, libplacebo, ...)
|
||||||
|
# into vendor/mpv/macos, pointing them at each other with @loader_path so the folder is
|
||||||
|
# self-contained; the bundle ships it as Contents/Frameworks.
|
||||||
# Linux: libmpv comes from the system package (libmpv2); nothing to copy.
|
# Linux: libmpv comes from the system package (libmpv2); nothing to copy.
|
||||||
set -eu
|
set -eu
|
||||||
root=$(cd "$(dirname "$0")/.." && pwd)
|
root=$(cd "$(dirname "$0")/.." && pwd)
|
||||||
case "$(uname -s)" in
|
case "$(uname -s)" in
|
||||||
Darwin)
|
Darwin)
|
||||||
|
out="$root/vendor/mpv/macos"
|
||||||
|
if [ -f "$out/libmpv.2.dylib" ] && [ "${1:-}" != "--force" ]; then
|
||||||
|
echo "libmpv already in vendor/mpv/macos (pass --force to refresh)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
brew list mpv >/dev/null 2>&1 || brew install mpv
|
brew list mpv >/dev/null 2>&1 || brew install mpv
|
||||||
mkdir -p "$root/vendor/mpv/macos"
|
command -v dylibbundler >/dev/null 2>&1 || brew install dylibbundler
|
||||||
cp "$(brew --prefix mpv)/lib/libmpv.2.dylib" "$root/vendor/mpv/macos/"
|
rm -rf "$out" && mkdir -p "$out"
|
||||||
echo "libmpv copied to vendor/mpv/macos" ;;
|
cp "$(brew --prefix mpv)/lib/libmpv.2.dylib" "$out/"
|
||||||
|
chmod u+w "$out/libmpv.2.dylib"
|
||||||
|
install_name_tool -id @loader_path/libmpv.2.dylib "$out/libmpv.2.dylib"
|
||||||
|
# -of: overwrite, -b: bundle dependencies, -x: fix this file, -d: where they go,
|
||||||
|
# -p: how they're referenced, -s: also search Homebrew's lib folder for @rpath names.
|
||||||
|
dylibbundler -of -b -x "$out/libmpv.2.dylib" -d "$out" -p @loader_path/ -s "$(brew --prefix)/lib" >/dev/null
|
||||||
|
for f in "$out"/*.dylib; do
|
||||||
|
# dylibbundler can repeat an rpath, which dyld refuses to load; keep one of each.
|
||||||
|
for rpath in $(otool -l "$f" | awk '/cmd LC_RPATH/{getline; getline; print $2}' | sort | uniq -d); do
|
||||||
|
while [ "$(otool -l "$f" | awk '/cmd LC_RPATH/{getline; getline; print $2}' | grep -cx "$rpath")" -gt 1 ]; do
|
||||||
|
install_name_tool -delete_rpath "$rpath" "$f" 2>/dev/null
|
||||||
|
done
|
||||||
|
done
|
||||||
|
# Rewriting load commands invalidates signatures; Apple silicon refuses unsigned code.
|
||||||
|
codesign --force --sign - "$f" 2>/dev/null
|
||||||
|
done
|
||||||
|
# Homebrew builds for the macOS it runs on: the oldest macOS these libraries load on.
|
||||||
|
minos=$(for f in "$out"/*.dylib; do otool -l "$f" | awk '/LC_BUILD_VERSION/{b=1} b&&/minos/{print $2; b=0}'; done | sort -V | tail -1)
|
||||||
|
echo "libmpv and $(($(ls "$out" | wc -l) - 1)) libraries copied to vendor/mpv/macos (need macOS $minos or later)" ;;
|
||||||
Linux)
|
Linux)
|
||||||
echo "Install libmpv from your distribution (e.g. apt install libmpv2 libmpv-dev)." ;;
|
echo "Install libmpv from your distribution (e.g. apt install libmpv2 libmpv-dev)." ;;
|
||||||
*) echo "Use scripts/fetch-libmpv.ps1 on Windows." ;;
|
*) echo "Use scripts/fetch-libmpv.ps1 on Windows." ;;
|
||||||
|
|
|
||||||
56
scripts/publish-release.mjs
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
// Creates (or reuses) a Forgejo release for a tag and uploads this machine's build of it:
|
||||||
|
// the Windows installer, or the macOS disk image and updater archive, each with its
|
||||||
|
// updater signature. Run it on each OS after building; both land in the same release.
|
||||||
|
// Reads FORGEJO_TOKEN from the environment or the ignored .env.
|
||||||
|
// Usage: node scripts/publish-release.mjs <version> [--prerelease]
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { api, bundleDir, releaseNotes, token } from './release-common.mjs';
|
||||||
|
|
||||||
|
const version = process.argv[2];
|
||||||
|
const prerelease = process.argv.includes('--prerelease');
|
||||||
|
if (!version) {
|
||||||
|
console.error('usage: node scripts/publish-release.mjs <version> [--prerelease]');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** This version's release files as built on this OS (scripts/build.ps1 or scripts/build.sh). */
|
||||||
|
function builtFiles() {
|
||||||
|
if (process.platform === 'win32') {
|
||||||
|
const dir = path.join(bundleDir, 'nsis');
|
||||||
|
return [`Kaleido_${version}_x64-setup.exe`, `Kaleido_${version}_x64-setup.exe.sig`].map((n) => path.join(dir, n));
|
||||||
|
}
|
||||||
|
if (process.platform === 'darwin') {
|
||||||
|
const arch = process.arch === 'arm64' ? 'aarch64' : 'x64';
|
||||||
|
return [
|
||||||
|
path.join(bundleDir, 'dmg', `Kaleido_${version}_${arch}.dmg`),
|
||||||
|
path.join(bundleDir, 'macos', `Kaleido_${version}_${arch}.app.tar.gz`),
|
||||||
|
path.join(bundleDir, 'macos', `Kaleido_${version}_${arch}.app.tar.gz.sig`),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
throw new Error('Publish releases from Windows or macOS.');
|
||||||
|
}
|
||||||
|
|
||||||
|
token(true);
|
||||||
|
const files = builtFiles();
|
||||||
|
for (const file of files) {
|
||||||
|
if (!fs.existsSync(file)) throw new Error(`Missing ${file}; build this version first.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tag = `v${version}`;
|
||||||
|
let release = await api('GET', `/releases/tags/${tag}`).catch(() => null);
|
||||||
|
if (!release) {
|
||||||
|
release = await api('POST', '/releases', { tag_name: tag, name: `Kaleido Desktop ${version}`, body: releaseNotes(version), prerelease, draft: false });
|
||||||
|
console.log(`Created release ${release.name}`);
|
||||||
|
} else console.log(`Using existing release ${release.name}`);
|
||||||
|
|
||||||
|
for (const file of files) {
|
||||||
|
const name = path.basename(file);
|
||||||
|
const existing = release.assets?.find((a) => a.name === name);
|
||||||
|
if (existing) await api('DELETE', `/releases/${release.id}/assets/${existing.id}`);
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('attachment', new Blob([fs.readFileSync(file)]), name);
|
||||||
|
const asset = await api('POST', `/releases/${release.id}/assets?name=${encodeURIComponent(name)}`, form);
|
||||||
|
console.log(`Uploaded ${asset.name} (${asset.size} bytes): ${asset.browser_download_url}`);
|
||||||
|
}
|
||||||
|
console.log(release.html_url);
|
||||||
49
scripts/release-common.mjs
Normal file
|
|
@ -0,0 +1,49 @@
|
||||||
|
// Shared by the release scripts: the Forgejo API (FORGEJO_TOKEN from the environment or
|
||||||
|
// the ignored .env, never printed), release notes and the bundle folder.
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
export const API = 'https://git.elijahkuntz.com/api/v1/repos/Elijah/Kaleido-Desktop';
|
||||||
|
export const root = path.resolve(import.meta.dirname, '..');
|
||||||
|
export const bundleDir = path.join(root, 'src-tauri/target/release/bundle');
|
||||||
|
|
||||||
|
/** FORGEJO_TOKEN; reads of a public repository work without it, uploads don't. */
|
||||||
|
export function token(required = false) {
|
||||||
|
let t = process.env.FORGEJO_TOKEN;
|
||||||
|
if (!t && fs.existsSync(path.join(root, '.env'))) {
|
||||||
|
t = fs.readFileSync(path.join(root, '.env'), 'utf8').match(/^FORGEJO_TOKEN=(.*)$/m)?.[1]?.trim().replace(/^"|"$/g, '');
|
||||||
|
}
|
||||||
|
if (!t && required) {
|
||||||
|
console.error('FORGEJO_TOKEN is not set.');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auth = () => (token() ? { Authorization: `token ${token()}` } : {});
|
||||||
|
|
||||||
|
export async function api(method, url, body) {
|
||||||
|
const headers = { ...auth(), Accept: 'application/json' };
|
||||||
|
const r = await fetch(url.startsWith('http') ? url : API + url, {
|
||||||
|
method,
|
||||||
|
headers: body instanceof FormData ? headers : { ...headers, 'Content-Type': 'application/json' },
|
||||||
|
body: body === undefined ? undefined : body instanceof FormData ? body : JSON.stringify(body),
|
||||||
|
});
|
||||||
|
const text = await r.text();
|
||||||
|
if (!r.ok) throw new Error(`${method} ${url} → ${r.status} ${text.slice(0, 300)}`);
|
||||||
|
return text ? JSON.parse(text) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Downloads a release asset's text (an updater signature). */
|
||||||
|
export async function download(url) {
|
||||||
|
const r = await fetch(url, { headers: auth() });
|
||||||
|
if (!r.ok) throw new Error(`GET ${url} → ${r.status}`);
|
||||||
|
return r.text();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The version's section of CHANGELOG.md. */
|
||||||
|
export function releaseNotes(version) {
|
||||||
|
const changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8');
|
||||||
|
const section = changelog.split(/^## /m).find((s) => s.startsWith(version));
|
||||||
|
return section ? section.slice(version.length).trim() : '';
|
||||||
|
}
|
||||||
|
|
@ -1,47 +1,56 @@
|
||||||
// Writes updates/latest.json, the feed Kaleido's updater reads, from built bundles.
|
// Writes updates/latest.json, the feed Kaleido's updater reads, from a published release:
|
||||||
// Usage: node scripts/update-manifest.mjs <version> <baseDownloadUrl> [notesFile]
|
// each platform's updater artifact and signature are taken from the release's assets, so
|
||||||
// Each platform's signed artifact (and its .sig) must be in src-tauri/target/release/bundle,
|
// the feed only ever points at this version's files, whichever machine runs it.
|
||||||
// or pass several bundle folders via KALEIDO_BUNDLES (path;path) when collecting CI outputs.
|
// Usage: node scripts/update-manifest.mjs <version> [--allow-missing] [notesFile]
|
||||||
|
// Every platform in PLATFORMS must be in the release (publish from each OS first);
|
||||||
|
// --allow-missing writes the feed anyway, leaving the missing platforms out of it, so
|
||||||
|
// their installs simply see no update until the feed is regenerated.
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
|
import { api, download, releaseNotes, root } from './release-common.mjs';
|
||||||
|
|
||||||
const [version, baseUrl, notesFile] = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
if (!version || !baseUrl) {
|
const allowMissing = args.includes('--allow-missing');
|
||||||
console.error('usage: node scripts/update-manifest.mjs <version> <baseDownloadUrl> [notesFile]');
|
const [version, notesFile] = args.filter((a) => !a.startsWith('--'));
|
||||||
|
if (!version) {
|
||||||
|
console.error('usage: node scripts/update-manifest.mjs <version> [--allow-missing] [notesFile]');
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
const root = path.resolve(import.meta.dirname, '..');
|
|
||||||
const bundles = (process.env.KALEIDO_BUNDLES ?? path.join(root, 'src-tauri/target/release/bundle')).split(';');
|
|
||||||
|
|
||||||
/** Tauri updater platform keys and the artifact each one installs. */
|
/** Tauri updater platform keys and the release asset each one installs. */
|
||||||
const PLATFORMS = [
|
const PLATFORMS = [
|
||||||
{ key: 'windows-x86_64', dir: 'nsis', match: /-setup\.exe$/ },
|
{ key: 'windows-x86_64', match: (f) => f === `Kaleido_${version}_x64-setup.exe` },
|
||||||
{ key: 'darwin-aarch64', dir: 'macos', match: /aarch64.*\.app\.tar\.gz$/ },
|
{ key: 'darwin-aarch64', match: (f) => f === `Kaleido_${version}_aarch64.app.tar.gz` },
|
||||||
{ key: 'darwin-x86_64', dir: 'macos', match: /x64.*\.app\.tar\.gz$/ },
|
|
||||||
{ key: 'linux-x86_64', dir: 'appimage', match: /\.AppImage$/ },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
const manifestPath = path.join(root, 'updates/latest.json');
|
const release = await api('GET', `/releases/tags/v${version}`).catch(() => null);
|
||||||
const manifest = fs.existsSync(manifestPath) ? JSON.parse(fs.readFileSync(manifestPath, 'utf8')) : { platforms: {} };
|
if (!release) throw new Error(`No release v${version}; publish it with scripts/publish-release.mjs first.`);
|
||||||
manifest.version = version;
|
const assets = release.assets ?? [];
|
||||||
manifest.notes = notesFile ? fs.readFileSync(notesFile, 'utf8').trim() : manifest.notes ?? '';
|
|
||||||
manifest.pub_date = new Date().toISOString();
|
|
||||||
manifest.platforms ??= {};
|
|
||||||
|
|
||||||
for (const bundle of bundles) {
|
const platforms = {};
|
||||||
for (const p of PLATFORMS) {
|
const missing = [];
|
||||||
const dir = path.join(bundle, p.dir);
|
for (const p of PLATFORMS) {
|
||||||
if (!fs.existsSync(dir)) continue;
|
const artifact = assets.find((a) => p.match(a.name));
|
||||||
const file = fs.readdirSync(dir).find((f) => p.match.test(f) && f.includes(version));
|
const sig = artifact && assets.find((a) => a.name === `${artifact.name}.sig`);
|
||||||
if (!file || !fs.existsSync(path.join(dir, `${file}.sig`))) continue;
|
if (!artifact || !sig) {
|
||||||
manifest.platforms[p.key] = {
|
missing.push(p.key);
|
||||||
signature: fs.readFileSync(path.join(dir, `${file}.sig`), 'utf8').trim(),
|
continue;
|
||||||
url: `${baseUrl.replace(/\/$/, '')}/${encodeURIComponent(file)}`,
|
|
||||||
};
|
|
||||||
console.log(`${p.key}: ${file}`);
|
|
||||||
}
|
}
|
||||||
|
platforms[p.key] = { signature: (await download(sig.browser_download_url)).trim(), url: artifact.browser_download_url };
|
||||||
|
console.log(`${p.key}: ${artifact.name}`);
|
||||||
}
|
}
|
||||||
|
if (missing.length && !allowMissing) {
|
||||||
|
console.error(`v${version} has no build for ${missing.join(', ')}. Publish it from that OS, or pass --allow-missing.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
if (!Object.keys(platforms).length) throw new Error(`v${version} has no updater artifacts.`);
|
||||||
|
|
||||||
fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
|
const manifest = {
|
||||||
|
version,
|
||||||
|
notes: notesFile ? fs.readFileSync(notesFile, 'utf8').trim() : releaseNotes(version),
|
||||||
|
pub_date: new Date().toISOString(),
|
||||||
|
platforms,
|
||||||
|
};
|
||||||
|
const manifestPath = path.join(root, 'updates/latest.json');
|
||||||
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
||||||
console.log(`Wrote ${path.relative(root, manifestPath)}`);
|
console.log(`Wrote ${path.relative(root, manifestPath)}${missing.length ? ` (without ${missing.join(', ')})` : ''}`);
|
||||||
|
|
|
||||||
57
src-tauri/Cargo.lock
generated
|
|
@ -2173,13 +2173,21 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "kaleido"
|
name = "kaleido"
|
||||||
version = "0.1.0-beta.1"
|
version = "1.0.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"fs2",
|
"fs2",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"keyring",
|
"keyring",
|
||||||
"libloading 0.8.9",
|
"libloading 0.8.9",
|
||||||
"log",
|
"log",
|
||||||
|
"objc2",
|
||||||
|
"objc2-app-kit",
|
||||||
|
"objc2-core-foundation",
|
||||||
|
"objc2-core-graphics",
|
||||||
|
"objc2-core-video",
|
||||||
|
"objc2-foundation",
|
||||||
|
"objc2-open-gl",
|
||||||
|
"objc2-quartz-core",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"parking_lot",
|
"parking_lot",
|
||||||
"reqwest 0.12.28",
|
"reqwest 0.12.28",
|
||||||
|
|
@ -2605,8 +2613,15 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags 2.13.2",
|
"bitflags 2.13.2",
|
||||||
"block2",
|
"block2",
|
||||||
|
"libc",
|
||||||
"objc2",
|
"objc2",
|
||||||
|
"objc2-cloud-kit",
|
||||||
|
"objc2-core-data",
|
||||||
"objc2-core-foundation",
|
"objc2-core-foundation",
|
||||||
|
"objc2-core-graphics",
|
||||||
|
"objc2-core-image",
|
||||||
|
"objc2-core-text",
|
||||||
|
"objc2-core-video",
|
||||||
"objc2-foundation",
|
"objc2-foundation",
|
||||||
"objc2-quartz-core",
|
"objc2-quartz-core",
|
||||||
]
|
]
|
||||||
|
|
@ -2628,6 +2643,7 @@ version = "0.3.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"
|
checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
"objc2",
|
"objc2",
|
||||||
"objc2-foundation",
|
"objc2-foundation",
|
||||||
]
|
]
|
||||||
|
|
@ -2688,6 +2704,19 @@ dependencies = [
|
||||||
"objc2-core-graphics",
|
"objc2-core-graphics",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "objc2-core-video"
|
||||||
|
version = "0.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"objc2",
|
||||||
|
"objc2-core-foundation",
|
||||||
|
"objc2-core-graphics",
|
||||||
|
"objc2-io-surface",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "objc2-encode"
|
name = "objc2-encode"
|
||||||
version = "4.1.0"
|
version = "4.1.0"
|
||||||
|
|
@ -2727,6 +2756,26 @@ dependencies = [
|
||||||
"objc2-core-foundation",
|
"objc2-core-foundation",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "objc2-metal"
|
||||||
|
version = "0.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"objc2",
|
||||||
|
"objc2-foundation",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "objc2-open-gl"
|
||||||
|
version = "0.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0ecc7fd7519a189d9ba9ed9de51af81e41d096aea1d08cca59fd9d8c65d8f585"
|
||||||
|
dependencies = [
|
||||||
|
"objc2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "objc2-osa-kit"
|
name = "objc2-osa-kit"
|
||||||
version = "0.3.2"
|
version = "0.3.2"
|
||||||
|
|
@ -2746,9 +2795,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
|
checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags 2.13.2",
|
"bitflags 2.13.2",
|
||||||
|
"block2",
|
||||||
|
"libc",
|
||||||
"objc2",
|
"objc2",
|
||||||
"objc2-core-foundation",
|
"objc2-core-foundation",
|
||||||
|
"objc2-core-graphics",
|
||||||
|
"objc2-core-video",
|
||||||
"objc2-foundation",
|
"objc2-foundation",
|
||||||
|
"objc2-metal",
|
||||||
|
"objc2-open-gl",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
[package]
|
[package]
|
||||||
name = "kaleido"
|
name = "kaleido"
|
||||||
version = "0.1.0-beta.1"
|
version = "1.0.1"
|
||||||
description = "Kaleido — a Plex client for Windows"
|
description = "Kaleido — a Plex client for Windows"
|
||||||
authors = ["Elijah"]
|
authors = ["Elijah"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
@ -34,6 +34,14 @@ log = "0.4"
|
||||||
# Credentials use each OS's native store: Credential Manager, Keychain, Secret Service.
|
# Credentials use each OS's native store: Credential Manager, Keychain, Secret Service.
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
keyring = { version = "3", features = ["apple-native"] }
|
keyring = { version = "3", features = ["apple-native"] }
|
||||||
|
objc2 = "0.6"
|
||||||
|
objc2-foundation = { version = "0.3", features = ["NSGeometry", "NSString", "NSValue", "NSHost", "NSProcessInfo", "NSKeyValueCoding"] }
|
||||||
|
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFDate", "CFString"] }
|
||||||
|
objc2-app-kit = { version = "0.3", features = ["NSView", "NSWindow", "NSResponder", "NSButton", "NSControl", "NSGraphics"] }
|
||||||
|
objc2-quartz-core = { version = "0.3", features = ["CALayer", "CAOpenGLLayer", "CATransaction", "CAMediaTiming", "objc2-open-gl", "objc2-core-video", "objc2-core-graphics"] }
|
||||||
|
objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGColorSpace"] }
|
||||||
|
objc2-open-gl = { version = "0.3", default-features = false, features = ["std", "CGLTypes", "CGLCurrent"] }
|
||||||
|
objc2-core-video = { version = "0.3", default-features = false, features = ["std", "CVBase"] }
|
||||||
|
|
||||||
[target.'cfg(target_os = "linux")'.dependencies]
|
[target.'cfg(target_os = "linux")'.dependencies]
|
||||||
keyring = { version = "3", features = ["sync-secret-service", "crypto-rust"] }
|
keyring = { version = "3", features = ["sync-secret-service", "crypto-rust"] }
|
||||||
|
|
@ -54,6 +62,13 @@ windows = { version = "0.61", features = [
|
||||||
"Win32_Graphics_Direct3D",
|
"Win32_Graphics_Direct3D",
|
||||||
"Win32_Graphics_Direct3D11",
|
"Win32_Graphics_Direct3D11",
|
||||||
"Foundation_Numerics",
|
"Foundation_Numerics",
|
||||||
|
# Hang and crash dumps (diagnostics.rs).
|
||||||
|
"Win32_System_Diagnostics_Debug",
|
||||||
|
"Win32_System_Kernel",
|
||||||
|
"Win32_System_Memory",
|
||||||
|
"Win32_System_Threading",
|
||||||
|
# The miniplayer window's rounded corners (mini.rs).
|
||||||
|
"Win32_Graphics_Dwm",
|
||||||
] }
|
] }
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,10 @@
|
||||||
{
|
{
|
||||||
"$schema": "../gen/schemas/desktop-schema.json",
|
"$schema": "../gen/schemas/desktop-schema.json",
|
||||||
"identifier": "default",
|
"identifier": "default",
|
||||||
"description": "Kaleido main window",
|
"description": "Kaleido main window and miniplayer window",
|
||||||
"windows": [
|
"windows": [
|
||||||
"main"
|
"main",
|
||||||
|
"mini"
|
||||||
],
|
],
|
||||||
"permissions": [
|
"permissions": [
|
||||||
"core:default",
|
"core:default",
|
||||||
|
|
|
||||||
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 29 KiB |
|
Before Width: | Height: | Size: 1.8 KiB After Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 4.7 KiB After Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 9.9 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 33 KiB After Width: | Height: | Size: 33 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 37 KiB |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 6.2 KiB |
|
Before Width: | Height: | Size: 7.6 KiB After Width: | Height: | Size: 8.1 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 4 KiB |
|
Before Width: | Height: | Size: 153 KiB After Width: | Height: | Size: 447 KiB |
35
src-tauri/icons/app-icon.svg
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
|
||||||
|
<!-- Source for app-icon.png: the brand mark filling ~77% of the tile. Regenerate the
|
||||||
|
icon set with `npx tauri icon` (see docs/development.md → App icon). -->
|
||||||
|
<defs>
|
||||||
|
<radialGradient id="teal" cx="900" cy="110" r="920" gradientUnits="userSpaceOnUse">
|
||||||
|
<stop offset="0" stop-color="#3D7C7B" stop-opacity="0.38"/>
|
||||||
|
<stop offset="1" stop-color="#3D7C7B" stop-opacity="0"/>
|
||||||
|
</radialGradient>
|
||||||
|
<radialGradient id="warm" cx="110" cy="950" r="820" gradientUnits="userSpaceOnUse">
|
||||||
|
<stop offset="0" stop-color="#D0A977" stop-opacity="0.17"/>
|
||||||
|
<stop offset="1" stop-color="#D0A977" stop-opacity="0"/>
|
||||||
|
</radialGradient>
|
||||||
|
<radialGradient id="core" cx="512" cy="512" r="300" gradientUnits="userSpaceOnUse">
|
||||||
|
<stop offset="0" stop-color="#71B9B0" stop-opacity="0.12"/>
|
||||||
|
<stop offset="1" stop-color="#71B9B0" stop-opacity="0"/>
|
||||||
|
</radialGradient>
|
||||||
|
<clipPath id="tile">
|
||||||
|
<rect width="1024" height="1024" rx="200"/>
|
||||||
|
</clipPath>
|
||||||
|
</defs>
|
||||||
|
<g clip-path="url(#tile)">
|
||||||
|
<rect width="1024" height="1024" fill="#0d1011"/>
|
||||||
|
<rect width="1024" height="1024" fill="url(#teal)"/>
|
||||||
|
<rect width="1024" height="1024" fill="url(#warm)"/>
|
||||||
|
<rect width="1024" height="1024" fill="url(#core)"/>
|
||||||
|
</g>
|
||||||
|
<g transform="translate(64 64) scale(14)">
|
||||||
|
<path fill="#C3E8D3" d="M33,4 L55.5,17 L42.5,24.5 L33,19 Z"/>
|
||||||
|
<path fill="#71B9B0" d="M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z"/>
|
||||||
|
<path fill="#3D7C7B" d="M55.5,47 L33,60 L33,45 L42.5,39.5 Z"/>
|
||||||
|
<path fill="#D0A977" d="M31,60 L8.5,47 L21.5,39.5 L31,45 Z"/>
|
||||||
|
<path fill="#E9D8AE" d="M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z"/>
|
||||||
|
<path fill="#EEF2DD" d="M8.5,17 L31,4 L31,19 L21.5,24.5 Z"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 43 KiB After Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 67 KiB After Width: | Height: | Size: 93 KiB |
272
src-tauri/shaders/CAS-prescale.glsl
Normal file
|
|
@ -0,0 +1,272 @@
|
||||||
|
// Kaleido: also sharpens before upscaling (WHEN changed as the notes above describe), SHARPENING 0.0.
|
||||||
|
|
||||||
|
// LICENSE
|
||||||
|
// =======
|
||||||
|
// Copyright (c) 2017-2019 Advanced Micro Devices, Inc. All rights reserved.
|
||||||
|
// -------
|
||||||
|
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
|
||||||
|
// files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
|
||||||
|
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
|
||||||
|
// Software is furnished to do so, subject to the following conditions:
|
||||||
|
// -------
|
||||||
|
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
|
||||||
|
// Software.
|
||||||
|
// -------
|
||||||
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
||||||
|
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||||
|
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||||
|
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
|
// FidelityFX CAS by AMD
|
||||||
|
// ported to mpv by agyild
|
||||||
|
|
||||||
|
// Changelog
|
||||||
|
// Optimized texture lookups for OpenGL 4.0+, DirectX 10+, and OpenGL ES 3.1+ (9 -> 4).
|
||||||
|
// Changed rcp + mul operations to div for better clarity when CAS_GO_SLOWER is set to 1, since the compiler should automatically
|
||||||
|
// optimize those instructions anyway.
|
||||||
|
// Made it directly operate on LUMA plane, since the original shader was operating on LUMA by deriving it from RGB. This should
|
||||||
|
// cause a major increase in performance, especially on OpenGL 4.0+ renderers (4 texture lookups vs. 9)
|
||||||
|
// Removed transparency preservation mechanism since the alpha channel is a separate source plan than LUMA
|
||||||
|
// Added custom gamma curve support for relinearization
|
||||||
|
// Removed final blending between the original and the sharpened pixels since it was redundant
|
||||||
|
//
|
||||||
|
// Notes
|
||||||
|
// The filter is designed to run in linear light, and does have an optional relinerization and delinearization pass which
|
||||||
|
// assumes BT.1886 content by default. Do not forget to change SOURCE_TRC and TARGET_TRC variables depending
|
||||||
|
// on what kind of content the filter is running on. You might want to create seperate versions of the file with different
|
||||||
|
// colorspace values, and apply them via autoprofiles. Note that running in non-linear light will result in oversharpening.
|
||||||
|
//
|
||||||
|
// By default the shader only runs on non-scaled content since it is designed for use without scaling, if the content is
|
||||||
|
// scaled you should probably use CAS-scaled.glsl instead. However this behavior can be overriden by changing the WHEN
|
||||||
|
// directives with "OUTPUT.w OUTPUT.h * LUMA.w LUMA.h * / 1.0 < !" which allows it to be used as a pre-upscale sharpener.
|
||||||
|
|
||||||
|
//!HOOK LUMA
|
||||||
|
//!BIND HOOKED
|
||||||
|
//!DESC FidelityFX Sharpening (Relinearization)
|
||||||
|
//!WHEN OUTPUT.w OUTPUT.h * LUMA.w LUMA.h * / 1.0 < !
|
||||||
|
|
||||||
|
// User variables - Relinearization
|
||||||
|
// Compatibility
|
||||||
|
#define SOURCE_TRC 4 // Is needed to convert from source colorspace to linear light. 0 = None (Skip conversion), 1 = Rec709, 2 = PQ, 3 = sRGB, 4 = BT.1886, 5 = HLG, 6 = Custom
|
||||||
|
#define CUSTOM_GAMMA 2.2 // Custom power gamma curve to use if and when SOURCE_TRC is 6.
|
||||||
|
|
||||||
|
// Shader code
|
||||||
|
|
||||||
|
float From709(float rec709) {
|
||||||
|
return max(min(rec709 / float(4.5), float(0.081)), pow((rec709 + float(0.099)) / float(1.099), float(1.0 / 0.45)));
|
||||||
|
}
|
||||||
|
|
||||||
|
float FromPq(float pq) {
|
||||||
|
float p = pow(pq, float(0.0126833));
|
||||||
|
return (pow(clamp(p - float(0.835938), 0.0, 1.0) / (float(18.8516) - float(18.6875) * p), float(6.27739)));
|
||||||
|
}
|
||||||
|
|
||||||
|
float FromSrgb(float srgb) {
|
||||||
|
return max(min(srgb / 12.92, float(0.04045)), pow((srgb + float(0.055)) / float(1.055), float(2.4)));
|
||||||
|
}
|
||||||
|
|
||||||
|
float FromHlg(float hlg) {
|
||||||
|
const float a = 0.17883277;
|
||||||
|
const float b = 0.28466892;
|
||||||
|
const float c = 0.55991073;
|
||||||
|
|
||||||
|
float linear;
|
||||||
|
if (hlg >= 0.0 && hlg <= 0.5) {
|
||||||
|
linear = pow(hlg, 2.0) / 3.0;
|
||||||
|
} else {
|
||||||
|
linear = (exp((hlg - c) / a) + b) / 12.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return linear;
|
||||||
|
}
|
||||||
|
|
||||||
|
vec4 hook() {
|
||||||
|
vec4 col = HOOKED_tex(HOOKED_pos);
|
||||||
|
col.r = clamp(col.r, 0.0, 1.0);
|
||||||
|
#if (SOURCE_TRC == 1)
|
||||||
|
col.r = From709(col.r);
|
||||||
|
#elif (SOURCE_TRC == 2)
|
||||||
|
col.r = FromPq(col.r);
|
||||||
|
#elif (SOURCE_TRC == 3)
|
||||||
|
col.r = FromSrgb(col.r);
|
||||||
|
#elif (SOURCE_TRC == 4)
|
||||||
|
col.r = pow(col.r, float(2.4));
|
||||||
|
#elif (SOURCE_TRC == 5)
|
||||||
|
col.r = FromHlg(col.r);
|
||||||
|
#elif (SOURCE_TRC == 6)
|
||||||
|
col.r = pow(col.r, float(CUSTOM_GAMMA));
|
||||||
|
#endif
|
||||||
|
return col;
|
||||||
|
}
|
||||||
|
|
||||||
|
//!HOOK LUMA
|
||||||
|
//!BIND HOOKED
|
||||||
|
//!DESC FidelityFX Sharpening
|
||||||
|
//!WHEN OUTPUT.w OUTPUT.h * LUMA.w LUMA.h * / 1.0 < !
|
||||||
|
|
||||||
|
// User variables
|
||||||
|
// Intensity
|
||||||
|
#define SHARPENING 0.0 // Adjusts the range the shader adapts to high contrast (0 is not all the way off). Higher values = more high contrast sharpening. 0.0 to 1.0.
|
||||||
|
|
||||||
|
// Performance
|
||||||
|
#define CAS_BETTER_DIAGONALS 1 // If set to 0, drops certain math and texture lookup operations for better performance. 0 or 1.
|
||||||
|
#define CAS_GO_SLOWER 0 // If set to 1, disables the use of optimized approximate transcendental functions which might slightly increase accuracy in exchange of performance. 0 or 1.
|
||||||
|
|
||||||
|
// Compatibility
|
||||||
|
#define TARGET_TRC 4 // Is needed to convert from source colorspace to target colorspace. 0 = None (Skip conversion), 1 = Rec709, 2 = PQ, 3 = sRGB, 4 = BT.1886, 5 = HLG, 6 = Custom
|
||||||
|
#define CUSTOM_GAMMA 2.2 // Custom power gamma curve to use if and when TARGET_TRC is 6.
|
||||||
|
|
||||||
|
// Shader code
|
||||||
|
|
||||||
|
float To709(float linear) {
|
||||||
|
return max(min(linear * float(4.5), float(0.018)), float(1.099) * pow(linear, float(0.45)) - float(0.099));
|
||||||
|
}
|
||||||
|
|
||||||
|
float ToPq(float linear) {
|
||||||
|
float p = pow(linear, float(0.159302));
|
||||||
|
return pow((float(0.835938) + float(18.8516) * p) / (float(1.0) + float(18.6875) * p), float(78.8438));
|
||||||
|
}
|
||||||
|
|
||||||
|
float ToSrgb(float linear) {
|
||||||
|
return max(min(linear * float(12.92), float(0.0031308)), float(1.055) * pow(linear, float(0.41666)) - float(0.055));
|
||||||
|
}
|
||||||
|
|
||||||
|
float ToHlg(float linear) {
|
||||||
|
const float a = 0.17883277;
|
||||||
|
const float b = 0.28466892;
|
||||||
|
const float c = 0.55991073;
|
||||||
|
|
||||||
|
float hlg;
|
||||||
|
if (linear <= 1.0 / 12.0) {
|
||||||
|
hlg = sqrt(3.0 * linear);
|
||||||
|
} else {
|
||||||
|
hlg = a * log(12.0 * linear - b) + c;
|
||||||
|
}
|
||||||
|
|
||||||
|
return hlg;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if (CAS_GO_SLOWER == 0)
|
||||||
|
|
||||||
|
float APrxLoSqrtF1(float a) {
|
||||||
|
return uintBitsToFloat((floatBitsToUint(a) >> uint(1)) + uint(0x1fbc4639));
|
||||||
|
}
|
||||||
|
|
||||||
|
float APrxLoRcpF1(float a) {
|
||||||
|
return uintBitsToFloat(uint(0x7ef07ebb) - floatBitsToUint(a));
|
||||||
|
}
|
||||||
|
|
||||||
|
float APrxMedRcpF1(float a) {
|
||||||
|
float b = uintBitsToFloat(uint(0x7ef19fff) - floatBitsToUint(a));
|
||||||
|
return b * (-b * a + float(2.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
vec4 hook()
|
||||||
|
{
|
||||||
|
// fetch a 3x3 neighborhood around the pixel 'e',
|
||||||
|
// a b c
|
||||||
|
// d(e)f
|
||||||
|
// g h i
|
||||||
|
|
||||||
|
#if (defined(HOOKED_gather) && (__VERSION__ >= 400 || (GL_ES && __VERSION__ >= 310)))
|
||||||
|
vec4 efhi = HOOKED_gather(vec2(HOOKED_pos + vec2(0.5) * HOOKED_pt), 0);
|
||||||
|
|
||||||
|
float e = efhi.w;
|
||||||
|
float f = efhi.z;
|
||||||
|
float h = efhi.x;
|
||||||
|
|
||||||
|
vec3 abd = HOOKED_gather(vec2(HOOKED_pos - vec2(0.5) * HOOKED_pt), 0).wzx;
|
||||||
|
float b = abd.y;
|
||||||
|
float d = abd.z;
|
||||||
|
|
||||||
|
#if (CAS_BETTER_DIAGONALS == 1)
|
||||||
|
float a = abd.x;
|
||||||
|
float i = efhi.y;
|
||||||
|
#endif
|
||||||
|
#else
|
||||||
|
float e = HOOKED_tex(HOOKED_pos).r;
|
||||||
|
float f = HOOKED_texOff(vec2(1.0, 0.0)).r;
|
||||||
|
float h = HOOKED_texOff(vec2(0.0, 1.0)).r;
|
||||||
|
|
||||||
|
#if (CAS_BETTER_DIAGONALS == 1)
|
||||||
|
float a = HOOKED_texOff(vec2(-1.0, -1.0)).r;
|
||||||
|
float i = HOOKED_texOff(vec2(1.0, 1.0)).r;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
float b = HOOKED_texOff(vec2( 0.0, -1.0)).r;
|
||||||
|
float d = HOOKED_texOff(vec2(-1.0, 0.0)).r;
|
||||||
|
#endif
|
||||||
|
#if (CAS_BETTER_DIAGONALS == 1)
|
||||||
|
float c = HOOKED_texOff(vec2( 1.0, -1.0)).r;
|
||||||
|
float g = HOOKED_texOff(vec2(-1.0, 1.0)).r;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Soft min and max.
|
||||||
|
// a b c b
|
||||||
|
// d e f * 0.5 + d e f * 0.5
|
||||||
|
// g h i h
|
||||||
|
// These are 2.0x bigger (factored out the extra multiply).
|
||||||
|
|
||||||
|
float mnL = min(min(min(d, e), min(f, b)), h);
|
||||||
|
float mxL = max(max(max(d, e), max(f, b)), h);
|
||||||
|
#if (CAS_BETTER_DIAGONALS == 1)
|
||||||
|
float mnL2 = min(mnL, min(min(a, c), min(g, i)));
|
||||||
|
mnL += mnL2;
|
||||||
|
|
||||||
|
float mxL2 = max(mxL, max(max(a, c), max(g, i)));
|
||||||
|
mxL += mxL2;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Smooth minimum distance to signal limit divided by smooth max.
|
||||||
|
const float bdval = bool(CAS_BETTER_DIAGONALS) ? 2.0 : 1.0;
|
||||||
|
#if (CAS_GO_SLOWER == 1)
|
||||||
|
float ampL = clamp(min(mnL, bdval - mxL) / mxL, 0.0, 1.0);
|
||||||
|
#else
|
||||||
|
float ampL = clamp(min(mnL, bdval - mxL) * APrxLoRcpF1(mxL), 0.0, 1.0);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Shaping amount of sharpening.
|
||||||
|
#if (CAS_GO_SLOWER == 1)
|
||||||
|
ampL = sqrt(ampL);
|
||||||
|
#else
|
||||||
|
ampL = APrxLoSqrtF1(ampL);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Filter shape.
|
||||||
|
// 0 w 0
|
||||||
|
// w 1 w
|
||||||
|
// 0 w 0
|
||||||
|
|
||||||
|
const float peak = -(mix(8.0, 5.0, clamp(SHARPENING, 0.0, 1.0)));
|
||||||
|
float wL = ampL / peak;
|
||||||
|
|
||||||
|
// Filter.
|
||||||
|
// Using green coef only
|
||||||
|
float Weight = 1.0 + 4.0 * wL;
|
||||||
|
vec4 pix = vec4(0.0, 0.0, 0.0, 1.0);
|
||||||
|
pix.r = ((b + d + f + h) * wL) + e;
|
||||||
|
#if (CAS_GO_SLOWER == 1)
|
||||||
|
pix.r /= Weight;
|
||||||
|
#else
|
||||||
|
pix.r *= APrxMedRcpF1(Weight);
|
||||||
|
#endif
|
||||||
|
pix.r = clamp(pix.r, 0.0, 1.0);
|
||||||
|
|
||||||
|
#if (TARGET_TRC == 1)
|
||||||
|
pix.r = To709(pix.r);
|
||||||
|
#elif (TARGET_TRC == 2)
|
||||||
|
pix.r = ToPq(pix.r);
|
||||||
|
#elif (TARGET_TRC == 3)
|
||||||
|
pix.r = ToSrgb(pix.r);
|
||||||
|
#elif (TARGET_TRC == 4)
|
||||||
|
pix.r = pow(pix.r, float(1.0 / 2.4));
|
||||||
|
#elif (TARGET_TRC == 5)
|
||||||
|
pix.r = ToHlg(pix.r);
|
||||||
|
#elif (TARGET_TRC == 6)
|
||||||
|
pix.r = pow(pix.r, float(1.0 / CUSTOM_GAMMA));
|
||||||
|
#endif
|
||||||
|
|
||||||
|
return pix;
|
||||||
|
}
|
||||||
272
src-tauri/shaders/CAS.glsl
Normal file
|
|
@ -0,0 +1,272 @@
|
||||||
|
// Kaleido: native-resolution sharpening (unchanged WHEN), SHARPENING 0.25.
|
||||||
|
|
||||||
|
// LICENSE
|
||||||
|
// =======
|
||||||
|
// Copyright (c) 2017-2019 Advanced Micro Devices, Inc. All rights reserved.
|
||||||
|
// -------
|
||||||
|
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
|
||||||
|
// files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
|
||||||
|
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
|
||||||
|
// Software is furnished to do so, subject to the following conditions:
|
||||||
|
// -------
|
||||||
|
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
|
||||||
|
// Software.
|
||||||
|
// -------
|
||||||
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
||||||
|
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||||
|
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||||
|
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
|
// FidelityFX CAS by AMD
|
||||||
|
// ported to mpv by agyild
|
||||||
|
|
||||||
|
// Changelog
|
||||||
|
// Optimized texture lookups for OpenGL 4.0+, DirectX 10+, and OpenGL ES 3.1+ (9 -> 4).
|
||||||
|
// Changed rcp + mul operations to div for better clarity when CAS_GO_SLOWER is set to 1, since the compiler should automatically
|
||||||
|
// optimize those instructions anyway.
|
||||||
|
// Made it directly operate on LUMA plane, since the original shader was operating on LUMA by deriving it from RGB. This should
|
||||||
|
// cause a major increase in performance, especially on OpenGL 4.0+ renderers (4 texture lookups vs. 9)
|
||||||
|
// Removed transparency preservation mechanism since the alpha channel is a separate source plan than LUMA
|
||||||
|
// Added custom gamma curve support for relinearization
|
||||||
|
// Removed final blending between the original and the sharpened pixels since it was redundant
|
||||||
|
//
|
||||||
|
// Notes
|
||||||
|
// The filter is designed to run in linear light, and does have an optional relinerization and delinearization pass which
|
||||||
|
// assumes BT.1886 content by default. Do not forget to change SOURCE_TRC and TARGET_TRC variables depending
|
||||||
|
// on what kind of content the filter is running on. You might want to create seperate versions of the file with different
|
||||||
|
// colorspace values, and apply them via autoprofiles. Note that running in non-linear light will result in oversharpening.
|
||||||
|
//
|
||||||
|
// By default the shader only runs on non-scaled content since it is designed for use without scaling, if the content is
|
||||||
|
// scaled you should probably use CAS-scaled.glsl instead. However this behavior can be overriden by changing the WHEN
|
||||||
|
// directives with "OUTPUT.w OUTPUT.h * LUMA.w LUMA.h * / 1.0 < !" which allows it to be used as a pre-upscale sharpener.
|
||||||
|
|
||||||
|
//!HOOK LUMA
|
||||||
|
//!BIND HOOKED
|
||||||
|
//!DESC FidelityFX Sharpening (Relinearization)
|
||||||
|
//!WHEN OUTPUT.w OUTPUT.h * LUMA.w LUMA.h * / 1.0 > ! OUTPUT.w OUTPUT.h * LUMA.w LUMA.h * / 1.0 < ! *
|
||||||
|
|
||||||
|
// User variables - Relinearization
|
||||||
|
// Compatibility
|
||||||
|
#define SOURCE_TRC 4 // Is needed to convert from source colorspace to linear light. 0 = None (Skip conversion), 1 = Rec709, 2 = PQ, 3 = sRGB, 4 = BT.1886, 5 = HLG, 6 = Custom
|
||||||
|
#define CUSTOM_GAMMA 2.2 // Custom power gamma curve to use if and when SOURCE_TRC is 6.
|
||||||
|
|
||||||
|
// Shader code
|
||||||
|
|
||||||
|
float From709(float rec709) {
|
||||||
|
return max(min(rec709 / float(4.5), float(0.081)), pow((rec709 + float(0.099)) / float(1.099), float(1.0 / 0.45)));
|
||||||
|
}
|
||||||
|
|
||||||
|
float FromPq(float pq) {
|
||||||
|
float p = pow(pq, float(0.0126833));
|
||||||
|
return (pow(clamp(p - float(0.835938), 0.0, 1.0) / (float(18.8516) - float(18.6875) * p), float(6.27739)));
|
||||||
|
}
|
||||||
|
|
||||||
|
float FromSrgb(float srgb) {
|
||||||
|
return max(min(srgb / 12.92, float(0.04045)), pow((srgb + float(0.055)) / float(1.055), float(2.4)));
|
||||||
|
}
|
||||||
|
|
||||||
|
float FromHlg(float hlg) {
|
||||||
|
const float a = 0.17883277;
|
||||||
|
const float b = 0.28466892;
|
||||||
|
const float c = 0.55991073;
|
||||||
|
|
||||||
|
float linear;
|
||||||
|
if (hlg >= 0.0 && hlg <= 0.5) {
|
||||||
|
linear = pow(hlg, 2.0) / 3.0;
|
||||||
|
} else {
|
||||||
|
linear = (exp((hlg - c) / a) + b) / 12.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return linear;
|
||||||
|
}
|
||||||
|
|
||||||
|
vec4 hook() {
|
||||||
|
vec4 col = HOOKED_tex(HOOKED_pos);
|
||||||
|
col.r = clamp(col.r, 0.0, 1.0);
|
||||||
|
#if (SOURCE_TRC == 1)
|
||||||
|
col.r = From709(col.r);
|
||||||
|
#elif (SOURCE_TRC == 2)
|
||||||
|
col.r = FromPq(col.r);
|
||||||
|
#elif (SOURCE_TRC == 3)
|
||||||
|
col.r = FromSrgb(col.r);
|
||||||
|
#elif (SOURCE_TRC == 4)
|
||||||
|
col.r = pow(col.r, float(2.4));
|
||||||
|
#elif (SOURCE_TRC == 5)
|
||||||
|
col.r = FromHlg(col.r);
|
||||||
|
#elif (SOURCE_TRC == 6)
|
||||||
|
col.r = pow(col.r, float(CUSTOM_GAMMA));
|
||||||
|
#endif
|
||||||
|
return col;
|
||||||
|
}
|
||||||
|
|
||||||
|
//!HOOK LUMA
|
||||||
|
//!BIND HOOKED
|
||||||
|
//!DESC FidelityFX Sharpening
|
||||||
|
//!WHEN OUTPUT.w OUTPUT.h * LUMA.w LUMA.h * / 1.0 > ! OUTPUT.w OUTPUT.h * LUMA.w LUMA.h * / 1.0 < ! *
|
||||||
|
|
||||||
|
// User variables
|
||||||
|
// Intensity
|
||||||
|
#define SHARPENING 0.25 // Adjusts the range the shader adapts to high contrast (0 is not all the way off). Higher values = more high contrast sharpening. 0.0 to 1.0.
|
||||||
|
|
||||||
|
// Performance
|
||||||
|
#define CAS_BETTER_DIAGONALS 1 // If set to 0, drops certain math and texture lookup operations for better performance. 0 or 1.
|
||||||
|
#define CAS_GO_SLOWER 0 // If set to 1, disables the use of optimized approximate transcendental functions which might slightly increase accuracy in exchange of performance. 0 or 1.
|
||||||
|
|
||||||
|
// Compatibility
|
||||||
|
#define TARGET_TRC 4 // Is needed to convert from source colorspace to target colorspace. 0 = None (Skip conversion), 1 = Rec709, 2 = PQ, 3 = sRGB, 4 = BT.1886, 5 = HLG, 6 = Custom
|
||||||
|
#define CUSTOM_GAMMA 2.2 // Custom power gamma curve to use if and when TARGET_TRC is 6.
|
||||||
|
|
||||||
|
// Shader code
|
||||||
|
|
||||||
|
float To709(float linear) {
|
||||||
|
return max(min(linear * float(4.5), float(0.018)), float(1.099) * pow(linear, float(0.45)) - float(0.099));
|
||||||
|
}
|
||||||
|
|
||||||
|
float ToPq(float linear) {
|
||||||
|
float p = pow(linear, float(0.159302));
|
||||||
|
return pow((float(0.835938) + float(18.8516) * p) / (float(1.0) + float(18.6875) * p), float(78.8438));
|
||||||
|
}
|
||||||
|
|
||||||
|
float ToSrgb(float linear) {
|
||||||
|
return max(min(linear * float(12.92), float(0.0031308)), float(1.055) * pow(linear, float(0.41666)) - float(0.055));
|
||||||
|
}
|
||||||
|
|
||||||
|
float ToHlg(float linear) {
|
||||||
|
const float a = 0.17883277;
|
||||||
|
const float b = 0.28466892;
|
||||||
|
const float c = 0.55991073;
|
||||||
|
|
||||||
|
float hlg;
|
||||||
|
if (linear <= 1.0 / 12.0) {
|
||||||
|
hlg = sqrt(3.0 * linear);
|
||||||
|
} else {
|
||||||
|
hlg = a * log(12.0 * linear - b) + c;
|
||||||
|
}
|
||||||
|
|
||||||
|
return hlg;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if (CAS_GO_SLOWER == 0)
|
||||||
|
|
||||||
|
float APrxLoSqrtF1(float a) {
|
||||||
|
return uintBitsToFloat((floatBitsToUint(a) >> uint(1)) + uint(0x1fbc4639));
|
||||||
|
}
|
||||||
|
|
||||||
|
float APrxLoRcpF1(float a) {
|
||||||
|
return uintBitsToFloat(uint(0x7ef07ebb) - floatBitsToUint(a));
|
||||||
|
}
|
||||||
|
|
||||||
|
float APrxMedRcpF1(float a) {
|
||||||
|
float b = uintBitsToFloat(uint(0x7ef19fff) - floatBitsToUint(a));
|
||||||
|
return b * (-b * a + float(2.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
vec4 hook()
|
||||||
|
{
|
||||||
|
// fetch a 3x3 neighborhood around the pixel 'e',
|
||||||
|
// a b c
|
||||||
|
// d(e)f
|
||||||
|
// g h i
|
||||||
|
|
||||||
|
#if (defined(HOOKED_gather) && (__VERSION__ >= 400 || (GL_ES && __VERSION__ >= 310)))
|
||||||
|
vec4 efhi = HOOKED_gather(vec2(HOOKED_pos + vec2(0.5) * HOOKED_pt), 0);
|
||||||
|
|
||||||
|
float e = efhi.w;
|
||||||
|
float f = efhi.z;
|
||||||
|
float h = efhi.x;
|
||||||
|
|
||||||
|
vec3 abd = HOOKED_gather(vec2(HOOKED_pos - vec2(0.5) * HOOKED_pt), 0).wzx;
|
||||||
|
float b = abd.y;
|
||||||
|
float d = abd.z;
|
||||||
|
|
||||||
|
#if (CAS_BETTER_DIAGONALS == 1)
|
||||||
|
float a = abd.x;
|
||||||
|
float i = efhi.y;
|
||||||
|
#endif
|
||||||
|
#else
|
||||||
|
float e = HOOKED_tex(HOOKED_pos).r;
|
||||||
|
float f = HOOKED_texOff(vec2(1.0, 0.0)).r;
|
||||||
|
float h = HOOKED_texOff(vec2(0.0, 1.0)).r;
|
||||||
|
|
||||||
|
#if (CAS_BETTER_DIAGONALS == 1)
|
||||||
|
float a = HOOKED_texOff(vec2(-1.0, -1.0)).r;
|
||||||
|
float i = HOOKED_texOff(vec2(1.0, 1.0)).r;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
float b = HOOKED_texOff(vec2( 0.0, -1.0)).r;
|
||||||
|
float d = HOOKED_texOff(vec2(-1.0, 0.0)).r;
|
||||||
|
#endif
|
||||||
|
#if (CAS_BETTER_DIAGONALS == 1)
|
||||||
|
float c = HOOKED_texOff(vec2( 1.0, -1.0)).r;
|
||||||
|
float g = HOOKED_texOff(vec2(-1.0, 1.0)).r;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Soft min and max.
|
||||||
|
// a b c b
|
||||||
|
// d e f * 0.5 + d e f * 0.5
|
||||||
|
// g h i h
|
||||||
|
// These are 2.0x bigger (factored out the extra multiply).
|
||||||
|
|
||||||
|
float mnL = min(min(min(d, e), min(f, b)), h);
|
||||||
|
float mxL = max(max(max(d, e), max(f, b)), h);
|
||||||
|
#if (CAS_BETTER_DIAGONALS == 1)
|
||||||
|
float mnL2 = min(mnL, min(min(a, c), min(g, i)));
|
||||||
|
mnL += mnL2;
|
||||||
|
|
||||||
|
float mxL2 = max(mxL, max(max(a, c), max(g, i)));
|
||||||
|
mxL += mxL2;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Smooth minimum distance to signal limit divided by smooth max.
|
||||||
|
const float bdval = bool(CAS_BETTER_DIAGONALS) ? 2.0 : 1.0;
|
||||||
|
#if (CAS_GO_SLOWER == 1)
|
||||||
|
float ampL = clamp(min(mnL, bdval - mxL) / mxL, 0.0, 1.0);
|
||||||
|
#else
|
||||||
|
float ampL = clamp(min(mnL, bdval - mxL) * APrxLoRcpF1(mxL), 0.0, 1.0);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Shaping amount of sharpening.
|
||||||
|
#if (CAS_GO_SLOWER == 1)
|
||||||
|
ampL = sqrt(ampL);
|
||||||
|
#else
|
||||||
|
ampL = APrxLoSqrtF1(ampL);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Filter shape.
|
||||||
|
// 0 w 0
|
||||||
|
// w 1 w
|
||||||
|
// 0 w 0
|
||||||
|
|
||||||
|
const float peak = -(mix(8.0, 5.0, clamp(SHARPENING, 0.0, 1.0)));
|
||||||
|
float wL = ampL / peak;
|
||||||
|
|
||||||
|
// Filter.
|
||||||
|
// Using green coef only
|
||||||
|
float Weight = 1.0 + 4.0 * wL;
|
||||||
|
vec4 pix = vec4(0.0, 0.0, 0.0, 1.0);
|
||||||
|
pix.r = ((b + d + f + h) * wL) + e;
|
||||||
|
#if (CAS_GO_SLOWER == 1)
|
||||||
|
pix.r /= Weight;
|
||||||
|
#else
|
||||||
|
pix.r *= APrxMedRcpF1(Weight);
|
||||||
|
#endif
|
||||||
|
pix.r = clamp(pix.r, 0.0, 1.0);
|
||||||
|
|
||||||
|
#if (TARGET_TRC == 1)
|
||||||
|
pix.r = To709(pix.r);
|
||||||
|
#elif (TARGET_TRC == 2)
|
||||||
|
pix.r = ToPq(pix.r);
|
||||||
|
#elif (TARGET_TRC == 3)
|
||||||
|
pix.r = ToSrgb(pix.r);
|
||||||
|
#elif (TARGET_TRC == 4)
|
||||||
|
pix.r = pow(pix.r, float(1.0 / 2.4));
|
||||||
|
#elif (TARGET_TRC == 5)
|
||||||
|
pix.r = ToHlg(pix.r);
|
||||||
|
#elif (TARGET_TRC == 6)
|
||||||
|
pix.r = pow(pix.r, float(1.0 / CUSTOM_GAMMA));
|
||||||
|
#endif
|
||||||
|
|
||||||
|
return pix;
|
||||||
|
}
|
||||||
1151
src-tauri/shaders/FSRCNNX_x2_16-0-4-1.glsl
Normal file
213
src-tauri/shaders/KrigBilateral.glsl
Normal file
|
|
@ -0,0 +1,213 @@
|
||||||
|
// KrigBilateral by Shiandow
|
||||||
|
//
|
||||||
|
// This library is free software; you can redistribute it and/or
|
||||||
|
// modify it under the terms of the GNU Lesser General Public
|
||||||
|
// License as published by the Free Software Foundation; either
|
||||||
|
// version 3.0 of the License, or (at your option) any later version.
|
||||||
|
//
|
||||||
|
// This library is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||||
|
// Lesser General Public License for more details.
|
||||||
|
//
|
||||||
|
// You should have received a copy of the GNU Lesser General Public
|
||||||
|
// License along with this library.
|
||||||
|
|
||||||
|
//!HOOK CHROMA
|
||||||
|
//!BIND LUMA
|
||||||
|
//!BIND HOOKED
|
||||||
|
//!SAVE LOWRES_Y
|
||||||
|
//!WIDTH LUMA.w
|
||||||
|
//!WHEN CHROMA.w LUMA.w <
|
||||||
|
//!DESC KrigBilateral Downscaling Y pass 1
|
||||||
|
|
||||||
|
#define offset vec2(0)
|
||||||
|
|
||||||
|
#define axis 1
|
||||||
|
|
||||||
|
#define Kernel(x) dot(vec3(0.42659, -0.49656, 0.076849), cos(vec3(0, 1, 2) * acos(-1.) * (x + 1.)))
|
||||||
|
|
||||||
|
vec4 hook() {
|
||||||
|
// Calculate bounds
|
||||||
|
float low = ceil((LUMA_pos - CHROMA_pt) * LUMA_size - offset - 0.5)[axis];
|
||||||
|
float high = floor((LUMA_pos + CHROMA_pt) * LUMA_size - offset - 0.5)[axis];
|
||||||
|
|
||||||
|
float W = 0.0;
|
||||||
|
vec4 avg = vec4(0);
|
||||||
|
vec2 pos = LUMA_pos;
|
||||||
|
|
||||||
|
for (float k = low; k <= high; k++) {
|
||||||
|
pos[axis] = LUMA_pt[axis] * (k - offset[axis] + 0.5);
|
||||||
|
float rel = (pos[axis] - LUMA_pos[axis])*CHROMA_size[axis];
|
||||||
|
float w = Kernel(rel);
|
||||||
|
|
||||||
|
vec4 y = textureGrad(LUMA_raw, pos, vec2(0.0), vec2(0.0)).xxxx * LUMA_mul;
|
||||||
|
y.y *= y.y;
|
||||||
|
avg += w * y;
|
||||||
|
W += w;
|
||||||
|
}
|
||||||
|
avg /= W;
|
||||||
|
avg.y = abs(avg.y - avg.x * avg.x);
|
||||||
|
return avg;
|
||||||
|
}
|
||||||
|
|
||||||
|
//!HOOK CHROMA
|
||||||
|
//!BIND LOWRES_Y
|
||||||
|
//!BIND HOOKED
|
||||||
|
//!SAVE LOWRES_Y
|
||||||
|
//!WHEN CHROMA.w LUMA.w <
|
||||||
|
//!DESC KrigBilateral Downscaling Y pass 2
|
||||||
|
|
||||||
|
#define offset vec2(0)
|
||||||
|
|
||||||
|
#define axis 0
|
||||||
|
|
||||||
|
#define Kernel(x) dot(vec3(0.42659, -0.49656, 0.076849), cos(vec3(0, 1, 2) * acos(-1.) * (x + 1.)))
|
||||||
|
|
||||||
|
vec4 hook() {
|
||||||
|
// Calculate bounds
|
||||||
|
float low = ceil((LOWRES_Y_pos - CHROMA_pt) * LOWRES_Y_size - offset - 0.5)[axis];
|
||||||
|
float high = floor((LOWRES_Y_pos + CHROMA_pt) * LOWRES_Y_size - offset - 0.5)[axis];
|
||||||
|
|
||||||
|
float W = 0.0;
|
||||||
|
vec4 avg = vec4(0);
|
||||||
|
vec2 pos = LOWRES_Y_pos;
|
||||||
|
|
||||||
|
for (float k = low; k <= high; k++) {
|
||||||
|
pos[axis] = LOWRES_Y_pt[axis] * (k - offset[axis] + 0.5);
|
||||||
|
float rel = (pos[axis] - LOWRES_Y_pos[axis])*CHROMA_size[axis];
|
||||||
|
float w = Kernel(rel);
|
||||||
|
|
||||||
|
vec4 y = textureGrad(LOWRES_Y_raw, pos, vec2(0.0), vec2(0.0)).xxxx * LOWRES_Y_mul;
|
||||||
|
y.y *= y.y;
|
||||||
|
avg += w * y;
|
||||||
|
W += w;
|
||||||
|
}
|
||||||
|
avg /= W;
|
||||||
|
avg.y = abs(avg.y - avg.x * avg.x) + LOWRES_Y_texOff(0).y;
|
||||||
|
return avg;
|
||||||
|
}
|
||||||
|
|
||||||
|
//!HOOK CHROMA
|
||||||
|
//!BIND HOOKED
|
||||||
|
//!BIND LUMA
|
||||||
|
//!BIND LOWRES_Y
|
||||||
|
//!WIDTH LUMA.w
|
||||||
|
//!HEIGHT LUMA.h
|
||||||
|
//!WHEN CHROMA.w LUMA.w <
|
||||||
|
//!OFFSET ALIGN
|
||||||
|
//!DESC KrigBilateral Upscaling UV
|
||||||
|
|
||||||
|
#define sigma_nsq 256.0/(255.0*255.0)
|
||||||
|
#define N 8
|
||||||
|
#define sqr(x) dot(x,x)
|
||||||
|
|
||||||
|
#define M(i,j) Mx[min(i,j)*N + max(i,j) - (min(i,j)*(min(i,j)+1))/2]
|
||||||
|
|
||||||
|
#define C(i,j) (inversesqrt(1.0 + (X[i].y + X[j].y) / Var) * exp(-0.5 * (sqr(X[i].x - X[j].x) / (localVar + X[i].y + X[j].y) + sqr((coords[i] - coords[j]) / radius))) /*+ (X[i].x - y) * (X[j].x - y) / Var*/) // commented out part works well only on test patterns
|
||||||
|
#define c(i) (inversesqrt(1.0 + X[i].y / Var) * exp(-0.5 * (sqr(X[i].x - y) / (localVar + X[i].y) + sqr((coords[i] - offset) / radius))))
|
||||||
|
|
||||||
|
#define getnsum(i) X[i] = vec4(LOWRES_Y_tex(LOWRES_Y_pt*(pos+coords[i]+vec2(0.5))).xy, \
|
||||||
|
CHROMA_tex(CHROMA_pt*(pos+coords[i]+vec2(0.5))).xy); \
|
||||||
|
w = clamp(1.5 - abs(coords[i]), 0.0, 1.0); \
|
||||||
|
total += w.x*w.y*vec4(X[i].x, X[i].x * X[i].x, X[i].y, 1.0);
|
||||||
|
|
||||||
|
#define I3(f, n) f(n) f(n+1) f(n+2)
|
||||||
|
#define I9(f, n) I3(f, n) I3(f, n+3) I3(f, n+6)
|
||||||
|
|
||||||
|
vec4 hook() {
|
||||||
|
vec2 pos = CHROMA_pos * HOOKED_size - vec2(0.5);
|
||||||
|
vec2 offset = pos - round(pos);
|
||||||
|
pos -= offset;
|
||||||
|
|
||||||
|
vec2 coords[N+1];
|
||||||
|
vec4 X[N+1];
|
||||||
|
vec2 w;
|
||||||
|
vec4 total = vec4(0);
|
||||||
|
|
||||||
|
coords[0] = vec2(-1,-1); coords[1] = vec2(-1, 0); coords[2] = vec2(-1, 1);
|
||||||
|
coords[3] = vec2( 0,-1); coords[4] = vec2( 0, 1); coords[5] = vec2( 1,-1);
|
||||||
|
coords[6] = vec2( 1, 0); coords[7] = vec2( 1, 1); coords[8] = vec2( 0, 0);
|
||||||
|
|
||||||
|
I9(getnsum, 0)
|
||||||
|
|
||||||
|
total.xyz /= total.w;
|
||||||
|
float localVar = abs(total.y - total.x * total.x) + sigma_nsq;
|
||||||
|
float Var = localVar + total.z;
|
||||||
|
float radius = 1.5; // mix(1.5, 1.0, sigma_nsq / Var);
|
||||||
|
|
||||||
|
float y = LUMA_texOff(0).x;
|
||||||
|
float Mx[(N*(N+1))/2];
|
||||||
|
float b[N];
|
||||||
|
vec2 interp = X[N].zw;
|
||||||
|
|
||||||
|
b[0] = c(0) - c(N) - C(0,N) + C(N,N); M(0, 0) = C(0,0) - C(0,N) - C(0,N) + C(N,N); M(0, 1) = C(0,1) - C(1,N) - C(0,N) + C(N,N); M(0, 2) = C(0,2) - C(2,N) - C(0,N) + C(N,N); M(0, 3) = C(0,3) - C(3,N) - C(0,N) + C(N,N); M(0, 4) = C(0,4) - C(4,N) - C(0,N) + C(N,N); M(0, 5) = C(0,5) - C(5,N) - C(0,N) + C(N,N); M(0, 6) = C(0,6) - C(6,N) - C(0,N) + C(N,N); M(0, 7) = C(0,7) - C(7,N) - C(0,N) + C(N,N);
|
||||||
|
b[1] = c(1) - c(N) - C(1,N) + C(N,N); M(1, 1) = C(1,1) - C(1,N) - C(1,N) + C(N,N); M(1, 2) = C(1,2) - C(2,N) - C(1,N) + C(N,N); M(1, 3) = C(1,3) - C(3,N) - C(1,N) + C(N,N); M(1, 4) = C(1,4) - C(4,N) - C(1,N) + C(N,N); M(1, 5) = C(1,5) - C(5,N) - C(1,N) + C(N,N); M(1, 6) = C(1,6) - C(6,N) - C(1,N) + C(N,N); M(1, 7) = C(1,7) - C(7,N) - C(1,N) + C(N,N);
|
||||||
|
b[2] = c(2) - c(N) - C(2,N) + C(N,N); M(2, 2) = C(2,2) - C(2,N) - C(2,N) + C(N,N); M(2, 3) = C(2,3) - C(3,N) - C(2,N) + C(N,N); M(2, 4) = C(2,4) - C(4,N) - C(2,N) + C(N,N); M(2, 5) = C(2,5) - C(5,N) - C(2,N) + C(N,N); M(2, 6) = C(2,6) - C(6,N) - C(2,N) + C(N,N); M(2, 7) = C(2,7) - C(7,N) - C(2,N) + C(N,N);
|
||||||
|
b[3] = c(3) - c(N) - C(3,N) + C(N,N); M(3, 3) = C(3,3) - C(3,N) - C(3,N) + C(N,N); M(3, 4) = C(3,4) - C(4,N) - C(3,N) + C(N,N); M(3, 5) = C(3,5) - C(5,N) - C(3,N) + C(N,N); M(3, 6) = C(3,6) - C(6,N) - C(3,N) + C(N,N); M(3, 7) = C(3,7) - C(7,N) - C(3,N) + C(N,N);
|
||||||
|
b[4] = c(4) - c(N) - C(4,N) + C(N,N); M(4, 4) = C(4,4) - C(4,N) - C(4,N) + C(N,N); M(4, 5) = C(4,5) - C(5,N) - C(4,N) + C(N,N); M(4, 6) = C(4,6) - C(6,N) - C(4,N) + C(N,N); M(4, 7) = C(4,7) - C(7,N) - C(4,N) + C(N,N);
|
||||||
|
b[5] = c(5) - c(N) - C(5,N) + C(N,N); M(5, 5) = C(5,5) - C(5,N) - C(5,N) + C(N,N); M(5, 6) = C(5,6) - C(6,N) - C(5,N) + C(N,N); M(5, 7) = C(5,7) - C(7,N) - C(5,N) + C(N,N);
|
||||||
|
b[6] = c(6) - c(N) - C(6,N) + C(N,N); M(6, 6) = C(6,6) - C(6,N) - C(6,N) + C(N,N); M(6, 7) = C(6,7) - C(7,N) - C(6,N) + C(N,N);
|
||||||
|
b[7] = c(7) - c(N) - C(7,N) + C(N,N); M(7, 7) = C(7,7) - C(7,N) - C(7,N) + C(N,N);
|
||||||
|
|
||||||
|
b[1] -= b[0] * M(0, 1) / M(0, 0); M(1, 1) -= M(0, 1) * M(0, 1) / M(0, 0); M(1, 2) -= M(0, 2) * M(0, 1) / M(0, 0); M(1, 3) -= M(0, 3) * M(0, 1) / M(0, 0); M(1, 4) -= M(0, 4) * M(0, 1) / M(0, 0); M(1, 5) -= M(0, 5) * M(0, 1) / M(0, 0); M(1, 6) -= M(0, 6) * M(0, 1) / M(0, 0); M(1, 7) -= M(0, 7) * M(0, 1) / M(0, 0);
|
||||||
|
b[2] -= b[0] * M(0, 2) / M(0, 0); M(2, 2) -= M(0, 2) * M(0, 2) / M(0, 0); M(2, 3) -= M(0, 3) * M(0, 2) / M(0, 0); M(2, 4) -= M(0, 4) * M(0, 2) / M(0, 0); M(2, 5) -= M(0, 5) * M(0, 2) / M(0, 0); M(2, 6) -= M(0, 6) * M(0, 2) / M(0, 0); M(2, 7) -= M(0, 7) * M(0, 2) / M(0, 0);
|
||||||
|
b[3] -= b[0] * M(0, 3) / M(0, 0); M(3, 3) -= M(0, 3) * M(0, 3) / M(0, 0); M(3, 4) -= M(0, 4) * M(0, 3) / M(0, 0); M(3, 5) -= M(0, 5) * M(0, 3) / M(0, 0); M(3, 6) -= M(0, 6) * M(0, 3) / M(0, 0); M(3, 7) -= M(0, 7) * M(0, 3) / M(0, 0);
|
||||||
|
b[4] -= b[0] * M(0, 4) / M(0, 0); M(4, 4) -= M(0, 4) * M(0, 4) / M(0, 0); M(4, 5) -= M(0, 5) * M(0, 4) / M(0, 0); M(4, 6) -= M(0, 6) * M(0, 4) / M(0, 0); M(4, 7) -= M(0, 7) * M(0, 4) / M(0, 0);
|
||||||
|
b[5] -= b[0] * M(0, 5) / M(0, 0); M(5, 5) -= M(0, 5) * M(0, 5) / M(0, 0); M(5, 6) -= M(0, 6) * M(0, 5) / M(0, 0); M(5, 7) -= M(0, 7) * M(0, 5) / M(0, 0);
|
||||||
|
b[6] -= b[0] * M(0, 6) / M(0, 0); M(6, 6) -= M(0, 6) * M(0, 6) / M(0, 0); M(6, 7) -= M(0, 7) * M(0, 6) / M(0, 0);
|
||||||
|
b[7] -= b[0] * M(0, 7) / M(0, 0); M(7, 7) -= M(0, 7) * M(0, 7) / M(0, 0);
|
||||||
|
|
||||||
|
b[2] -= b[1] * M(1, 2) / M(1, 1); M(2, 2) -= M(1, 2) * M(1, 2) / M(1, 1); M(2, 3) -= M(1, 3) * M(1, 2) / M(1, 1); M(2, 4) -= M(1, 4) * M(1, 2) / M(1, 1); M(2, 5) -= M(1, 5) * M(1, 2) / M(1, 1); M(2, 6) -= M(1, 6) * M(1, 2) / M(1, 1); M(2, 7) -= M(1, 7) * M(1, 2) / M(1, 1);
|
||||||
|
b[3] -= b[1] * M(1, 3) / M(1, 1); M(3, 3) -= M(1, 3) * M(1, 3) / M(1, 1); M(3, 4) -= M(1, 4) * M(1, 3) / M(1, 1); M(3, 5) -= M(1, 5) * M(1, 3) / M(1, 1); M(3, 6) -= M(1, 6) * M(1, 3) / M(1, 1); M(3, 7) -= M(1, 7) * M(1, 3) / M(1, 1);
|
||||||
|
b[4] -= b[1] * M(1, 4) / M(1, 1); M(4, 4) -= M(1, 4) * M(1, 4) / M(1, 1); M(4, 5) -= M(1, 5) * M(1, 4) / M(1, 1); M(4, 6) -= M(1, 6) * M(1, 4) / M(1, 1); M(4, 7) -= M(1, 7) * M(1, 4) / M(1, 1);
|
||||||
|
b[5] -= b[1] * M(1, 5) / M(1, 1); M(5, 5) -= M(1, 5) * M(1, 5) / M(1, 1); M(5, 6) -= M(1, 6) * M(1, 5) / M(1, 1); M(5, 7) -= M(1, 7) * M(1, 5) / M(1, 1);
|
||||||
|
b[6] -= b[1] * M(1, 6) / M(1, 1); M(6, 6) -= M(1, 6) * M(1, 6) / M(1, 1); M(6, 7) -= M(1, 7) * M(1, 6) / M(1, 1);
|
||||||
|
b[7] -= b[1] * M(1, 7) / M(1, 1); M(7, 7) -= M(1, 7) * M(1, 7) / M(1, 1);
|
||||||
|
|
||||||
|
b[3] -= b[2] * M(2, 3) / M(2, 2); M(3, 3) -= M(2, 3) * M(2, 3) / M(2, 2); M(3, 4) -= M(2, 4) * M(2, 3) / M(2, 2); M(3, 5) -= M(2, 5) * M(2, 3) / M(2, 2); M(3, 6) -= M(2, 6) * M(2, 3) / M(2, 2); M(3, 7) -= M(2, 7) * M(2, 3) / M(2, 2);
|
||||||
|
b[4] -= b[2] * M(2, 4) / M(2, 2); M(4, 4) -= M(2, 4) * M(2, 4) / M(2, 2); M(4, 5) -= M(2, 5) * M(2, 4) / M(2, 2); M(4, 6) -= M(2, 6) * M(2, 4) / M(2, 2); M(4, 7) -= M(2, 7) * M(2, 4) / M(2, 2);
|
||||||
|
b[5] -= b[2] * M(2, 5) / M(2, 2); M(5, 5) -= M(2, 5) * M(2, 5) / M(2, 2); M(5, 6) -= M(2, 6) * M(2, 5) / M(2, 2); M(5, 7) -= M(2, 7) * M(2, 5) / M(2, 2);
|
||||||
|
b[6] -= b[2] * M(2, 6) / M(2, 2); M(6, 6) -= M(2, 6) * M(2, 6) / M(2, 2); M(6, 7) -= M(2, 7) * M(2, 6) / M(2, 2);
|
||||||
|
b[7] -= b[2] * M(2, 7) / M(2, 2); M(7, 7) -= M(2, 7) * M(2, 7) / M(2, 2);
|
||||||
|
|
||||||
|
b[4] -= b[3] * M(3, 4) / M(3, 3); M(4, 4) -= M(3, 4) * M(3, 4) / M(3, 3); M(4, 5) -= M(3, 5) * M(3, 4) / M(3, 3); M(4, 6) -= M(3, 6) * M(3, 4) / M(3, 3); M(4, 7) -= M(3, 7) * M(3, 4) / M(3, 3);
|
||||||
|
b[5] -= b[3] * M(3, 5) / M(3, 3); M(5, 5) -= M(3, 5) * M(3, 5) / M(3, 3); M(5, 6) -= M(3, 6) * M(3, 5) / M(3, 3); M(5, 7) -= M(3, 7) * M(3, 5) / M(3, 3);
|
||||||
|
b[6] -= b[3] * M(3, 6) / M(3, 3); M(6, 6) -= M(3, 6) * M(3, 6) / M(3, 3); M(6, 7) -= M(3, 7) * M(3, 6) / M(3, 3);
|
||||||
|
b[7] -= b[3] * M(3, 7) / M(3, 3); M(7, 7) -= M(3, 7) * M(3, 7) / M(3, 3);
|
||||||
|
|
||||||
|
b[5] -= b[4] * M(4, 5) / M(4, 4); M(5, 5) -= M(4, 5) * M(4, 5) / M(4, 4); M(5, 6) -= M(4, 6) * M(4, 5) / M(4, 4); M(5, 7) -= M(4, 7) * M(4, 5) / M(4, 4);
|
||||||
|
b[6] -= b[4] * M(4, 6) / M(4, 4); M(6, 6) -= M(4, 6) * M(4, 6) / M(4, 4); M(6, 7) -= M(4, 7) * M(4, 6) / M(4, 4);
|
||||||
|
b[7] -= b[4] * M(4, 7) / M(4, 4); M(7, 7) -= M(4, 7) * M(4, 7) / M(4, 4);
|
||||||
|
|
||||||
|
b[6] -= b[5] * M(5, 6) / M(5, 5); M(6, 6) -= M(5, 6) * M(5, 6) / M(5, 5); M(6, 7) -= M(5, 7) * M(5, 6) / M(5, 5);
|
||||||
|
b[7] -= b[5] * M(5, 7) / M(5, 5); M(7, 7) -= M(5, 7) * M(5, 7) / M(5, 5);
|
||||||
|
|
||||||
|
b[7] -= b[6] * M(6, 7) / M(6, 6); M(7, 7) -= M(6, 7) * M(6, 7) / M(6, 6);
|
||||||
|
|
||||||
|
b[7] /= M(7, 7);
|
||||||
|
interp += b[7] * (X[7] - X[N]).zw;
|
||||||
|
|
||||||
|
b[6] -= M(6, 7) * b[7]; b[6] /= M(6, 6);
|
||||||
|
interp += b[6] * (X[6] - X[N]).zw;
|
||||||
|
|
||||||
|
b[5] -= M(5, 6) * b[6]; b[5] -= M(5, 7) * b[7]; b[5] /= M(5, 5);
|
||||||
|
interp += b[5] * (X[5] - X[N]).zw;
|
||||||
|
|
||||||
|
b[4] -= M(4, 5) * b[5]; b[4] -= M(4, 6) * b[6]; b[4] -= M(4, 7) * b[7]; b[4] /= M(4, 4);
|
||||||
|
interp += b[4] * (X[4] - X[N]).zw;
|
||||||
|
|
||||||
|
b[3] -= M(3, 4) * b[4]; b[3] -= M(3, 5) * b[5]; b[3] -= M(3, 6) * b[6]; b[3] -= M(3, 7) * b[7]; b[3] /= M(3, 3);
|
||||||
|
interp += b[3] * (X[3] - X[N]).zw;
|
||||||
|
|
||||||
|
b[2] -= M(2, 3) * b[3]; b[2] -= M(2, 4) * b[4]; b[2] -= M(2, 5) * b[5]; b[2] -= M(2, 6) * b[6]; b[2] -= M(2, 7) * b[7]; b[2] /= M(2, 2);
|
||||||
|
interp += b[2] * (X[2] - X[N]).zw;
|
||||||
|
|
||||||
|
b[1] -= M(1, 2) * b[2]; b[1] -= M(1, 3) * b[3]; b[1] -= M(1, 4) * b[4]; b[1] -= M(1, 5) * b[5]; b[1] -= M(1, 6) * b[6]; b[1] -= M(1, 7) * b[7]; b[1] /= M(1, 1);
|
||||||
|
interp += b[1] * (X[1] - X[N]).zw;
|
||||||
|
|
||||||
|
b[0] -= M(0, 1) * b[1]; b[0] -= M(0, 2) * b[2]; b[0] -= M(0, 3) * b[3]; b[0] -= M(0, 4) * b[4]; b[0] -= M(0, 5) * b[5]; b[0] -= M(0, 6) * b[6]; b[0] -= M(0, 7) * b[7]; b[0] /= M(0, 0);
|
||||||
|
interp += b[0] * (X[0] - X[N]).zw;
|
||||||
|
|
||||||
|
return interp.xyxy;
|
||||||
|
}
|
||||||
2725
src-tauri/shaders/nlmeans_light.glsl
Normal file
158
src-tauri/src/diagnostics.rs
Normal file
|
|
@ -0,0 +1,158 @@
|
||||||
|
//! Diagnostics that stay on this computer, in the app's log folder
|
||||||
|
//! (`%LOCALAPPDATA%\tv.kaleido.desktop\logs` on Windows):
|
||||||
|
//!
|
||||||
|
//! - A watchdog: if the UI thread stops answering for `HANG_AFTER`, it writes
|
||||||
|
//! a dump of every thread's stack (`kaleido-hang-*.dmp`), once per stall.
|
||||||
|
//! - Crashes write a dump of the crashing thread and the rest
|
||||||
|
//! (`kaleido-crash-*.dmp`; Windows only), and panics are logged.
|
||||||
|
//! - `diagnostics.log` notes each of these with the time.
|
||||||
|
//!
|
||||||
|
//! Nothing is uploaded. Dumps need the release's `kaleido.pdb` to read; the
|
||||||
|
//! build script keeps one per version (docs/development.md → Diagnostics).
|
||||||
|
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use tauri::{AppHandle, Manager, Runtime};
|
||||||
|
|
||||||
|
/// How long the UI thread may go without answering before a hang dump.
|
||||||
|
const HANG_AFTER: Duration = Duration::from_secs(5);
|
||||||
|
/// Dumps kept of each kind; older ones are removed.
|
||||||
|
const KEEP_DUMPS: usize = 5;
|
||||||
|
|
||||||
|
static DIR: OnceLock<PathBuf> = OnceLock::new();
|
||||||
|
static ORIGIN: OnceLock<Instant> = OnceLock::new();
|
||||||
|
/// When the UI thread last answered, in ms since `ORIGIN`.
|
||||||
|
static BEAT: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
||||||
|
fn now_ms() -> u64 {
|
||||||
|
ORIGIN.get_or_init(Instant::now).elapsed().as_millis() as u64
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The folder for logs and dumps, once `start` has run.
|
||||||
|
pub fn dir() -> Option<&'static Path> {
|
||||||
|
DIR.get().map(PathBuf::as_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// UTC date and time, e.g. `2026-11-04 16:43:07` (file names use `-` for `:`).
|
||||||
|
fn timestamp() -> String {
|
||||||
|
let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||||
|
let (days, rem) = (secs / 86_400, secs % 86_400);
|
||||||
|
// Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
|
||||||
|
let z = days as i64 + 719_468;
|
||||||
|
let era = z.div_euclid(146_097);
|
||||||
|
let doe = z - era * 146_097;
|
||||||
|
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
|
||||||
|
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||||
|
let mp = (5 * doy + 2) / 153;
|
||||||
|
let day = doy - (153 * mp + 2) / 5 + 1;
|
||||||
|
let month = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||||
|
let year = yoe + era * 400 + i64::from(month <= 2);
|
||||||
|
format!("{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02}", rem / 3600, rem / 60 % 60, rem % 60)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends a line to `diagnostics.log`.
|
||||||
|
pub fn log(line: &str) {
|
||||||
|
let Some(dir) = dir() else { return };
|
||||||
|
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("diagnostics.log")) {
|
||||||
|
let _ = writeln!(f, "{} UTC {line}", timestamp());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new dump's path, after removing the oldest of its kind beyond `KEEP_DUMPS`.
|
||||||
|
pub fn dump_path(kind: &str) -> Option<PathBuf> {
|
||||||
|
let dir = dir()?;
|
||||||
|
let prefix = format!("kaleido-{kind}-");
|
||||||
|
if let Ok(entries) = std::fs::read_dir(dir) {
|
||||||
|
let mut old: Vec<PathBuf> = entries
|
||||||
|
.flatten()
|
||||||
|
.map(|e| e.path())
|
||||||
|
.filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(&prefix) && n.ends_with(".dmp")))
|
||||||
|
.collect();
|
||||||
|
old.sort();
|
||||||
|
while old.len() >= KEEP_DUMPS {
|
||||||
|
let _ = std::fs::remove_file(old.remove(0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let name = format!("{prefix}{}-v{}.dmp", timestamp().replace([' ', ':'], "-"), env!("CARGO_PKG_VERSION"));
|
||||||
|
Some(dir.join(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets up the log folder, crash and panic reporting, and the hang watchdog.
|
||||||
|
pub fn start<R: Runtime>(app: &AppHandle<R>) {
|
||||||
|
let Ok(dir) = app.path().app_log_dir() else { return };
|
||||||
|
if std::fs::create_dir_all(&dir).is_err() || DIR.set(dir).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
crate::platform::install_crash_handler();
|
||||||
|
|
||||||
|
let previous = std::panic::take_hook();
|
||||||
|
std::panic::set_hook(Box::new(move |info| {
|
||||||
|
let thread = std::thread::current();
|
||||||
|
log(&format!(
|
||||||
|
"panic on thread {}: {info}\n{}",
|
||||||
|
thread.name().unwrap_or("unnamed"),
|
||||||
|
std::backtrace::Backtrace::force_capture()
|
||||||
|
));
|
||||||
|
previous(info);
|
||||||
|
}));
|
||||||
|
|
||||||
|
let app = app.clone();
|
||||||
|
let _ = std::thread::Builder::new().name("ui-watchdog".into()).spawn(move || watchdog(app));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Development builds only: holds the UI thread for `seconds`, to test the watchdog.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn debug_freeze_ui<R: Runtime>(app: AppHandle<R>, seconds: u64) -> Result<(), String> {
|
||||||
|
if !cfg!(debug_assertions) {
|
||||||
|
return Err("Only available in development builds.".into());
|
||||||
|
}
|
||||||
|
app.run_on_main_thread(move || std::thread::sleep(Duration::from_secs(seconds.min(30)))).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Development builds only: crashes with an access violation, to test crash dumps.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn debug_crash() -> Result<(), String> {
|
||||||
|
if !cfg!(debug_assertions) {
|
||||||
|
return Err("Only available in development builds.".into());
|
||||||
|
}
|
||||||
|
let _ = std::thread::Builder::new().name("debug-crash".into()).spawn(|| unsafe {
|
||||||
|
std::ptr::null_mut::<u8>().write_volatile(1);
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asks the UI thread to note the time every second; if it hasn't for
|
||||||
|
/// `HANG_AFTER`, the UI thread is stuck: dump every thread's stack.
|
||||||
|
fn watchdog<R: Runtime>(app: AppHandle<R>) {
|
||||||
|
BEAT.store(now_ms(), Ordering::Relaxed);
|
||||||
|
let mut last_tick = now_ms();
|
||||||
|
let mut stalled_since: Option<u64> = None;
|
||||||
|
loop {
|
||||||
|
let _ = app.run_on_main_thread(|| BEAT.store(now_ms(), Ordering::Relaxed));
|
||||||
|
std::thread::sleep(Duration::from_secs(1));
|
||||||
|
let now = now_ms();
|
||||||
|
// This thread was itself held up (the computer slept): not a hang.
|
||||||
|
if now - last_tick > 3_000 {
|
||||||
|
BEAT.store(now, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
last_tick = now;
|
||||||
|
let silent = now.saturating_sub(BEAT.load(Ordering::Relaxed));
|
||||||
|
if silent >= HANG_AFTER.as_millis() as u64 {
|
||||||
|
if stalled_since.is_none() {
|
||||||
|
stalled_since = Some(now - silent);
|
||||||
|
let written = dump_path("hang").map(|p| (crate::platform::write_dump(&p), p));
|
||||||
|
match written {
|
||||||
|
Some((Ok(()), path)) => log(&format!("UI thread stopped answering for {}s; wrote {}", silent / 1000, path.display())),
|
||||||
|
Some((Err(e), _)) => log(&format!("UI thread stopped answering for {}s; no dump: {e}", silent / 1000)),
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if let Some(since) = stalled_since.take() {
|
||||||
|
log(&format!("UI thread answering again after {:.1}s", (now - since) as f64 / 1000.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -5,8 +5,9 @@
|
||||||
//! server-relative source path; resuming after a restart asks the interface for
|
//! server-relative source path; resuming after a restart asks the interface for
|
||||||
//! a freshly signed URL.
|
//! a freshly signed URL.
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
|
@ -47,10 +48,19 @@ pub struct Item {
|
||||||
pub speed: u64,
|
pub speed: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The transfer task that currently owns a download (and its `.part` file).
|
||||||
|
struct Worker {
|
||||||
|
generation: u64,
|
||||||
|
cancel: watch::Sender<bool>,
|
||||||
|
/// Closes once the task has exited and let go of the file.
|
||||||
|
done: watch::Receiver<()>,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct Downloads {
|
pub struct Downloads {
|
||||||
items: Mutex<Vec<Item>>,
|
items: Mutex<Vec<Item>>,
|
||||||
dir: Mutex<Option<PathBuf>>,
|
dir: Mutex<Option<PathBuf>>,
|
||||||
cancels: Mutex<HashMap<String, watch::Sender<bool>>>,
|
workers: Mutex<HashMap<String, Worker>>,
|
||||||
|
generation: AtomicU64,
|
||||||
permits: Arc<Semaphore>,
|
permits: Arc<Semaphore>,
|
||||||
client: reqwest::Client,
|
client: reqwest::Client,
|
||||||
}
|
}
|
||||||
|
|
@ -60,7 +70,8 @@ impl Default for Downloads {
|
||||||
Downloads {
|
Downloads {
|
||||||
items: Mutex::new(Vec::new()),
|
items: Mutex::new(Vec::new()),
|
||||||
dir: Mutex::new(None),
|
dir: Mutex::new(None),
|
||||||
cancels: Mutex::new(HashMap::new()),
|
workers: Mutex::new(HashMap::new()),
|
||||||
|
generation: AtomicU64::new(0),
|
||||||
permits: Arc::new(Semaphore::new(MAX_ACTIVE)),
|
permits: Arc::new(Semaphore::new(MAX_ACTIVE)),
|
||||||
client: reqwest::Client::builder()
|
client: reqwest::Client::builder()
|
||||||
.connect_timeout(Duration::from_secs(20))
|
.connect_timeout(Duration::from_secs(20))
|
||||||
|
|
@ -168,8 +179,11 @@ pub async fn download_start<R: Runtime>(app: AppHandle<R>, request: StartRequest
|
||||||
let mut meta = request.meta.clone();
|
let mut meta = request.meta.clone();
|
||||||
if let Value::Object(map) = &mut meta {
|
if let Value::Object(map) = &mut meta {
|
||||||
let mut local = serde_json::Map::new();
|
let mut local = serde_json::Map::new();
|
||||||
|
// Episodes share their season's folder, so artwork is named after the file it
|
||||||
|
// belongs to: one episode's still never replaces another's.
|
||||||
|
let stem = file_path.file_stem().and_then(|s| s.to_str()).map(sanitize).unwrap_or_else(|| sanitize(&request.id));
|
||||||
for (name, url) in &request.assets {
|
for (name, url) in &request.assets {
|
||||||
let target = folder.join(format!(".{}.jpg", sanitize(name)));
|
let target = folder.join(format!(".{stem}.{}.jpg", sanitize(name)));
|
||||||
if fetch_to(&state.client, url, &target).await.is_ok() {
|
if fetch_to(&state.client, url, &target).await.is_ok() {
|
||||||
local.insert(name.clone(), Value::String(target.display().to_string()));
|
local.insert(name.clone(), Value::String(target.display().to_string()));
|
||||||
}
|
}
|
||||||
|
|
@ -204,21 +218,48 @@ async fn fetch_to(client: &reqwest::Client, url: &str, target: &Path) -> Result<
|
||||||
tokio::fs::write(target, bytes).await.map_err(|e| e.to_string())
|
tokio::fs::write(target, bytes).await.map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Starts a transfer task for `id`, taking over from any task still running for it:
|
||||||
|
/// that one is cancelled and the new one waits for it to exit before touching the file.
|
||||||
fn spawn<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
fn spawn<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
||||||
|
let state = app.state::<Downloads>();
|
||||||
|
let generation = state.generation.fetch_add(1, Ordering::Relaxed);
|
||||||
let (tx, rx) = watch::channel(false);
|
let (tx, rx) = watch::channel(false);
|
||||||
app.state::<Downloads>().cancels.lock().insert(id.clone(), tx);
|
let (done_tx, done_rx) = watch::channel(());
|
||||||
|
let previous = state.workers.lock().insert(id.clone(), Worker { generation, cancel: tx, done: done_rx });
|
||||||
|
let previous = previous.map(|w| {
|
||||||
|
let _ = w.cancel.send(true);
|
||||||
|
w.done
|
||||||
|
});
|
||||||
tauri::async_runtime::spawn(async move {
|
tauri::async_runtime::spawn(async move {
|
||||||
|
// Held until this task ends: whoever waits on `done` then knows the file is free.
|
||||||
|
let _done = done_tx;
|
||||||
|
let took_over = previous.is_some();
|
||||||
|
if let Some(done) = previous {
|
||||||
|
exited(done).await;
|
||||||
|
}
|
||||||
|
let stopped = rx.clone();
|
||||||
|
if *stopped.borrow() {
|
||||||
|
release(&app, &id, generation);
|
||||||
|
return;
|
||||||
|
}
|
||||||
let permits = app.state::<Downloads>().permits.clone();
|
let permits = app.state::<Downloads>().permits.clone();
|
||||||
let _permit = tokio::select! {
|
let _permit = tokio::select! {
|
||||||
p = permits.acquire_owned() => p,
|
p = permits.acquire_owned() => p,
|
||||||
_ = cancelled(rx.clone()) => return,
|
_ = cancelled(rx.clone()) => { release(&app, &id, generation); return; }
|
||||||
};
|
};
|
||||||
let result = transfer(&app, &id, &url, rx).await;
|
// The task it replaced may have finished the file just as it was stopped.
|
||||||
app.state::<Downloads>().cancels.lock().remove(&id);
|
let result = if took_over && finished_file(&app, &id) { Ok(true) } else { transfer(&app, &id, &url, rx).await };
|
||||||
|
release(&app, &id, generation);
|
||||||
|
// Once paused, removed or replaced, the outcome is no longer this task's to
|
||||||
|
// report, except a finished file, which is complete whatever happened since.
|
||||||
|
if *stopped.borrow() && !matches!(result, Ok(true)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
match result {
|
match result {
|
||||||
Ok(true) => {
|
Ok(true) => {
|
||||||
update(&app, &id, |i| {
|
update(&app, &id, |i| {
|
||||||
i.status = Status::Completed;
|
i.status = Status::Completed;
|
||||||
|
i.error = None;
|
||||||
i.speed = 0;
|
i.speed = 0;
|
||||||
i.received = i.total.max(i.received);
|
i.received = i.total.max(i.received);
|
||||||
});
|
});
|
||||||
|
|
@ -236,6 +277,30 @@ fn spawn<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Drops the worker entry, unless a newer task has taken it over.
|
||||||
|
fn release<R: Runtime>(app: &AppHandle<R>, id: &str, generation: u64) {
|
||||||
|
let state = app.state::<Downloads>();
|
||||||
|
let mut workers = state.workers.lock();
|
||||||
|
if workers.get(id).map(|w| w.generation) == Some(generation) {
|
||||||
|
workers.remove(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The download's file is in place and nothing is left to transfer.
|
||||||
|
fn finished_file<R: Runtime>(app: &AppHandle<R>, id: &str) -> bool {
|
||||||
|
let Some(path) = app.state::<Downloads>().items.lock().iter().find(|i| i.id == id).map(|i| PathBuf::from(&i.file_path)) else { return false };
|
||||||
|
path.exists() && !part_path(&path).exists()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn part_path(path: &Path) -> PathBuf {
|
||||||
|
path.with_extension(format!("{}.part", path.extension().and_then(|e| e.to_str()).unwrap_or("bin")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves once a worker task has exited.
|
||||||
|
async fn exited(mut done: watch::Receiver<()>) {
|
||||||
|
while done.changed().await.is_ok() {}
|
||||||
|
}
|
||||||
|
|
||||||
async fn cancelled(mut rx: watch::Receiver<bool>) {
|
async fn cancelled(mut rx: watch::Receiver<bool>) {
|
||||||
while !*rx.borrow() {
|
while !*rx.borrow() {
|
||||||
if rx.changed().await.is_err() {
|
if rx.changed().await.is_err() {
|
||||||
|
|
@ -248,10 +313,7 @@ async fn cancelled(mut rx: watch::Receiver<bool>) {
|
||||||
async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch::Receiver<bool>) -> Result<bool, String> {
|
async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch::Receiver<bool>) -> Result<bool, String> {
|
||||||
let Some(item) = app.state::<Downloads>().items.lock().iter().find(|i| i.id == id).cloned() else { return Ok(false) };
|
let Some(item) = app.state::<Downloads>().items.lock().iter().find(|i| i.id == id).cloned() else { return Ok(false) };
|
||||||
let final_path = PathBuf::from(&item.file_path);
|
let final_path = PathBuf::from(&item.file_path);
|
||||||
let part_path = final_path.with_extension(format!(
|
let part_path = part_path(&final_path);
|
||||||
"{}.part",
|
|
||||||
final_path.extension().and_then(|e| e.to_str()).unwrap_or("bin")
|
|
||||||
));
|
|
||||||
let existing = tokio::fs::metadata(&part_path).await.map(|m| m.len()).unwrap_or(0);
|
let existing = tokio::fs::metadata(&part_path).await.map(|m| m.len()).unwrap_or(0);
|
||||||
|
|
||||||
let client = app.state::<Downloads>().client.clone();
|
let client = app.state::<Downloads>().client.clone();
|
||||||
|
|
@ -259,7 +321,10 @@ async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch
|
||||||
if existing > 0 {
|
if existing > 0 {
|
||||||
request = request.header("Range", format!("bytes={existing}-"));
|
request = request.header("Range", format!("bytes={existing}-"));
|
||||||
}
|
}
|
||||||
let response = request.send().await.map_err(|e| format!("Could not reach the server: {e}"))?;
|
let response = tokio::select! {
|
||||||
|
r = request.send() => r.map_err(|e| format!("Could not reach the server: {e}"))?,
|
||||||
|
_ = cancelled(rx.clone()) => return Ok(false),
|
||||||
|
};
|
||||||
let status = response.status();
|
let status = response.status();
|
||||||
if status.as_u16() == 401 || status.as_u16() == 403 {
|
if status.as_u16() == 401 || status.as_u16() == 403 {
|
||||||
return Err("The server does not allow downloads for this account.".into());
|
return Err("The server does not allow downloads for this account.".into());
|
||||||
|
|
@ -336,10 +401,14 @@ async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cancel<R: Runtime>(app: &AppHandle<R>, id: &str) {
|
/// Stops the transfer for `id`, if one is running; the receiver closes once it has exited.
|
||||||
if let Some(tx) = app.state::<Downloads>().cancels.lock().remove(id) {
|
/// The entry stays until then, so a task started meanwhile knows to wait for it.
|
||||||
let _ = tx.send(true);
|
fn cancel<R: Runtime>(app: &AppHandle<R>, id: &str) -> Option<watch::Receiver<()>> {
|
||||||
}
|
let state = app.state::<Downloads>();
|
||||||
|
let workers = state.workers.lock();
|
||||||
|
let worker = workers.get(id)?;
|
||||||
|
let _ = worker.cancel.send(true);
|
||||||
|
Some(worker.done.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
|
@ -356,7 +425,7 @@ pub fn download_pause<R: Runtime>(app: AppHandle<R>, id: String) {
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn download_resume<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
pub fn download_resume<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
||||||
cancel(&app, &id);
|
// `spawn` takes over from a transfer still winding down.
|
||||||
update(&app, &id, |i| {
|
update(&app, &id, |i| {
|
||||||
i.status = Status::Queued;
|
i.status = Status::Queued;
|
||||||
i.error = None;
|
i.error = None;
|
||||||
|
|
@ -366,7 +435,7 @@ pub fn download_resume<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn download_remove<R: Runtime>(app: AppHandle<R>, id: String, delete_files: bool) -> Result<(), String> {
|
pub async fn download_remove<R: Runtime>(app: AppHandle<R>, id: String, delete_files: bool) -> Result<(), String> {
|
||||||
cancel(&app, &id);
|
let running = cancel(&app, &id);
|
||||||
let removed = {
|
let removed = {
|
||||||
let state = app.state::<Downloads>();
|
let state = app.state::<Downloads>();
|
||||||
let mut items = state.items.lock();
|
let mut items = state.items.lock();
|
||||||
|
|
@ -375,14 +444,24 @@ pub async fn download_remove<R: Runtime>(app: AppHandle<R>, id: String, delete_f
|
||||||
};
|
};
|
||||||
if let (Some(item), true) = (removed, delete_files) {
|
if let (Some(item), true) = (removed, delete_files) {
|
||||||
let path = PathBuf::from(&item.file_path);
|
let path = PathBuf::from(&item.file_path);
|
||||||
// Give the cancelled transfer a moment to release its file handle.
|
// Let the cancelled transfer release its file handle first.
|
||||||
tokio::time::sleep(Duration::from_millis(150)).await;
|
if let Some(done) = running {
|
||||||
|
let _ = tokio::time::timeout(Duration::from_secs(10), exited(done)).await;
|
||||||
|
}
|
||||||
let _ = tokio::fs::remove_file(&path).await;
|
let _ = tokio::fs::remove_file(&path).await;
|
||||||
let part = path.with_extension(format!("{}.part", path.extension().and_then(|e| e.to_str()).unwrap_or("bin")));
|
let _ = tokio::fs::remove_file(part_path(&path)).await;
|
||||||
let _ = tokio::fs::remove_file(&part).await;
|
// Older downloads shared artwork between a season's episodes: keep what others still use.
|
||||||
|
let in_use: HashSet<String> = app
|
||||||
|
.state::<Downloads>()
|
||||||
|
.items
|
||||||
|
.lock()
|
||||||
|
.iter()
|
||||||
|
.filter_map(|i| i.meta.get("localAssets").and_then(Value::as_object))
|
||||||
|
.flat_map(|a| a.values().filter_map(Value::as_str).map(str::to_owned))
|
||||||
|
.collect();
|
||||||
if let Value::Object(assets) = &item.meta["localAssets"] {
|
if let Value::Object(assets) = &item.meta["localAssets"] {
|
||||||
for v in assets.values() {
|
for v in assets.values() {
|
||||||
if let Some(p) = v.as_str() {
|
if let Some(p) = v.as_str().filter(|p| !in_use.contains(*p)) {
|
||||||
let _ = tokio::fs::remove_file(p).await;
|
let _ = tokio::fs::remove_file(p).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,6 @@
|
||||||
|
mod diagnostics;
|
||||||
mod downloads;
|
mod downloads;
|
||||||
|
mod mini;
|
||||||
mod mpv;
|
mod mpv;
|
||||||
mod platform;
|
mod platform;
|
||||||
mod player;
|
mod player;
|
||||||
|
|
@ -15,6 +17,8 @@ pub fn run() {
|
||||||
.plugin(tauri_plugin_process::init())
|
.plugin(tauri_plugin_process::init())
|
||||||
.plugin(
|
.plugin(
|
||||||
tauri_plugin_window_state::Builder::default()
|
tauri_plugin_window_state::Builder::default()
|
||||||
|
// The miniplayer window is always placed from the main window (mini.rs).
|
||||||
|
.with_denylist(&["mini"])
|
||||||
.with_state_flags(
|
.with_state_flags(
|
||||||
tauri_plugin_window_state::StateFlags::SIZE
|
tauri_plugin_window_state::StateFlags::SIZE
|
||||||
| tauri_plugin_window_state::StateFlags::POSITION
|
| tauri_plugin_window_state::StateFlags::POSITION
|
||||||
|
|
@ -23,15 +27,24 @@ pub fn run() {
|
||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
.manage(player::PlayerState::default())
|
.manage(player::PlayerState::default())
|
||||||
|
.manage(mini::MiniState::default())
|
||||||
.manage(downloads::Downloads::default())
|
.manage(downloads::Downloads::default())
|
||||||
.setup(|app| {
|
.setup(|app| {
|
||||||
let handle = app.handle().clone();
|
let handle = app.handle().clone();
|
||||||
|
diagnostics::start(&handle);
|
||||||
downloads::restore(&handle);
|
downloads::restore(&handle);
|
||||||
if let Some(window) = app.get_webview_window("main") {
|
if let Some(window) = app.get_webview_window("main") {
|
||||||
let w = window.clone();
|
let w = window.clone();
|
||||||
window.on_window_event(move |event| {
|
window.on_window_event(move |event| {
|
||||||
|
// On the UI thread: places the miniplayer window without waiting on anything.
|
||||||
|
if let WindowEvent::Moved(_) | WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event {
|
||||||
|
mini::follow_main(&w);
|
||||||
|
}
|
||||||
if let WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event {
|
if let WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event {
|
||||||
player::on_resize(&w);
|
// Never on the UI thread: the player's locks may be held by a
|
||||||
|
// command that is itself waiting on the UI thread (see player.rs).
|
||||||
|
let w = w.clone();
|
||||||
|
tauri::async_runtime::spawn_blocking(move || player::on_resize(&w));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -40,9 +53,11 @@ pub fn run() {
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
player::player_init,
|
player::player_init,
|
||||||
player::player_show,
|
player::player_show,
|
||||||
|
player::player_rect,
|
||||||
player::player_command,
|
player::player_command,
|
||||||
player::player_set,
|
player::player_set,
|
||||||
player::player_get,
|
player::player_get,
|
||||||
|
player::window_buttons,
|
||||||
system::secret_get,
|
system::secret_get,
|
||||||
system::secret_set,
|
system::secret_set,
|
||||||
system::secret_delete,
|
system::secret_delete,
|
||||||
|
|
@ -58,6 +73,13 @@ pub fn run() {
|
||||||
downloads::download_list,
|
downloads::download_list,
|
||||||
downloads::download_set_dir,
|
downloads::download_set_dir,
|
||||||
downloads::download_write_meta,
|
downloads::download_write_meta,
|
||||||
|
mini::mini_show,
|
||||||
|
mini::mini_hide,
|
||||||
|
mini::mini_drag_start,
|
||||||
|
mini::mini_drag,
|
||||||
|
mini::mini_snap,
|
||||||
|
diagnostics::debug_freeze_ui,
|
||||||
|
diagnostics::debug_crash,
|
||||||
])
|
])
|
||||||
.run(tauri::generate_context!())
|
.run(tauri::generate_context!())
|
||||||
.expect("error while running Kaleido");
|
.expect("error while running Kaleido");
|
||||||
|
|
|
||||||
334
src-tauri/src/mini.rs
Normal file
|
|
@ -0,0 +1,334 @@
|
||||||
|
//! The miniplayer as a window of its own (where `platform::SEPARATE_MINI`):
|
||||||
|
//! a small borderless window owned by the main one, which the video moves
|
||||||
|
//! into. Dragging moves the whole window, so video and controls move as one;
|
||||||
|
//! letting go glides it to a corner of the main window. Its page is
|
||||||
|
//! `mini.html` (src/mini/), which mirrors the player's state from the main
|
||||||
|
//! window and sends its buttons back (src/player/miniWindow.ts).
|
||||||
|
//!
|
||||||
|
//! Positions are physical screen pixels. Never hold `MiniState`'s locks while
|
||||||
|
//! calling a window getter: off the UI thread those wait for it (player.rs).
|
||||||
|
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, Runtime, WebviewUrl, WebviewWindow, WebviewWindowBuilder, WindowEvent};
|
||||||
|
|
||||||
|
const LABEL: &str = "mini";
|
||||||
|
/// Logical pixels, as in the page's former in-window miniplayer (player.css).
|
||||||
|
const MARGIN: f64 = 24.0;
|
||||||
|
/// Top corners sit below the main window's navigation bar (64px).
|
||||||
|
const TOP_INSET: f64 = 64.0 + 12.0;
|
||||||
|
const SNAP: Duration = Duration::from_millis(260);
|
||||||
|
/// How far a flick carries the box when choosing a corner (ms of travel).
|
||||||
|
const FLICK_MS: f64 = 220.0;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq)]
|
||||||
|
enum Corner {
|
||||||
|
TopLeft,
|
||||||
|
TopRight,
|
||||||
|
BottomLeft,
|
||||||
|
BottomRight,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Corner {
|
||||||
|
fn parse(s: &str) -> Corner {
|
||||||
|
match s {
|
||||||
|
"tl" => Corner::TopLeft,
|
||||||
|
"tr" => Corner::TopRight,
|
||||||
|
"bl" => Corner::BottomLeft,
|
||||||
|
_ => Corner::BottomRight,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Corner::TopLeft => "tl",
|
||||||
|
Corner::TopRight => "tr",
|
||||||
|
Corner::BottomLeft => "bl",
|
||||||
|
Corner::BottomRight => "br",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The main window's client area on screen and the miniplayer's size there.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
struct Bounds {
|
||||||
|
left: i32,
|
||||||
|
top: i32,
|
||||||
|
width: i32,
|
||||||
|
height: i32,
|
||||||
|
mini_w: i32,
|
||||||
|
mini_h: i32,
|
||||||
|
scale: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Bounds {
|
||||||
|
fn of<R: Runtime>(main: &WebviewWindow<R>) -> Option<Bounds> {
|
||||||
|
let pos = main.inner_position().ok()?;
|
||||||
|
let size = main.inner_size().ok()?;
|
||||||
|
let scale = main.scale_factor().ok()?;
|
||||||
|
// As the page sized it: 26% of the window's width, 300 to 440 logical pixels, 16:9.
|
||||||
|
let w = (size.width as f64 / scale * 0.26).clamp(300.0, 440.0);
|
||||||
|
Some(Bounds {
|
||||||
|
left: pos.x,
|
||||||
|
top: pos.y,
|
||||||
|
width: size.width as i32,
|
||||||
|
height: size.height as i32,
|
||||||
|
mini_w: (w * scale).round() as i32,
|
||||||
|
mini_h: (w * 9.0 / 16.0 * scale).round() as i32,
|
||||||
|
scale,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn corner(&self, corner: Corner) -> (i32, i32) {
|
||||||
|
let margin = (MARGIN * self.scale).round() as i32;
|
||||||
|
let x = match corner {
|
||||||
|
Corner::TopLeft | Corner::BottomLeft => self.left + margin,
|
||||||
|
_ => self.left + self.width - self.mini_w - margin,
|
||||||
|
};
|
||||||
|
let y = match corner {
|
||||||
|
Corner::TopLeft | Corner::TopRight => self.top + (TOP_INSET * self.scale).round() as i32,
|
||||||
|
_ => self.top + self.height - self.mini_h - margin,
|
||||||
|
};
|
||||||
|
(x, y)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keeps the box inside the main window while it's dragged.
|
||||||
|
fn clamp(&self, x: i32, y: i32) -> (i32, i32) {
|
||||||
|
let x = x.clamp(self.left, (self.left + self.width - self.mini_w).max(self.left));
|
||||||
|
let y = y.clamp(self.top, (self.top + self.height - self.mini_h).max(self.top));
|
||||||
|
(x, y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
struct Drag {
|
||||||
|
/// Where the window's visible area was when the drag began.
|
||||||
|
start: (i32, i32),
|
||||||
|
bounds: Bounds,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MiniState {
|
||||||
|
corner: Mutex<Corner>,
|
||||||
|
/// From the window's outer position to its visible area: Windows keeps an
|
||||||
|
/// invisible resize border around shadowed windows. Positions here are of
|
||||||
|
/// the visible area; `place` converts.
|
||||||
|
frame: Mutex<(i32, i32)>,
|
||||||
|
drag: Mutex<Option<Drag>>,
|
||||||
|
visible: AtomicBool,
|
||||||
|
/// Dragged or gliding: the main window's moves don't re-place it meanwhile.
|
||||||
|
busy: AtomicBool,
|
||||||
|
/// Bumped to stop a glide that's under way.
|
||||||
|
glide: AtomicU64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for MiniState {
|
||||||
|
fn default() -> Self {
|
||||||
|
MiniState { corner: Mutex::new(Corner::BottomRight), frame: Mutex::new((0, 0)), drag: Mutex::new(None), visible: AtomicBool::new(false), busy: AtomicBool::new(false), glide: AtomicU64::new(0) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the window so its visible area's top left is at `(x, y)`.
|
||||||
|
fn place<R: Runtime>(app: &AppHandle<R>, mini: &WebviewWindow<R>, (x, y): (i32, i32)) {
|
||||||
|
let (fx, fy) = *app.state::<MiniState>().frame.lock();
|
||||||
|
let _ = mini.set_position(PhysicalPosition::new(x - fx, y - fy));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the visible area is now (outer position plus the frame).
|
||||||
|
fn visible_position<R: Runtime>(app: &AppHandle<R>, mini: &WebviewWindow<R>) -> Result<(i32, i32), String> {
|
||||||
|
let pos = mini.outer_position().map_err(|e| e.to_string())?;
|
||||||
|
let (fx, fy) = *app.state::<MiniState>().frame.lock();
|
||||||
|
Ok((pos.x + fx, pos.y + fy))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main_window<R: Runtime>(app: &AppHandle<R>) -> Result<WebviewWindow<R>, String> {
|
||||||
|
app.get_webview_window("main").ok_or_else(|| "The main window is gone.".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The miniplayer window, created hidden the first time (its page is small).
|
||||||
|
fn window<R: Runtime>(app: &AppHandle<R>) -> Result<WebviewWindow<R>, String> {
|
||||||
|
if let Some(w) = app.get_webview_window(LABEL) {
|
||||||
|
return Ok(w);
|
||||||
|
}
|
||||||
|
let main = main_window(app)?;
|
||||||
|
let w = WebviewWindowBuilder::new(app, LABEL, WebviewUrl::App("mini.html".into()))
|
||||||
|
.title("Kaleido")
|
||||||
|
.decorations(false)
|
||||||
|
.transparent(true)
|
||||||
|
.shadow(true)
|
||||||
|
.resizable(false)
|
||||||
|
.skip_taskbar(true)
|
||||||
|
.focused(false)
|
||||||
|
.visible(false)
|
||||||
|
.inner_size(440.0, 247.5)
|
||||||
|
// Owned by the main window: kept just above it, hidden when it's minimized.
|
||||||
|
.parent(&main)
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.build()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
if let Some(hwnd) = crate::platform::host_handle(&w) {
|
||||||
|
crate::platform::style_mini_window(hwnd);
|
||||||
|
}
|
||||||
|
// mpv draws at the window's size; resizing happens off the UI thread (player.rs).
|
||||||
|
let handle = app.clone();
|
||||||
|
w.on_window_event(move |event| {
|
||||||
|
if let WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event {
|
||||||
|
let handle = handle.clone();
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
if let Some(main) = handle.get_webview_window("main") {
|
||||||
|
crate::player::on_resize(&main);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Ok(w)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates the window ahead of its first use, so going to the miniplayer is instant.
|
||||||
|
pub fn prepare<R: Runtime>(app: &AppHandle<R>) {
|
||||||
|
if crate::platform::SEPARATE_MINI {
|
||||||
|
let _ = window(app);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unsupported() -> Result<(), String> {
|
||||||
|
Err("The miniplayer window isn't used on this platform.".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the video into the miniplayer window and shows it in `corner`.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn mini_show<R: Runtime>(app: AppHandle<R>, corner: String) -> Result<(), String> {
|
||||||
|
if !crate::platform::SEPARATE_MINI {
|
||||||
|
return unsupported();
|
||||||
|
}
|
||||||
|
let state = app.state::<MiniState>();
|
||||||
|
let corner = Corner::parse(&corner);
|
||||||
|
*state.corner.lock() = corner;
|
||||||
|
state.glide.fetch_add(1, Ordering::SeqCst);
|
||||||
|
state.busy.store(false, Ordering::SeqCst);
|
||||||
|
let mini = window(&app)?;
|
||||||
|
let bounds = Bounds::of(&main_window(&app)?).ok_or("The main window has no size.")?;
|
||||||
|
let _ = mini.set_size(PhysicalSize::new(bounds.mini_w as u32, bounds.mini_h as u32));
|
||||||
|
if let (Ok(outer), Ok(inner)) = (mini.outer_position(), mini.inner_position()) {
|
||||||
|
*state.frame.lock() = (inner.x - outer.x, inner.y - outer.y);
|
||||||
|
}
|
||||||
|
place(&app, &mini, bounds.corner(corner));
|
||||||
|
let hwnd = crate::platform::host_handle(&mini).ok_or("The miniplayer window has no handle.")?;
|
||||||
|
crate::player::set_video_host(&app, Some(hwnd))?;
|
||||||
|
crate::platform::show_inactive(hwnd);
|
||||||
|
state.visible.store(true, Ordering::SeqCst);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the video back to the main window and hides the miniplayer window.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn mini_hide<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {
|
||||||
|
if !crate::platform::SEPARATE_MINI {
|
||||||
|
return unsupported();
|
||||||
|
}
|
||||||
|
let state = app.state::<MiniState>();
|
||||||
|
state.visible.store(false, Ordering::SeqCst);
|
||||||
|
state.glide.fetch_add(1, Ordering::SeqCst);
|
||||||
|
*state.drag.lock() = None;
|
||||||
|
crate::player::set_video_host(&app, None)?;
|
||||||
|
if let Some(mini) = app.get_webview_window(LABEL) {
|
||||||
|
// Shown natively (without activation), so hidden natively too.
|
||||||
|
if let Some(hwnd) = crate::platform::host_handle(&mini) {
|
||||||
|
crate::platform::hide_window(hwnd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn mini_drag_start<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {
|
||||||
|
let state = app.state::<MiniState>();
|
||||||
|
state.busy.store(true, Ordering::SeqCst);
|
||||||
|
state.glide.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let mini = window(&app)?;
|
||||||
|
let bounds = Bounds::of(&main_window(&app)?).ok_or("The main window has no size.")?;
|
||||||
|
let start = visible_position(&app, &mini)?;
|
||||||
|
*state.drag.lock() = Some(Drag { start, bounds });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Follows the pointer: `dx`/`dy` are logical pixels moved since the drag began.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn mini_drag<R: Runtime>(app: AppHandle<R>, dx: f64, dy: f64) -> Result<(), String> {
|
||||||
|
let Some(drag) = *app.state::<MiniState>().drag.lock() else { return Ok(()) };
|
||||||
|
let b = drag.bounds;
|
||||||
|
let to = b.clamp(drag.start.0 + (dx * b.scale).round() as i32, drag.start.1 + (dy * b.scale).round() as i32);
|
||||||
|
if let Some(mini) = app.get_webview_window(LABEL) {
|
||||||
|
place(&app, &mini, to);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ends a drag: glides to the corner nearest where the box is heading (a flick,
|
||||||
|
/// `vx`/`vy` in logical pixels per millisecond, carries it on) and returns it.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn mini_snap<R: Runtime>(app: AppHandle<R>, vx: f64, vy: f64) -> Result<String, String> {
|
||||||
|
let state = app.state::<MiniState>();
|
||||||
|
let drag = state.drag.lock().take();
|
||||||
|
let mini = window(&app)?;
|
||||||
|
let b = match drag {
|
||||||
|
Some(d) => d.bounds,
|
||||||
|
None => Bounds::of(&main_window(&app)?).ok_or("The main window has no size.")?,
|
||||||
|
};
|
||||||
|
let from = visible_position(&app, &mini)?;
|
||||||
|
let cx = from.0 as f64 + b.mini_w as f64 / 2.0 + vx * FLICK_MS * b.scale;
|
||||||
|
let cy = from.1 as f64 + b.mini_h as f64 / 2.0 + vy * FLICK_MS * b.scale;
|
||||||
|
let left = cx < b.left as f64 + b.width as f64 / 2.0;
|
||||||
|
let top = cy < b.top as f64 + b.height as f64 / 2.0;
|
||||||
|
let corner = match (top, left) {
|
||||||
|
(true, true) => Corner::TopLeft,
|
||||||
|
(true, false) => Corner::TopRight,
|
||||||
|
(false, true) => Corner::BottomLeft,
|
||||||
|
(false, false) => Corner::BottomRight,
|
||||||
|
};
|
||||||
|
*state.corner.lock() = corner;
|
||||||
|
let to = b.corner(corner);
|
||||||
|
let generation = state.glide.fetch_add(1, Ordering::SeqCst) + 1;
|
||||||
|
|
||||||
|
// Ease out over SNAP, a step per display frame; stops if another drag starts.
|
||||||
|
let handle = app.clone();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let state = handle.state::<MiniState>();
|
||||||
|
let steps = (SNAP.as_millis() / 8) as i32;
|
||||||
|
let start = std::time::Instant::now();
|
||||||
|
for i in 1..=steps {
|
||||||
|
if state.glide.load(Ordering::SeqCst) != generation {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let t = (start.elapsed().as_secs_f64() / SNAP.as_secs_f64()).min(1.0);
|
||||||
|
let e = 1.0 - (1.0 - t).powi(3);
|
||||||
|
let x = from.0 + ((to.0 - from.0) as f64 * e).round() as i32;
|
||||||
|
let y = from.1 + ((to.1 - from.1) as f64 * e).round() as i32;
|
||||||
|
place(&handle, &mini, (x, y));
|
||||||
|
if t >= 1.0 || i == steps {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(8));
|
||||||
|
}
|
||||||
|
place(&handle, &mini, to);
|
||||||
|
if state.glide.load(Ordering::SeqCst) == generation {
|
||||||
|
state.busy.store(false, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Ok(corner.name().into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keeps the miniplayer in its corner as the main window moves or resizes.
|
||||||
|
/// Runs on the UI thread (window events), where window getters answer directly.
|
||||||
|
pub fn follow_main<R: Runtime>(main: &WebviewWindow<R>) {
|
||||||
|
let app = main.app_handle();
|
||||||
|
let Some(state) = app.try_state::<MiniState>() else { return };
|
||||||
|
if !state.visible.load(Ordering::SeqCst) || state.busy.load(Ordering::SeqCst) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(mini) = app.get_webview_window(LABEL) else { return };
|
||||||
|
let Some(bounds) = Bounds::of(main) else { return };
|
||||||
|
let corner = *state.corner.lock();
|
||||||
|
let _ = mini.set_size(PhysicalSize::new(bounds.mini_w as u32, bounds.mini_h as u32));
|
||||||
|
place(&app, &mini, bounds.corner(corner));
|
||||||
|
}
|
||||||
|
|
@ -192,6 +192,21 @@ impl Mpv {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The raw client handle, for platform code using parts of libmpv this
|
||||||
|
/// binding doesn't wrap (the render API).
|
||||||
|
pub fn raw_handle(&self) -> *mut c_void {
|
||||||
|
self.handle
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Looks up another libmpv function by name.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// `T` must be the function's exact pointer type.
|
||||||
|
pub unsafe fn symbol<T: Copy>(&self, name: &str) -> Option<T> {
|
||||||
|
let name = CString::new(name).ok()?;
|
||||||
|
self.api._lib.get::<T>(name.as_bytes_with_nul()).ok().map(|s| *s)
|
||||||
|
}
|
||||||
|
|
||||||
fn error(&self, code: c_int) -> String {
|
fn error(&self, code: c_int) -> String {
|
||||||
unsafe { CStr::from_ptr((self.api.error_string)(code)).to_string_lossy().into_owned() }
|
unsafe { CStr::from_ptr((self.api.error_string)(code)).to_string_lossy().into_owned() }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
//! Linux: render mpv through its render API (OpenGL) beneath the WebKitGTK
|
//! Linux: render mpv through its render API (OpenGL) beneath the WebKitGTK
|
||||||
//! view, then implement `VideoSurface` here.
|
//! view, then implement `VideoSurface` here (see macos.rs for the same idea).
|
||||||
//!
|
//!
|
||||||
//! Browsing, downloads, settings and updates already work here; only native
|
//! Browsing, downloads, settings and updates already work here; only native
|
||||||
//! video composition remains to be written.
|
//! video composition remains to be written.
|
||||||
|
|
@ -20,12 +20,61 @@ impl VideoSurface {
|
||||||
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
|
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
}
|
}
|
||||||
|
pub fn start(&mut self, _: &std::sync::Arc<Mpv>) -> Result<(), String> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
pub fn on_property(&mut self, _: &str, _: &serde_json::Value) {}
|
pub fn on_property(&mut self, _: &str, _: &serde_json::Value) {}
|
||||||
pub fn show(&mut self, _: bool) {}
|
pub fn show<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: bool) {}
|
||||||
pub fn fit<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: Option<&Mpv>) {}
|
pub fn fit<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: Option<&Mpv>) {}
|
||||||
|
pub fn set_rect<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: Option<&Mpv>, _: Option<(i32, i32, i32, i32)>) {}
|
||||||
|
|
||||||
|
/// The video stays in the main window here (`SEPARATE_MINI` is false).
|
||||||
|
pub fn set_host(&mut self, _: Option<isize>, _: Option<&Mpv>) -> Result<(), String> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Not needed yet: the only GPU-specific tier (RTX Video) is Windows-only.
|
||||||
|
pub fn gpu_names() -> Vec<String> {
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn device_name() -> String {
|
||||||
|
std::fs::read_to_string("/etc/hostname").map(|h| h.trim().to_string()).ok().filter(|h| !h.is_empty()).unwrap_or_else(|| "Linux PC".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn os_version() -> String {
|
||||||
|
String::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_window_buttons<R: Runtime>(_: &WebviewWindow<R>, _: bool) {}
|
||||||
|
|
||||||
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
|
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
|
||||||
// TODO(Linux): org.freedesktop.ScreenSaver.Inhibit over D-Bus.
|
// TODO(Linux): org.freedesktop.ScreenSaver.Inhibit over D-Bus.
|
||||||
let _ = rx.recv();
|
let _ = rx.recv();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// —— Diagnostics (see diagnostics.rs) ————————————————————————————————————
|
||||||
|
|
||||||
|
/// Hang dumps are Windows-only for now; the watchdog still logs the stall.
|
||||||
|
pub fn write_dump(_: &std::path::Path) -> Result<(), String> {
|
||||||
|
Err("dumps are not written on this platform".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Crashes are left to the system's crash reporter here.
|
||||||
|
pub fn install_crash_handler() {}
|
||||||
|
|
||||||
|
// —— Miniplayer window (see mini.rs) ——————————————————————————————————————
|
||||||
|
|
||||||
|
/// The miniplayer stays inside the main window's page here (PlayerOverlay).
|
||||||
|
pub const SEPARATE_MINI: bool = false;
|
||||||
|
|
||||||
|
pub fn host_handle<R: Runtime>(_: &WebviewWindow<R>) -> Option<isize> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn style_mini_window(_: isize) {}
|
||||||
|
|
||||||
|
pub fn show_inactive(_: isize) {}
|
||||||
|
|
||||||
|
pub fn hide_window(_: isize) {}
|
||||||
|
|
|
||||||
|
|
@ -1,31 +1,568 @@
|
||||||
//! macOS: render mpv through its render API (libplacebo) into a CAMetalLayer
|
//! macOS: libmpv's render API (OpenGL) draws into a CAOpenGLLayer hosted by a
|
||||||
//! placed beneath the WKWebView, then implement `VideoSurface` here.
|
//! view placed beneath the WKWebView; libmpv names, power assertions, window
|
||||||
|
//! buttons and host details.
|
||||||
//!
|
//!
|
||||||
//! Browsing, downloads, settings and updates already work here; only native
|
//! OpenGL is deprecated on macOS but still supported (on Metal); it is the
|
||||||
//! video composition remains to be written.
|
//! render API libmpv offers, and what IINA and other mpv front ends use.
|
||||||
|
#![allow(deprecated)]
|
||||||
|
|
||||||
|
use std::ffi::{c_char, c_int, c_void, CStr};
|
||||||
|
use std::ptr::{self, NonNull};
|
||||||
|
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use objc2::rc::Retained;
|
||||||
|
use objc2::{define_class, msg_send, AllocAnyThread, DefinedClass, MainThreadMarker};
|
||||||
|
use objc2_app_kit::{NSAutoresizingMaskOptions, NSView, NSWindow, NSWindowButton, NSWindowOrderingMode};
|
||||||
|
use objc2_core_foundation::{CFRetained, CFTimeInterval};
|
||||||
|
use objc2_core_graphics::{kCGColorSpaceITUR_2100_PQ, kCGColorSpaceSRGB, CGColorSpace};
|
||||||
|
use objc2_core_video::CVTimeStamp;
|
||||||
|
use objc2_foundation::{NSNumber, NSPoint, NSRect, NSSize, NSString};
|
||||||
|
use objc2_open_gl::*;
|
||||||
|
use objc2_quartz_core::{CALayer, CAOpenGLLayer, CATransaction};
|
||||||
|
use parking_lot::Mutex;
|
||||||
use tauri::{Runtime, WebviewWindow};
|
use tauri::{Runtime, WebviewWindow};
|
||||||
|
|
||||||
use crate::mpv::Mpv;
|
use crate::mpv::Mpv;
|
||||||
|
|
||||||
pub const SURFACE_PROPERTIES: &[&str] = &[];
|
// —— OpenGL ————————————————————————————————————————————————————————————
|
||||||
pub const MPV_LIBRARIES: &[&str] = &["libmpv.2.dylib", "libmpv.dylib"];
|
|
||||||
|
|
||||||
pub struct VideoSurface;
|
const GL_COLOR_BUFFER_BIT: u32 = 0x4000;
|
||||||
|
const GL_VIEWPORT: u32 = 0x0BA2;
|
||||||
|
const GL_DRAW_FRAMEBUFFER_BINDING: u32 = 0x8CA6;
|
||||||
|
const GL_RGBA16F: c_int = 0x881A;
|
||||||
|
const RTLD_LAZY: c_int = 0x1;
|
||||||
|
|
||||||
|
#[link(name = "OpenGL", kind = "framework")]
|
||||||
|
extern "C" {
|
||||||
|
fn glGetIntegerv(pname: u32, data: *mut i32);
|
||||||
|
fn glClearColor(r: f32, g: f32, b: f32, a: f32);
|
||||||
|
fn glClear(mask: u32);
|
||||||
|
fn glFlush();
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
fn dlopen(path: *const c_char, mode: c_int) -> *mut c_void;
|
||||||
|
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// mpv resolves OpenGL functions through this (`ctx` is OpenGL.framework's handle).
|
||||||
|
extern "C" fn get_proc_address(ctx: *mut c_void, name: *const c_char) -> *mut c_void {
|
||||||
|
unsafe { dlsym(ctx, name) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A 3.2 core context; 16-bit float colour (needed for HDR) when the renderer
|
||||||
|
/// offers it. Returns whether it got float colour.
|
||||||
|
unsafe fn create_gl_context() -> Result<(CGLContextObj, CGLPixelFormatObj, bool), String> {
|
||||||
|
let base = [
|
||||||
|
CGLPixelFormatAttribute::CGLPFAOpenGLProfile.0,
|
||||||
|
CGLOpenGLProfile::CGLOGLPVersion_3_2_Core.0,
|
||||||
|
CGLPixelFormatAttribute::CGLPFAAccelerated.0,
|
||||||
|
CGLPixelFormatAttribute::CGLPFADoubleBuffer.0,
|
||||||
|
CGLPixelFormatAttribute::CGLPFAAllowOfflineRenderers.0,
|
||||||
|
CGLPixelFormatAttribute::CGLPFASupportsAutomaticGraphicsSwitching.0,
|
||||||
|
];
|
||||||
|
let deep = [CGLPixelFormatAttribute::CGLPFAColorSize.0, 64, CGLPixelFormatAttribute::CGLPFAColorFloat.0];
|
||||||
|
for extra in [&deep[..], &[]] {
|
||||||
|
let mut attrs: Vec<CGLPixelFormatAttribute> = base.iter().chain(extra).map(|&a| CGLPixelFormatAttribute(a)).collect();
|
||||||
|
attrs.push(CGLPixelFormatAttribute(0));
|
||||||
|
let mut pf: CGLPixelFormatObj = ptr::null_mut();
|
||||||
|
let mut count = 0;
|
||||||
|
CGLChoosePixelFormat(NonNull::new_unchecked(attrs.as_mut_ptr()), NonNull::from(&mut pf), NonNull::from(&mut count));
|
||||||
|
if pf.is_null() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut ctx: CGLContextObj = ptr::null_mut();
|
||||||
|
CGLCreateContext(pf, ptr::null_mut(), NonNull::from(&mut ctx));
|
||||||
|
if !ctx.is_null() {
|
||||||
|
return Ok((ctx, pf, !extra.is_empty()));
|
||||||
|
}
|
||||||
|
CGLReleasePixelFormat(pf);
|
||||||
|
}
|
||||||
|
Err("OpenGL is unavailable, so video can't be shown.".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
// —— mpv render API ————————————————————————————————————————————————————
|
||||||
|
|
||||||
|
const RENDER_PARAM_API_TYPE: c_int = 1;
|
||||||
|
const RENDER_PARAM_OPENGL_INIT_PARAMS: c_int = 2;
|
||||||
|
const RENDER_PARAM_OPENGL_FBO: c_int = 3;
|
||||||
|
const RENDER_PARAM_FLIP_Y: c_int = 4;
|
||||||
|
const RENDER_UPDATE_FRAME: u64 = 1;
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
struct RenderParam {
|
||||||
|
kind: c_int,
|
||||||
|
data: *mut c_void,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
struct OpenGlInitParams {
|
||||||
|
get_proc_address: extern "C" fn(*mut c_void, *const c_char) -> *mut c_void,
|
||||||
|
get_proc_address_ctx: *mut c_void,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
struct OpenGlFbo {
|
||||||
|
fbo: c_int,
|
||||||
|
w: c_int,
|
||||||
|
h: c_int,
|
||||||
|
internal_format: c_int,
|
||||||
|
}
|
||||||
|
|
||||||
|
type RenderCtx = *mut c_void;
|
||||||
|
|
||||||
|
/// An mpv render context and the functions that drive it. Every call happens
|
||||||
|
/// with the layer's OpenGL context locked and current, as libmpv requires.
|
||||||
|
struct Render {
|
||||||
|
ctx: RenderCtx,
|
||||||
|
render: unsafe extern "C" fn(RenderCtx, *mut RenderParam) -> c_int,
|
||||||
|
update: unsafe extern "C" fn(RenderCtx) -> u64,
|
||||||
|
report_swap: unsafe extern "C" fn(RenderCtx),
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl Send for Render {}
|
||||||
|
unsafe impl Sync for Render {}
|
||||||
|
|
||||||
|
/// libmpv calls this from its own threads when a frame is ready; it may not
|
||||||
|
/// call back into libmpv, so it only wakes the render thread.
|
||||||
|
extern "C" fn on_update(wake: *mut c_void) {
|
||||||
|
let wake = unsafe { &*(wake as *const SyncSender<()>) };
|
||||||
|
let _ = wake.try_send(());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn srgb() -> Option<CFRetained<CGColorSpace>> {
|
||||||
|
CGColorSpace::with_name(Some(unsafe { kCGColorSpaceSRGB }))
|
||||||
|
}
|
||||||
|
|
||||||
|
// —— The video layer ———————————————————————————————————————————————————
|
||||||
|
|
||||||
|
struct LayerIvars {
|
||||||
|
cgl: CGLContextObj,
|
||||||
|
pixel_format: CGLPixelFormatObj,
|
||||||
|
/// The framebuffer holds 16-bit floats (so mpv needn't dither to 8 bits).
|
||||||
|
float: bool,
|
||||||
|
render: Mutex<Option<Arc<Render>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
define_class!(
|
||||||
|
#[unsafe(super(CAOpenGLLayer, CALayer))]
|
||||||
|
#[name = "KaleidoVideoLayer"]
|
||||||
|
#[ivars = LayerIvars]
|
||||||
|
struct VideoLayer;
|
||||||
|
|
||||||
|
impl VideoLayer {
|
||||||
|
#[unsafe(method(copyCGLPixelFormatForDisplayMask:))]
|
||||||
|
fn copy_pixel_format(&self, _mask: u32) -> CGLPixelFormatObj {
|
||||||
|
unsafe { CGLRetainPixelFormat(self.ivars().pixel_format) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(method(copyCGLContextForPixelFormat:))]
|
||||||
|
fn copy_context(&self, _pf: CGLPixelFormatObj) -> CGLContextObj {
|
||||||
|
unsafe { CGLRetainContext(self.ivars().cgl) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(method(releaseCGLContext:))]
|
||||||
|
fn release_context(&self, ctx: CGLContextObj) {
|
||||||
|
unsafe { CGLReleaseContext(ctx) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(method(canDrawInCGLContext:pixelFormat:forLayerTime:displayTime:))]
|
||||||
|
fn can_draw(&self, _ctx: CGLContextObj, _pf: CGLPixelFormatObj, _t: CFTimeInterval, _ts: *const CVTimeStamp) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unsafe(method(drawInCGLContext:pixelFormat:forLayerTime:displayTime:))]
|
||||||
|
fn draw(&self, ctx: CGLContextObj, _pf: CGLPixelFormatObj, _t: CFTimeInterval, _ts: *const CVTimeStamp) {
|
||||||
|
let render = self.ivars().render.lock().clone();
|
||||||
|
unsafe {
|
||||||
|
CGLLockContext(ctx);
|
||||||
|
CGLSetCurrentContext(ctx);
|
||||||
|
match render {
|
||||||
|
Some(r) => {
|
||||||
|
let mut fbo = 0;
|
||||||
|
let mut viewport = [0i32; 4];
|
||||||
|
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &mut fbo);
|
||||||
|
glGetIntegerv(GL_VIEWPORT, viewport.as_mut_ptr());
|
||||||
|
let mut target = OpenGlFbo { fbo, w: viewport[2], h: viewport[3], internal_format: if self.ivars().float { GL_RGBA16F } else { 0 } };
|
||||||
|
let mut flip: c_int = 1;
|
||||||
|
let mut params = [
|
||||||
|
RenderParam { kind: RENDER_PARAM_OPENGL_FBO, data: &mut target as *mut _ as *mut c_void },
|
||||||
|
RenderParam { kind: RENDER_PARAM_FLIP_Y, data: &mut flip as *mut _ as *mut c_void },
|
||||||
|
RenderParam { kind: 0, data: ptr::null_mut() },
|
||||||
|
];
|
||||||
|
(r.render)(r.ctx, params.as_mut_ptr());
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
glClearColor(0.0, 0.0, 0.0, 1.0);
|
||||||
|
glClear(GL_COLOR_BUFFER_BIT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
glFlush();
|
||||||
|
CGLUnlockContext(ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// The layer is drawn from the render thread as well as by Core Animation;
|
||||||
|
// its mutable state is behind a mutex and the CGL context lock.
|
||||||
|
unsafe impl Send for VideoLayer {}
|
||||||
|
unsafe impl Sync for VideoLayer {}
|
||||||
|
|
||||||
|
impl VideoLayer {
|
||||||
|
fn new(cgl: CGLContextObj, pixel_format: CGLPixelFormatObj, float: bool) -> Retained<VideoLayer> {
|
||||||
|
let this = VideoLayer::alloc().set_ivars(LayerIvars { cgl, pixel_format, float, render: Mutex::new(None) });
|
||||||
|
let layer: Retained<VideoLayer> = unsafe { msg_send![super(this), init] };
|
||||||
|
layer.setAsynchronous(false);
|
||||||
|
// A float framebuffer without a colour space would be read as linear
|
||||||
|
// light, washing SDR out; mpv writes gamma-encoded SDR, as for Windows.
|
||||||
|
layer.setColorspace(srgb().as_deref());
|
||||||
|
layer.setNeedsDisplayOnBoundsChange(true);
|
||||||
|
layer.setOpaque(true);
|
||||||
|
layer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Redraws whenever mpv has a new frame. Drawing off the main thread needs an
|
||||||
|
/// explicit flush for Core Animation to pick the frame up.
|
||||||
|
fn render_loop(layer: Retained<VideoLayer>, wake: Receiver<()>) {
|
||||||
|
let cgl = layer.ivars().cgl;
|
||||||
|
while wake.recv().is_ok() {
|
||||||
|
let Some(render) = layer.ivars().render.lock().clone() else { continue };
|
||||||
|
let flags = unsafe {
|
||||||
|
CGLLockContext(cgl);
|
||||||
|
CGLSetCurrentContext(cgl);
|
||||||
|
let flags = (render.update)(render.ctx);
|
||||||
|
CGLUnlockContext(cgl);
|
||||||
|
flags
|
||||||
|
};
|
||||||
|
if flags & RENDER_UPDATE_FRAME != 0 {
|
||||||
|
layer.display();
|
||||||
|
CATransaction::flush();
|
||||||
|
unsafe {
|
||||||
|
CGLLockContext(cgl);
|
||||||
|
CGLSetCurrentContext(cgl);
|
||||||
|
(render.report_swap)(render.ctx);
|
||||||
|
CGLUnlockContext(cgl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// —— VideoSurface ——————————————————————————————————————————————————————
|
||||||
|
|
||||||
|
/// The view is only touched on the main thread; the layer is also drawn by the
|
||||||
|
/// render thread and reconfigured for HDR inside explicit transactions.
|
||||||
|
struct Ui {
|
||||||
|
view: Retained<NSView>,
|
||||||
|
layer: Retained<VideoLayer>,
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl Send for Ui {}
|
||||||
|
unsafe impl Sync for Ui {}
|
||||||
|
|
||||||
|
pub struct VideoSurface {
|
||||||
|
ui: Arc<Ui>,
|
||||||
|
wake: &'static SyncSender<()>,
|
||||||
|
wake_rx: Option<Receiver<()>>,
|
||||||
|
/// Where the video is drawn, in physical pixels; `None` fills the window.
|
||||||
|
rect: Option<(i32, i32, i32, i32)>,
|
||||||
|
mpv: Option<Arc<Mpv>>,
|
||||||
|
/// HDR passthrough is on (the `target-colorspace-hint` option, as on Windows).
|
||||||
|
passthrough: bool,
|
||||||
|
/// The layer is showing HDR in extended dynamic range.
|
||||||
|
edr: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `f` on the main thread with the window's web view and waits for it.
|
||||||
|
fn on_main<R: Runtime, T: Send + 'static>(
|
||||||
|
window: &WebviewWindow<R>,
|
||||||
|
f: impl FnOnce(&NSView, &NSWindow) -> T + Send + 'static,
|
||||||
|
) -> Result<T, String> {
|
||||||
|
let (tx, rx) = std::sync::mpsc::channel();
|
||||||
|
window
|
||||||
|
.with_webview(move |webview| unsafe {
|
||||||
|
let view = &*(webview.inner() as *const NSView);
|
||||||
|
let window = &*(webview.ns_window() as *const NSWindow);
|
||||||
|
let _ = tx.send(f(view, window));
|
||||||
|
})
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
rx.recv().map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Places the video view: the whole web view, or a rectangle of it given in
|
||||||
|
/// physical pixels from the top left (the web page's coordinates).
|
||||||
|
fn place(ui: &Ui, webview: &NSView, window: &NSWindow, rect: Option<(i32, i32, i32, i32)>) {
|
||||||
|
let bounds = webview.frame();
|
||||||
|
let scale = window.backingScaleFactor();
|
||||||
|
let frame = match rect {
|
||||||
|
None => bounds,
|
||||||
|
Some((x, y, w, h)) => {
|
||||||
|
let (x, y, w, h) = (x as f64 / scale, y as f64 / scale, (w.max(16)) as f64 / scale, (h.max(16)) as f64 / scale);
|
||||||
|
let flipped = unsafe { webview.superview() }.is_some_and(|s| s.isFlipped());
|
||||||
|
let top = if flipped { bounds.origin.y + y } else { bounds.origin.y + bounds.size.height - y - h };
|
||||||
|
NSRect::new(NSPoint::new(bounds.origin.x + x, top), NSSize::new(w, h))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
ui.view.setFrame(frame);
|
||||||
|
ui.view.setAutoresizingMask(if rect.is_none() {
|
||||||
|
NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewHeightSizable
|
||||||
|
} else {
|
||||||
|
NSAutoresizingMaskOptions::ViewNotSizable
|
||||||
|
});
|
||||||
|
if ui.layer.contentsScale() != scale {
|
||||||
|
ui.layer.setContentsScale(scale);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl VideoSurface {
|
impl VideoSurface {
|
||||||
pub fn create<R: Runtime>(_: &WebviewWindow<R>) -> Result<VideoSurface, String> {
|
pub fn create<R: Runtime>(window: &WebviewWindow<R>) -> Result<VideoSurface, String> {
|
||||||
Err("Video playback is not available on this platform yet.".into())
|
let (cgl, pixel_format, float) = unsafe { create_gl_context()? };
|
||||||
|
let layer = VideoLayer::new(cgl, pixel_format, float);
|
||||||
|
let ui = on_main(window, move |webview, window| unsafe {
|
||||||
|
let view = NSView::initWithFrame(MainThreadMarker::new_unchecked().alloc(), webview.frame());
|
||||||
|
// Layer-hosting: set the layer before asking for one.
|
||||||
|
view.setLayer(Some(&layer));
|
||||||
|
view.setWantsLayer(true);
|
||||||
|
view.setHidden(true);
|
||||||
|
// Let the video show through wherever the page is transparent.
|
||||||
|
let no = NSNumber::new_bool(false);
|
||||||
|
let _: () = msg_send![webview, setValue: &*no, forKey: &*NSString::from_str("drawsBackground")];
|
||||||
|
if let Some(parent) = webview.superview() {
|
||||||
|
parent.addSubview_positioned_relativeTo(&view, NSWindowOrderingMode::Below, Some(webview));
|
||||||
|
}
|
||||||
|
let ui = Ui { view, layer };
|
||||||
|
place(&ui, webview, window, None);
|
||||||
|
ui
|
||||||
|
})?;
|
||||||
|
let (wake, wake_rx) = sync_channel::<()>(1);
|
||||||
|
Ok(VideoSurface {
|
||||||
|
ui: Arc::new(ui),
|
||||||
|
wake: Box::leak(Box::new(wake)),
|
||||||
|
wake_rx: Some(wake_rx),
|
||||||
|
rect: None,
|
||||||
|
mpv: None,
|
||||||
|
passthrough: false,
|
||||||
|
edr: false,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// mpv renders through the render API (`vo=libmpv`). Its window is forced
|
||||||
|
/// open only once the render context exists (`start`).
|
||||||
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
|
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
|
||||||
Vec::new()
|
vec![("vo", "libmpv".into()), ("force-window", "no".into())]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates mpv's render context on the layer's OpenGL context and starts
|
||||||
|
/// the render thread. Runs once, after `mpv_initialize`.
|
||||||
|
pub fn start(&mut self, mpv: &Arc<Mpv>) -> Result<(), String> {
|
||||||
|
let Some(wake_rx) = self.wake_rx.take() else { return Ok(()) };
|
||||||
|
let hint = mpv.get_property("target-colorspace-hint").unwrap_or_default();
|
||||||
|
self.passthrough = (hint == serde_json::Value::Bool(true) || hint == "yes") && self.ui.layer.ivars().float;
|
||||||
|
self.mpv = Some(mpv.clone());
|
||||||
|
type Create = unsafe extern "C" fn(*mut RenderCtx, *mut c_void, *mut RenderParam) -> c_int;
|
||||||
|
type SetCallback = unsafe extern "C" fn(RenderCtx, extern "C" fn(*mut c_void), *mut c_void);
|
||||||
|
unsafe {
|
||||||
|
let missing = |name: &str| format!("libmpv is missing {name}");
|
||||||
|
let create: Create = mpv.symbol("mpv_render_context_create").ok_or_else(|| missing("mpv_render_context_create"))?;
|
||||||
|
let set_callback: SetCallback = mpv.symbol("mpv_render_context_set_update_callback").ok_or_else(|| missing("the render API"))?;
|
||||||
|
let render = mpv.symbol("mpv_render_context_render").ok_or_else(|| missing("the render API"))?;
|
||||||
|
let update = mpv.symbol("mpv_render_context_update").ok_or_else(|| missing("the render API"))?;
|
||||||
|
let report_swap = mpv.symbol("mpv_render_context_report_swap").ok_or_else(|| missing("the render API"))?;
|
||||||
|
|
||||||
|
let gl = dlopen(c"/System/Library/Frameworks/OpenGL.framework/OpenGL".as_ptr(), RTLD_LAZY);
|
||||||
|
let mut init = OpenGlInitParams { get_proc_address, get_proc_address_ctx: gl };
|
||||||
|
let mut params = [
|
||||||
|
RenderParam { kind: RENDER_PARAM_API_TYPE, data: c"opengl".as_ptr() as *mut c_void },
|
||||||
|
RenderParam { kind: RENDER_PARAM_OPENGL_INIT_PARAMS, data: &mut init as *mut _ as *mut c_void },
|
||||||
|
RenderParam { kind: 0, data: ptr::null_mut() },
|
||||||
|
];
|
||||||
|
let cgl = self.ui.layer.ivars().cgl;
|
||||||
|
let mut ctx: RenderCtx = ptr::null_mut();
|
||||||
|
CGLLockContext(cgl);
|
||||||
|
CGLSetCurrentContext(cgl);
|
||||||
|
let code = create(&mut ctx, mpv.raw_handle(), params.as_mut_ptr());
|
||||||
|
CGLUnlockContext(cgl);
|
||||||
|
if code < 0 || ctx.is_null() {
|
||||||
|
return Err(format!("The video renderer couldn't start ({code})."));
|
||||||
|
}
|
||||||
|
set_callback(ctx, on_update, self.wake as *const SyncSender<()> as *mut c_void);
|
||||||
|
*self.ui.layer.ivars().render.lock() = Some(Arc::new(Render { ctx, render, update, report_swap }));
|
||||||
|
}
|
||||||
|
let layer = self.ui.layer.clone();
|
||||||
|
std::thread::Builder::new()
|
||||||
|
.name("mpv-render".into())
|
||||||
|
.spawn(move || render_loop(layer, wake_rx))
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
mpv.set_property("force-window", &serde_json::Value::Bool(true))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// HDR passthrough: for PQ or HLG video, mpv outputs PQ (BT.2020) instead of
|
||||||
|
/// tone-mapping to SDR, and the layer shows it in extended dynamic range, so
|
||||||
|
/// macOS maps it to the display's HDR headroom. SDR video is shown as sRGB.
|
||||||
|
pub fn on_property(&mut self, name: &str, value: &serde_json::Value) {
|
||||||
|
if name != "video-params/gamma" {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let edr = self.passthrough && matches!(value.as_str(), Some("pq" | "hlg"));
|
||||||
|
if edr == self.edr {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.edr = edr;
|
||||||
|
if let Some(mpv) = &self.mpv {
|
||||||
|
let target = |v: &str| serde_json::Value::String(v.into());
|
||||||
|
let (trc, prim) = if edr { ("pq", "bt.2020") } else { ("auto", "auto") };
|
||||||
|
let _ = mpv.set_property("target-trc", &target(trc));
|
||||||
|
let _ = mpv.set_property("target-prim", &target(prim));
|
||||||
|
}
|
||||||
|
// Layer properties may change off the main thread inside a transaction.
|
||||||
|
let layer = &self.ui.layer;
|
||||||
|
CATransaction::begin();
|
||||||
|
layer.setWantsExtendedDynamicRangeContent(edr);
|
||||||
|
let space = if edr { CGColorSpace::with_name(Some(unsafe { kCGColorSpaceITUR_2100_PQ })) } else { srgb() };
|
||||||
|
layer.setColorspace(space.as_deref());
|
||||||
|
CATransaction::commit();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn show<R: Runtime>(&mut self, window: &WebviewWindow<R>, visible: bool) {
|
||||||
|
let ui = self.ui.clone();
|
||||||
|
let _ = window.run_on_main_thread(move || {
|
||||||
|
ui.view.setHidden(!visible);
|
||||||
|
if visible {
|
||||||
|
ui.layer.setNeedsDisplay();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keeps the video view matched to the web view, or to the miniplayer
|
||||||
|
/// rectangle when one is set.
|
||||||
|
pub fn fit<R: Runtime>(&mut self, window: &WebviewWindow<R>, _: Option<&Mpv>) {
|
||||||
|
let ui = self.ui.clone();
|
||||||
|
let rect = self.rect;
|
||||||
|
let _ = window.with_webview(move |webview| unsafe {
|
||||||
|
let view = &*(webview.inner() as *const NSView);
|
||||||
|
let window = &*(webview.ns_window() as *const NSWindow);
|
||||||
|
place(&ui, view, window, rect);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_rect<R: Runtime>(&mut self, window: &WebviewWindow<R>, mpv: Option<&Mpv>, rect: Option<(i32, i32, i32, i32)>) {
|
||||||
|
self.rect = rect;
|
||||||
|
self.fit(window, mpv);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The video stays in the main window here (`SEPARATE_MINI` is false).
|
||||||
|
pub fn set_host(&mut self, _: Option<isize>, _: Option<&Mpv>) -> Result<(), String> {
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
pub fn on_property(&mut self, _: &str, _: &serde_json::Value) {}
|
|
||||||
pub fn show(&mut self, _: bool) {}
|
|
||||||
pub fn fit<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: Option<&Mpv>) {}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
|
/// mpv properties the surface needs to observe.
|
||||||
// TODO(macOS): IOPMAssertionCreateWithName(PreventUserIdleDisplaySleep).
|
pub const SURFACE_PROPERTIES: &[&str] = &["video-params/gamma"];
|
||||||
let _ = rx.recv();
|
|
||||||
|
/// File names libmpv may have on this platform.
|
||||||
|
pub const MPV_LIBRARIES: &[&str] = &["libmpv.2.dylib", "libmpv.dylib"];
|
||||||
|
|
||||||
|
/// Not needed: the only GPU-specific tier (RTX Video) is Windows-only.
|
||||||
|
pub fn gpu_names() -> Vec<String> {
|
||||||
|
Vec::new()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The Mac's name as set in System Settings → General → Sharing.
|
||||||
|
pub fn device_name() -> String {
|
||||||
|
objc2_foundation::NSHost::currentHost()
|
||||||
|
.localizedName()
|
||||||
|
.map(|n| n.to_string())
|
||||||
|
.filter(|n| !n.is_empty())
|
||||||
|
.unwrap_or_else(|| "Mac".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// macOS version, e.g. "15.4".
|
||||||
|
pub fn os_version() -> String {
|
||||||
|
let v = objc2_foundation::NSProcessInfo::processInfo().operatingSystemVersion();
|
||||||
|
if v.patchVersion > 0 {
|
||||||
|
format!("{}.{}.{}", v.majorVersion, v.minorVersion, v.patchVersion)
|
||||||
|
} else {
|
||||||
|
format!("{}.{}", v.majorVersion, v.minorVersion)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shows or hides the traffic lights (they fade with the player's controls).
|
||||||
|
pub fn set_window_buttons<R: Runtime>(window: &WebviewWindow<R>, visible: bool) {
|
||||||
|
let Ok(ns_window) = window.ns_window() else { return };
|
||||||
|
let ns_window = ns_window as usize;
|
||||||
|
let _ = window.run_on_main_thread(move || unsafe {
|
||||||
|
let window = &*(ns_window as *const NSWindow);
|
||||||
|
for kind in [NSWindowButton::CloseButton, NSWindowButton::MiniaturizeButton, NSWindowButton::ZoomButton] {
|
||||||
|
if let Some(button) = window.standardWindowButton(kind) {
|
||||||
|
button.setHidden(!visible);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// AppKit lays the buttons out again at their default place; the window's
|
||||||
|
// view restores the configured position (trafficLightPosition) when drawn.
|
||||||
|
if let Some(view) = window.contentView() {
|
||||||
|
view.setNeedsDisplay(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// —— Power —————————————————————————————————————————————————————————————
|
||||||
|
|
||||||
|
type CFStringRef = *const c_void;
|
||||||
|
const CF_STRING_ENCODING_UTF8: u32 = 0x0800_0100;
|
||||||
|
const IOPM_ASSERTION_LEVEL_ON: u32 = 255;
|
||||||
|
|
||||||
|
#[link(name = "CoreFoundation", kind = "framework")]
|
||||||
|
extern "C" {
|
||||||
|
fn CFStringCreateWithCString(alloc: *const c_void, s: *const c_char, encoding: u32) -> CFStringRef;
|
||||||
|
fn CFRelease(cf: *const c_void);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[link(name = "IOKit", kind = "framework")]
|
||||||
|
extern "C" {
|
||||||
|
fn IOPMAssertionCreateWithName(kind: CFStringRef, level: u32, name: CFStringRef, id: *mut u32) -> i32;
|
||||||
|
fn IOPMAssertionRelease(id: u32) -> i32;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keeps the display awake until `rx` closes or receives.
|
||||||
|
pub fn hold_awake(rx: Receiver<()>) {
|
||||||
|
let cf = |s: &CStr| unsafe { CFStringCreateWithCString(ptr::null(), s.as_ptr(), CF_STRING_ENCODING_UTF8) };
|
||||||
|
let kind = cf(c"PreventUserIdleDisplaySleep");
|
||||||
|
let name = cf(c"Kaleido is playing video");
|
||||||
|
let mut id = 0u32;
|
||||||
|
let held = unsafe { IOPMAssertionCreateWithName(kind, IOPM_ASSERTION_LEVEL_ON, name, &mut id) } == 0;
|
||||||
|
let _ = rx.recv();
|
||||||
|
unsafe {
|
||||||
|
if held {
|
||||||
|
IOPMAssertionRelease(id);
|
||||||
|
}
|
||||||
|
CFRelease(kind);
|
||||||
|
CFRelease(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// —— Diagnostics (see diagnostics.rs) ————————————————————————————————————
|
||||||
|
|
||||||
|
/// Hang dumps are Windows-only for now; the watchdog still logs the stall.
|
||||||
|
pub fn write_dump(_: &std::path::Path) -> Result<(), String> {
|
||||||
|
Err("dumps are not written on this platform".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Crashes are left to the system's crash reporter here.
|
||||||
|
pub fn install_crash_handler() {}
|
||||||
|
|
||||||
|
// —— Miniplayer window (see mini.rs) ——————————————————————————————————————
|
||||||
|
|
||||||
|
/// The miniplayer stays inside the main window's page here (PlayerOverlay).
|
||||||
|
pub const SEPARATE_MINI: bool = false;
|
||||||
|
|
||||||
|
pub fn host_handle<R: Runtime>(_: &WebviewWindow<R>) -> Option<isize> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn style_mini_window(_: isize) {}
|
||||||
|
|
||||||
|
pub fn show_inactive(_: isize) {}
|
||||||
|
|
||||||
|
pub fn hide_window(_: isize) {}
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,14 @@
|
||||||
//! Each platform file exposes the same items:
|
//! Each platform file exposes the same items:
|
||||||
//!
|
//!
|
||||||
//! - `VideoSurface`: composes mpv's output beneath the web view
|
//! - `VideoSurface`: composes mpv's output beneath the web view
|
||||||
//! (`create`, `mpv_options`, `on_property`, `show`, `fit`).
|
//! (`create`, `mpv_options`, `start`, `on_property`, `show`, `fit`, `set_rect`).
|
||||||
//! - `SURFACE_PROPERTIES`: mpv properties the surface observes.
|
//! - `SURFACE_PROPERTIES`: mpv properties the surface observes.
|
||||||
//! - `MPV_LIBRARIES`: libmpv file names to look for.
|
//! - `MPV_LIBRARIES`: libmpv file names to look for.
|
||||||
//! - `hold_awake`: prevents display sleep until the receiver closes.
|
//! - `hold_awake`: prevents display sleep until the receiver closes.
|
||||||
|
//! - `gpu_names`: the graphics adapters, by name.
|
||||||
|
//! - `device_name`, `os_version`: how the computer identifies itself to Plex.
|
||||||
|
//! - `set_window_buttons`: shows or hides native window buttons (macOS).
|
||||||
|
//! - `write_dump`, `install_crash_handler`: hang and crash dumps (Windows).
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
mod windows;
|
mod windows;
|
||||||
|
|
|
||||||
|
|
@ -10,11 +10,19 @@ use ::windows::Win32::UI::WindowsAndMessaging::GetClientRect;
|
||||||
use crate::mpv::Mpv;
|
use crate::mpv::Mpv;
|
||||||
|
|
||||||
pub struct VideoSurface {
|
pub struct VideoSurface {
|
||||||
|
/// The window showing the video now: the main window, or the miniplayer's
|
||||||
|
/// (`set_host`). Window handles are kept so fitting needn't ask the UI
|
||||||
|
/// thread for them (Tauri's `hwnd()` waits on the UI thread elsewhere).
|
||||||
|
hwnd: HWND,
|
||||||
|
main: HWND,
|
||||||
attached: usize,
|
attached: usize,
|
||||||
device: IDCompositionDevice,
|
device: IDCompositionDevice,
|
||||||
_target: IDCompositionTarget,
|
/// One composition target per window the video has been shown in.
|
||||||
|
targets: Vec<(isize, IDCompositionTarget)>,
|
||||||
root: IDCompositionVisual,
|
root: IDCompositionVisual,
|
||||||
visible: bool,
|
visible: bool,
|
||||||
|
/// Where the video is drawn, in client pixels; `None` fills the window.
|
||||||
|
rect: Option<(i32, i32, i32, i32)>,
|
||||||
pub width: i32,
|
pub width: i32,
|
||||||
pub height: i32,
|
pub height: i32,
|
||||||
}
|
}
|
||||||
|
|
@ -42,13 +50,15 @@ impl VideoSurface {
|
||||||
let root = device.CreateVisual().map_err(|e| e.to_string())?;
|
let root = device.CreateVisual().map_err(|e| e.to_string())?;
|
||||||
let (width, height) = client_size(hwnd);
|
let (width, height) = client_size(hwnd);
|
||||||
device.Commit().map_err(|e| e.to_string())?;
|
device.Commit().map_err(|e| e.to_string())?;
|
||||||
let _ = ⌖
|
|
||||||
Ok(VideoSurface {
|
Ok(VideoSurface {
|
||||||
|
hwnd,
|
||||||
|
main: hwnd,
|
||||||
attached: 0,
|
attached: 0,
|
||||||
device,
|
device,
|
||||||
_target: target,
|
targets: vec![(hwnd.0 as isize, target)],
|
||||||
root,
|
root,
|
||||||
visible: false,
|
visible: false,
|
||||||
|
rect: None,
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
})
|
})
|
||||||
|
|
@ -66,6 +76,11 @@ impl VideoSurface {
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Nothing to set up once mpv is initialized: it creates its swapchain itself.
|
||||||
|
pub fn start(&mut self, _: &std::sync::Arc<Mpv>) -> Result<(), String> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn on_property(&mut self, name: &str, value: &serde_json::Value) {
|
pub fn on_property(&mut self, name: &str, value: &serde_json::Value) {
|
||||||
if name == "display-swapchain" {
|
if name == "display-swapchain" {
|
||||||
self.attach(value.as_i64().unwrap_or(0) as usize);
|
self.attach(value.as_i64().unwrap_or(0) as usize);
|
||||||
|
|
@ -91,20 +106,69 @@ impl VideoSurface {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn show(&mut self, visible: bool) {
|
fn target(&self, hwnd: HWND) -> Option<&IDCompositionTarget> {
|
||||||
|
self.targets.iter().find(|(h, _)| *h == hwnd.0 as isize).map(|(_, t)| t)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn show<R: Runtime>(&mut self, _: &WebviewWindow<R>, visible: bool) {
|
||||||
if self.visible == visible {
|
if self.visible == visible {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
self.visible = visible;
|
self.visible = visible;
|
||||||
unsafe {
|
if let Some(target) = self.target(self.hwnd) {
|
||||||
let _ = if visible { self._target.SetRoot(&self.root) } else { self._target.SetRoot(None::<&IDCompositionVisual>) };
|
unsafe {
|
||||||
let _ = self.device.Commit();
|
let _ = if visible { target.SetRoot(&self.root) } else { target.SetRoot(None::<&IDCompositionVisual>) };
|
||||||
|
let _ = self.device.Commit();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fit<R: Runtime>(&mut self, window: &WebviewWindow<R>, mpv: Option<&Mpv>) {
|
/// Moves the video to another window (the miniplayer's, a raw `HWND`), or
|
||||||
let Ok(h) = window.hwnd() else { return };
|
/// back to the main window with `None`, filling its client area. Both
|
||||||
let (w, h) = client_size(HWND(h.0 as _));
|
/// changes go out in one commit, so the video is never shown twice.
|
||||||
|
pub fn set_host(&mut self, host: Option<isize>, mpv: Option<&Mpv>) -> Result<(), String> {
|
||||||
|
let next = host.map(|h| HWND(h as _)).unwrap_or(self.main);
|
||||||
|
if next == self.hwnd {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
unsafe {
|
||||||
|
if self.target(next).is_none() {
|
||||||
|
// Behind the window's children (its web view), as in the main window.
|
||||||
|
let target = self.device.CreateTargetForHwnd(next, false).map_err(|e| e.to_string())?;
|
||||||
|
self.targets.push((next.0 as isize, target));
|
||||||
|
}
|
||||||
|
if self.visible {
|
||||||
|
if let Some(old) = self.target(self.hwnd) {
|
||||||
|
let _ = old.SetRoot(None::<&IDCompositionVisual>);
|
||||||
|
}
|
||||||
|
if let Some(new) = self.target(next) {
|
||||||
|
let _ = new.SetRoot(&self.root);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.hwnd = next;
|
||||||
|
self.rect = None;
|
||||||
|
self.fit_host(mpv);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Matches mpv's composition size and the visual's position to the
|
||||||
|
/// window's client area, or to the miniplayer rectangle when one is set.
|
||||||
|
pub fn fit<R: Runtime>(&mut self, _: &WebviewWindow<R>, mpv: Option<&Mpv>) {
|
||||||
|
self.fit_host(mpv);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fit_host(&mut self, mpv: Option<&Mpv>) {
|
||||||
|
let (cw, ch) = client_size(self.hwnd);
|
||||||
|
let (x, y, w, h) = match self.rect {
|
||||||
|
Some((x, y, w, h)) => (x, y, w.max(16), h.max(16)),
|
||||||
|
None => (0, 0, cw, ch),
|
||||||
|
};
|
||||||
|
unsafe {
|
||||||
|
let _ = self.root.SetOffsetX2(x as f32);
|
||||||
|
let _ = self.root.SetOffsetY2(y as f32);
|
||||||
|
let _ = self.device.Commit();
|
||||||
|
}
|
||||||
if (w, h) == (self.width, self.height) {
|
if (w, h) == (self.width, self.height) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -114,6 +178,11 @@ impl VideoSurface {
|
||||||
let _ = mpv.set_property("d3d11-composition-size", &serde_json::Value::String(format!("{w}x{h}")));
|
let _ = mpv.set_property("d3d11-composition-size", &serde_json::Value::String(format!("{w}x{h}")));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn set_rect<R: Runtime>(&mut self, window: &WebviewWindow<R>, mpv: Option<&Mpv>, rect: Option<(i32, i32, i32, i32)>) {
|
||||||
|
self.rect = rect;
|
||||||
|
self.fit(window, mpv);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// mpv properties the surface needs to observe.
|
/// mpv properties the surface needs to observe.
|
||||||
|
|
@ -122,6 +191,188 @@ pub const SURFACE_PROPERTIES: &[&str] = &["display-swapchain"];
|
||||||
/// File names libmpv may have on this platform.
|
/// File names libmpv may have on this platform.
|
||||||
pub const MPV_LIBRARIES: &[&str] = &["libmpv-2.dll", "mpv-2.dll"];
|
pub const MPV_LIBRARIES: &[&str] = &["libmpv-2.dll", "mpv-2.dll"];
|
||||||
|
|
||||||
|
/// Hardware graphics adapters as DXGI names them (e.g. "NVIDIA GeForce RTX 4080").
|
||||||
|
pub fn gpu_names() -> Vec<String> {
|
||||||
|
use ::windows::Win32::Graphics::Dxgi::*;
|
||||||
|
let mut names = Vec::new();
|
||||||
|
unsafe {
|
||||||
|
let Ok(factory) = CreateDXGIFactory1::<IDXGIFactory1>() else { return names };
|
||||||
|
let mut i = 0;
|
||||||
|
while let Ok(adapter) = factory.EnumAdapters1(i) {
|
||||||
|
i += 1;
|
||||||
|
let Ok(desc) = adapter.GetDesc1() else { continue };
|
||||||
|
if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let len = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
|
||||||
|
let name = String::from_utf16_lossy(&desc.Description[..len]);
|
||||||
|
if !names.contains(&name) {
|
||||||
|
names.push(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
names
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The computer's name, as Plex shows it.
|
||||||
|
pub fn device_name() -> String {
|
||||||
|
std::env::var("COMPUTERNAME").unwrap_or_else(|_| "Windows PC".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn os_version() -> String {
|
||||||
|
"11".into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Windows draws its own caption buttons in the page.
|
||||||
|
pub fn set_window_buttons<R: Runtime>(_: &WebviewWindow<R>, _: bool) {}
|
||||||
|
|
||||||
|
// —— Miniplayer window (see mini.rs) ——————————————————————————————————————
|
||||||
|
|
||||||
|
/// The miniplayer is a window of its own here: the video moves into it, so
|
||||||
|
/// dragging moves video and controls together.
|
||||||
|
pub const SEPARATE_MINI: bool = true;
|
||||||
|
|
||||||
|
/// The window's handle, for `VideoSurface::set_host`. Asks the UI thread, so
|
||||||
|
/// never call it while holding a lock the UI thread may wait on.
|
||||||
|
pub fn host_handle<R: Runtime>(window: &WebviewWindow<R>) -> Option<isize> {
|
||||||
|
window.hwnd().ok().map(|h| h.0 as isize)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rounded corners (Windows 11) and no activation on click, so the main
|
||||||
|
/// window keeps focus and its keyboard shortcuts while the miniplayer is used.
|
||||||
|
pub fn style_mini_window(hwnd: isize) {
|
||||||
|
use ::windows::Win32::Graphics::Dwm::{DwmSetWindowAttribute, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_ROUND};
|
||||||
|
use ::windows::Win32::UI::WindowsAndMessaging::{GetWindowLongPtrW, SetWindowLongPtrW, GWL_EXSTYLE, WS_EX_NOACTIVATE};
|
||||||
|
let hwnd = HWND(hwnd as _);
|
||||||
|
unsafe {
|
||||||
|
let preference = DWMWCP_ROUND;
|
||||||
|
let _ = DwmSetWindowAttribute(hwnd, DWMWA_WINDOW_CORNER_PREFERENCE, &preference as *const _ as *const c_void, std::mem::size_of_val(&preference) as u32);
|
||||||
|
let style = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
|
||||||
|
SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style | WS_EX_NOACTIVATE.0 as isize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shows a window without activating it (Tauri's `show` activates).
|
||||||
|
pub fn show_inactive(hwnd: isize) {
|
||||||
|
use ::windows::Win32::UI::WindowsAndMessaging::{ShowWindow, SW_SHOWNOACTIVATE};
|
||||||
|
unsafe {
|
||||||
|
let _ = ShowWindow(HWND(hwnd as _), SW_SHOWNOACTIVATE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hides a window shown by `show_inactive`. Tauri's `hide` would skip it: it
|
||||||
|
/// never saw the window shown, so believes it hidden already.
|
||||||
|
pub fn hide_window(hwnd: isize) {
|
||||||
|
use ::windows::Win32::UI::WindowsAndMessaging::{ShowWindow, SW_HIDE};
|
||||||
|
unsafe {
|
||||||
|
let _ = ShowWindow(HWND(hwnd as _), SW_HIDE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// —— Diagnostics (see diagnostics.rs) ————————————————————————————————————
|
||||||
|
|
||||||
|
use ::windows::Win32::System::Diagnostics::Debug::{
|
||||||
|
MiniDumpWithHandleData, MiniDumpWithThreadInfo, MiniDumpWithUnloadedModules, MiniDumpWriteDump, SetUnhandledExceptionFilter,
|
||||||
|
EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, MINIDUMP_EXCEPTION_INFORMATION, MINIDUMP_TYPE,
|
||||||
|
};
|
||||||
|
use ::windows::Win32::System::Threading::{GetCurrentProcess, GetCurrentProcessId, GetCurrentThreadId};
|
||||||
|
use std::os::windows::io::AsRawHandle;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
|
|
||||||
|
/// Every thread's stack and state, the loaded and unloaded modules and the
|
||||||
|
/// open handles: what a hang or crash needs, in a few megabytes.
|
||||||
|
const DUMP_TYPE: MINIDUMP_TYPE = MINIDUMP_TYPE(MiniDumpWithThreadInfo.0 | MiniDumpWithHandleData.0 | MiniDumpWithUnloadedModules.0);
|
||||||
|
|
||||||
|
fn write_dump_with(path: &Path, exception: Option<*const EXCEPTION_POINTERS>) -> Result<(), String> {
|
||||||
|
let file = std::fs::File::create(path).map_err(|e| e.to_string())?;
|
||||||
|
let info = exception.map(|pointers| MINIDUMP_EXCEPTION_INFORMATION {
|
||||||
|
ThreadId: unsafe { GetCurrentThreadId() },
|
||||||
|
ExceptionPointers: pointers as *mut _,
|
||||||
|
ClientPointers: false.into(),
|
||||||
|
});
|
||||||
|
let file_handle = ::windows::Win32::Foundation::HANDLE(file.as_raw_handle());
|
||||||
|
unsafe {
|
||||||
|
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), file_handle, DUMP_TYPE, info.as_ref().map(|i| i as *const _), None, None)
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dumps this process as it is now (the hang watchdog's snapshot).
|
||||||
|
pub fn write_dump(path: &Path) -> Result<(), String> {
|
||||||
|
write_dump_with(path, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "access violation at libmpv-2.dll+0x1234 (0xC0000005)", for the log.
|
||||||
|
unsafe fn describe(pointers: *const EXCEPTION_POINTERS) -> String {
|
||||||
|
use ::windows::Win32::Foundation::HMODULE;
|
||||||
|
use ::windows::Win32::System::LibraryLoader::*;
|
||||||
|
let Some(record) = (*pointers).ExceptionRecord.as_ref() else { return "unknown exception".into() };
|
||||||
|
let code = record.ExceptionCode.0 as u32;
|
||||||
|
let address = record.ExceptionAddress as usize;
|
||||||
|
let mut module = HMODULE::default();
|
||||||
|
let place = if GetModuleHandleExW(
|
||||||
|
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||||
|
::windows::core::PCWSTR(address as *const u16),
|
||||||
|
&mut module,
|
||||||
|
)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
let mut name = [0u16; 260];
|
||||||
|
let len = GetModuleFileNameW(Some(module), &mut name) as usize;
|
||||||
|
let path = String::from_utf16_lossy(&name[..len]);
|
||||||
|
let file = path.rsplit('\\').next().unwrap_or(&path).to_string();
|
||||||
|
format!("{file}+{:#x}", address - module.0 as usize)
|
||||||
|
} else {
|
||||||
|
format!("{address:#x}")
|
||||||
|
};
|
||||||
|
let what = match code {
|
||||||
|
0xC000_0005 => "access violation",
|
||||||
|
0xC000_00FD => "stack overflow",
|
||||||
|
0xC000_0409 => "fail-fast (security check)",
|
||||||
|
0xC000_001D => "illegal instruction",
|
||||||
|
0xC000_0094 => "integer division by zero",
|
||||||
|
_ => "exception",
|
||||||
|
};
|
||||||
|
format!("{what} at {place} ({code:#010X})")
|
||||||
|
}
|
||||||
|
|
||||||
|
static PREVIOUS_FILTER: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
static CRASHED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
unsafe extern "system" fn on_crash(pointers: *const EXCEPTION_POINTERS) -> i32 {
|
||||||
|
if !CRASHED.swap(true, Ordering::SeqCst) {
|
||||||
|
let what = describe(pointers);
|
||||||
|
match crate::diagnostics::dump_path("crash") {
|
||||||
|
Some(path) => match write_dump_with(&path, Some(pointers)) {
|
||||||
|
Ok(()) => crate::diagnostics::log(&format!("crash: {what}; wrote {}", path.display())),
|
||||||
|
Err(e) => crate::diagnostics::log(&format!("crash: {what}; no dump: {e}")),
|
||||||
|
},
|
||||||
|
None => crate::diagnostics::log(&format!("crash: {what}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Then whatever handled it before (Windows Error Reporting by default).
|
||||||
|
match PREVIOUS_FILTER.load(Ordering::SeqCst) {
|
||||||
|
0 => EXCEPTION_CONTINUE_SEARCH,
|
||||||
|
previous => {
|
||||||
|
let previous: unsafe extern "system" fn(*const EXCEPTION_POINTERS) -> i32 = std::mem::transmute(previous);
|
||||||
|
previous(pointers)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes a dump when the process is about to die of an unhandled exception.
|
||||||
|
/// Called again once libmpv is loaded, in case its runtime replaced it.
|
||||||
|
pub fn install_crash_handler() {
|
||||||
|
unsafe {
|
||||||
|
if let Some(previous) = SetUnhandledExceptionFilter(Some(on_crash)) {
|
||||||
|
if previous as usize != on_crash as *const () as usize {
|
||||||
|
PREVIOUS_FILTER.store(previous as usize, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Keeps the display awake until `rx` closes or receives.
|
/// Keeps the display awake until `rx` closes or receives.
|
||||||
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
|
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
|
||||||
use ::windows::Win32::System::Power::*;
|
use ::windows::Win32::System::Power::*;
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,10 @@ use tauri::{AppHandle, Emitter, Manager, Runtime, WebviewWindow};
|
||||||
use crate::mpv::{self, Event, Mpv};
|
use crate::mpv::{self, Event, Mpv};
|
||||||
use crate::platform::VideoSurface;
|
use crate::platform::VideoSurface;
|
||||||
|
|
||||||
|
/// Both locks are taken by commands on background threads, and some window
|
||||||
|
/// calls made while holding them (Tauri's getters, such as `hwnd()`) wait for
|
||||||
|
/// the UI thread to answer. So the UI thread must never wait on these locks:
|
||||||
|
/// window events hand their work to a background thread (lib.rs).
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct PlayerState {
|
pub struct PlayerState {
|
||||||
mpv: Mutex<Option<Arc<Mpv>>>,
|
mpv: Mutex<Option<Arc<Mpv>>>,
|
||||||
|
|
@ -60,6 +64,8 @@ fn emit<R: Runtime>(app: &AppHandle<R>, payload: Value) {
|
||||||
fn create_player<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindow<R>, opts: &InitOptions) -> Result<Arc<Mpv>, String> {
|
fn create_player<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindow<R>, opts: &InitOptions) -> Result<Arc<Mpv>, String> {
|
||||||
let resource_dir = app.path().resource_dir().ok();
|
let resource_dir = app.path().resource_dir().ok();
|
||||||
let mpv = Mpv::load(&mpv::library_candidates(resource_dir))?;
|
let mpv = Mpv::load(&mpv::library_candidates(resource_dir))?;
|
||||||
|
// libmpv's runtime may install its own crash filter as it loads; ours goes back on top.
|
||||||
|
crate::platform::install_crash_handler();
|
||||||
let surface = VideoSurface::create(window)?;
|
let surface = VideoSurface::create(window)?;
|
||||||
let render_options = surface.mpv_options();
|
let render_options = surface.mpv_options();
|
||||||
*app.state::<PlayerState>().surface.lock() = Some(surface);
|
*app.state::<PlayerState>().surface.lock() = Some(surface);
|
||||||
|
|
@ -71,7 +77,9 @@ fn create_player<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindow<R>, opts
|
||||||
set("hwdec", opts.hwdec.as_deref().unwrap_or("auto-safe"))?;
|
set("hwdec", opts.hwdec.as_deref().unwrap_or("auto-safe"))?;
|
||||||
set("keep-open", "yes")?;
|
set("keep-open", "yes")?;
|
||||||
set("idle", "yes")?;
|
set("idle", "yes")?;
|
||||||
set("force-window", "yes")?;
|
if !render_options.iter().any(|(k, _)| *k == "force-window") {
|
||||||
|
set("force-window", "yes")?;
|
||||||
|
}
|
||||||
set("osc", "no")?;
|
set("osc", "no")?;
|
||||||
set("osd-level", "0")?;
|
set("osd-level", "0")?;
|
||||||
set("input-default-bindings", "no")?;
|
set("input-default-bindings", "no")?;
|
||||||
|
|
@ -91,6 +99,14 @@ fn create_player<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindow<R>, opts
|
||||||
set("hr-seek", "yes")?;
|
set("hr-seek", "yes")?;
|
||||||
set("background-color", "#000000")?;
|
set("background-color", "#000000")?;
|
||||||
set("user-agent", "Kaleido")?;
|
set("user-agent", "Kaleido")?;
|
||||||
|
// Keep compiled shaders between runs: translating the larger upscaling
|
||||||
|
// shaders for Direct3D can take seconds, and should only happen once.
|
||||||
|
if let Ok(dir) = app.path().app_cache_dir() {
|
||||||
|
let dir = dir.join("shader-cache");
|
||||||
|
if std::fs::create_dir_all(&dir).is_ok() {
|
||||||
|
let _ = set("gpu-shader-cache-dir", &dir.to_string_lossy());
|
||||||
|
}
|
||||||
|
}
|
||||||
if opts.hdr.unwrap_or(true) {
|
if opts.hdr.unwrap_or(true) {
|
||||||
let _ = set("target-colorspace-hint", "yes");
|
let _ = set("target-colorspace-hint", "yes");
|
||||||
}
|
}
|
||||||
|
|
@ -99,6 +115,9 @@ fn create_player<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindow<R>, opts
|
||||||
}
|
}
|
||||||
mpv.request_log_messages("warn");
|
mpv.request_log_messages("warn");
|
||||||
mpv.initialize()?;
|
mpv.initialize()?;
|
||||||
|
if let Some(surface) = app.state::<PlayerState>().surface.lock().as_mut() {
|
||||||
|
surface.start(&mpv)?;
|
||||||
|
}
|
||||||
for (i, name) in OBSERVED.iter().chain(crate::platform::SURFACE_PROPERTIES).enumerate() {
|
for (i, name) in OBSERVED.iter().chain(crate::platform::SURFACE_PROPERTIES).enumerate() {
|
||||||
mpv.observe(i as u64 + 1, name);
|
mpv.observe(i as u64 + 1, name);
|
||||||
}
|
}
|
||||||
|
|
@ -161,13 +180,29 @@ fn player<R: Runtime>(app: &AppHandle<R>) -> Result<Arc<Mpv>, String> {
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn player_init<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, options: Option<InitOptions>) -> Result<(), String> {
|
pub async fn player_init<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, options: Option<InitOptions>) -> Result<(), String> {
|
||||||
let state = app.state::<PlayerState>();
|
let state = app.state::<PlayerState>();
|
||||||
let mut guard = state.mpv.lock();
|
{
|
||||||
if guard.is_none() {
|
let mut guard = state.mpv.lock();
|
||||||
*guard = Some(create_player(&app, &window, &options.unwrap_or_default())?);
|
if guard.is_none() {
|
||||||
|
*guard = Some(create_player(&app, &window, &options.unwrap_or_default())?);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
// Outside the lock: creating a window waits on the UI thread.
|
||||||
|
crate::mini::prepare(&app);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Moves the video into another window (the miniplayer's, mini.rs) or back to
|
||||||
|
/// the main one. Off the UI thread only (it takes the player's locks).
|
||||||
|
pub fn set_video_host<R: Runtime>(app: &AppHandle<R>, host: Option<isize>) -> Result<(), String> {
|
||||||
|
let state = app.state::<PlayerState>();
|
||||||
|
let mpv = state.mpv.lock().clone();
|
||||||
|
let mut surface = state.surface.lock();
|
||||||
|
match surface.as_mut() {
|
||||||
|
Some(surface) => surface.set_host(host, mpv.as_deref()),
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn player_show<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, visible: bool) -> Result<(), String> {
|
pub async fn player_show<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, visible: bool) -> Result<(), String> {
|
||||||
let state = app.state::<PlayerState>();
|
let state = app.state::<PlayerState>();
|
||||||
|
|
@ -175,7 +210,29 @@ pub async fn player_show<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>
|
||||||
let mut surface = state.surface.lock();
|
let mut surface = state.surface.lock();
|
||||||
if let Some(surface) = surface.as_mut() {
|
if let Some(surface) = surface.as_mut() {
|
||||||
surface.fit(&window, mpv.as_deref());
|
surface.fit(&window, mpv.as_deref());
|
||||||
surface.show(visible);
|
surface.show(&window, visible);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct VideoRect {
|
||||||
|
x: f64,
|
||||||
|
y: f64,
|
||||||
|
width: f64,
|
||||||
|
height: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Draws the video in a rectangle of the window (physical pixels), for the
|
||||||
|
/// miniplayer; `None` fills the window again.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_rect<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, rect: Option<VideoRect>) -> Result<(), String> {
|
||||||
|
let state = app.state::<PlayerState>();
|
||||||
|
let mpv = state.mpv.lock().clone();
|
||||||
|
let mut surface = state.surface.lock();
|
||||||
|
if let Some(surface) = surface.as_mut() {
|
||||||
|
let rect = rect.map(|r| (r.x.round() as i32, r.y.round() as i32, r.width.round() as i32, r.height.round() as i32));
|
||||||
|
surface.set_rect(&window, mpv.as_deref(), rect);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
@ -195,6 +252,13 @@ pub async fn player_get<R: Runtime>(app: AppHandle<R>, name: String) -> Result<V
|
||||||
player(&app)?.get_property(&name)
|
player(&app)?.get_property(&name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Shows or hides the native window buttons where the OS draws them (the
|
||||||
|
/// macOS traffic lights fade with the player's controls).
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn window_buttons<R: Runtime>(window: WebviewWindow<R>, visible: bool) {
|
||||||
|
crate::platform::set_window_buttons(&window, visible);
|
||||||
|
}
|
||||||
|
|
||||||
/// Keeps the video surface matched to the window's client area.
|
/// Keeps the video surface matched to the window's client area.
|
||||||
pub fn on_resize<R: Runtime>(window: &WebviewWindow<R>) {
|
pub fn on_resize<R: Runtime>(window: &WebviewWindow<R>) {
|
||||||
let app = window.app_handle();
|
let app = window.app_handle();
|
||||||
|
|
|
||||||
|
|
@ -13,9 +13,14 @@ fn entry(key: &str) -> Result<keyring::Entry, String> {
|
||||||
keyring::Entry::new(SERVICE, key).map_err(|e| e.to_string())
|
keyring::Entry::new(SERVICE, key).map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Secrets (Plex tokens) live in Windows Credential Manager, never in plain files.
|
/// Secrets (Plex tokens) live in the OS's credential store (Windows Credential
|
||||||
|
/// Manager, the macOS Keychain), never in plain files; except in macOS debug
|
||||||
|
/// builds, see `dev_secrets`.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn secret_get(key: String) -> Result<Option<String>, String> {
|
pub fn secret_get<R: Runtime>(app: AppHandle<R>, key: String) -> Result<Option<String>, String> {
|
||||||
|
if let Some(path) = dev_secrets(&app) {
|
||||||
|
return Ok(read_dev_secrets(&path).get(&key).and_then(|v| v.as_str()).map(String::from));
|
||||||
|
}
|
||||||
match entry(&key)?.get_password() {
|
match entry(&key)?.get_password() {
|
||||||
Ok(v) => Ok(Some(v)),
|
Ok(v) => Ok(Some(v)),
|
||||||
Err(keyring::Error::NoEntry) => Ok(None),
|
Err(keyring::Error::NoEntry) => Ok(None),
|
||||||
|
|
@ -24,18 +29,66 @@ pub fn secret_get(key: String) -> Result<Option<String>, String> {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn secret_set(key: String, value: String) -> Result<(), String> {
|
pub fn secret_set<R: Runtime>(app: AppHandle<R>, key: String, value: String) -> Result<(), String> {
|
||||||
entry(&key)?.set_password(&value).map_err(|e| e.to_string())
|
if let Some(path) = dev_secrets(&app) {
|
||||||
|
let mut all = read_dev_secrets(&path);
|
||||||
|
all.insert(key, Value::String(value));
|
||||||
|
return write_dev_secrets(&path, &all);
|
||||||
|
}
|
||||||
|
let entry = entry(&key)?;
|
||||||
|
match entry.set_password(&value) {
|
||||||
|
Ok(()) => Ok(()),
|
||||||
|
// A Keychain item left by a differently signed build can be impossible to
|
||||||
|
// update yet still block adding; replacing it recovers.
|
||||||
|
Err(keyring::Error::PlatformFailure(_)) if cfg!(target_os = "macos") => {
|
||||||
|
let _ = entry.delete_credential();
|
||||||
|
entry.set_password(&value).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
Err(e) => Err(e.to_string()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn secret_delete(key: String) -> Result<(), String> {
|
pub fn secret_delete<R: Runtime>(app: AppHandle<R>, key: String) -> Result<(), String> {
|
||||||
|
if let Some(path) = dev_secrets(&app) {
|
||||||
|
let mut all = read_dev_secrets(&path);
|
||||||
|
all.remove(&key);
|
||||||
|
return write_dev_secrets(&path, &all);
|
||||||
|
}
|
||||||
match entry(&key)?.delete_credential() {
|
match entry(&key)?.delete_credential() {
|
||||||
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
|
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
|
||||||
Err(e) => Err(e.to_string()),
|
Err(e) => Err(e.to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// macOS ties Keychain access to the app's code signature, and every debug
|
||||||
|
/// build is a new unsigned binary, so the Keychain would ask for permission
|
||||||
|
/// after each rebuild. Debug builds there keep secrets in a private file in the
|
||||||
|
/// app data folder instead (development only, like the `.env` sign-in).
|
||||||
|
fn dev_secrets<R: Runtime>(app: &AppHandle<R>) -> Option<std::path::PathBuf> {
|
||||||
|
if !(cfg!(debug_assertions) && cfg!(target_os = "macos")) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
app.path().app_data_dir().ok().map(|d| d.join("dev-secrets.json"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_dev_secrets(path: &std::path::Path) -> serde_json::Map<String, Value> {
|
||||||
|
std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_dev_secrets(path: &std::path::Path, all: &serde_json::Map<String, Value>) -> Result<(), String> {
|
||||||
|
use std::io::Write;
|
||||||
|
if let Some(dir) = path.parent() {
|
||||||
|
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
let mut options = std::fs::OpenOptions::new();
|
||||||
|
options.write(true).create(true).truncate(true);
|
||||||
|
#[cfg(unix)]
|
||||||
|
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||||
|
let mut file = options.open(path).map_err(|e| e.to_string())?;
|
||||||
|
file.write_all(Value::Object(all.clone()).to_string().as_bytes()).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct AppInfo {
|
pub struct AppInfo {
|
||||||
|
|
@ -43,7 +96,10 @@ pub struct AppInfo {
|
||||||
data_dir: String,
|
data_dir: String,
|
||||||
default_download_dir: String,
|
default_download_dir: String,
|
||||||
platform: String,
|
platform: String,
|
||||||
|
os_version: String,
|
||||||
device_name: String,
|
device_name: String,
|
||||||
|
/// Graphics adapters by name (decides which upscaling tiers are offered).
|
||||||
|
gpus: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
|
@ -61,7 +117,9 @@ pub fn app_info<R: Runtime>(app: AppHandle<R>) -> AppInfo {
|
||||||
data_dir: data,
|
data_dir: data,
|
||||||
default_download_dir: downloads,
|
default_download_dir: downloads,
|
||||||
platform: std::env::consts::OS.to_string(),
|
platform: std::env::consts::OS.to_string(),
|
||||||
device_name: std::env::var("COMPUTERNAME").unwrap_or_else(|_| "Windows PC".into()),
|
os_version: crate::platform::os_version(),
|
||||||
|
device_name: crate::platform::device_name(),
|
||||||
|
gpus: crate::platform::gpu_names(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "Kaleido",
|
"productName": "Kaleido",
|
||||||
"version": "0.1.0-beta.1",
|
"version": "1.0.1",
|
||||||
"identifier": "tv.kaleido.desktop",
|
"identifier": "tv.kaleido.desktop",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "npm run dev",
|
"beforeDevCommand": "npm run dev",
|
||||||
|
|
@ -31,15 +31,21 @@
|
||||||
"csp": null,
|
"csp": null,
|
||||||
"assetProtocol": {
|
"assetProtocol": {
|
||||||
"enable": true,
|
"enable": true,
|
||||||
"scope": [
|
"scope": {
|
||||||
"**"
|
"allow": [
|
||||||
]
|
"**"
|
||||||
|
],
|
||||||
|
"requireLiteralLeadingDot": false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"bundle": {
|
"bundle": {
|
||||||
"active": true,
|
"active": true,
|
||||||
"createUpdaterArtifacts": true,
|
"createUpdaterArtifacts": true,
|
||||||
|
"resources": {
|
||||||
|
"shaders/*": "shaders/"
|
||||||
|
},
|
||||||
"icon": [
|
"icon": [
|
||||||
"icons/32x32.png",
|
"icons/32x32.png",
|
||||||
"icons/128x128.png",
|
"icons/128x128.png",
|
||||||
|
|
@ -55,7 +61,7 @@
|
||||||
},
|
},
|
||||||
"plugins": {
|
"plugins": {
|
||||||
"updater": {
|
"updater": {
|
||||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEU0MTA2RjI0OUFFQzU1QzUKUldURlZleWFKRzhRNUlqTTR3U095STFYS3BsUXd2UnZMYlRrQmt3aUk5YU5WSjdqcUxVcHllU1EK",
|
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEUxQjk1OTExMzBCRTRENEUKUldST1RiNHdFVm01NFFMQ1EvYm9CYlhhNU9jNTZXb254dVZOQW8relJYRlQ4ZjdLQll3cHR3VE4K",
|
||||||
"endpoints": [
|
"endpoints": [
|
||||||
"https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/raw/branch/main/updates/latest.json"
|
"https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/raw/branch/main/updates/latest.json"
|
||||||
]
|
]
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,39 @@
|
||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
|
"app": {
|
||||||
|
"windows": [
|
||||||
|
{
|
||||||
|
"label": "main",
|
||||||
|
"title": "Kaleido",
|
||||||
|
"width": 1480,
|
||||||
|
"height": 900,
|
||||||
|
"minWidth": 900,
|
||||||
|
"minHeight": 580,
|
||||||
|
"center": true,
|
||||||
|
"decorations": true,
|
||||||
|
"titleBarStyle": "Overlay",
|
||||||
|
"hiddenTitle": true,
|
||||||
|
"trafficLightPosition": { "x": 22, "y": 35 },
|
||||||
|
"backgroundColor": "#090a0c",
|
||||||
|
"transparent": false,
|
||||||
|
"shadow": true,
|
||||||
|
"visible": false,
|
||||||
|
"dragDropEnabled": false
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
"bundle": {
|
"bundle": {
|
||||||
"targets": [
|
"targets": [
|
||||||
"app",
|
"app",
|
||||||
"dmg"
|
"dmg"
|
||||||
],
|
],
|
||||||
"macOS": {
|
"macOS": {
|
||||||
"minimumSystemVersion": "12.0",
|
"minimumSystemVersion": "26.0",
|
||||||
"frameworks": [
|
"signingIdentity": "-",
|
||||||
"../vendor/mpv/macos/libmpv.2.dylib"
|
"hardenedRuntime": false,
|
||||||
]
|
"files": {
|
||||||
|
"Frameworks": "../vendor/mpv/macos"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ import { PageLoader } from '../ui/primitives';
|
||||||
import { Splash } from '../screens/Splash';
|
import { Splash } from '../screens/Splash';
|
||||||
import { SignIn } from '../screens/SignIn';
|
import { SignIn } from '../screens/SignIn';
|
||||||
import { ServerPicker } from '../screens/ServerPicker';
|
import { ServerPicker } from '../screens/ServerPicker';
|
||||||
import { win } from '../platform/native';
|
import { isMac, isNative, win } from '../platform/native';
|
||||||
import { usePlayer } from '../player/store';
|
import { usePlayer } from '../player/store';
|
||||||
import { PlayerOverlay } from '../player/PlayerOverlay';
|
import { PlayerOverlay } from '../player/PlayerOverlay';
|
||||||
import { DialogHost } from '../screens/dialogs/DialogHost';
|
import { DialogHost } from '../screens/dialogs/DialogHost';
|
||||||
|
|
@ -33,7 +33,7 @@ function Screen({ route }: { route: Route }) {
|
||||||
case 'home':
|
case 'home':
|
||||||
return <Home />;
|
return <Home />;
|
||||||
case 'section':
|
case 'section':
|
||||||
return <SectionScreen kind={route.kind} tab={route.tab} />;
|
return <SectionScreen kind={route.kind} tab={route.tab} genre={route.genre} genreTitle={route.genreTitle} />;
|
||||||
case 'item':
|
case 'item':
|
||||||
return <ItemScreen id={route.id} />;
|
return <ItemScreen id={route.id} />;
|
||||||
case 'person':
|
case 'person':
|
||||||
|
|
@ -94,23 +94,26 @@ function Page({ onScrolled }: { onScrolled: (top: number) => void }) {
|
||||||
function useGlobalShortcuts() {
|
function useGlobalShortcuts() {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const isTyping = (t: EventTarget | null) => t instanceof HTMLElement && (t.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName));
|
const isTyping = (t: EventTarget | null) => t instanceof HTMLElement && (t.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName));
|
||||||
|
const playerFull = () => usePlayer.getState().open && !usePlayer.getState().mini;
|
||||||
const onKey = (e: KeyboardEvent) => {
|
const onKey = (e: KeyboardEvent) => {
|
||||||
if (usePlayer.getState().open) return;
|
if (playerFull()) return;
|
||||||
if ((e.ctrlKey || e.metaKey) && (e.key === 'k' || e.key === 'f')) {
|
if ((e.ctrlKey || e.metaKey) && (e.key === 'k' || e.key === 'f')) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
navigate({ name: 'search' });
|
navigate({ name: 'search' });
|
||||||
} else if (e.altKey && e.key === 'ArrowLeft') {
|
} else if ((e.altKey && e.key === 'ArrowLeft') || (isMac && e.metaKey && e.key === '[')) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
useRouter.getState().back();
|
useRouter.getState().back();
|
||||||
} else if (e.altKey && e.key === 'ArrowRight') {
|
} else if ((e.altKey && e.key === 'ArrowRight') || (isMac && e.metaKey && e.key === ']')) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
useRouter.getState().forward();
|
useRouter.getState().forward();
|
||||||
} else if (e.key === 'F11') {
|
} else if (e.key === 'F11' || (isMac && e.metaKey && e.ctrlKey && e.key.toLowerCase() === 'f')) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
win.isFullscreen().then((fs) => win.setFullscreen(!fs));
|
win.isFullscreen().then((fs) => win.setFullscreen(!fs));
|
||||||
} else if ((e.key === 'Escape' || e.key === 'Backspace') && !isTyping(e.target) && !document.querySelector('.menu-layer, .dialog-layer')) {
|
} else if ((e.key === 'Escape' || e.key === 'Backspace') && !isTyping(e.target) && !document.querySelector('.menu-layer, .dialog-layer')) {
|
||||||
if (e.key === 'Escape' && document.fullscreenElement) return;
|
if (e.key === 'Escape' && document.fullscreenElement) return;
|
||||||
useRouter.getState().back();
|
// Esc leaves full screen first (kept from the player when it went to the corner).
|
||||||
|
if (e.key === 'Escape' && isNative) win.isFullscreen().then((fs) => (fs ? win.setFullscreen(false) : useRouter.getState().back()));
|
||||||
|
else useRouter.getState().back();
|
||||||
} else if ((e.ctrlKey || e.metaKey) && e.key === ',') {
|
} else if ((e.ctrlKey || e.metaKey) && e.key === ',') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
navigate({ name: 'settings', mode: 'app', tab: 'general' });
|
navigate({ name: 'settings', mode: 'app', tab: 'general' });
|
||||||
|
|
@ -118,7 +121,7 @@ function useGlobalShortcuts() {
|
||||||
};
|
};
|
||||||
// Mouse back/forward buttons.
|
// Mouse back/forward buttons.
|
||||||
const onMouse = (e: MouseEvent) => {
|
const onMouse = (e: MouseEvent) => {
|
||||||
if (usePlayer.getState().open) return;
|
if (playerFull()) return;
|
||||||
if (e.button === 3) {
|
if (e.button === 3) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
useRouter.getState().back();
|
useRouter.getState().back();
|
||||||
|
|
@ -144,7 +147,7 @@ function useLibrarySync() {
|
||||||
let last = '';
|
let last = '';
|
||||||
let stopped = false;
|
let stopped = false;
|
||||||
const tick = async () => {
|
const tick = async () => {
|
||||||
if (stopped || document.hidden || usePlayer.getState().open) return;
|
if (stopped || document.hidden || (usePlayer.getState().open && !usePlayer.getState().mini)) return;
|
||||||
try {
|
try {
|
||||||
const rev = await libraryRevision(server);
|
const rev = await libraryRevision(server);
|
||||||
if (last && rev !== last) invalidateLibrary();
|
if (last && rev !== last) invalidateLibrary();
|
||||||
|
|
@ -167,7 +170,7 @@ function useLibrarySync() {
|
||||||
|
|
||||||
function Shell() {
|
function Shell() {
|
||||||
const [scrolled, setScrolled] = useState(false);
|
const [scrolled, setScrolled] = useState(false);
|
||||||
const playerOpen = usePlayer((s) => s.open);
|
const playerOpen = usePlayer((s) => s.open && !s.mini);
|
||||||
const startPage = useSettings.getState().startPage;
|
const startPage = useSettings.getState().startPage;
|
||||||
useGlobalShortcuts();
|
useGlobalShortcuts();
|
||||||
useLibrarySync();
|
useLibrarySync();
|
||||||
|
|
@ -224,7 +227,16 @@ export function App() {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
useSession.getState().init();
|
useSession.getState().init();
|
||||||
// The window appears once the first frame is painted (no white flash).
|
// The window appears once the first frame is painted (no white flash).
|
||||||
requestAnimationFrame(() => win.show());
|
// WKWebView runs no animation frames until its window is shown, so a
|
||||||
|
// timeout stands in there.
|
||||||
|
let shown = false;
|
||||||
|
const show = () => {
|
||||||
|
if (!shown) win.show();
|
||||||
|
shown = true;
|
||||||
|
};
|
||||||
|
requestAnimationFrame(show);
|
||||||
|
const fallback = setTimeout(show, 150);
|
||||||
|
return () => clearTimeout(fallback);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ import { useSettings } from './settings';
|
||||||
import { Icon } from '../ui/Icon';
|
import { Icon } from '../ui/Icon';
|
||||||
import { KaleidoMark } from '../ui/primitives';
|
import { KaleidoMark } from '../ui/primitives';
|
||||||
import { openMenu, type MenuItem } from '../ui/overlays';
|
import { openMenu, type MenuItem } from '../ui/overlays';
|
||||||
import { isNative, win } from '../platform/native';
|
import { isMac, isNative, shortcut, win } from '../platform/native';
|
||||||
import { useDownloads } from '../downloads/store';
|
import { useDownloads } from '../downloads/store';
|
||||||
import { useHomeUsers } from './useHomeUsers';
|
import { useHomeUsers } from './useHomeUsers';
|
||||||
|
|
||||||
|
|
@ -16,25 +16,40 @@ const NAV = [
|
||||||
{ id: 'downloads', label: 'Downloads', route: { name: 'downloads' } as const },
|
{ id: 'downloads', label: 'Downloads', route: { name: 'downloads' } as const },
|
||||||
];
|
];
|
||||||
|
|
||||||
function WindowControls() {
|
/** Caption buttons drawn by the page; macOS shows its own traffic lights instead. */
|
||||||
|
export function WindowControls() {
|
||||||
const [maximized, setMaximized] = useState(false);
|
const [maximized, setMaximized] = useState(false);
|
||||||
|
const [fullscreen, setFullscreen] = useState(false);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isNative) return;
|
if (!isNative || isMac) return;
|
||||||
let off: (() => void) | undefined;
|
let off: (() => void) | undefined;
|
||||||
const sync = () => win.isMaximized().then(setMaximized);
|
let gone = false;
|
||||||
|
const sync = () => {
|
||||||
|
win.isMaximized().then((m) => !gone && setMaximized(m));
|
||||||
|
win.isFullscreen().then((f) => !gone && setFullscreen(f));
|
||||||
|
};
|
||||||
sync();
|
sync();
|
||||||
win.onResized(sync).then((u) => (off = u));
|
win.onResized(sync).then((u) => (gone ? u() : (off = u)));
|
||||||
return () => off?.();
|
return () => {
|
||||||
|
gone = true;
|
||||||
|
off?.();
|
||||||
|
};
|
||||||
}, []);
|
}, []);
|
||||||
if (!isNative) return null;
|
if (!isNative || isMac) return null;
|
||||||
return (
|
return (
|
||||||
<div className="window-controls">
|
<div className="window-controls">
|
||||||
<button aria-label="Minimize" onClick={() => win.minimize()}>
|
<button aria-label="Minimize" onClick={() => win.minimize()}>
|
||||||
<Icon name="minimize" size={15} strokeWidth={1.4} />
|
<Icon name="minimize" size={15} strokeWidth={1.4} />
|
||||||
</button>
|
</button>
|
||||||
<button aria-label={maximized ? 'Restore' : 'Maximize'} onClick={() => win.toggleMaximize()}>
|
{fullscreen ? (
|
||||||
<Icon name={maximized ? 'restore' : 'maximize'} size={13} strokeWidth={1.4} />
|
<button aria-label="Exit full screen" title="Exit full screen (Esc)" onClick={() => win.setFullscreen(false)}>
|
||||||
</button>
|
<Icon name="collapse" size={14} strokeWidth={1.4} />
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button aria-label={maximized ? 'Restore' : 'Maximize'} onClick={() => win.toggleMaximize()}>
|
||||||
|
<Icon name={maximized ? 'restore' : 'maximize'} size={13} strokeWidth={1.4} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button aria-label="Close" className="close" onClick={() => win.close()}>
|
<button aria-label="Close" className="close" onClick={() => win.close()}>
|
||||||
<Icon name="x" size={15} strokeWidth={1.4} />
|
<Icon name="x" size={15} strokeWidth={1.4} />
|
||||||
</button>
|
</button>
|
||||||
|
|
@ -67,11 +82,8 @@ function Avatar() {
|
||||||
submenu: home.users.map((u) => ({ label: u.title, checked: u.uuid === user?.uuid, onSelect: () => home.switchTo(u) })),
|
submenu: home.users.map((u) => ({ label: u.title, checked: u.uuid === user?.uuid, onSelect: () => home.switchTo(u) })),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
items.push(
|
// Settings has its own button in the bar; the menu keeps account actions.
|
||||||
{ divider: true },
|
if (server?.owned) items.push({ divider: true }, { label: 'Server dashboard', icon: 'activity', onSelect: () => navigate({ name: 'settings', mode: 'server', tab: 'dashboard' }) });
|
||||||
{ label: 'Settings', icon: 'settings', onSelect: () => navigate({ name: 'settings', mode: 'app', tab: 'general' }) },
|
|
||||||
);
|
|
||||||
if (server?.owned) items.push({ label: 'Server dashboard', icon: 'activity', onSelect: () => navigate({ name: 'settings', mode: 'server', tab: 'dashboard' }) });
|
|
||||||
items.push({ divider: true }, { label: 'Sign out', icon: 'logout', onSelect: signOut });
|
items.push({ divider: true }, { label: 'Sign out', icon: 'logout', onSelect: signOut });
|
||||||
openMenu(items, el, { align: 'end', minWidth: 250 });
|
openMenu(items, el, { align: 'end', minWidth: 250 });
|
||||||
};
|
};
|
||||||
|
|
@ -112,7 +124,7 @@ export function TopBar({ solid }: { solid: boolean }) {
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
<div className="topbar-right" data-tauri-drag-region>
|
<div className="topbar-right" data-tauri-drag-region>
|
||||||
<button className={`icon-btn${active === 'search' ? ' on' : ''}`} aria-label="Search" title="Search (Ctrl+K)" onClick={() => navigate({ name: 'search' })}>
|
<button className={`icon-btn${active === 'search' ? ' on' : ''}`} aria-label="Search" title={`Search (${shortcut('K')})`} onClick={() => navigate({ name: 'search' })}>
|
||||||
<Icon name="search" size={19} />
|
<Icon name="search" size={19} />
|
||||||
</button>
|
</button>
|
||||||
<button className={`icon-btn${active === 'settings' ? ' on' : ''}`} aria-label="Settings" title="Settings" onClick={() => navigate({ name: 'settings', mode: 'app', tab: 'general' })}>
|
<button className={`icon-btn${active === 'settings' ? ' on' : ''}`} aria-label="Settings" title="Settings" onClick={() => navigate({ name: 'settings', mode: 'app', tab: 'general' })}>
|
||||||
|
|
|
||||||
|
|
@ -36,10 +36,19 @@ export function progress(item: Item): number {
|
||||||
return Math.min(1, Math.max(0, item.viewOffset / item.duration));
|
return Math.min(1, Math.max(0, item.viewOffset / item.duration));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Watched once Plex has counted a full play. A rewatch left partway through keeps the
|
||||||
|
* title watched; its position only matters for resuming (`resumable`).
|
||||||
|
*/
|
||||||
export function isWatched(item: Item, percent = 90): boolean {
|
export function isWatched(item: Item, percent = 90): boolean {
|
||||||
if (item.type === 'show' || item.type === 'season') return item.leafCount > 0 && item.viewedLeafCount >= item.leafCount;
|
if (item.type === 'show' || item.type === 'season') return item.leafCount > 0 && item.viewedLeafCount >= item.leafCount;
|
||||||
if (item.viewOffset > 0 && item.duration > 0) return item.viewCount > 0 && item.viewOffset / item.duration >= percent / 100;
|
if (item.viewCount > 0) return true;
|
||||||
return item.viewCount > 0;
|
return item.viewOffset > 0 && item.duration > 0 && item.viewOffset / item.duration >= percent / 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Has a saved position worth resuming from (not one at the very end). */
|
||||||
|
export function resumable(item: Item): boolean {
|
||||||
|
return item.viewOffset > 0 && item.duration > 0 && item.viewOffset < item.duration * 0.97;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function remainingEpisodes(item: Item): number {
|
export function remainingEpisodes(item: Item): number {
|
||||||
|
|
@ -174,17 +183,24 @@ export function plural(n: number, word: string, pluralWord = `${word}s`) {
|
||||||
return `${n.toLocaleString()} ${n === 1 ? word : pluralWord}`;
|
return `${n.toLocaleString()} ${n === 1 ? word : pluralWord}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Hex UltraBlur colors → CSS gradient layers for the artwork colour wash. */
|
/** Hex UltraBlur colors → the wash's four corner colours, each at its own strength. */
|
||||||
export function washGradient(u: Item['ultraBlur'], strength = 1): string {
|
export function washColors(u: Item['ultraBlur'], strength = 1) {
|
||||||
if (!u) return '';
|
if (!u) return null;
|
||||||
const c = (hex: string, a: number) => {
|
const c = (hex: string, a: number) => {
|
||||||
const n = parseInt(hex, 16);
|
const n = parseInt(hex, 16);
|
||||||
return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${(a * strength).toFixed(3)})`;
|
return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${(a * strength).toFixed(3)})`;
|
||||||
};
|
};
|
||||||
|
return { topRight: c(u.topRight, 0.95), topLeft: c(u.topLeft, 0.7), bottomRight: c(u.bottomRight, 0.55), bottomLeft: c(u.bottomLeft, 0.45) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hex UltraBlur colors → CSS gradient layers for the artwork colour wash. */
|
||||||
|
export function washGradient(u: Item['ultraBlur'], strength = 1): string {
|
||||||
|
const c = washColors(u, strength);
|
||||||
|
if (!c) return '';
|
||||||
return [
|
return [
|
||||||
`radial-gradient(ellipse at 100% 0%, ${c(u.topRight, 0.95)} 0%, transparent 62%)`,
|
`radial-gradient(ellipse at 100% 0%, ${c.topRight} 0%, transparent 62%)`,
|
||||||
`radial-gradient(ellipse at 0% 0%, ${c(u.topLeft, 0.7)} 0%, transparent 55%)`,
|
`radial-gradient(ellipse at 0% 0%, ${c.topLeft} 0%, transparent 55%)`,
|
||||||
`radial-gradient(ellipse at 100% 100%, ${c(u.bottomRight, 0.55)} 0%, transparent 60%)`,
|
`radial-gradient(ellipse at 100% 100%, ${c.bottomRight} 0%, transparent 60%)`,
|
||||||
`radial-gradient(ellipse at 0% 100%, ${c(u.bottomLeft, 0.45)} 0%, transparent 60%)`,
|
`radial-gradient(ellipse at 0% 100%, ${c.bottomLeft} 0%, transparent 60%)`,
|
||||||
].join(', ');
|
].join(', ');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,9 @@
|
||||||
/**
|
/**
|
||||||
* Arrow-key movement between titles, for keyboard users. Focus moves to the
|
* Arrow-key movement between titles, for keyboard users. Focus moves to the
|
||||||
* nearest card in the pressed direction (by on-screen geometry), so it works
|
* nearest card in the pressed direction (by on-screen geometry), so it works
|
||||||
* the same across shelves, grids, episode lists and people rows.
|
* the same across shelves, grids and people rows.
|
||||||
*/
|
*/
|
||||||
const TARGETS = '.card, .person-card:not(:disabled), .episode-row, .shelf-title-link';
|
const TARGETS = '.card, .person-card:not(:disabled), .shelf-title-link';
|
||||||
|
|
||||||
function center(r: DOMRect) {
|
function center(r: DOMRect) {
|
||||||
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { QueryClient, useQuery, type UseQueryOptions } from '@tanstack/react-query';
|
import { QueryClient, useQuery, type UseQueryOptions } from '@tanstack/react-query';
|
||||||
import * as api from '../plex/api';
|
import * as api from '../plex/api';
|
||||||
import type { Item, Section } from '../plex/types';
|
import type { Item, Section } from '../plex/types';
|
||||||
import { useServer } from './session';
|
import { useServer, useSession } from './session';
|
||||||
import { useSettings } from './settings';
|
import { useSettings } from './settings';
|
||||||
|
|
||||||
export const queryClient = new QueryClient({
|
export const queryClient = new QueryClient({
|
||||||
|
|
@ -15,6 +15,25 @@ export const queryClient = new QueryClient({
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Watch state changes from other Plex apps too (a TV, a phone), so the queries that show
|
||||||
|
* it refresh when Kaleido comes back into view and, for the progress rows, every minute
|
||||||
|
* while it is on screen. Polling pauses while the window is hidden or minimised.
|
||||||
|
*/
|
||||||
|
export const WATCH_STATE = { refetchOnWindowFocus: true } as const;
|
||||||
|
export const PROGRESS = { ...WATCH_STATE, staleTime: 15_000, refetchInterval: 60_000 } as const;
|
||||||
|
|
||||||
|
// React Query treats a visibility change as focus. Switching back to Kaleido from another
|
||||||
|
// app doesn't change visibility, so a window focus counts as well.
|
||||||
|
window.addEventListener('focus', () => queryClient.getQueryCache().onFocus());
|
||||||
|
|
||||||
|
// Keys carry the server but not the account, and another account (or a Home profile) on
|
||||||
|
// the same server sees different watch state and libraries. Whenever the credentials
|
||||||
|
// behind the connection change, nothing cached under the old ones may be shown.
|
||||||
|
useSession.subscribe((st, prev) => {
|
||||||
|
if (prev.server && st.server !== prev.server && st.server?.token !== prev.server.token) queryClient.clear();
|
||||||
|
});
|
||||||
|
|
||||||
/** Every key starts with the server so switching servers never mixes caches. */
|
/** Every key starts with the server so switching servers never mixes caches. */
|
||||||
export function useKey(...parts: unknown[]) {
|
export function useKey(...parts: unknown[]) {
|
||||||
const server = useServer();
|
const server = useServer();
|
||||||
|
|
@ -37,9 +56,9 @@ export function useSectionFor(kind: 'movie' | 'show'): { section: Section | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useItem = (id: string | undefined, opts: Partial<UseQueryOptions<Item>> = {}) =>
|
export const useItem = (id: string | undefined, opts: Partial<UseQueryOptions<Item>> = {}) =>
|
||||||
useServerQuery(['item', id], (s) => api.metadata(s, id!), { enabled: !!id, staleTime: 30_000, ...opts });
|
useServerQuery(['item', id], (s) => api.metadata(s, id!), { enabled: !!id, staleTime: 30_000, ...WATCH_STATE, ...opts });
|
||||||
|
|
||||||
export const useChildren = (id: string | undefined) => useServerQuery(['children', id], (s) => api.children(s, id!), { enabled: !!id, staleTime: 30_000 });
|
export const useChildren = (id: string | undefined) => useServerQuery(['children', id], (s) => api.children(s, id!), { enabled: !!id, staleTime: 30_000, ...WATCH_STATE });
|
||||||
|
|
||||||
export const useRelated = (id: string | undefined) => useServerQuery(['related', id], (s) => api.related(s, id!), { enabled: !!id, staleTime: 10 * 60_000 });
|
export const useRelated = (id: string | undefined) => useServerQuery(['related', id], (s) => api.related(s, id!), { enabled: !!id, staleTime: 10 * 60_000 });
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,11 @@
|
||||||
import { create } from 'zustand';
|
import { create } from 'zustand';
|
||||||
|
|
||||||
export type SectionKind = 'movie' | 'show';
|
export type SectionKind = 'movie' | 'show';
|
||||||
export type SectionTab = 'discover' | 'library' | 'collections';
|
export type SectionTab = 'discover' | 'library' | 'categories';
|
||||||
|
|
||||||
export type Route =
|
export type Route =
|
||||||
| { name: 'home' }
|
| { name: 'home' }
|
||||||
| { name: 'section'; kind: SectionKind; tab: SectionTab }
|
| { name: 'section'; kind: SectionKind; tab: SectionTab; genre?: string; genreTitle?: string }
|
||||||
| { name: 'item'; id: string; title?: string }
|
| { name: 'item'; id: string; title?: string }
|
||||||
| { name: 'person'; id: string; title: string; thumb?: string }
|
| { name: 'person'; id: string; title: string; thumb?: string }
|
||||||
| { name: 'hub'; key: string; title: string }
|
| { name: 'hub'; key: string; title: string }
|
||||||
|
|
|
||||||
|
|
@ -54,7 +54,7 @@ export const useSession = create<SessionState>((set, get) => ({
|
||||||
|
|
||||||
async init() {
|
async init() {
|
||||||
const info = await appInfo();
|
const info = await appInfo();
|
||||||
configureClient({ version: info.version, deviceName: info.deviceName });
|
configureClient({ version: info.version, deviceName: info.deviceName, platformVersion: info.osVersion });
|
||||||
let token = await secrets.get('account-token');
|
let token = await secrets.get('account-token');
|
||||||
const stored = loadStoredServer();
|
const stored = loadStoredServer();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,10 @@ import { persist } from 'zustand/middleware';
|
||||||
export type Quality = 'original' | '2160' | '1080' | '720' | '480';
|
export type Quality = 'original' | '2160' | '1080' | '720' | '480';
|
||||||
export type SkipMode = 'off' | 'button' | 'auto';
|
export type SkipMode = 'off' | 'button' | 'auto';
|
||||||
export type SubtitleMode = 'auto' | 'always' | 'forced' | 'off';
|
export type SubtitleMode = 'auto' | 'always' | 'forced' | 'off';
|
||||||
|
export type SubtitleEdge = 'outline' | 'shadow' | 'raised' | 'none';
|
||||||
|
export type SubtitleBox = 'none' | 'translucent' | 'solid';
|
||||||
|
export type SubtitlePosition = 'low' | 'normal' | 'high';
|
||||||
|
export type Upscaling = 'off' | 'performance' | 'balanced' | 'quality';
|
||||||
|
|
||||||
export interface Preferences {
|
export interface Preferences {
|
||||||
// Playback
|
// Playback
|
||||||
|
|
@ -15,14 +19,25 @@ export interface Preferences {
|
||||||
countdownSeconds: number;
|
countdownSeconds: number;
|
||||||
skipIntro: SkipMode;
|
skipIntro: SkipMode;
|
||||||
skipCredits: SkipMode;
|
skipCredits: SkipMode;
|
||||||
|
/** Seconds a "Skip automatically" marker waits, so it can be cancelled; 0 skips at once. */
|
||||||
|
autoSkipDelay: number;
|
||||||
watchedPercent: number;
|
watchedPercent: number;
|
||||||
audioLanguage: string;
|
audioLanguage: string;
|
||||||
subtitleMode: SubtitleMode;
|
subtitleMode: SubtitleMode;
|
||||||
subtitleLanguage: string;
|
subtitleLanguage: string;
|
||||||
subtitleScale: number;
|
subtitleScale: number;
|
||||||
subtitleBackground: boolean;
|
subtitleColor: string;
|
||||||
|
subtitleEdge: SubtitleEdge;
|
||||||
|
subtitleBox: SubtitleBox;
|
||||||
|
subtitleBold: boolean;
|
||||||
|
subtitlePosition: SubtitlePosition;
|
||||||
volume: number;
|
volume: number;
|
||||||
seekStep: number;
|
seekStep: number;
|
||||||
|
/** Video enhancement, chosen in the player, and its optional stages. */
|
||||||
|
upscaling: Upscaling;
|
||||||
|
enhanceDeband: boolean;
|
||||||
|
enhanceSharpen: boolean;
|
||||||
|
enhanceDenoise: boolean;
|
||||||
// Interface
|
// Interface
|
||||||
startPage: 'home' | 'movies' | 'shows';
|
startPage: 'home' | 'movies' | 'shows';
|
||||||
colorWash: boolean;
|
colorWash: boolean;
|
||||||
|
|
@ -49,14 +64,23 @@ export const defaults: Preferences = {
|
||||||
countdownSeconds: 8,
|
countdownSeconds: 8,
|
||||||
skipIntro: 'button',
|
skipIntro: 'button',
|
||||||
skipCredits: 'button',
|
skipCredits: 'button',
|
||||||
|
autoSkipDelay: 5,
|
||||||
watchedPercent: 90,
|
watchedPercent: 90,
|
||||||
audioLanguage: '',
|
audioLanguage: '',
|
||||||
subtitleMode: 'auto',
|
subtitleMode: 'auto',
|
||||||
subtitleLanguage: '',
|
subtitleLanguage: '',
|
||||||
subtitleScale: 1,
|
subtitleScale: 1,
|
||||||
subtitleBackground: false,
|
subtitleColor: '#FFFFFF',
|
||||||
|
subtitleEdge: 'outline',
|
||||||
|
subtitleBox: 'none',
|
||||||
|
subtitleBold: false,
|
||||||
|
subtitlePosition: 'normal',
|
||||||
volume: 100,
|
volume: 100,
|
||||||
seekStep: 10,
|
seekStep: 10,
|
||||||
|
upscaling: 'off',
|
||||||
|
enhanceDeband: true,
|
||||||
|
enhanceSharpen: true,
|
||||||
|
enhanceDenoise: true,
|
||||||
startPage: 'home',
|
startPage: 'home',
|
||||||
colorWash: true,
|
colorWash: true,
|
||||||
reducedMotion: false,
|
reducedMotion: false,
|
||||||
|
|
@ -82,7 +106,19 @@ export const useSettings = create<SettingsState>()(
|
||||||
set: (key, value) => set({ [key]: value } as Partial<SettingsState>),
|
set: (key, value) => set({ [key]: value } as Partial<SettingsState>),
|
||||||
reset: () => set({ ...defaults }),
|
reset: () => set({ ...defaults }),
|
||||||
}),
|
}),
|
||||||
{ name: 'kaleido.settings', version: 1 },
|
{
|
||||||
|
name: 'kaleido.settings',
|
||||||
|
version: 2,
|
||||||
|
migrate: (persisted, version) => {
|
||||||
|
const p = (persisted ?? {}) as Record<string, unknown>;
|
||||||
|
// 1 → 2: the subtitle background switch became a box style.
|
||||||
|
if (version < 2 && 'subtitleBackground' in p) {
|
||||||
|
p.subtitleBox = p.subtitleBackground ? 'translucent' : 'none';
|
||||||
|
delete p.subtitleBackground;
|
||||||
|
}
|
||||||
|
return p as unknown as SettingsState;
|
||||||
|
},
|
||||||
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -100,3 +136,22 @@ export const QUALITY_PROFILE: Record<Exclude<Quality, 'original'>, { kbps: numbe
|
||||||
'720': { kbps: 4000, width: 1280, height: 720 },
|
'720': { kbps: 4000, width: 1280, height: 720 },
|
||||||
'480': { kbps: 1500, width: 854, height: 480 },
|
'480': { kbps: 1500, width: 854, height: 480 },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const SUBTITLE_COLORS: { value: string; label: string }[] = [
|
||||||
|
{ value: '#FFFFFF', label: 'White' },
|
||||||
|
{ value: '#FFE14D', label: 'Yellow' },
|
||||||
|
{ value: '#7FE3F0', label: 'Cyan' },
|
||||||
|
{ value: '#9BE58A', label: 'Green' },
|
||||||
|
{ value: '#F4A6D7', label: 'Pink' },
|
||||||
|
{ value: '#BFC5CA', label: 'Grey' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Bottom margin in mpv's scaled pixels (720 = window height). */
|
||||||
|
export const SUBTITLE_MARGIN: Record<SubtitlePosition, number> = { low: 14, normal: 34, high: 80 };
|
||||||
|
|
||||||
|
export const UPSCALING: Record<Upscaling, { label: string; detail: string }> = {
|
||||||
|
off: { label: 'Off', detail: 'mpv’s standard scaling' },
|
||||||
|
performance: { label: 'Performance', detail: 'Sharp scaling, debanding and light sharpening' },
|
||||||
|
balanced: { label: 'Balanced', detail: 'Light denoising, neural upscaling (FSRCNNX 16), colour reconstruction, debanding and sharpening' },
|
||||||
|
quality: { label: 'Quality', detail: 'NVIDIA RTX Video Super Resolution: AI upscaling that also cleans up compression. SDR video; HDR uses Balanced' },
|
||||||
|
};
|
||||||
|
|
|
||||||
|
|
@ -52,12 +52,16 @@ function sanitize(s: string) {
|
||||||
return s.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').trim() || 'Untitled';
|
return s.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').trim() || 'Untitled';
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Trims metadata kept for offline display: no extras, related hubs or raw blobs. */
|
/**
|
||||||
function slim(raw: any) {
|
* Trims metadata kept for offline display: no extras, related hubs or raw blobs, and
|
||||||
|
* only the version downloaded, so its streams describe the file that plays.
|
||||||
|
*/
|
||||||
|
function slim(raw: any, mediaIndex: number) {
|
||||||
const { Extras, Related, OnDeck, ...rest } = raw ?? {};
|
const { Extras, Related, OnDeck, ...rest } = raw ?? {};
|
||||||
void Extras;
|
void Extras;
|
||||||
void Related;
|
void Related;
|
||||||
void OnDeck;
|
void OnDeck;
|
||||||
|
if (Array.isArray(rest.Media) && rest.Media[mediaIndex]) rest.Media = [rest.Media[mediaIndex]];
|
||||||
return rest;
|
return rest;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -102,9 +106,12 @@ export const useDownloads = create<DownloadsState>((set, get) => ({
|
||||||
try {
|
try {
|
||||||
await get().init();
|
await get().init();
|
||||||
const item = await api.metadata(server, input.id);
|
const item = await api.metadata(server, input.id);
|
||||||
const media = item.media[0];
|
// A download is one file. A version split across several (CD1, CD2) would be
|
||||||
|
// kept as its first part only, so prefer a version in one piece.
|
||||||
|
const media = item.media.find((m) => m.parts.length === 1) ?? item.media[0];
|
||||||
const part = media?.parts[0];
|
const part = media?.parts[0];
|
||||||
if (!part) throw new Error('This title has no downloadable file.');
|
if (!part) throw new Error('This title has no downloadable file.');
|
||||||
|
if (media.parts.length > 1) throw new Error('This title is split across several files, which Kaleido can’t download yet.');
|
||||||
const id = get().idFor(item.id);
|
const id = get().idFor(item.id);
|
||||||
if (get().items.some((d) => d.id === id && d.status !== 'failed')) {
|
if (get().items.some((d) => d.id === id && d.status !== 'failed')) {
|
||||||
toast('This title is already in Downloads.');
|
toast('This title is already in Downloads.');
|
||||||
|
|
@ -129,7 +136,7 @@ export const useDownloads = create<DownloadsState>((set, get) => ({
|
||||||
url: server.signed(part.key, { download: 1 }),
|
url: server.signed(part.key, { download: 1 }),
|
||||||
folder,
|
folder,
|
||||||
fileName: sanitize(baseName),
|
fileName: sanitize(baseName),
|
||||||
meta: { serverId: server.machineId, serverName: server.name, ratingKey: item.id, partKey: part.key, raw: slim(item.raw) } satisfies DownloadMeta,
|
meta: { serverId: server.machineId, serverName: server.name, ratingKey: item.id, partKey: part.key, raw: slim(item.raw, item.media.indexOf(media)) } satisfies DownloadMeta,
|
||||||
assets,
|
assets,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
|
||||||
13
src/main.tsx
|
|
@ -12,8 +12,10 @@ import { useSession } from './app/session';
|
||||||
import { useRouter } from './app/router';
|
import { useRouter } from './app/router';
|
||||||
import { usePlayer } from './player/store';
|
import { usePlayer } from './player/store';
|
||||||
import { useSettings } from './app/settings';
|
import { useSettings } from './app/settings';
|
||||||
|
import { useDownloads } from './downloads/store';
|
||||||
|
import { hostOS, isMac, isNative, win } from './platform/native';
|
||||||
|
|
||||||
if (import.meta.env.DEV) (window as any).__kaleido = { useSession, useRouter, usePlayer, useSettings };
|
if (import.meta.env.DEV) (window as any).__kaleido = { useSession, useRouter, usePlayer, useSettings, useDownloads };
|
||||||
|
|
||||||
// No browser context menu or text-selection chrome outside inputs: this is an app.
|
// No browser context menu or text-selection chrome outside inputs: this is an app.
|
||||||
window.addEventListener('contextmenu', (e) => {
|
window.addEventListener('contextmenu', (e) => {
|
||||||
|
|
@ -23,6 +25,15 @@ window.addEventListener('contextmenu', (e) => {
|
||||||
|
|
||||||
installKeyboardNav();
|
installKeyboardNav();
|
||||||
|
|
||||||
|
// Platform styling: macOS keeps its traffic lights at the top left, except in
|
||||||
|
// full screen, where the system hides them.
|
||||||
|
document.documentElement.classList.add(`os-${hostOS}`);
|
||||||
|
if (isNative && isMac) {
|
||||||
|
const syncFullscreen = () => win.isFullscreen().then((fs) => document.documentElement.classList.toggle('window-fullscreen', fs));
|
||||||
|
syncFullscreen();
|
||||||
|
win.onResized(syncFullscreen);
|
||||||
|
}
|
||||||
|
|
||||||
createRoot(document.getElementById('root')!).render(
|
createRoot(document.getElementById('root')!).render(
|
||||||
<StrictMode>
|
<StrictMode>
|
||||||
<App />
|
<App />
|
||||||
|
|
|
||||||
153
src/mini/main.tsx
Normal file
|
|
@ -0,0 +1,153 @@
|
||||||
|
/**
|
||||||
|
* The miniplayer window's page (mini.html; src-tauri/src/mini.rs). The video
|
||||||
|
* is drawn beneath this transparent page by the native side; this page draws
|
||||||
|
* the controls, mirrors the main window's player (src/player/miniWindow.ts)
|
||||||
|
* and sends its buttons back. Dragging moves the whole window natively.
|
||||||
|
*/
|
||||||
|
import { StrictMode, useEffect, useState, type PointerEvent as ReactPointerEvent } from 'react';
|
||||||
|
import { createRoot } from 'react-dom/client';
|
||||||
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
|
import { emitTo, listen } from '@tauri-apps/api/event';
|
||||||
|
import '@fontsource-variable/inter';
|
||||||
|
import '../styles/base.css';
|
||||||
|
import '../styles/ui.css';
|
||||||
|
import '../styles/player.css';
|
||||||
|
import './mini.css';
|
||||||
|
import { Icon } from '../ui/Icon';
|
||||||
|
import { MINI_CORNER_KEY, type MiniAction, type MiniState } from './types';
|
||||||
|
|
||||||
|
const send = (type: MiniAction) => emitTo('main', 'mini:action', { type }).catch(() => {});
|
||||||
|
|
||||||
|
window.addEventListener('contextmenu', (e) => e.preventDefault());
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drags the window: moves go to the native side one at a time, latest first
|
||||||
|
* (each is relative to where the drag began), and letting go glides it to a
|
||||||
|
* corner. A drag that ends over a button doesn't press it.
|
||||||
|
*/
|
||||||
|
function startDrag(e: ReactPointerEvent<HTMLElement>) {
|
||||||
|
if (e.button !== 0) return;
|
||||||
|
const el = e.currentTarget;
|
||||||
|
const pointer = e.pointerId;
|
||||||
|
const origin = { x: e.screenX, y: e.screenY };
|
||||||
|
const trail: { t: number; x: number; y: number }[] = [];
|
||||||
|
let dragging = false;
|
||||||
|
let started: Promise<unknown> | null = null;
|
||||||
|
let inFlight: Promise<unknown> | null = null;
|
||||||
|
let latest: { dx: number; dy: number } | null = null;
|
||||||
|
|
||||||
|
const pump = () => {
|
||||||
|
if (inFlight || !latest || !started) return;
|
||||||
|
const next = latest;
|
||||||
|
latest = null;
|
||||||
|
inFlight = started
|
||||||
|
.then(() => invoke('mini_drag', next))
|
||||||
|
.catch(() => {})
|
||||||
|
.finally(() => {
|
||||||
|
inFlight = null;
|
||||||
|
pump();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const move = (ev: PointerEvent) => {
|
||||||
|
const dx = ev.screenX - origin.x;
|
||||||
|
const dy = ev.screenY - origin.y;
|
||||||
|
trail.push({ t: ev.timeStamp, x: ev.screenX, y: ev.screenY });
|
||||||
|
while (trail.length > 2 && ev.timeStamp - trail[0].t > 100) trail.shift();
|
||||||
|
if (!dragging) {
|
||||||
|
if (Math.hypot(dx, dy) < 4) return;
|
||||||
|
dragging = true;
|
||||||
|
document.documentElement.classList.add('dragging');
|
||||||
|
el.setPointerCapture(pointer);
|
||||||
|
started = invoke('mini_drag_start').catch(() => {});
|
||||||
|
}
|
||||||
|
latest = { dx, dy };
|
||||||
|
pump();
|
||||||
|
};
|
||||||
|
|
||||||
|
const up = async () => {
|
||||||
|
window.removeEventListener('pointermove', move);
|
||||||
|
window.removeEventListener('pointerup', up);
|
||||||
|
window.removeEventListener('pointercancel', up);
|
||||||
|
if (!dragging) return;
|
||||||
|
document.documentElement.classList.remove('dragging');
|
||||||
|
const swallow = (c: MouseEvent) => {
|
||||||
|
c.stopPropagation();
|
||||||
|
c.preventDefault();
|
||||||
|
};
|
||||||
|
window.addEventListener('click', swallow, { capture: true, once: true });
|
||||||
|
setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0);
|
||||||
|
|
||||||
|
const first = trail[0];
|
||||||
|
const last = trail[trail.length - 1];
|
||||||
|
const dt = first && last ? Math.max(1, last.t - first.t) : 1;
|
||||||
|
const vx = first && last ? (last.x - first.x) / dt : 0;
|
||||||
|
const vy = first && last ? (last.y - first.y) / dt : 0;
|
||||||
|
// The last move lands before the glide begins.
|
||||||
|
while (inFlight || latest) await (inFlight ?? Promise.resolve(pump()));
|
||||||
|
const corner = await invoke<string>('mini_snap', { vx, vy }).catch(() => '');
|
||||||
|
if (corner) localStorage.setItem(MINI_CORNER_KEY, corner);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('pointermove', move);
|
||||||
|
window.addEventListener('pointerup', up);
|
||||||
|
window.addEventListener('pointercancel', up);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Mini() {
|
||||||
|
const [s, setS] = useState<MiniState | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const unlisten = listen<MiniState>('mini:state', (e) => setS(e.payload));
|
||||||
|
unlisten.then(() => send('ready'));
|
||||||
|
return () => void unlisten.then((f) => f());
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!s) return <div className="mini-player loading" />;
|
||||||
|
const pct = s.duration ? Math.min(100, (s.position / s.duration) * 100) : 0;
|
||||||
|
return (
|
||||||
|
<div className={`mini-player${s.loading || s.error ? ' loading' : ''}`} onPointerDown={startDrag} onDoubleClick={() => send('expand')}>
|
||||||
|
<div className="mini-scrim" />
|
||||||
|
<div className="mini-top">
|
||||||
|
<button className="mini-icon" aria-label="Back to full screen player" title="Expand" onClick={() => send('expand')}>
|
||||||
|
<Icon name="expand" size={17} />
|
||||||
|
</button>
|
||||||
|
<button className="mini-icon" aria-label="Stop playback" title="Close" onClick={() => send('close')}>
|
||||||
|
<Icon name="x" size={18} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="mini-center">
|
||||||
|
{(s.loading || s.buffering) && !s.error ? (
|
||||||
|
<span className="spinner" style={{ width: 30, height: 30 }} aria-label="Loading" />
|
||||||
|
) : s.error ? (
|
||||||
|
<span className="mini-error">Playback stopped</span>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<button className="mini-icon" aria-label="Back 10 seconds" onClick={() => send('back')}>
|
||||||
|
<Icon name="replay10" size={22} />
|
||||||
|
</button>
|
||||||
|
<button className="mini-icon big" aria-label={s.paused ? 'Play' : 'Pause'} onClick={() => send('toggle')}>
|
||||||
|
<Icon name={s.paused || s.ended ? 'play' : 'pause'} size={26} />
|
||||||
|
</button>
|
||||||
|
<button className="mini-icon" aria-label="Forward 10 seconds" onClick={() => send('forward')}>
|
||||||
|
<Icon name="forward10" size={22} />
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mini-caption">
|
||||||
|
<b>{s.title}</b>
|
||||||
|
{s.subtitle && <span>{s.subtitle}</span>}
|
||||||
|
</div>
|
||||||
|
<div className="mini-progress">
|
||||||
|
<i style={{ width: `${pct}%` }} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<Mini />
|
||||||
|
</StrictMode>,
|
||||||
|
);
|
||||||
32
src/mini/mini.css
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
/* The miniplayer window (mini.html): the page is transparent over the video
|
||||||
|
and the box fills the window, whose corners Windows rounds. */
|
||||||
|
html.mini-window,
|
||||||
|
html.mini-window body,
|
||||||
|
html.mini-window #root {
|
||||||
|
height: 100%;
|
||||||
|
margin: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
html.mini-window .mini-player {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
width: auto;
|
||||||
|
height: auto;
|
||||||
|
border-radius: 0;
|
||||||
|
box-shadow: none;
|
||||||
|
animation: none;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
html.mini-window.dragging .mini-player {
|
||||||
|
cursor: grabbing;
|
||||||
|
}
|
||||||
|
/* While dragged, the title stays and the buttons step back. */
|
||||||
|
html.mini-window.dragging .mini-scrim,
|
||||||
|
html.mini-window.dragging .mini-caption {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
html.mini-window.dragging .mini-top,
|
||||||
|
html.mini-window.dragging .mini-center {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
17
src/mini/types.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
/** What the miniplayer window shows, sent from the main window (src/player/miniWindow.ts). */
|
||||||
|
export interface MiniState {
|
||||||
|
title: string;
|
||||||
|
subtitle: string;
|
||||||
|
paused: boolean;
|
||||||
|
ended: boolean;
|
||||||
|
position: number;
|
||||||
|
duration: number;
|
||||||
|
loading: boolean;
|
||||||
|
buffering: boolean;
|
||||||
|
error: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Buttons and gestures in the miniplayer window, carried out by the main window's player. */
|
||||||
|
export type MiniAction = 'ready' | 'toggle' | 'back' | 'forward' | 'expand' | 'close';
|
||||||
|
|
||||||
|
export const MINI_CORNER_KEY = 'kaleido.miniCorner';
|
||||||
|
|
@ -7,6 +7,16 @@ import type { UnlistenFn } from '@tauri-apps/api/event';
|
||||||
|
|
||||||
export const isNative = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
|
export const isNative = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
|
||||||
|
|
||||||
|
/** The host OS, known synchronously from the web view (WebView2, WKWebView, WebKitGTK). */
|
||||||
|
export const hostOS: 'windows' | 'macos' | 'linux' =
|
||||||
|
typeof navigator !== 'undefined' && /Macintosh|Mac OS X/.test(navigator.userAgent) ? 'macos' : typeof navigator !== 'undefined' && /Linux|X11/.test(navigator.userAgent) ? 'linux' : 'windows';
|
||||||
|
export const isMac = hostOS === 'macos';
|
||||||
|
|
||||||
|
/** A shortcut with the platform's command key: "⌘K" on macOS, "Ctrl + K" elsewhere. */
|
||||||
|
export const shortcut = (key: string) => (isMac ? `⌘${key}` : `Ctrl + ${key}`);
|
||||||
|
/** How the window enters full screen from the keyboard. */
|
||||||
|
export const fullscreenShortcut = isMac ? '⌃⌘F' : 'F11';
|
||||||
|
|
||||||
export async function invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
|
export async function invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
|
||||||
if (!isNative) throw new Error(`${cmd} is only available in the desktop app.`);
|
if (!isNative) throw new Error(`${cmd} is only available in the desktop app.`);
|
||||||
const { invoke } = await import('@tauri-apps/api/core');
|
const { invoke } = await import('@tauri-apps/api/core');
|
||||||
|
|
@ -47,7 +57,10 @@ export interface AppInfo {
|
||||||
dataDir: string;
|
dataDir: string;
|
||||||
defaultDownloadDir: string;
|
defaultDownloadDir: string;
|
||||||
platform: string;
|
platform: string;
|
||||||
|
osVersion: string;
|
||||||
deviceName: string;
|
deviceName: string;
|
||||||
|
/** Graphics adapters by name (empty where not reported). */
|
||||||
|
gpus: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
let info: AppInfo | null = null;
|
let info: AppInfo | null = null;
|
||||||
|
|
@ -55,7 +68,7 @@ export async function appInfo(): Promise<AppInfo> {
|
||||||
if (info) return info;
|
if (info) return info;
|
||||||
info = isNative
|
info = isNative
|
||||||
? await invoke<AppInfo>('app_info')
|
? await invoke<AppInfo>('app_info')
|
||||||
: { version: '0.1.0-dev', dataDir: '', defaultDownloadDir: '', platform: 'browser', deviceName: 'Browser preview' };
|
: { version: '0.1.0-dev', dataDir: '', defaultDownloadDir: '', platform: 'browser', osVersion: '', deviceName: 'Browser preview', gpus: [] };
|
||||||
return info;
|
return info;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -105,6 +118,10 @@ export const win = {
|
||||||
await w.setFocus();
|
await w.setFocus();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
/** The OS's own window buttons (the macOS traffic lights); elsewhere the page draws them. */
|
||||||
|
async setButtonsVisible(visible: boolean) {
|
||||||
|
if (isNative && isMac) await invoke('window_buttons', { visible }).catch(() => {});
|
||||||
|
},
|
||||||
async onResized(cb: () => void): Promise<UnlistenFn> {
|
async onResized(cb: () => void): Promise<UnlistenFn> {
|
||||||
if (!isNative) {
|
if (!isNative) {
|
||||||
window.addEventListener('resize', cb);
|
window.addEventListener('resize', cb);
|
||||||
|
|
@ -156,6 +173,13 @@ export async function localFileUrl(path: string): Promise<string> {
|
||||||
return convertFileSrc(path);
|
return convertFileSrc(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Absolute path of a file bundled with the app (Tauri resources), or '' in a browser. */
|
||||||
|
export async function resourcePath(relative: string): Promise<string> {
|
||||||
|
if (!isNative) return '';
|
||||||
|
const { resolveResource } = await import('@tauri-apps/api/path');
|
||||||
|
return resolveResource(relative);
|
||||||
|
}
|
||||||
|
|
||||||
export function keepAwake(enabled: boolean) {
|
export function keepAwake(enabled: boolean) {
|
||||||
if (isNative) invoke('keep_awake', { enabled }).catch(() => {});
|
if (isNative) invoke('keep_awake', { enabled }).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,30 +1,56 @@
|
||||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
|
import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react';
|
||||||
import { usePlayer } from './store';
|
import { usePlayer } from './store';
|
||||||
import { useSession } from '../app/session';
|
import { useSession } from '../app/session';
|
||||||
import { useSettings, QUALITY_LABEL, type Quality } from '../app/settings';
|
import { useSettings, QUALITY_LABEL, UPSCALING, type Quality, type SubtitleBox, type Upscaling } from '../app/settings';
|
||||||
import { clock, episodeLabel } from '../app/format';
|
import { bitrate, channelLabel, clock, episodeLabel, resolutionLabel } from '../app/format';
|
||||||
import { Icon } from '../ui/Icon';
|
import { Icon } from '../ui/Icon';
|
||||||
import { Facts, TitleArt } from '../ui/media';
|
import { Facts, TitleArt } from '../ui/media';
|
||||||
import { Button, Spinner } from '../ui/primitives';
|
import { Button, Spinner } from '../ui/primitives';
|
||||||
import { win, isNative } from '../platform/native';
|
import { win, isNative } from '../platform/native';
|
||||||
|
import { WindowControls } from '../app/TopBar';
|
||||||
|
import { navigate } from '../app/router';
|
||||||
|
import { mpv } from './engine';
|
||||||
|
import { separateMini } from './miniWindow';
|
||||||
|
import { PREPARING_NOTICE_MS, UPSCALING_ORDER, hasFailed, readDiagnostics, requestEnhancement, tierAvailable, toggleBypass, type Diagnostics } from './enhance';
|
||||||
|
import { toast } from '../ui/overlays';
|
||||||
import type { Item } from '../plex/types';
|
import type { Item } from '../plex/types';
|
||||||
|
import { PostPlay } from './PostPlay';
|
||||||
|
|
||||||
const HIDE_AFTER = 3000;
|
const HIDE_AFTER = 3000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Controls show on pointer movement and hide after a few seconds of stillness,
|
||||||
|
* or straight away when the pointer leaves the window. They stay while paused
|
||||||
|
* (until the pointer leaves) and while a panel is open or the timeline is held.
|
||||||
|
*/
|
||||||
function useAutoHide(paused: boolean, pinned: boolean) {
|
function useAutoHide(paused: boolean, pinned: boolean) {
|
||||||
const [visible, setVisible] = useState(true);
|
const [visible, setVisible] = useState(true);
|
||||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
const state = useRef({ paused, pinned });
|
||||||
|
state.current = { paused, pinned };
|
||||||
const poke = useCallback(() => {
|
const poke = useCallback(() => {
|
||||||
setVisible(true);
|
setVisible(true);
|
||||||
if (timer.current) clearTimeout(timer.current);
|
if (timer.current) clearTimeout(timer.current);
|
||||||
timer.current = setTimeout(() => setVisible(false), HIDE_AFTER);
|
timer.current = null;
|
||||||
|
if (!state.current.paused && !state.current.pinned) timer.current = setTimeout(() => setVisible(false), HIDE_AFTER);
|
||||||
}, []);
|
}, []);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (paused || pinned) {
|
poke();
|
||||||
if (timer.current) clearTimeout(timer.current);
|
|
||||||
setVisible(true);
|
|
||||||
} else poke();
|
|
||||||
}, [paused, pinned, poke]);
|
}, [paused, pinned, poke]);
|
||||||
|
useEffect(() => {
|
||||||
|
const leave = () => {
|
||||||
|
if (state.current.pinned) return;
|
||||||
|
if (timer.current) clearTimeout(timer.current);
|
||||||
|
timer.current = null;
|
||||||
|
setVisible(false);
|
||||||
|
};
|
||||||
|
const root = document.documentElement;
|
||||||
|
root.addEventListener('mouseleave', leave);
|
||||||
|
return () => {
|
||||||
|
root.removeEventListener('mouseleave', leave);
|
||||||
|
if (timer.current) clearTimeout(timer.current);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
return { visible, poke };
|
return { visible, poke };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -123,28 +149,35 @@ function Timeline({ onScrub }: { onScrub: (active: boolean) => void }) {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Panel({ title, onClose, children, className = '' }: { title: string; onClose: () => void; children: ReactNode; className?: string }) {
|
function Panel({ title, onClose, onBack, children, className = '' }: { title: string; onClose: () => void; onBack?: () => void; children: ReactNode; className?: string }) {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onKey = (e: KeyboardEvent) => {
|
const onKey = (e: KeyboardEvent) => {
|
||||||
if (e.key === 'Escape') {
|
if (e.key === 'Escape') {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
onClose();
|
(onBack ?? onClose)();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
window.addEventListener('keydown', onKey, true);
|
window.addEventListener('keydown', onKey, true);
|
||||||
return () => window.removeEventListener('keydown', onKey, true);
|
return () => window.removeEventListener('keydown', onKey, true);
|
||||||
}, [onClose]);
|
}, [onClose, onBack]);
|
||||||
return (
|
return (
|
||||||
<div className={`player-panel ${className}`} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
<div className={`player-panel ${className}`} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||||
<div className="player-panel-title">{title}</div>
|
<div className="player-panel-title">
|
||||||
|
{onBack && (
|
||||||
|
<button className="panel-back" onClick={onBack} aria-label="Back">
|
||||||
|
<Icon name="back" size={15} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{title}
|
||||||
|
</div>
|
||||||
{children}
|
{children}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Option({ selected, label, detail, onClick }: { selected: boolean; label: string; detail?: string; onClick: () => void }) {
|
function Option({ selected, label, detail, disabled, onClick }: { selected: boolean; label: string; detail?: string; disabled?: boolean; onClick: () => void }) {
|
||||||
return (
|
return (
|
||||||
<button className={`panel-option${selected ? ' selected' : ''}`} onClick={onClick}>
|
<button className={`panel-option${selected ? ' selected' : ''}`} disabled={disabled} onClick={onClick}>
|
||||||
<span className="panel-check">{selected && <Icon name="check" size={16} />}</span>
|
<span className="panel-check">{selected && <Icon name="check" size={16} />}</span>
|
||||||
<span className="panel-label">
|
<span className="panel-label">
|
||||||
{label}
|
{label}
|
||||||
|
|
@ -172,58 +205,229 @@ function TracksPanel({ onClose }: { onClose: () => void }) {
|
||||||
{st.subTracks.map((t) => (
|
{st.subTracks.map((t) => (
|
||||||
<Option key={t.key} selected={t.key === st.subKey} label={t.label} detail={t.detail} onClick={() => st.selectSubtitle(t.key)} />
|
<Option key={t.key} selected={t.key === st.subKey} label={t.label} detail={t.detail} onClick={() => st.selectSubtitle(t.key)} />
|
||||||
))}
|
))}
|
||||||
{st.subKey && st.delivery?.mode !== 'transcode' && (
|
{st.subKey && st.delivery?.mode !== 'transcode' && <Stepper label="Timing" value={st.subDelay} onChange={st.setSubDelay} />}
|
||||||
<div className="panel-delay">
|
|
||||||
<span>Timing</span>
|
|
||||||
<button onClick={() => st.setSubDelay(st.subDelay - 0.1)}>−</button>
|
|
||||||
<b>{st.subDelay > 0 ? '+' : ''}{st.subDelay.toFixed(1)}s</b>
|
|
||||||
<button onClick={() => st.setSubDelay(st.subDelay + 0.1)}>+</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Panel>
|
</Panel>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function Stepper({ label, value, onChange }: { label: string; value: number; onChange: (v: number) => void }) {
|
||||||
|
return (
|
||||||
|
<div className="panel-delay">
|
||||||
|
<span>{label}</span>
|
||||||
|
<button onClick={() => onChange(Math.round((value - 0.1) * 10) / 10)} aria-label={`${label} earlier`}>
|
||||||
|
−
|
||||||
|
</button>
|
||||||
|
<b>
|
||||||
|
{value > 0 ? '+' : ''}
|
||||||
|
{value.toFixed(1)}s
|
||||||
|
</b>
|
||||||
|
<button onClick={() => onChange(Math.round((value + 0.1) * 10) / 10)} aria-label={`${label} later`}>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const SUB_SIZES = [
|
||||||
|
{ value: 0.8, label: 'Small' },
|
||||||
|
{ value: 1, label: 'Normal' },
|
||||||
|
{ value: 1.25, label: 'Large' },
|
||||||
|
{ value: 1.5, label: 'Extra large' },
|
||||||
|
];
|
||||||
|
const SUB_BOXES: { value: SubtitleBox; label: string }[] = [
|
||||||
|
{ value: 'none', label: 'None' },
|
||||||
|
{ value: 'translucent', label: 'Translucent' },
|
||||||
|
{ value: 'solid', label: 'Solid' },
|
||||||
|
];
|
||||||
|
|
||||||
|
type SettingsView = 'main' | 'audio' | 'subtitles' | 'quality' | 'upscaling' | 'speed' | 'version' | 'chapters' | 'subSize' | 'subBox';
|
||||||
|
|
||||||
|
/** True once `flag` has stayed true for `ms` (a quick blip never shows). */
|
||||||
|
function useLasting(flag: boolean, ms: number) {
|
||||||
|
const [on, setOn] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!flag) return setOn(false);
|
||||||
|
const t = setTimeout(() => setOn(true), ms);
|
||||||
|
return () => clearTimeout(t);
|
||||||
|
}, [flag, ms]);
|
||||||
|
return on;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Polls what mpv's renderer is doing while a panel shows it. */
|
||||||
|
function useDiagnostics(enabled: boolean) {
|
||||||
|
const [d, setD] = useState<Diagnostics | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!enabled || !isNative) return;
|
||||||
|
let alive = true;
|
||||||
|
const tick = () => readDiagnostics().then((x) => alive && setD(x), () => {});
|
||||||
|
tick();
|
||||||
|
const t = setInterval(tick, 1000);
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
clearInterval(t);
|
||||||
|
};
|
||||||
|
}, [enabled]);
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Requested vs running tier, for the panel row. */
|
||||||
|
function upscalingValue(requested: Upscaling, active: Upscaling, bypass: boolean) {
|
||||||
|
if (bypass) return 'Off (comparing)';
|
||||||
|
return active === requested ? UPSCALING[requested].label : `${UPSCALING[active].label} (${UPSCALING[requested].label} failed)`;
|
||||||
|
}
|
||||||
|
|
||||||
function SettingsPanel({ onClose }: { onClose: () => void }) {
|
function SettingsPanel({ onClose }: { onClose: () => void }) {
|
||||||
const st = usePlayer();
|
const st = usePlayer();
|
||||||
const [view, setView] = useState<'main' | 'quality' | 'speed' | 'version' | 'chapters'>('main');
|
const prefs = useSettings();
|
||||||
const speeds = [0.5, 0.75, 1, 1.25, 1.5, 2];
|
const [view, setView] = useState<SettingsView>('main');
|
||||||
|
const diag = useDiagnostics(view === 'main' || view === 'upscaling');
|
||||||
|
const speeds = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];
|
||||||
const media = st.item?.media ?? [];
|
const media = st.item?.media ?? [];
|
||||||
|
const source = media[st.mediaIndex];
|
||||||
const local = st.delivery?.mode === 'local';
|
const local = st.delivery?.mode === 'local';
|
||||||
|
const back = () => setView('main');
|
||||||
|
const audio = st.audioTracks.find((t) => t.key === st.audioKey);
|
||||||
|
const sub = st.subTracks.find((t) => t.key === st.subKey);
|
||||||
|
const qualityLabel = (q: Quality) => (q === 'original' ? `Original${source?.bitrate ? ` · ${bitrate(source.bitrate)}` : ''}` : QUALITY_LABEL[q]);
|
||||||
|
|
||||||
|
if (view === 'audio')
|
||||||
|
return (
|
||||||
|
<Panel title="Audio" onClose={onClose} onBack={back}>
|
||||||
|
{st.audioTracks.map((t) => (
|
||||||
|
<Option key={t.key} selected={t.key === st.audioKey} label={t.label} detail={t.detail} onClick={() => (st.selectAudio(t.key), back())} />
|
||||||
|
))}
|
||||||
|
{!st.audioTracks.length && <div className="panel-empty">No audio tracks</div>}
|
||||||
|
{st.delivery?.mode !== 'transcode' && <Stepper label="Audio sync" value={st.audioDelay} onChange={st.setAudioDelay} />}
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
|
if (view === 'subtitles')
|
||||||
|
return (
|
||||||
|
<Panel title="Subtitles" onClose={onClose} onBack={back}>
|
||||||
|
<Option selected={!st.subKey} label="Off" onClick={() => (st.selectSubtitle(''), back())} />
|
||||||
|
{st.subTracks.map((t) => (
|
||||||
|
<Option key={t.key} selected={t.key === st.subKey} label={t.label} detail={t.detail} onClick={() => (st.selectSubtitle(t.key), back())} />
|
||||||
|
))}
|
||||||
|
{st.subKey && st.delivery?.mode !== 'transcode' && <Stepper label="Subtitle timing" value={st.subDelay} onChange={st.setSubDelay} />}
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
if (view === 'quality')
|
if (view === 'quality')
|
||||||
return (
|
return (
|
||||||
<Panel title="Quality" onClose={onClose}>
|
<Panel title="Quality" onClose={onClose} onBack={back}>
|
||||||
{(Object.keys(QUALITY_LABEL) as Quality[]).map((q) => (
|
{(Object.keys(QUALITY_LABEL) as Quality[]).map((q) => (
|
||||||
<Option key={q} selected={st.quality === q} label={QUALITY_LABEL[q]} detail={q === 'original' ? 'Direct play of the source file' : 'Converted by your Plex server'} onClick={() => (st.setQuality(q), onClose())} />
|
<Option
|
||||||
|
key={q}
|
||||||
|
selected={st.quality === q}
|
||||||
|
label={qualityLabel(q)}
|
||||||
|
detail={q === 'original' ? [resolutionLabel(source), source?.videoCodec.toUpperCase(), 'Direct play of the source file'].filter(Boolean).join(' · ') : 'Converted by your Plex server'}
|
||||||
|
onClick={() => (st.setQuality(q), onClose())}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</Panel>
|
</Panel>
|
||||||
);
|
);
|
||||||
|
if (view === 'upscaling')
|
||||||
|
return (
|
||||||
|
<Panel title="Upscaling" onClose={onClose} onBack={back} className="upscaling">
|
||||||
|
{UPSCALING_ORDER.map((m) => (
|
||||||
|
<Option
|
||||||
|
key={m}
|
||||||
|
selected={prefs.upscaling === m}
|
||||||
|
label={UPSCALING[m].label}
|
||||||
|
detail={!tierAvailable(m) ? 'Needs an NVIDIA RTX graphics card on Windows' : hasFailed(m) ? 'Couldn’t start on this computer' : UPSCALING[m].detail}
|
||||||
|
disabled={!tierAvailable(m)}
|
||||||
|
onClick={() => prefs.set('upscaling', m)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
<div className="panel-subhead">Stages</div>
|
||||||
|
<Option selected={prefs.enhanceDeband} label="Debanding" detail="Smooths banding in gradients" onClick={() => prefs.set('enhanceDeband', !prefs.enhanceDeband)} />
|
||||||
|
<Option selected={prefs.enhanceSharpen} label="Sharpening" detail="AMD CAS · SDR only" onClick={() => prefs.set('enhanceSharpen', !prefs.enhanceSharpen)} />
|
||||||
|
<Option selected={prefs.enhanceDenoise} label="Denoising" detail="Non-local means, at any size · Balanced tier, SDR only" onClick={() => prefs.set('enhanceDenoise', !prefs.enhanceDenoise)} />
|
||||||
|
<button className={`panel-compare${st.enhance.bypass ? ' on' : ''}`} onClick={() => toggleBypass()}>
|
||||||
|
{st.enhance.bypass ? 'Turn enhancement back on' : 'Compare with enhancement off'}
|
||||||
|
<kbd>B</kbd>
|
||||||
|
</button>
|
||||||
|
{diag && (
|
||||||
|
<div className="panel-stats">
|
||||||
|
<div>
|
||||||
|
<span>Running</span>
|
||||||
|
<b>{diag.stages.length ? diag.stages.join(' · ') : 'Standard scaling'}</b>
|
||||||
|
</div>
|
||||||
|
{diag.input && (
|
||||||
|
<div>
|
||||||
|
<span>Size</span>
|
||||||
|
<b>
|
||||||
|
{diag.input} → {diag.output}
|
||||||
|
</b>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div>
|
||||||
|
<span>GPU time</span>
|
||||||
|
<b className={diag.gpuMs > diag.budgetMs * 0.8 ? 'warn' : ''}>
|
||||||
|
{diag.gpuMs.toFixed(1)} ms per frame <small>of {diag.budgetMs.toFixed(0)} ms</small>
|
||||||
|
</b>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span>Dropped</span>
|
||||||
|
<b>{diag.dropped} frames</b>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
if (view === 'speed')
|
if (view === 'speed')
|
||||||
return (
|
return (
|
||||||
<Panel title="Playback speed" onClose={onClose}>
|
<Panel title="Playback speed" onClose={onClose} onBack={back}>
|
||||||
{speeds.map((s) => (
|
{speeds.map((s) => (
|
||||||
<Option key={s} selected={Math.abs(st.speed - s) < 0.01} label={s === 1 ? 'Normal' : `${s}×`} onClick={() => (st.setSpeed(s), onClose())} />
|
<Option key={s} selected={Math.abs(st.speed - s) < 0.01} label={s === 1 ? 'Normal' : `${s}×`} onClick={() => (st.setSpeed(s), back())} />
|
||||||
))}
|
))}
|
||||||
</Panel>
|
</Panel>
|
||||||
);
|
);
|
||||||
if (view === 'version')
|
if (view === 'version')
|
||||||
return (
|
return (
|
||||||
<Panel title="Version" onClose={onClose}>
|
<Panel title="Version" onClose={onClose} onBack={back}>
|
||||||
{media.map((m, i) => (
|
{media.map((m, i) => (
|
||||||
<Option key={m.id} selected={st.mediaIndex === i} label={m.title || `${m.videoResolution.toUpperCase()} ${m.videoCodec.toUpperCase()}`} detail={[m.container.toUpperCase(), m.bitrate ? `${Math.round(m.bitrate / 1000)} Mbps` : ''].filter(Boolean).join(' · ')} onClick={() => (st.selectVersion(i), onClose())} />
|
<Option
|
||||||
|
key={m.id}
|
||||||
|
selected={st.mediaIndex === i}
|
||||||
|
label={m.title || [resolutionLabel(m), m.videoCodec.toUpperCase()].filter(Boolean).join(' ')}
|
||||||
|
detail={[m.container.toUpperCase(), bitrate(m.bitrate), [m.audioCodec.toUpperCase(), channelLabel(m.audioChannels)].filter(Boolean).join(' ')].filter(Boolean).join(' · ')}
|
||||||
|
onClick={() => (st.selectVersion(i), onClose())}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</Panel>
|
</Panel>
|
||||||
);
|
);
|
||||||
if (view === 'chapters')
|
if (view === 'chapters')
|
||||||
return (
|
return (
|
||||||
<Panel title="Chapters" onClose={onClose} className="chapters">
|
<Panel title="Chapters" onClose={onClose} onBack={back} className="chapters">
|
||||||
{st.chapters.map((c) => (
|
{st.chapters.map((c, i) => (
|
||||||
<Option key={c.time} selected={false} label={c.title} detail={clock(c.time)} onClick={() => (st.seek(c.time), onClose())} />
|
<Option
|
||||||
|
key={c.time}
|
||||||
|
selected={st.position >= c.time && st.position < (st.chapters[i + 1]?.time ?? Infinity)}
|
||||||
|
label={c.title}
|
||||||
|
detail={clock(c.time)}
|
||||||
|
onClick={() => (st.seek(c.time), onClose())}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</Panel>
|
</Panel>
|
||||||
);
|
);
|
||||||
|
if (view === 'subSize')
|
||||||
|
return (
|
||||||
|
<Panel title="Subtitle size" onClose={onClose} onBack={back}>
|
||||||
|
{SUB_SIZES.map((o) => (
|
||||||
|
<Option key={o.value} selected={prefs.subtitleScale === o.value} label={o.label} onClick={() => (prefs.set('subtitleScale', o.value), back())} />
|
||||||
|
))}
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
|
if (view === 'subBox')
|
||||||
|
return (
|
||||||
|
<Panel title="Subtitle background" onClose={onClose} onBack={back}>
|
||||||
|
{SUB_BOXES.map((o) => (
|
||||||
|
<Option key={o.value} selected={prefs.subtitleBox === o.value} label={o.label} onClick={() => (prefs.set('subtitleBox', o.value), back())} />
|
||||||
|
))}
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
|
|
||||||
const row = (label: string, value: string, go: () => void, disabled = false) => (
|
const row = (label: string, value: string, go: () => void, disabled = false) => (
|
||||||
<button className="panel-row" onClick={go} disabled={disabled}>
|
<button className="panel-row" onClick={go} disabled={disabled}>
|
||||||
<span>{label}</span>
|
<span>{label}</span>
|
||||||
|
|
@ -231,19 +435,35 @@ function SettingsPanel({ onClose }: { onClose: () => void }) {
|
||||||
<Icon name="next" size={14} />
|
<Icon name="next" size={14} />
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
|
const v = st.video;
|
||||||
|
const stats: [string, string][] = [
|
||||||
|
['Playback', st.delivery?.mode === 'direct' ? 'Direct play' : st.delivery?.mode === 'transcode' ? `Converting to ${QUALITY_LABEL[st.quality]}` : local ? 'Downloaded file' : ''],
|
||||||
|
];
|
||||||
|
if (v && v.width > 0)
|
||||||
|
stats.push(['Video', [`${v.width}×${v.height}`, v.codec.toUpperCase(), source?.dynamicRange, v.hwdec && v.hwdec !== 'no' ? 'Hardware decoding' : 'Software decoding'].filter(Boolean).join(' · ')]);
|
||||||
|
if (audio) stats.push(['Audio', [audio.label, audio.detail].filter(Boolean).join(' · ')]);
|
||||||
|
if (diag && st.enhance.active !== 'off' && !st.enhance.bypass) stats.push(['Upscaling', [...diag.stages, `${diag.gpuMs.toFixed(1)} ms`].join(' · ')]);
|
||||||
|
if (source?.bitrate && !local) stats.push(['Bitrate', st.delivery?.mode === 'transcode' ? `${bitrate(source.bitrate)} source` : bitrate(source.bitrate)]);
|
||||||
|
if (source?.container) stats.push(['Container', source.container.toUpperCase()]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Panel title="Playback" onClose={onClose}>
|
<Panel title="Playback" onClose={onClose}>
|
||||||
{!local && row('Quality', QUALITY_LABEL[st.quality], () => setView('quality'))}
|
{row('Audio', audio ? audio.label : st.audioTracks.length ? 'Choose' : 'None', () => setView('audio'), !st.audioTracks.length)}
|
||||||
|
{row('Subtitles', sub ? sub.label : 'Off', () => setView('subtitles'))}
|
||||||
|
{!local && row('Quality', qualityLabel(st.quality), () => setView('quality'))}
|
||||||
|
{row('Upscaling', upscalingValue(prefs.upscaling, st.enhance.active, st.enhance.bypass), () => setView('upscaling'))}
|
||||||
{row('Speed', st.speed === 1 ? 'Normal' : `${st.speed}×`, () => setView('speed'))}
|
{row('Speed', st.speed === 1 ? 'Normal' : `${st.speed}×`, () => setView('speed'))}
|
||||||
{media.length > 1 && !local && row('Version', `${st.mediaIndex + 1} of ${media.length}`, () => setView('version'))}
|
{media.length > 1 && !local && row('Version', `${st.mediaIndex + 1} of ${media.length}`, () => setView('version'))}
|
||||||
{st.chapters.length > 1 && row('Chapters', `${st.chapters.length}`, () => setView('chapters'))}
|
{st.chapters.length > 1 && row('Chapters', `${st.chapters.length}`, () => setView('chapters'))}
|
||||||
<div className="panel-info">
|
{row('Subtitle size', SUB_SIZES.find((o) => o.value === prefs.subtitleScale)?.label ?? 'Custom', () => setView('subSize'))}
|
||||||
{st.delivery?.mode === 'direct' && 'Direct play'}
|
{row('Subtitle background', SUB_BOXES.find((o) => o.value === prefs.subtitleBox)?.label ?? '', () => setView('subBox'))}
|
||||||
{st.delivery?.mode === 'transcode' && `Converting to ${st.delivery.label}`}
|
<div className="panel-stats">
|
||||||
{st.delivery?.mode === 'local' && 'Playing from this computer'}
|
{stats.map(([k, val]) => (
|
||||||
{st.video && st.video.width > 0 && ` · ${st.video.width}×${st.video.height}`}
|
<div key={k}>
|
||||||
{st.video?.codec && ` · ${st.video.codec.toUpperCase()}`}
|
<span>{k}</span>
|
||||||
{st.video?.hwdec && st.video.hwdec !== 'no' ? ' · Hardware decoding' : ''}
|
<b>{val}</b>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</Panel>
|
</Panel>
|
||||||
);
|
);
|
||||||
|
|
@ -273,79 +493,300 @@ function Volume() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A seek that lands inside a marker this recently means the viewer chose to be there. */
|
||||||
|
const SEEK_GRACE_MS = 1500;
|
||||||
|
const MODIFIER_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'AltGraph', 'CapsLock']);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Skip intro / Skip credits. With "Skip automatically" the button counts down for the
|
||||||
|
* chosen delay, filling as it goes, then skips. Pausing, seeking or pressing a key
|
||||||
|
* before then keeps watching: the button stays as a plain skip for the rest of the marker.
|
||||||
|
*/
|
||||||
function SkipButton() {
|
function SkipButton() {
|
||||||
const item = usePlayer((s) => s.item);
|
const item = usePlayer((s) => s.item);
|
||||||
const position = usePlayer((s) => s.position);
|
const position = usePlayer((s) => s.position);
|
||||||
const seek = usePlayer((s) => s.seek);
|
const seek = usePlayer((s) => s.seek);
|
||||||
const nextUp = usePlayer((s) => s.nextUp);
|
|
||||||
const countdown = usePlayer((s) => s.countdown);
|
const countdown = usePlayer((s) => s.countdown);
|
||||||
|
const postPlayDismissed = usePlayer((s) => s.postPlayDismissed);
|
||||||
|
const paused = usePlayer((s) => s.paused);
|
||||||
|
const ready = usePlayer((s) => s.firstFrame);
|
||||||
|
const lastSeek = usePlayer((s) => s.lastSeek);
|
||||||
const skipIntro = useSettings((s) => s.skipIntro);
|
const skipIntro = useSettings((s) => s.skipIntro);
|
||||||
const skipCredits = useSettings((s) => s.skipCredits);
|
const skipCredits = useSettings((s) => s.skipCredits);
|
||||||
const autoSkipped = useRef(new Set<string>());
|
const delay = useSettings((s) => s.autoSkipDelay);
|
||||||
|
// Markers already skipped, or whose automatic skip was cancelled, don't count down again.
|
||||||
|
const settled = useRef(new Set<string>());
|
||||||
|
const [pending, setPending] = useState<{ key: string; from: number } | null>(null);
|
||||||
const ms = position * 1000;
|
const ms = position * 1000;
|
||||||
const marker = item?.markers.find((m) => (m.type === 'intro' || m.type === 'credits') && ms >= m.start && ms < m.end - 1000);
|
const marker = item?.markers.find((m) => (m.type === 'intro' || m.type === 'credits') && ms >= m.start && ms < m.end - 1000);
|
||||||
const mode = marker?.type === 'intro' ? skipIntro : skipCredits;
|
const key = item && marker ? `${item.id}:${marker.type}:${marker.start}` : '';
|
||||||
|
const episodeCredits = marker?.type === 'credits' && item?.type === 'episode';
|
||||||
|
const mode = marker?.type === 'intro' ? skipIntro : episodeCredits ? 'button' : skipCredits;
|
||||||
|
const auto = !!marker && !episodeCredits && mode === 'auto';
|
||||||
|
const counting = pending && pending.key === key ? pending : null;
|
||||||
|
|
||||||
|
const skip = () => {
|
||||||
|
if (!marker) return;
|
||||||
|
settled.current.add(key);
|
||||||
|
setPending(null);
|
||||||
|
if (marker.type === 'credits' && item?.type === 'episode') usePlayer.getState().showPostPlay();
|
||||||
|
else seek(marker.end / 1000);
|
||||||
|
};
|
||||||
|
const cancel = () => {
|
||||||
|
if (!pending) return;
|
||||||
|
settled.current.add(pending.key);
|
||||||
|
setPending(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Start counting once an automatic marker is playing.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (marker && mode === 'auto' && !autoSkipped.current.has(marker.id + marker.start) && !(marker.type === 'credits' && nextUp)) {
|
if (!auto || !ready || paused || settled.current.has(key) || pending?.key === key) return;
|
||||||
autoSkipped.current.add(marker.id + marker.start);
|
if (Date.now() - usePlayer.getState().lastSeek < SEEK_GRACE_MS) {
|
||||||
seek(marker.end / 1000);
|
settled.current.add(key);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}, [marker?.id, marker?.start, mode]);
|
if (delay <= 0) return skip();
|
||||||
if (!marker || mode === 'off' || countdown !== null) return null;
|
setPending({ key, from: usePlayer.getState().position });
|
||||||
if (marker.type === 'credits' && nextUp) return null;
|
}, [key, auto, ready, paused, delay]);
|
||||||
|
|
||||||
|
// Count playback time, so buffering doesn't eat into the delay.
|
||||||
|
useEffect(() => {
|
||||||
|
if (counting && position - counting.from >= delay) skip();
|
||||||
|
else if (pending && !counting) setPending(null);
|
||||||
|
}, [position, key]);
|
||||||
|
|
||||||
|
// Pausing or seeking means the viewer is watching.
|
||||||
|
useEffect(() => {
|
||||||
|
if (paused) cancel();
|
||||||
|
}, [paused]);
|
||||||
|
useEffect(cancel, [lastSeek]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!counting) return;
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (!MODIFIER_KEYS.has(e.key)) cancel();
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKey, true);
|
||||||
|
return () => window.removeEventListener('keydown', onKey, true);
|
||||||
|
}, [counting]);
|
||||||
|
|
||||||
|
if (!marker || (episodeCredits && !postPlayDismissed) || mode === 'off' || countdown !== null) return null;
|
||||||
|
const what = marker.type === 'intro' ? 'intro' : 'credits';
|
||||||
|
const elapsed = counting ? Math.max(0, position - counting.from) : 0;
|
||||||
return (
|
return (
|
||||||
<button className="skip-button" onClick={() => seek(marker.end / 1000)}>
|
<button
|
||||||
{marker.type === 'intro' ? 'Skip intro' : 'Skip credits'}
|
className={`skip-button${counting ? ' counting' : ''}`}
|
||||||
|
style={counting ? { ['--p' as string]: `${Math.min(1, elapsed / delay) * 100}%` } : undefined}
|
||||||
|
title={counting ? 'Click to skip now. Pause, seek or press any key to keep watching.' : undefined}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
skip();
|
||||||
|
}}
|
||||||
|
onDoubleClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<span>{counting ? `Skipping ${what}` : `Skip ${what}`}</span>
|
||||||
<Icon name="skipNext" size={16} />
|
<Icon name="skipNext" size={16} />
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function PostPlay() {
|
/** The title opens its show or movie page, with playback moving to the miniplayer. */
|
||||||
const server = useSession((s) => s.server);
|
function openFromPlayer(id: string | undefined) {
|
||||||
const nextUp = usePlayer((s) => s.nextUp);
|
if (!id) return;
|
||||||
const countdown = usePlayer((s) => s.countdown);
|
usePlayer.getState().minimize();
|
||||||
const playNext = usePlayer((s) => s.playNext);
|
navigate({ name: 'item', id });
|
||||||
const cancel = usePlayer((s) => s.cancelCountdown);
|
}
|
||||||
if (!nextUp || countdown === null || !server) return null;
|
|
||||||
|
function TitleBlock({ item }: { item: Item }) {
|
||||||
|
const linkable = item.type === 'movie' || item.type === 'episode';
|
||||||
|
const art = <TitleArt item={item.type === 'episode' ? { ...item, logo: item.raw?.Image?.find?.((i: any) => i.type === 'clearLogo')?.url ?? '' } : item} maxWidth={240} maxHeight={60} as="h2" />;
|
||||||
return (
|
return (
|
||||||
<div className="post-play" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
<div className="player-title">
|
||||||
<div className="post-play-art">
|
{linkable ? (
|
||||||
<img src={server.image(nextUp.thumb, 360, 202)} alt="" draggable={false} />
|
<button className="player-title-link" title={`Go to ${item.type === 'episode' ? item.grandparentTitle : item.title}`} onClick={() => openFromPlayer(item.type === 'episode' ? item.grandparentId : item.id)}>
|
||||||
{countdown > 0 && (
|
{art}
|
||||||
<svg className="post-play-ring" viewBox="0 0 40 40">
|
</button>
|
||||||
<circle cx="20" cy="20" r="17" />
|
) : (
|
||||||
</svg>
|
art
|
||||||
)}
|
)}
|
||||||
</div>
|
{item.type === 'episode' && (
|
||||||
<div className="post-play-text">
|
<button className="player-episode" title="Go to this episode" onClick={() => openFromPlayer(item.id)}>
|
||||||
<span className="micro">Next episode{countdown > 0 ? ` in ${countdown}` : ''}</span>
|
{episodeLabel(item)} · {item.title}
|
||||||
<b>
|
</button>
|
||||||
{episodeLabel(nextUp)} · {nextUp.title}
|
)}
|
||||||
</b>
|
{item.type !== 'clip' && <Facts item={item} withFormats={false} episode={false} />}
|
||||||
<div className="actions">
|
|
||||||
<Button variant="primary" size="sm" icon="play" onClick={playNext}>
|
|
||||||
Play now
|
|
||||||
</Button>
|
|
||||||
<Button variant="ghost" size="sm" onClick={cancel}>
|
|
||||||
{countdown > 0 ? 'Cancel' : 'Dismiss'}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TitleBlock({ item }: { item: Item }) {
|
/** Where the miniplayer was dragged to: its distance from the window's right and bottom edges. */
|
||||||
|
type MiniPos = { x: number; y: number };
|
||||||
|
const MINI_POS_KEY = 'kaleido.miniPosition';
|
||||||
|
const MINI_MARGIN = 8;
|
||||||
|
let miniPos: MiniPos | null | undefined;
|
||||||
|
|
||||||
|
function savedMiniPos(): MiniPos | null {
|
||||||
|
if (miniPos === undefined) {
|
||||||
|
try {
|
||||||
|
const p = JSON.parse(localStorage.getItem(MINI_POS_KEY) ?? 'null');
|
||||||
|
miniPos = p && Number.isFinite(p.x) && Number.isFinite(p.y) ? p : null;
|
||||||
|
} catch {
|
||||||
|
miniPos = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return miniPos ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keeps the whole box inside the window. */
|
||||||
|
function clampMini(el: HTMLElement, pos: MiniPos): MiniPos {
|
||||||
|
const cs = getComputedStyle(el);
|
||||||
|
const maxX = window.innerWidth - parseFloat(cs.width) - MINI_MARGIN;
|
||||||
|
const maxY = window.innerHeight - parseFloat(cs.height) - MINI_MARGIN;
|
||||||
|
return { x: Math.round(Math.max(MINI_MARGIN, Math.min(maxX, pos.x))), y: Math.round(Math.max(MINI_MARGIN, Math.min(maxY, pos.y))) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The box and the page's hole for the video (base.css) both follow these. */
|
||||||
|
function applyMiniPos(pos: MiniPos | null) {
|
||||||
|
const root = document.documentElement.style;
|
||||||
|
if (!pos) {
|
||||||
|
root.removeProperty('--mini-x');
|
||||||
|
root.removeProperty('--mini-y');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
root.setProperty('--mini-x', `${pos.x}px`);
|
||||||
|
root.setProperty('--mini-y', `${pos.y}px`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Playing in the corner while browsing, and draggable anywhere in the window.
|
||||||
|
* The native video is drawn into this box's rectangle and the page has a
|
||||||
|
* matching hole (see `html.player-mini`).
|
||||||
|
*/
|
||||||
|
function MiniPlayer() {
|
||||||
|
const st = usePlayer();
|
||||||
|
const box = useRef<HTMLDivElement>(null);
|
||||||
|
const placeVideo = useRef(() => {});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const el = box.current;
|
||||||
|
if (!el) return;
|
||||||
|
let frame = 0;
|
||||||
|
const fit = () => {
|
||||||
|
const saved = savedMiniPos();
|
||||||
|
applyMiniPos(saved && clampMini(el, saved));
|
||||||
|
};
|
||||||
|
const place = () => {
|
||||||
|
cancelAnimationFrame(frame);
|
||||||
|
frame = requestAnimationFrame(() => {
|
||||||
|
// The layout box, not getBoundingClientRect: transforms (an entrance
|
||||||
|
// animation) must not move the video away from the page's hole.
|
||||||
|
const cs = getComputedStyle(el);
|
||||||
|
const width = parseFloat(cs.width);
|
||||||
|
const height = parseFloat(cs.height);
|
||||||
|
const x = window.innerWidth - parseFloat(cs.right) - width;
|
||||||
|
const y = window.innerHeight - parseFloat(cs.bottom) - height;
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
// A pixel of overdraw on each side keeps the hole covered at any scale.
|
||||||
|
if (isNative) mpv.rect({ x: x * dpr - 1, y: y * dpr - 1, width: width * dpr + 2, height: height * dpr + 2 }).catch(() => {});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
placeVideo.current = place;
|
||||||
|
const onResize = () => {
|
||||||
|
fit();
|
||||||
|
place();
|
||||||
|
};
|
||||||
|
onResize();
|
||||||
|
const ro = new ResizeObserver(place);
|
||||||
|
ro.observe(el);
|
||||||
|
window.addEventListener('resize', onResize);
|
||||||
|
return () => {
|
||||||
|
cancelAnimationFrame(frame);
|
||||||
|
ro.disconnect();
|
||||||
|
window.removeEventListener('resize', onResize);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const startDrag = (e: ReactPointerEvent) => {
|
||||||
|
const el = box.current;
|
||||||
|
if (e.button !== 0 || !el) return;
|
||||||
|
const cs = getComputedStyle(el);
|
||||||
|
const start = { px: e.clientX, py: e.clientY, x: parseFloat(cs.right), y: parseFloat(cs.bottom) };
|
||||||
|
let dragging = false;
|
||||||
|
const move = (ev: PointerEvent) => {
|
||||||
|
const dx = ev.clientX - start.px;
|
||||||
|
const dy = ev.clientY - start.py;
|
||||||
|
if (!dragging && Math.hypot(dx, dy) < 5) return;
|
||||||
|
dragging = true;
|
||||||
|
el.classList.add('dragging');
|
||||||
|
miniPos = clampMini(el, { x: start.x - dx, y: start.y - dy });
|
||||||
|
applyMiniPos(miniPos);
|
||||||
|
placeVideo.current();
|
||||||
|
};
|
||||||
|
const up = () => {
|
||||||
|
window.removeEventListener('pointermove', move);
|
||||||
|
window.removeEventListener('pointerup', up);
|
||||||
|
window.removeEventListener('pointercancel', up);
|
||||||
|
if (!dragging) return;
|
||||||
|
el.classList.remove('dragging');
|
||||||
|
localStorage.setItem(MINI_POS_KEY, JSON.stringify(miniPos));
|
||||||
|
// Letting go after a drag isn't a click on the button under the pointer.
|
||||||
|
const swallow = (c: MouseEvent) => {
|
||||||
|
c.stopPropagation();
|
||||||
|
c.preventDefault();
|
||||||
|
};
|
||||||
|
window.addEventListener('click', swallow, { capture: true, once: true });
|
||||||
|
setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0);
|
||||||
|
};
|
||||||
|
window.addEventListener('pointermove', move);
|
||||||
|
window.addEventListener('pointerup', up);
|
||||||
|
window.addEventListener('pointercancel', up);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!st.item) return null;
|
||||||
|
const item = st.item;
|
||||||
|
const loading = !st.firstFrame && !st.error;
|
||||||
|
const pct = st.duration ? Math.min(100, (st.position / st.duration) * 100) : 0;
|
||||||
return (
|
return (
|
||||||
<div className="player-title">
|
<div ref={box} className={`mini-player${loading || st.error ? ' loading' : ''}`} onPointerDown={startDrag} onDoubleClick={() => st.expand()}>
|
||||||
<TitleArt item={item.type === 'episode' ? { ...item, logo: item.raw?.Image?.find?.((i: any) => i.type === 'clearLogo')?.url ?? '' } : item} maxWidth={240} maxHeight={60} as="h2" />
|
<div className="mini-scrim" />
|
||||||
{item.type === 'episode' && (
|
<div className="mini-top">
|
||||||
<div className="player-episode">
|
<button className="mini-icon" aria-label="Back to full screen player" title="Expand" onClick={() => st.expand()}>
|
||||||
{episodeLabel(item)} · {item.title}
|
<Icon name="expand" size={17} />
|
||||||
</div>
|
</button>
|
||||||
)}
|
<button className="mini-icon" aria-label="Stop playback" title="Close" onClick={() => st.close()}>
|
||||||
{item.type !== 'clip' && <Facts item={item} withFormats={false} episode={false} />}
|
<Icon name="x" size={18} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="mini-center">
|
||||||
|
{(loading || st.buffering || st.reconnecting) && !st.error ? (
|
||||||
|
<Spinner size={30} />
|
||||||
|
) : st.error ? (
|
||||||
|
<span className="mini-error">Playback stopped</span>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<button className="mini-icon" aria-label="Back 10 seconds" onClick={() => st.seekBy(-10)}>
|
||||||
|
<Icon name="replay10" size={22} />
|
||||||
|
</button>
|
||||||
|
<button className="mini-icon big" aria-label={st.paused ? 'Play' : 'Pause'} onClick={() => st.togglePause()}>
|
||||||
|
<Icon name={st.paused || st.ended ? 'play' : 'pause'} size={26} />
|
||||||
|
</button>
|
||||||
|
<button className="mini-icon" aria-label="Forward 10 seconds" onClick={() => st.seekBy(10)}>
|
||||||
|
<Icon name="forward10" size={22} />
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mini-caption">
|
||||||
|
<b>{item.type === 'episode' ? item.grandparentTitle : item.title}</b>
|
||||||
|
{item.type === 'episode' && (
|
||||||
|
<span>
|
||||||
|
{episodeLabel(item)} · {item.title}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mini-progress">
|
||||||
|
<i style={{ width: `${pct}%` }} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -359,16 +800,20 @@ export function PlayerOverlay() {
|
||||||
const { visible, poke } = useAutoHide(st.paused || st.ended, !!panel || scrubbing || st.countdown !== null);
|
const { visible, poke } = useAutoHide(st.paused || st.ended, !!panel || scrubbing || st.countdown !== null);
|
||||||
const clickTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const clickTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
const seekStep = useSettings((s) => s.seekStep);
|
const seekStep = useSettings((s) => s.seekStep);
|
||||||
|
const preparing = useLasting(st.enhance.preparing, PREPARING_NOTICE_MS);
|
||||||
|
|
||||||
const showFlash = (icon: string) => setFlash({ icon, key: Date.now() });
|
const showFlash = (icon: string) => setFlash({ icon, key: Date.now() });
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!st.open) setPanel('');
|
if (!st.open || st.mini) setPanel('');
|
||||||
}, [st.open]);
|
}, [st.open, st.mini]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!st.open) return;
|
if (!st.open || st.mini) return;
|
||||||
const onKey = async (e: KeyboardEvent) => {
|
const onKey = async (e: KeyboardEvent) => {
|
||||||
|
// Up Next owns Tab, Space/Enter and Escape; player shortcuts must not
|
||||||
|
// seek or change volume while a viewer is browsing its episode rows.
|
||||||
|
if (usePlayer.getState().postPlay) return;
|
||||||
if ((e.target as HTMLElement)?.tagName === 'INPUT' && (e.target as HTMLInputElement).type !== 'range') return;
|
if ((e.target as HTMLElement)?.tagName === 'INPUT' && (e.target as HTMLInputElement).type !== 'range') return;
|
||||||
const p = usePlayer.getState();
|
const p = usePlayer.getState();
|
||||||
let handled = true;
|
let handled = true;
|
||||||
|
|
@ -411,6 +856,27 @@ export function PlayerOverlay() {
|
||||||
if (e.shiftKey && p.nextUp) p.playNext();
|
if (e.shiftKey && p.nextUp) p.playNext();
|
||||||
else handled = false;
|
else handled = false;
|
||||||
break;
|
break;
|
||||||
|
case 'p':
|
||||||
|
case 'P':
|
||||||
|
if (e.shiftKey && p.prevUp) p.playPrevious();
|
||||||
|
else handled = false;
|
||||||
|
break;
|
||||||
|
case 'u':
|
||||||
|
case 'U': {
|
||||||
|
const prefs = useSettings.getState();
|
||||||
|
const tiers = UPSCALING_ORDER.filter(tierAvailable);
|
||||||
|
const next = tiers[(tiers.indexOf(prefs.upscaling) + 1) % tiers.length];
|
||||||
|
prefs.set('upscaling', next);
|
||||||
|
// Confirm what is actually running once it's applied.
|
||||||
|
requestEnhancement().then(() => {
|
||||||
|
if (useSettings.getState().upscaling === next) toast(`Upscaling: ${upscalingValue(next, usePlayer.getState().enhance.active, false)}`);
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'b':
|
||||||
|
case 'B':
|
||||||
|
toggleBypass();
|
||||||
|
break;
|
||||||
case 'c':
|
case 'c':
|
||||||
case 'C': {
|
case 'C': {
|
||||||
const subs = p.subTracks;
|
const subs = p.subTracks;
|
||||||
|
|
@ -421,11 +887,11 @@ export function PlayerOverlay() {
|
||||||
case 'Escape': {
|
case 'Escape': {
|
||||||
const fs = await win.isFullscreen().catch(() => false);
|
const fs = await win.isFullscreen().catch(() => false);
|
||||||
if (fs) p.toggleFullscreen();
|
if (fs) p.toggleFullscreen();
|
||||||
else p.close();
|
else p.minimize();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'Backspace':
|
case 'Backspace':
|
||||||
p.close();
|
p.minimize();
|
||||||
break;
|
break;
|
||||||
case 'Home':
|
case 'Home':
|
||||||
p.seek(0);
|
p.seek(0);
|
||||||
|
|
@ -442,9 +908,20 @@ export function PlayerOverlay() {
|
||||||
};
|
};
|
||||||
window.addEventListener('keydown', onKey);
|
window.addEventListener('keydown', onKey);
|
||||||
return () => window.removeEventListener('keydown', onKey);
|
return () => window.removeEventListener('keydown', onKey);
|
||||||
}, [st.open, seekStep, poke]);
|
}, [st.open, st.mini, seekStep, poke]);
|
||||||
|
|
||||||
|
// The macOS traffic lights fade with the rest of the player's chrome.
|
||||||
|
const chromeHidden = st.open && !st.mini && !st.postPlay && !visible && st.firstFrame && !st.error;
|
||||||
|
useEffect(() => {
|
||||||
|
if (!chromeHidden) return;
|
||||||
|
win.setButtonsVisible(false);
|
||||||
|
return () => void win.setButtonsVisible(true);
|
||||||
|
}, [chromeHidden]);
|
||||||
|
|
||||||
if (!st.open || !st.item) return null;
|
if (!st.open || !st.item) return null;
|
||||||
|
// On Windows the miniplayer is a window of its own (miniWindow.ts).
|
||||||
|
if (st.mini) return separateMini ? null : <MiniPlayer />;
|
||||||
|
if (st.postPlay && !st.error) return <PostPlay key={st.item.id} />;
|
||||||
const item = st.item;
|
const item = st.item;
|
||||||
const loading = !st.firstFrame && !st.error;
|
const loading = !st.firstFrame && !st.error;
|
||||||
const art = item.type === 'episode' ? item.grandparentArt || item.art : item.art;
|
const art = item.type === 'episode' ? item.grandparentArt || item.art : item.art;
|
||||||
|
|
@ -482,14 +959,23 @@ export function PlayerOverlay() {
|
||||||
<div className="player-gradient bottom" />
|
<div className="player-gradient bottom" />
|
||||||
|
|
||||||
<div className="player-top" data-tauri-drag-region={isNative ? true : undefined} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
<div className="player-top" data-tauri-drag-region={isNative ? true : undefined} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||||
<button className="player-back" onClick={() => st.close()} aria-label="Back">
|
<button className="player-back" onClick={() => st.minimize()} aria-label="Back to browsing" title="Keep playing in the corner">
|
||||||
<Icon name="arrowLeft" size={22} />
|
<Icon name="arrowLeft" size={22} />
|
||||||
</button>
|
</button>
|
||||||
|
{!st.fullscreen && <WindowControls />}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{(loading || st.buffering || st.seeking) && !st.error && (
|
{(loading || st.buffering || st.seeking || preparing || st.reconnecting) && !st.error && (
|
||||||
<div className="player-center">
|
<div className="player-center">
|
||||||
<Spinner size={44} />
|
<Spinner size={44} />
|
||||||
|
{st.reconnecting ? (
|
||||||
|
<p className="player-preparing">Lost connection to {server?.name ?? 'the server'}</p>
|
||||||
|
) : preparing && (
|
||||||
|
<p className="player-preparing">
|
||||||
|
Preparing {UPSCALING[st.enhance.active].label} upscaling
|
||||||
|
<small>First time on this computer only</small>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{flash && !loading && (
|
{flash && !loading && (
|
||||||
|
|
@ -504,18 +990,25 @@ export function PlayerOverlay() {
|
||||||
<h2>Playback stopped</h2>
|
<h2>Playback stopped</h2>
|
||||||
<p>{st.error}</p>
|
<p>{st.error}</p>
|
||||||
<div className="actions">
|
<div className="actions">
|
||||||
<Button variant="primary" icon="refresh" onClick={() => st.play(item, { offsetMs: st.position * 1000, quality: st.quality === 'original' ? '1080' : st.quality })}>
|
{st.terminated ? (
|
||||||
Try converting
|
<Button variant="primary" onClick={() => st.close()}>
|
||||||
</Button>
|
Close
|
||||||
<Button variant="ghost" onClick={() => st.close()}>
|
</Button>
|
||||||
Close
|
) : (
|
||||||
</Button>
|
<>
|
||||||
|
<Button variant="primary" icon="refresh" onClick={() => st.play(item, { offsetMs: st.position * 1000, quality: st.quality === 'original' ? '1080' : st.quality })}>
|
||||||
|
Try converting
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" onClick={() => st.close()}>
|
||||||
|
Close
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<SkipButton />
|
<SkipButton />
|
||||||
<PostPlay />
|
|
||||||
|
|
||||||
{!st.error && (
|
{!st.error && (
|
||||||
<div className="player-bottom" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
<div className="player-bottom" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||||
|
|
@ -526,25 +1019,50 @@ export function PlayerOverlay() {
|
||||||
<Timeline onScrub={setScrubbing} />
|
<Timeline onScrub={setScrubbing} />
|
||||||
<div className="player-controls">
|
<div className="player-controls">
|
||||||
<div className="player-controls-left">
|
<div className="player-controls-left">
|
||||||
<button className="player-icon big" aria-label={st.paused ? 'Play' : 'Pause'} onClick={() => st.togglePause()}>
|
|
||||||
<Icon name={st.paused || st.ended ? 'play' : 'pause'} size={26} />
|
|
||||||
</button>
|
|
||||||
<button className="player-icon" aria-label="Back 10 seconds" onClick={() => st.seekBy(-10)}>
|
|
||||||
<Icon name="replay10" size={24} />
|
|
||||||
</button>
|
|
||||||
<button className="player-icon" aria-label="Forward 10 seconds" onClick={() => st.seekBy(10)}>
|
|
||||||
<Icon name="forward10" size={24} />
|
|
||||||
</button>
|
|
||||||
{st.nextUp && (
|
|
||||||
<button className="player-icon" aria-label="Next episode" title={`Next: ${episodeLabel(st.nextUp)} ${st.nextUp.title}`} onClick={() => st.playNext()}>
|
|
||||||
<Icon name="skipNext" size={22} />
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
<Volume />
|
<Volume />
|
||||||
<span className="player-time">
|
<span className="player-time">
|
||||||
{clock(st.position, st.duration >= 3600)} <span className="dim">/ {clock(st.duration, st.duration >= 3600)}</span>
|
{clock(st.position, st.duration >= 3600)} <span className="dim">/ {clock(st.duration, st.duration >= 3600)}</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="player-controls-center">
|
||||||
|
{/* Balances Stop on the other side, so play/pause stays centred. */}
|
||||||
|
<span className="player-icon-spacer" aria-hidden="true" />
|
||||||
|
{/* Both episode buttons stay for episodes (dimmed at either end) so play/pause holds its place. */}
|
||||||
|
{item.type === 'episode' && (
|
||||||
|
<button
|
||||||
|
className="player-icon"
|
||||||
|
aria-label="Previous episode"
|
||||||
|
title={st.prevUp ? `Previous: ${episodeLabel(st.prevUp)} ${st.prevUp.title}` : undefined}
|
||||||
|
disabled={!st.prevUp}
|
||||||
|
onClick={() => st.playPrevious()}
|
||||||
|
>
|
||||||
|
<Icon name="skipPrev" size={22} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button className="player-icon" aria-label="Back 10 seconds" onClick={() => st.seekBy(-10)}>
|
||||||
|
<Icon name="replay10" size={24} />
|
||||||
|
</button>
|
||||||
|
<button className="player-icon big" aria-label={st.paused ? 'Play' : 'Pause'} onClick={() => st.togglePause()}>
|
||||||
|
<Icon name={st.paused || st.ended ? 'play' : 'pause'} size={28} />
|
||||||
|
</button>
|
||||||
|
<button className="player-icon" aria-label="Forward 10 seconds" onClick={() => st.seekBy(10)}>
|
||||||
|
<Icon name="forward10" size={24} />
|
||||||
|
</button>
|
||||||
|
{item.type === 'episode' && (
|
||||||
|
<button
|
||||||
|
className="player-icon"
|
||||||
|
aria-label="Next episode"
|
||||||
|
title={st.nextUp ? `Next: ${episodeLabel(st.nextUp)} ${st.nextUp.title}` : undefined}
|
||||||
|
disabled={!st.nextUp}
|
||||||
|
onClick={() => st.playNext()}
|
||||||
|
>
|
||||||
|
<Icon name="skipNext" size={22} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button className="player-icon" aria-label="Stop playback" title="Stop" onClick={() => st.close()}>
|
||||||
|
<Icon name="stop" size={19} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<div className="player-controls-right">
|
<div className="player-controls-right">
|
||||||
<button className={`player-icon${panel === 'tracks' ? ' on' : ''}${st.subKey ? ' lit' : ''}`} aria-label="Audio and subtitles" onClick={() => setPanel(panel === 'tracks' ? '' : 'tracks')}>
|
<button className={`player-icon${panel === 'tracks' ? ' on' : ''}${st.subKey ? ' lit' : ''}`} aria-label="Audio and subtitles" onClick={() => setPanel(panel === 'tracks' ? '' : 'tracks')}>
|
||||||
<Icon name="captions" size={23} />
|
<Icon name="captions" size={23} />
|
||||||
|
|
|
||||||
334
src/player/PostPlay.tsx
Normal file
|
|
@ -0,0 +1,334 @@
|
||||||
|
import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { usePlayer } from './store';
|
||||||
|
import { mpv } from './engine';
|
||||||
|
import { isNative } from '../platform/native';
|
||||||
|
import { useSession } from '../app/session';
|
||||||
|
import { navigate } from '../app/router';
|
||||||
|
import { art, clock, duration, episodeLabel } from '../app/format';
|
||||||
|
import * as api from '../plex/api';
|
||||||
|
import type { Item } from '../plex/types';
|
||||||
|
import { Backdrop } from '../ui/Backdrop';
|
||||||
|
import { Facts, Shelf, TitleArt } from '../ui/media';
|
||||||
|
import { Artwork } from '../ui/primitives';
|
||||||
|
import { Icon } from '../ui/Icon';
|
||||||
|
import { WindowControls } from '../app/TopBar';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Up Next, adapted from Kaleido for Android TV: the credits keep playing in the
|
||||||
|
* top-left corner (the native video is drawn into that rectangle, with a matching
|
||||||
|
* hole in the page) beside the next episode, with the season and related shows
|
||||||
|
* below. Play next episode carries the one countdown; moving the mouse, clicking,
|
||||||
|
* scrolling or pressing a key stops it. Clicking the video, or Esc, returns to it.
|
||||||
|
*/
|
||||||
|
export function PostPlay() {
|
||||||
|
const item = usePlayer((s) => s.item)!;
|
||||||
|
const nextUp = usePlayer((s) => s.nextUp);
|
||||||
|
const contextReady = usePlayer((s) => s.episodeContextReady);
|
||||||
|
const fullscreen = usePlayer((s) => s.fullscreen);
|
||||||
|
const server = useSession((s) => s.server);
|
||||||
|
const root = useRef<HTMLDivElement>(null);
|
||||||
|
const video = useRef<HTMLButtonElement>(null);
|
||||||
|
const play = useRef<HTMLButtonElement>(null);
|
||||||
|
|
||||||
|
// The listed episode lacks the rating and full synopsis.
|
||||||
|
const details = useQuery({
|
||||||
|
queryKey: [server?.machineId, 'item', nextUp?.id],
|
||||||
|
queryFn: () => api.metadata(server!, nextUp!.id),
|
||||||
|
enabled: !!server && !!nextUp,
|
||||||
|
staleTime: 30_000,
|
||||||
|
});
|
||||||
|
const upcoming = nextUp && details.data?.id === nextUp.id ? details.data : nextUp;
|
||||||
|
|
||||||
|
useVideoRect(root, video);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
(play.current ?? video.current)?.focus({ preventScroll: true });
|
||||||
|
const stop = () => {
|
||||||
|
if (usePlayer.getState().countdown !== null) usePlayer.getState().cancelCountdown();
|
||||||
|
};
|
||||||
|
// Layout changes can send a mousemove without the mouse moving.
|
||||||
|
const move = (e: MouseEvent) => (e.movementX || e.movementY) && stop();
|
||||||
|
const key = (e: KeyboardEvent) => {
|
||||||
|
stop();
|
||||||
|
if (e.key === 'Escape' || e.key === 'Backspace') {
|
||||||
|
e.preventDefault();
|
||||||
|
usePlayer.getState().dismissPostPlay();
|
||||||
|
} else if (e.key === 'F11' || ((e.key === 'f' || e.key === 'F') && !e.ctrlKey && !e.metaKey && !e.altKey)) {
|
||||||
|
e.preventDefault();
|
||||||
|
usePlayer.getState().toggleFullscreen();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const opts = { capture: true, passive: true };
|
||||||
|
window.addEventListener('keydown', key, true);
|
||||||
|
window.addEventListener('pointerdown', stop, opts);
|
||||||
|
window.addEventListener('mousemove', move, opts);
|
||||||
|
window.addEventListener('wheel', stop, opts);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('keydown', key, true);
|
||||||
|
window.removeEventListener('pointerdown', stop, opts);
|
||||||
|
window.removeEventListener('mousemove', move, opts);
|
||||||
|
window.removeEventListener('wheel', stop, opts);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const backToVideo = () => usePlayer.getState().dismissPostPlay();
|
||||||
|
// As in the player: the show page opens with playback moving to the miniplayer.
|
||||||
|
const openShow = () => {
|
||||||
|
usePlayer.getState().minimize();
|
||||||
|
navigate({ name: 'item', id: item.grandparentId });
|
||||||
|
};
|
||||||
|
// The next episode's own still, as on Android TV: darker than most show art, so the copy reads.
|
||||||
|
const scene = upcoming ?? item;
|
||||||
|
const sceneArt = useMemo(() => ({ ...scene, grandparentArt: scene.thumb || scene.grandparentArt }), [scene]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="player up-next" ref={root} role="dialog" aria-modal="true" aria-labelledby="up-next-label">
|
||||||
|
<div className="up-next-scene">{server && <Backdrop item={sceneArt} className="up-next-backdrop" />}</div>
|
||||||
|
<div className="player-top up-next-top" data-tauri-drag-region={isNative ? true : undefined}>
|
||||||
|
<button className="player-back" onClick={() => usePlayer.getState().minimize()} aria-label="Back to browsing" title="Keep playing in the corner">
|
||||||
|
<Icon name="arrowLeft" size={22} />
|
||||||
|
</button>
|
||||||
|
<button className="player-icon up-next-fullscreen" aria-label={fullscreen ? 'Exit full screen' : 'Full screen'} title={fullscreen ? 'Exit full screen' : 'Full screen'} onClick={() => usePlayer.getState().toggleFullscreen()}>
|
||||||
|
<Icon name={fullscreen ? 'collapse' : 'expand'} size={21} />
|
||||||
|
</button>
|
||||||
|
{!fullscreen && <WindowControls />}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="up-next-head">
|
||||||
|
<div className="up-next-now">
|
||||||
|
<button ref={video} className="up-next-video" onClick={backToVideo} aria-label={`Return to ${item.title}`} />
|
||||||
|
<NowPlaying item={item} />
|
||||||
|
</div>
|
||||||
|
<div className="up-next-info">
|
||||||
|
<span className="micro" id="up-next-label">
|
||||||
|
{upcoming || !contextReady ? 'Up next' : 'More to watch'}
|
||||||
|
</span>
|
||||||
|
{item.grandparentId ? (
|
||||||
|
<button className="player-title-link up-next-logo" title={`Go to ${item.grandparentTitle}`} onClick={openShow}>
|
||||||
|
<TitleArt item={item} maxWidth={300} maxHeight={64} as="h2" />
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<TitleArt item={item} maxWidth={300} maxHeight={64} as="h2" className="up-next-logo" />
|
||||||
|
)}
|
||||||
|
{upcoming ? (
|
||||||
|
<>
|
||||||
|
<h1>{upcoming.title}</h1>
|
||||||
|
<Facts item={{ ...upcoming, viewOffset: 0, originallyAvailableAt: '' }} withFormats={false} />
|
||||||
|
{upcoming.summary && <p className="up-next-summary">{upcoming.summary}</p>}
|
||||||
|
<PlayNext ref={play} />
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
contextReady && <p className="up-next-summary">You’ve reached the end of this series.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{server && <UpNextRows item={item} nextUp={nextUp} />}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Draws the native video into the frame's rectangle and cuts the same hole in
|
||||||
|
* the page, following window resizes and display scale changes.
|
||||||
|
*/
|
||||||
|
function useVideoRect(root: React.RefObject<HTMLDivElement | null>, frame: React.RefObject<HTMLElement | null>) {
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const el = frame.current;
|
||||||
|
const page = root.current;
|
||||||
|
if (!el || !page) return;
|
||||||
|
let raf = 0;
|
||||||
|
const place = () => {
|
||||||
|
cancelAnimationFrame(raf);
|
||||||
|
raf = requestAnimationFrame(() => {
|
||||||
|
const r = el.getBoundingClientRect();
|
||||||
|
page.style.setProperty('--up-x', `${r.x}px`);
|
||||||
|
page.style.setProperty('--up-y', `${r.y}px`);
|
||||||
|
page.style.setProperty('--up-w', `${r.width}px`);
|
||||||
|
page.style.setProperty('--up-h', `${r.height}px`);
|
||||||
|
page.classList.add('placed');
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
// A pixel of overdraw on each side keeps the hole covered at any scale.
|
||||||
|
if (isNative) mpv.rect({ x: r.x * dpr - 1, y: r.y * dpr - 1, width: r.width * dpr + 2, height: r.height * dpr + 2 }).catch(() => {});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const ro = new ResizeObserver(place);
|
||||||
|
ro.observe(el);
|
||||||
|
window.addEventListener('resize', place);
|
||||||
|
place();
|
||||||
|
return () => {
|
||||||
|
cancelAnimationFrame(raf);
|
||||||
|
ro.disconnect();
|
||||||
|
window.removeEventListener('resize', place);
|
||||||
|
if (isNative) mpv.rect(null).catch(() => {});
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where the playing episode is, under the video. Its own subscription: position ticks re-render only this. */
|
||||||
|
function NowPlaying({ item }: { item: Item }) {
|
||||||
|
const position = usePlayer((s) => s.position);
|
||||||
|
const total = usePlayer((s) => s.duration);
|
||||||
|
return (
|
||||||
|
<div className="up-next-progress">
|
||||||
|
<div className="up-next-progress-text">
|
||||||
|
<span>
|
||||||
|
{episodeLabel(item)} · {item.title}
|
||||||
|
</span>
|
||||||
|
<small>−{clock(Math.max(0, total - position))}</small>
|
||||||
|
</div>
|
||||||
|
<div className="up-next-progress-bar">
|
||||||
|
<i style={{ width: `${total ? Math.min(100, (position / total) * 100) : 0}%` }} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Play next episode. While autoplay counts down, a lighter fill sweeps across it.
|
||||||
|
* The store counts in 50 ms steps; the fill is drawn every frame between them.
|
||||||
|
*/
|
||||||
|
function PlayNext({ ref }: { ref: React.Ref<HTMLButtonElement> }) {
|
||||||
|
const counting = usePlayer((s) => s.countdown !== null && s.countdownTotal > 0);
|
||||||
|
const fill = useRef<HTMLSpanElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!counting) return;
|
||||||
|
let last = { value: usePlayer.getState().countdown ?? 0, at: performance.now() };
|
||||||
|
const unsubscribe = usePlayer.subscribe((s, prev) => {
|
||||||
|
if (s.countdown !== prev.countdown && s.countdown !== null) last = { value: s.countdown, at: performance.now() };
|
||||||
|
});
|
||||||
|
let raf = 0;
|
||||||
|
const draw = () => {
|
||||||
|
const { countdownTotal: total } = usePlayer.getState();
|
||||||
|
// Run on from the last step, but never more than a couple of steps ahead (a held countdown stays held).
|
||||||
|
const remaining = Math.max(0, last.value - Math.min(performance.now() - last.at, 120) / 1000);
|
||||||
|
if (fill.current && total) fill.current.style.transform = `scaleX(${1 - remaining / total})`;
|
||||||
|
raf = requestAnimationFrame(draw);
|
||||||
|
};
|
||||||
|
draw();
|
||||||
|
return () => {
|
||||||
|
unsubscribe();
|
||||||
|
cancelAnimationFrame(raf);
|
||||||
|
};
|
||||||
|
}, [counting]);
|
||||||
|
return (
|
||||||
|
<button ref={ref} className={`btn primary lg up-next-play${counting ? ' counting' : ''}`} onClick={() => usePlayer.getState().playNext()}>
|
||||||
|
{counting && <span className="up-next-play-fill" ref={fill} aria-hidden="true" />}
|
||||||
|
<Icon name="play" size={17} />
|
||||||
|
<span>Play next episode</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function UpNextRows({ item, nextUp }: { item: Item; nextUp: Item | null }) {
|
||||||
|
const server = useSession((s) => s.server)!;
|
||||||
|
const season = useQuery({
|
||||||
|
queryKey: [server.machineId, 'children', item.parentId],
|
||||||
|
queryFn: () => api.children(server, item.parentId),
|
||||||
|
enabled: !!item.parentId,
|
||||||
|
staleTime: 30_000,
|
||||||
|
});
|
||||||
|
const related = useQuery({
|
||||||
|
queryKey: [server.machineId, 'related', item.grandparentId],
|
||||||
|
queryFn: () => api.related(server, item.grandparentId),
|
||||||
|
enabled: !!item.grandparentId,
|
||||||
|
staleTime: 10 * 60_000,
|
||||||
|
});
|
||||||
|
const episodes = (season.data ?? []).filter((e) => e.type === 'episode');
|
||||||
|
const seen = new Set([item.grandparentId]);
|
||||||
|
const shows = (related.data ?? []).flatMap((h) => h.items).filter((i) => i.type === 'show' && !seen.has(i.id) && !!seen.add(i.id));
|
||||||
|
|
||||||
|
// The season row starts just before the playing episode.
|
||||||
|
const seasonRow = useRef<HTMLDivElement>(null);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const row = seasonRow.current?.querySelector<HTMLElement>('.shelf');
|
||||||
|
const current = row?.querySelector<HTMLElement>('[aria-current]');
|
||||||
|
if (!row || !current) return;
|
||||||
|
const start = (current.previousElementSibling as HTMLElement | null) ?? current;
|
||||||
|
const target = row.scrollLeft + start.getBoundingClientRect().left - row.getBoundingClientRect().left - parseFloat(getComputedStyle(row).paddingLeft);
|
||||||
|
row.scrollTo({ left: target, behavior: 'instant' });
|
||||||
|
}, [episodes.length]);
|
||||||
|
|
||||||
|
const choose = (episode: Item) => {
|
||||||
|
const st = usePlayer.getState();
|
||||||
|
if (episode.id === item.id) st.dismissPostPlay();
|
||||||
|
else st.play(episode, { resume: true, quality: st.quality });
|
||||||
|
};
|
||||||
|
const browse = async (show: Item) => {
|
||||||
|
await usePlayer.getState().close();
|
||||||
|
navigate({ name: 'item', id: show.id, title: show.title });
|
||||||
|
};
|
||||||
|
if (!episodes.length && !shows.length) return null;
|
||||||
|
return (
|
||||||
|
<div className="up-next-rows">
|
||||||
|
{episodes.length > 0 && (
|
||||||
|
<div ref={seasonRow}>
|
||||||
|
<Shelf title={item.parentIndex ? `Season ${item.parentIndex}` : 'Episodes'} kind="landscape" className="up-next-shelf">
|
||||||
|
{episodes.map((ep) => (
|
||||||
|
<UpNextCard
|
||||||
|
key={ep.id}
|
||||||
|
item={ep}
|
||||||
|
current={ep.id === item.id}
|
||||||
|
caption={ep.id === item.id ? 'Now playing' : ep.id === nextUp?.id ? 'Up next' : duration(ep.duration)}
|
||||||
|
onChoose={() => choose(ep)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Shelf>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{shows.length > 0 && (
|
||||||
|
<Shelf title="Related shows" kind="landscape" className="up-next-shelf">
|
||||||
|
{shows.map((show) => (
|
||||||
|
<UpNextCard key={show.id} item={show} caption={show.year ? String(show.year) : ''} onChoose={() => void browse(show)} />
|
||||||
|
))}
|
||||||
|
</Shelf>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function UpNextCard({ item, caption, current, onChoose }: { item: Item; caption: string; current?: boolean; onChoose: () => void }) {
|
||||||
|
const server = useSession((s) => s.server)!;
|
||||||
|
const episode = item.type === 'episode';
|
||||||
|
const title = episode ? `${item.index}. ${item.title}` : item.title;
|
||||||
|
const progress = episode && !current && item.viewOffset && item.duration ? item.viewOffset / item.duration : 0;
|
||||||
|
return (
|
||||||
|
<article
|
||||||
|
className="card landscape"
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
|
aria-label={title}
|
||||||
|
aria-current={current || undefined}
|
||||||
|
onClick={onChoose}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key !== 'Enter' && e.key !== ' ') return;
|
||||||
|
e.preventDefault();
|
||||||
|
onChoose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="card-cover">
|
||||||
|
<Artwork src={server.image(art.landscape(item), 400, 225)} alt="" fallback={<span className="cover-fallback">{title}</span>} />
|
||||||
|
<div className="card-hover" />
|
||||||
|
{episode && !current && (
|
||||||
|
<div className="card-actions">
|
||||||
|
<span className="card-play" aria-hidden="true">
|
||||||
|
<Icon name="play" size={18} />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{progress > 0 && (
|
||||||
|
<span className="progress-line">
|
||||||
|
<i style={{ width: `${Math.max(3, progress * 100)}%` }} />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="card-caption">
|
||||||
|
<div className="card-title" title={title}>
|
||||||
|
{title}
|
||||||
|
</div>
|
||||||
|
{caption && <div className="card-meta">{caption}</div>}
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -39,5 +39,7 @@ export const mpv = {
|
||||||
set: (name: string, value: unknown) => invoke<void>('player_set', { name, value }),
|
set: (name: string, value: unknown) => invoke<void>('player_set', { name, value }),
|
||||||
get: <T = any>(name: string) => invoke<T>('player_get', { name }),
|
get: <T = any>(name: string) => invoke<T>('player_get', { name }),
|
||||||
show: (visible: boolean) => invoke<void>('player_show', { visible }),
|
show: (visible: boolean) => invoke<void>('player_show', { visible }),
|
||||||
|
/** Draws the video in part of the window (physical pixels), or all of it with null. */
|
||||||
|
rect: (rect: { x: number; y: number; width: number; height: number } | null) => invoke<void>('player_rect', { rect }),
|
||||||
on: (handler: (e: MpvEvent) => void) => listen<MpvEvent>('mpv', handler),
|
on: (handler: (e: MpvEvent) => void) => listen<MpvEvent>('mpv', handler),
|
||||||
};
|
};
|
||||||
|
|
|
||||||
430
src/player/enhance.ts
Normal file
|
|
@ -0,0 +1,430 @@
|
||||||
|
/**
|
||||||
|
* Video enhancement: upscaling tiers built from mpv's scalers, debanding, the
|
||||||
|
* shaders bundled in src-tauri/shaders and, on Windows with an NVIDIA RTX
|
||||||
|
* GPU, the driver's RTX Video Super Resolution.
|
||||||
|
*
|
||||||
|
* Shader tiers: each shader's WHEN condition decides whether it runs for the
|
||||||
|
* current video and window size, so one list covers every case. FSRCNNX 16
|
||||||
|
* doubles luma at any enlargement (1080p in a maximized 1440p window is
|
||||||
|
* doubled and scaled down), KrigBilateral rebuilds subsampled colour, CAS
|
||||||
|
* sharpens at native size (CAS-prescale also before upscaling) and nlmeans
|
||||||
|
* denoises lightly at any size. Against a 1080p reference shrunk to 480p,
|
||||||
|
* FSRCNNX 16 beat the smaller model, two network passes, RAVU and
|
||||||
|
* SSimSuperRes.
|
||||||
|
*
|
||||||
|
* Quality hands enlargement to the GPU's video processor (mpv's d3d11vpp
|
||||||
|
* filter with NVIDIA's scaling mode), sized to the window, which also
|
||||||
|
* removes compression artifacts. It needs D3D11 decoding and SDR video;
|
||||||
|
* otherwise (or at native size) it runs Balanced's chain.
|
||||||
|
*
|
||||||
|
* The tier the user chose (preferences) and the one actually running (player
|
||||||
|
* state) are kept apart: a tier that fails drops to the one below with a
|
||||||
|
* notice instead of silently showing plain scaling, and isn't retried.
|
||||||
|
*/
|
||||||
|
import { useSettings, UPSCALING, type Upscaling } from '../app/settings';
|
||||||
|
import { appInfo, isNative, resourcePath } from '../platform/native';
|
||||||
|
import { toast } from '../ui/overlays';
|
||||||
|
import { mpv } from './engine';
|
||||||
|
import { usePlayer } from './store';
|
||||||
|
|
||||||
|
export const UPSCALING_ORDER: Upscaling[] = ['off', 'performance', 'balanced', 'quality'];
|
||||||
|
|
||||||
|
/** mpv's own scaler settings, read once so Off can put them back. */
|
||||||
|
const SCALER_PROPS = ['scale', 'cscale', 'dscale', 'sigmoid-upscaling', 'deband', 'deband-iterations', 'deband-grain'] as const;
|
||||||
|
let scalerDefaults: Partial<Record<(typeof SCALER_PROPS)[number], unknown>> | null = null;
|
||||||
|
let shaderDir: Promise<string> | null = null;
|
||||||
|
|
||||||
|
const NETWORK = 'FSRCNNX_x2_16-0-4-1.glsl';
|
||||||
|
|
||||||
|
/** RTX Video needs Windows (D3D11) and an NVIDIA RTX GPU. */
|
||||||
|
let rtxVideo = false;
|
||||||
|
appInfo()
|
||||||
|
.then((info) => (rtxVideo = info.platform === 'windows' && info.gpus.some((n) => /NVIDIA/i.test(n) && /\bRTX\b/i.test(n))))
|
||||||
|
.catch(() => {});
|
||||||
|
|
||||||
|
/** Whether this computer can run a tier at all (Quality is greyed out otherwise). */
|
||||||
|
export const tierAvailable = (mode: Upscaling) => mode !== 'quality' || rtxVideo;
|
||||||
|
|
||||||
|
/** mpv label for the RTX Video filter, so other video filters are left alone. */
|
||||||
|
const VSR_LABEL = '@kaleido-vsr';
|
||||||
|
/** NVIDIA's video processor enlarges up to 4×; mpv scales any remainder. */
|
||||||
|
const VSR_MAX_SCALE = 4;
|
||||||
|
|
||||||
|
interface Plan {
|
||||||
|
props: Record<string, unknown>;
|
||||||
|
shaders: string[];
|
||||||
|
/** d3d11vpp settings for RTX Video, or '' for none. */
|
||||||
|
vsr: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a tier runs. Sharpening (CAS) and denoising (nlmeans) are tuned for
|
||||||
|
* SDR levels, so HDR video skips them; the upscalers and debanding stay.
|
||||||
|
* Balanced denoises first, so the network enlarges the picture rather than
|
||||||
|
* the compression noise. FSRCNNX is trained on general imagery, which suits
|
||||||
|
* live action.
|
||||||
|
*/
|
||||||
|
function plan(mode: Upscaling, hdr: boolean, scale: number): Plan {
|
||||||
|
const { enhanceDeband, enhanceSharpen, enhanceDenoise } = useSettings.getState();
|
||||||
|
const sharpen = enhanceSharpen && !hdr;
|
||||||
|
let props: Record<string, unknown>;
|
||||||
|
let shaders: string[] = [];
|
||||||
|
let vsr = '';
|
||||||
|
// RTX Video is SDR-only and only enlarges; otherwise Quality runs Balanced.
|
||||||
|
if (mode === 'quality' && (hdr || scale <= 1.05)) mode = 'balanced';
|
||||||
|
switch (mode) {
|
||||||
|
case 'performance':
|
||||||
|
props = { scale: 'spline36', cscale: 'spline36', dscale: 'mitchell', 'sigmoid-upscaling': true, deband: true, 'deband-iterations': 1, 'deband-grain': 24 };
|
||||||
|
if (sharpen) shaders = ['CAS-prescale.glsl'];
|
||||||
|
break;
|
||||||
|
case 'balanced':
|
||||||
|
props = { scale: 'ewa_lanczossharp', cscale: 'ewa_lanczossharp', dscale: 'mitchell', 'sigmoid-upscaling': true, deband: true, 'deband-iterations': 2, 'deband-grain': 12 };
|
||||||
|
shaders = [...(enhanceDenoise && !hdr ? ['nlmeans_light.glsl'] : []), NETWORK, 'KrigBilateral.glsl', ...(sharpen ? ['CAS.glsl'] : [])];
|
||||||
|
break;
|
||||||
|
case 'quality':
|
||||||
|
// The video processor deblocks as it enlarges; mpv only scales any remainder.
|
||||||
|
props = { scale: 'ewa_lanczossharp', cscale: 'ewa_lanczossharp', dscale: 'mitchell', 'sigmoid-upscaling': true, deband: true, 'deband-iterations': 1, 'deband-grain': 8 };
|
||||||
|
vsr = `d3d11vpp=scaling-mode=nvidia:scale=${Math.min(scale, VSR_MAX_SCALE).toFixed(2)}`;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return { props: { ...scalerDefaults }, shaders: [], vsr };
|
||||||
|
}
|
||||||
|
if (!enhanceDeband) props.deband = false;
|
||||||
|
return { props, shaders, vsr };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** HDR as decoded (a converted stream may already be SDR), else Plex's metadata. */
|
||||||
|
function isHdr() {
|
||||||
|
const st = usePlayer.getState();
|
||||||
|
if (st.videoGamma) return st.videoGamma === 'pq' || st.videoGamma === 'hlg';
|
||||||
|
return st.delivery?.mode !== 'transcode' && !!st.item?.media[st.mediaIndex]?.dynamicRange;
|
||||||
|
}
|
||||||
|
|
||||||
|
// —— Shader failures ————————————————————————————————————————————————
|
||||||
|
|
||||||
|
const shaderErrors: { at: number; text: string }[] = [];
|
||||||
|
|
||||||
|
/** Fed every mpv log line; keeps the ones that mean a user shader or RTX Video failed. */
|
||||||
|
export function noteMpvLog(level: string, prefix: string, text: string) {
|
||||||
|
if (/RTX Super Resolution/i.test(text) && /fail|not supported/i.test(text)) {
|
||||||
|
shaderErrors.push({ at: Date.now(), text: text.trim() });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (level !== 'error' && level !== 'fatal') return;
|
||||||
|
// A missing file is reported by mpv's file/stream layers; a broken one by the renderer.
|
||||||
|
if (/\.glsl/i.test(text) || (/^vo/.test(prefix) && /shader|glsl|hook|compil|spirv|parse/i.test(text))) {
|
||||||
|
shaderErrors.push({ at: Date.now(), text: text.trim() });
|
||||||
|
if (shaderErrors.length > 20) shaderErrors.shift();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
|
||||||
|
/** Descriptions of the render passes mpv ran for the last frame (or redraw). */
|
||||||
|
type Pass = { desc: string; avg: number; samples?: number[] };
|
||||||
|
export async function renderPasses(): Promise<{ desc: string; avg: number }[]> {
|
||||||
|
const passes = await mpv.get<{ fresh?: Pass[]; redraw?: Pass[] }>('vo-passes').catch(() => null);
|
||||||
|
const list = (passes?.fresh?.length ? passes.fresh : passes?.redraw) ?? [];
|
||||||
|
// The median of recent frames: the average includes one-off shader compiles.
|
||||||
|
return list.map((p) => {
|
||||||
|
const s = [...(p.samples ?? [])].sort((a, b) => a - b);
|
||||||
|
return { desc: p.desc, avg: s.length ? s[Math.floor(s.length / 2)] : p.avg };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How much the video is enlarged on screen. The full player fills the window,
|
||||||
|
* which is known before mpv has drawn anything; the miniplayer asks mpv.
|
||||||
|
*/
|
||||||
|
export async function scaleFactor(): Promise<number> {
|
||||||
|
const st = usePlayer.getState();
|
||||||
|
if (!st.video?.width) return 1;
|
||||||
|
if (!st.mini) {
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
return Math.min((window.innerWidth * dpr) / st.video.width, (window.innerHeight * dpr) / st.video.height);
|
||||||
|
}
|
||||||
|
const osd = await mpv.get<{ w: number; h: number; ml: number; mr: number; mt: number; mb: number }>('osd-dimensions').catch(() => null);
|
||||||
|
if (!osd) return 1;
|
||||||
|
return Math.min((osd.w - osd.ml - osd.mr) / st.video.width, (osd.h - osd.mt - osd.mb) / st.video.height);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether RTX Video is enlarging the picture (mpv's output exceeds the decoded size). */
|
||||||
|
async function vsrRunning() {
|
||||||
|
const st = usePlayer.getState();
|
||||||
|
const out = await mpv.get<{ w: number }>('video-out-params').catch(() => null);
|
||||||
|
return !!st.video?.width && !!out?.w && out.w > st.video.width * 1.05;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* After a tier is applied: wait for frames, then look for shader or RTX
|
||||||
|
* Video errors in mpv's log, for the passes that should be running at this
|
||||||
|
* size (the denoiser always, the network when enlarging) and for RTX Video's
|
||||||
|
* enlarged output. Any failing drops to the tier below.
|
||||||
|
*/
|
||||||
|
async function verify(id: number, mode: Upscaling, appliedAt: number, signature: string, { shaders, vsr }: Plan) {
|
||||||
|
for (let i = 0; i < 80 && !usePlayer.getState().firstFrame; i++) await sleep(250);
|
||||||
|
await sleep(1500);
|
||||||
|
if (id !== seq || !usePlayer.getState().open) return;
|
||||||
|
const expected: RegExp[] = [];
|
||||||
|
if (shaders.includes('nlmeans_light.glsl')) expected.push(/Non-local means/);
|
||||||
|
if (shaders.includes(NETWORK) && (await scaleFactor()) > 1) expected.push(/feature map/);
|
||||||
|
let error = shaderErrors.find((e) => e.at >= appliedAt);
|
||||||
|
let missing = false;
|
||||||
|
if (!error && vsr) {
|
||||||
|
missing = true;
|
||||||
|
for (let i = 0; i < 8 && id === seq && usePlayer.getState().open; i++) {
|
||||||
|
error = shaderErrors.find((e) => e.at >= appliedAt);
|
||||||
|
if (error || (await vsrRunning())) {
|
||||||
|
missing = !!error;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await sleep(1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!error && !missing && expected.length) {
|
||||||
|
// A first compile can hold the renderer for over a minute; wait for the
|
||||||
|
// expected passes to appear (or an error) rather than judging too early.
|
||||||
|
// Already compiled, they appear within a few frames.
|
||||||
|
missing = true;
|
||||||
|
const patience = usePlayer.getState().enhance.preparing ? 240 : 8;
|
||||||
|
for (let i = 0; i < patience && id === seq && usePlayer.getState().open; i++) {
|
||||||
|
error = shaderErrors.find((e) => e.at >= appliedAt);
|
||||||
|
const passes = await renderPasses();
|
||||||
|
if (error || expected.every((re) => passes.some((p) => re.test(p.desc)))) {
|
||||||
|
missing = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await sleep(1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (id !== seq) return;
|
||||||
|
if (!error && !missing) {
|
||||||
|
// Nothing compiled at this size (e.g. the network isn't needed) leaves the set unproven.
|
||||||
|
if (expected.length) markWarm(signature);
|
||||||
|
else clearPreparing();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
clearPreparing();
|
||||||
|
failed.add(mode);
|
||||||
|
const fallback = usable(mode);
|
||||||
|
console.warn('[upscaling]', mode, 'failed:', error?.text ?? (vsr ? 'RTX Video output not enlarged' : 'network passes not running'));
|
||||||
|
toast(`${UPSCALING[mode].label} upscaling couldn’t start. Using ${UPSCALING[fallback].label}.`, 'error');
|
||||||
|
requestEnhancement();
|
||||||
|
}
|
||||||
|
|
||||||
|
// —— Applying ——————————————————————————————————————————————————————
|
||||||
|
|
||||||
|
let seq = 0;
|
||||||
|
let chain: Promise<unknown> = Promise.resolve();
|
||||||
|
/** How long preparation must take before the player mentions it. */
|
||||||
|
export const PREPARING_NOTICE_MS = 3000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shader sets that have compiled on this computer. mpv keeps compiled shaders
|
||||||
|
* on disk (gpu-shader-cache-dir); a first compile for Direct3D can take a
|
||||||
|
* while on some GPUs, so until a set is known the player can say so (after a
|
||||||
|
* short delay, so a quick compile shows nothing).
|
||||||
|
*/
|
||||||
|
const WARM_KEY = 'kaleido.warmShaders';
|
||||||
|
function warmSet(): Set<string> {
|
||||||
|
try {
|
||||||
|
return new Set(JSON.parse(localStorage.getItem(WARM_KEY) ?? '[]'));
|
||||||
|
} catch {
|
||||||
|
return new Set();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function clearPreparing() {
|
||||||
|
if (usePlayer.getState().enhance.preparing) usePlayer.setState({ enhance: { ...usePlayer.getState().enhance, preparing: false } });
|
||||||
|
}
|
||||||
|
function markWarm(signature: string) {
|
||||||
|
const set = warmSet();
|
||||||
|
set.add(signature);
|
||||||
|
try {
|
||||||
|
localStorage.setItem(WARM_KEY, JSON.stringify([...set]));
|
||||||
|
} catch {
|
||||||
|
/* per-device convenience only */
|
||||||
|
}
|
||||||
|
if (usePlayer.getState().enhance.preparing) usePlayer.setState({ enhance: { ...usePlayer.getState().enhance, preparing: false } });
|
||||||
|
}
|
||||||
|
/** Tiers that failed this session. */
|
||||||
|
const failed = new Set<Upscaling>();
|
||||||
|
let missingWarned = false;
|
||||||
|
|
||||||
|
/** The chosen tier, or the nearest one below it that this computer can run and hasn't failed. */
|
||||||
|
function usable(mode: Upscaling): Upscaling {
|
||||||
|
let i = UPSCALING_ORDER.indexOf(mode);
|
||||||
|
while (i > 0 && (failed.has(UPSCALING_ORDER[i]) || !tierAvailable(UPSCALING_ORDER[i]))) i--;
|
||||||
|
return UPSCALING_ORDER[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
let mpvVersion = '';
|
||||||
|
/** The last settings sent to mpv (and when), so an identical re-apply leaves mpv alone. */
|
||||||
|
let lastApplied = '';
|
||||||
|
let lastAppliedAt = 0;
|
||||||
|
|
||||||
|
async function apply(id: number, requested: Upscaling) {
|
||||||
|
if (!isNative || id !== seq) return;
|
||||||
|
if (!scalerDefaults) {
|
||||||
|
scalerDefaults = {};
|
||||||
|
for (const p of SCALER_PROPS) scalerDefaults[p] = await mpv.get(p).catch(() => undefined);
|
||||||
|
mpvVersion = (await mpv.get<string>('mpv-version').catch(() => '')) ?? '';
|
||||||
|
}
|
||||||
|
const bypass = usePlayer.getState().enhance.bypass;
|
||||||
|
let mode = usable(requested);
|
||||||
|
const scale = await scaleFactor();
|
||||||
|
let { props, shaders, vsr } = plan(bypass ? 'off' : mode, isHdr(), scale);
|
||||||
|
const dir = await (shaderDir ??= resourcePath('shaders').catch(() => ''));
|
||||||
|
if (shaders.length && !dir) {
|
||||||
|
// No shaders at all: keep the scaler and debanding settings only.
|
||||||
|
if (!missingWarned) toast('The upscaling shaders are missing from this installation.', 'error');
|
||||||
|
missingWarned = true;
|
||||||
|
shaders = [];
|
||||||
|
if (mode !== 'performance') mode = 'performance';
|
||||||
|
({ props, vsr } = plan(mode, isHdr(), scale));
|
||||||
|
}
|
||||||
|
// Decided before touching mpv: while a shader compiles, mpv holds option
|
||||||
|
// changes until it finishes, so a notice set afterwards would come too late.
|
||||||
|
// Keyed by mpv's version too: a new libmpv recompiles everything.
|
||||||
|
// WHEN conditions are evaluated by mpv, not compiled, so changing them needs no recompile.
|
||||||
|
const signature = `${mpvVersion}|${shaders.join('|')}`;
|
||||||
|
const preparing = !bypass && shaders.length > 0 && !warmSet().has(signature);
|
||||||
|
usePlayer.setState({ enhance: { ...usePlayer.getState().enhance, active: mode, preparing } });
|
||||||
|
if (preparing && usePlayer.getState().firstFrame)
|
||||||
|
setTimeout(() => {
|
||||||
|
if (id === seq && usePlayer.getState().enhance.preparing) toast(`Preparing ${UPSCALING[mode].label} upscaling for the first time. The picture may pause for a moment.`);
|
||||||
|
}, PREPARING_NOTICE_MS);
|
||||||
|
|
||||||
|
const settings = JSON.stringify({ props, shaders, vsr });
|
||||||
|
if (settings !== lastApplied) {
|
||||||
|
lastApplied = settings;
|
||||||
|
lastAppliedAt = Date.now();
|
||||||
|
for (const [k, v] of Object.entries(props)) if (v !== undefined) await mpv.set(k, v).catch(() => {});
|
||||||
|
if (shaders.length) {
|
||||||
|
// mpv takes a path list: ';'-separated on Windows, ':' elsewhere.
|
||||||
|
const windows = dir.includes('\\');
|
||||||
|
const list = shaders.map((n) => `${dir}${windows ? '\\' : '/'}${n}`).join(windows ? ';' : ':');
|
||||||
|
await mpv.set('glsl-shaders', list).catch((e) => shaderErrors.push({ at: Date.now(), text: String(e) }));
|
||||||
|
} else await mpv.command('change-list', 'glsl-shaders', 'clr', '').catch(() => {});
|
||||||
|
// Replaced by label; removing one that isn't there is harmless.
|
||||||
|
await mpv.command('vf', 'remove', VSR_LABEL).catch(() => {});
|
||||||
|
if (vsr) await mpv.command('vf', 'add', `${VSR_LABEL}:${vsr}`).catch((e) => shaderErrors.push({ at: Date.now(), text: String(e) }));
|
||||||
|
}
|
||||||
|
// Errors count from when these shaders actually reached mpv, even if this
|
||||||
|
// re-apply changed nothing (mpv may have already reported a failure).
|
||||||
|
if (!bypass && (shaders.length || vsr)) verify(id, mode, lastAppliedAt, signature, { props, shaders, vsr });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies the chosen tier (and stage toggles) to the playing video. Requests
|
||||||
|
* are serialized and only the latest runs, so quick U presses can't interleave.
|
||||||
|
*/
|
||||||
|
export function requestEnhancement() {
|
||||||
|
const id = ++seq;
|
||||||
|
const run = chain.then(() => apply(id, useSettings.getState().upscaling));
|
||||||
|
chain = run.catch(() => {});
|
||||||
|
return run;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a tier failed this session (shown in the player's choices). */
|
||||||
|
export const hasFailed = (mode: Upscaling) => failed.has(mode);
|
||||||
|
|
||||||
|
/** Before/after comparison: enhancement off without changing the preference. */
|
||||||
|
export function toggleBypass() {
|
||||||
|
const st = usePlayer.getState();
|
||||||
|
const bypass = !st.enhance.bypass;
|
||||||
|
usePlayer.setState({ enhance: { ...st.enhance, bypass } });
|
||||||
|
toast(bypass ? 'Enhancement off for comparison · press B to turn it back on' : `Enhancement on · ${UPSCALING[useSettings.getState().upscaling].label}`);
|
||||||
|
return requestEnhancement();
|
||||||
|
}
|
||||||
|
|
||||||
|
// —— Diagnostics ———————————————————————————————————————————————————
|
||||||
|
|
||||||
|
export interface Diagnostics {
|
||||||
|
stages: string[];
|
||||||
|
gpuMs: number;
|
||||||
|
budgetMs: number;
|
||||||
|
dropped: number;
|
||||||
|
input: string;
|
||||||
|
output: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const STAGES: [RegExp, string][] = [
|
||||||
|
[/Non-local means/, 'nlmeans denoising'],
|
||||||
|
[/feature map|FSRCNN/i, 'FSRCNNX 2×'],
|
||||||
|
[/KrigBilateral/, 'KrigBilateral colour'],
|
||||||
|
[/^debanding/, 'Debanding'],
|
||||||
|
[/FidelityFX/, 'CAS sharpening'],
|
||||||
|
];
|
||||||
|
|
||||||
|
/** What the renderer actually did for the last frame, read from mpv. */
|
||||||
|
export async function readDiagnostics(): Promise<Diagnostics> {
|
||||||
|
const passes = await renderPasses();
|
||||||
|
const stages = STAGES.filter(([re]) => passes.some((p) => re.test(p.desc))).map(([, name]) => name);
|
||||||
|
// RTX Video runs in the GPU's video processor, before (and outside) mpv's passes.
|
||||||
|
if (await vsrRunning()) stages.unshift('RTX Video Super Resolution');
|
||||||
|
const scaler = passes.map((p) => /(up|down)scaling \(([\w-]+)\)/.exec(p.desc)).find(Boolean);
|
||||||
|
if (scaler) stages.push(`${scaler[2]} ${scaler[1]}scaling`);
|
||||||
|
const fps = (await mpv.get<number>('estimated-vf-fps').catch(() => 0)) || (await mpv.get<number>('container-fps').catch(() => 0)) || 24;
|
||||||
|
const dropped = ((await mpv.get<number>('frame-drop-count').catch(() => 0)) || 0) + ((await mpv.get<number>('decoder-frame-drop-count').catch(() => 0)) || 0);
|
||||||
|
const osd = await mpv.get<{ w: number; h: number; ml: number; mr: number; mt: number; mb: number }>('osd-dimensions').catch(() => null);
|
||||||
|
const v = usePlayer.getState().video;
|
||||||
|
return {
|
||||||
|
stages,
|
||||||
|
// Pass timings are in nanoseconds.
|
||||||
|
gpuMs: passes.reduce((a, p) => a + (p.avg || 0), 0) / 1e6,
|
||||||
|
budgetMs: 1000 / fps,
|
||||||
|
dropped,
|
||||||
|
input: v?.width ? `${v.width}×${v.height}` : '',
|
||||||
|
output: osd ? `${osd.w - osd.ml - osd.mr}×${osd.h - osd.mt - osd.mb}` : '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* While a neural tier plays, watch for dropped frames and suggest a lighter
|
||||||
|
* tier once per title if the GPU can't keep up.
|
||||||
|
*/
|
||||||
|
let watchTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
export function watchPerformance(active: boolean) {
|
||||||
|
if (watchTimer) clearInterval(watchTimer);
|
||||||
|
watchTimer = null;
|
||||||
|
if (!active || !isNative) return;
|
||||||
|
let last = -1;
|
||||||
|
let warned = false;
|
||||||
|
watchTimer = setInterval(async () => {
|
||||||
|
const st = usePlayer.getState();
|
||||||
|
const mode = st.enhance.active;
|
||||||
|
if (!st.open || st.paused || st.enhance.bypass || (mode !== 'quality' && mode !== 'balanced')) return void (last = -1);
|
||||||
|
const dropped = (await mpv.get<number>('frame-drop-count').catch(() => 0)) || 0;
|
||||||
|
if (last >= 0 && dropped - last >= 10 && !warned) {
|
||||||
|
warned = true;
|
||||||
|
toast(`${UPSCALING[mode].label} is dropping frames on this video. Try a lighter upscaling tier.`);
|
||||||
|
}
|
||||||
|
last = dropped;
|
||||||
|
}, 5000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stage toggles and the tier apply straight away while something plays.
|
||||||
|
useSettings.subscribe((prefs, prev) => {
|
||||||
|
if (!isNative || !usePlayer.getState().open) return;
|
||||||
|
if (prefs.upscaling !== prev.upscaling || prefs.enhanceDeband !== prev.enhanceDeband || prefs.enhanceSharpen !== prev.enhanceSharpen || prefs.enhanceDenoise !== prev.enhanceDenoise) requestEnhancement();
|
||||||
|
});
|
||||||
|
|
||||||
|
// RTX Video enlarges by a fixed factor, so Quality follows the video's size
|
||||||
|
// (known only once decoding starts), the miniplayer and the window.
|
||||||
|
let resizeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
function followSize(delay: number) {
|
||||||
|
const st = usePlayer.getState();
|
||||||
|
if (!isNative || !st.open || usable(useSettings.getState().upscaling) !== 'quality') return;
|
||||||
|
if (resizeTimer) clearTimeout(resizeTimer);
|
||||||
|
resizeTimer = setTimeout(() => requestEnhancement(), delay);
|
||||||
|
}
|
||||||
|
let following = false;
|
||||||
|
/** Called by the player when it opens (not at import: the store imports this module). */
|
||||||
|
export function followVideoSize() {
|
||||||
|
if (following) return;
|
||||||
|
following = true;
|
||||||
|
usePlayer.subscribe((st, prev) => {
|
||||||
|
if (st.video?.width !== prev.video?.width || st.video?.height !== prev.video?.height || st.mini !== prev.mini) followSize(st.mini !== prev.mini ? 600 : 0);
|
||||||
|
});
|
||||||
|
window.addEventListener('resize', () => followSize(400));
|
||||||
|
}
|
||||||
99
src/player/miniWindow.ts
Normal file
|
|
@ -0,0 +1,99 @@
|
||||||
|
/**
|
||||||
|
* The miniplayer as a window of its own (Windows, src-tauri/src/mini.rs): the
|
||||||
|
* video moves into it, so it drags as one piece. This side keeps its page
|
||||||
|
* (src/mini/) up to date and carries out its buttons; macOS keeps the
|
||||||
|
* in-page miniplayer (PlayerOverlay).
|
||||||
|
*/
|
||||||
|
import { hostOS, invoke, isNative, listen } from '../platform/native';
|
||||||
|
import { episodeLabel } from '../app/format';
|
||||||
|
import { MINI_CORNER_KEY, type MiniAction, type MiniState } from '../mini/types';
|
||||||
|
import type { Item } from '../plex/types';
|
||||||
|
|
||||||
|
export const separateMini = isNative && hostOS === 'windows';
|
||||||
|
|
||||||
|
export async function showMiniWindow() {
|
||||||
|
await invoke('mini_show', { corner: localStorage.getItem(MINI_CORNER_KEY) ?? 'br' });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Moves the video back to the main window; harmless when already there. */
|
||||||
|
export async function hideMiniWindow() {
|
||||||
|
await invoke('mini_hide').catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PlayerView {
|
||||||
|
open: boolean;
|
||||||
|
mini: boolean;
|
||||||
|
item: Item | null;
|
||||||
|
paused: boolean;
|
||||||
|
ended: boolean;
|
||||||
|
position: number;
|
||||||
|
duration: number;
|
||||||
|
firstFrame: boolean;
|
||||||
|
buffering: boolean;
|
||||||
|
reconnecting: boolean;
|
||||||
|
error: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PlayerActions {
|
||||||
|
togglePause(): void;
|
||||||
|
seekBy(delta: number): void;
|
||||||
|
expand(): void;
|
||||||
|
close(): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function view(st: PlayerView): MiniState {
|
||||||
|
const item = st.item;
|
||||||
|
return {
|
||||||
|
title: item ? (item.type === 'episode' ? item.grandparentTitle : item.title) : '',
|
||||||
|
subtitle: item?.type === 'episode' ? `${episodeLabel(item)} · ${item.title}` : '',
|
||||||
|
paused: st.paused,
|
||||||
|
ended: st.ended,
|
||||||
|
position: st.position,
|
||||||
|
duration: st.duration,
|
||||||
|
loading: !st.firstFrame && !st.error,
|
||||||
|
// Waiting for the server to come back shows as buffering.
|
||||||
|
buffering: st.buffering || st.reconnecting,
|
||||||
|
error: !!st.error,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mirrors the player into the miniplayer window and listens for its buttons. */
|
||||||
|
export function bridgeMiniWindow(store: { getState(): PlayerView & PlayerActions; subscribe(listener: (st: PlayerView, prev: PlayerView) => void): () => void }) {
|
||||||
|
if (!separateMini) return;
|
||||||
|
let lastSent = 0;
|
||||||
|
let pending: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
|
const send = async () => {
|
||||||
|
pending = null;
|
||||||
|
lastSent = Date.now();
|
||||||
|
const st = store.getState();
|
||||||
|
if (!st.open) return;
|
||||||
|
const { emitTo } = await import('@tauri-apps/api/event');
|
||||||
|
emitTo('mini', 'mini:state', view(st)).catch(() => {});
|
||||||
|
};
|
||||||
|
|
||||||
|
store.subscribe((st, prev) => {
|
||||||
|
if (!st.open || !st.mini) return;
|
||||||
|
// Everything but the position goes straight away; the position a few times a second.
|
||||||
|
const a = view(st);
|
||||||
|
const b = view(prev);
|
||||||
|
const only = (Object.keys(a) as (keyof MiniState)[]).every((k) => k === 'position' || a[k] === b[k]);
|
||||||
|
if (!only || st.mini !== prev.mini) {
|
||||||
|
if (pending) clearTimeout(pending);
|
||||||
|
send();
|
||||||
|
} else if (!pending) {
|
||||||
|
pending = setTimeout(send, Math.max(0, 250 - (Date.now() - lastSent)));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
listen<{ type: MiniAction }>('mini:action', ({ type }) => {
|
||||||
|
const st = store.getState();
|
||||||
|
if (type === 'ready') return send();
|
||||||
|
if (!st.open) return;
|
||||||
|
if (type === 'toggle') st.togglePause();
|
||||||
|
else if (type === 'back') st.seekBy(-10);
|
||||||
|
else if (type === 'forward') st.seekBy(10);
|
||||||
|
else if (type === 'expand') st.expand();
|
||||||
|
else if (type === 'close') st.close();
|
||||||
|
});
|
||||||
|
}
|
||||||
280
src/player/store.test.ts
Normal file
|
|
@ -0,0 +1,280 @@
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import type { MpvEvent } from './engine';
|
||||||
|
|
||||||
|
const harness = vi.hoisted(() => {
|
||||||
|
const memory = new Map<string, string>();
|
||||||
|
vi.stubGlobal('localStorage', { getItem: (k: string) => memory.get(k) ?? null, setItem: (k: string, v: string) => memory.set(k, v), removeItem: (k: string) => memory.delete(k) });
|
||||||
|
vi.stubGlobal('document', Object.assign(new EventTarget(), { hidden: false, hasFocus: () => true, documentElement: { classList: { toggle: vi.fn() } } }));
|
||||||
|
return { event: (_e: MpvEvent) => {}, next: [] as unknown[], focused: true, identity: vi.fn() };
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock('../platform/native', () => ({
|
||||||
|
isNative: true, invoke: vi.fn().mockResolvedValue(undefined), keepAwake: vi.fn(),
|
||||||
|
win: { isFullscreen: vi.fn().mockResolvedValue(false), setFullscreen: vi.fn(), onResized: vi.fn() },
|
||||||
|
}));
|
||||||
|
vi.mock('./engine', () => ({ mpv: {
|
||||||
|
init: vi.fn().mockResolvedValue(undefined), set: vi.fn().mockResolvedValue(undefined),
|
||||||
|
command: vi.fn().mockResolvedValue(undefined), show: vi.fn().mockResolvedValue(undefined),
|
||||||
|
rect: vi.fn().mockResolvedValue(undefined),
|
||||||
|
on: vi.fn(async (cb: typeof harness.event) => { harness.event = cb; return () => {}; }),
|
||||||
|
} }));
|
||||||
|
vi.mock('../app/session', async () => {
|
||||||
|
const { create } = await import('zustand');
|
||||||
|
return { useSession: create(() => ({ server: { machineId: 'test', token: 'test-only', name: 'Test', get: harness.identity }, connection: { local: true } })) };
|
||||||
|
});
|
||||||
|
vi.mock('../downloads/store', () => ({ useDownloads: { getState: () => ({ items: [] }) } }));
|
||||||
|
vi.mock('../app/queries', () => ({ invalidateLibrary: vi.fn() }));
|
||||||
|
vi.mock('../ui/overlays', () => ({ toast: vi.fn() }));
|
||||||
|
vi.mock('./theme', () => ({ stopThemeMusic: vi.fn() }));
|
||||||
|
vi.mock('./miniWindow', () => ({ bridgeMiniWindow: vi.fn(), hideMiniWindow: vi.fn(), showMiniWindow: vi.fn(), separateMini: false }));
|
||||||
|
vi.mock('./enhance', () => ({ followVideoSize: vi.fn(), noteMpvLog: vi.fn(), requestEnhancement: vi.fn().mockResolvedValue(undefined), watchPerformance: vi.fn() }));
|
||||||
|
vi.mock('../plex/playback', () => ({ directUrl: () => 'test://video', previewUrl: () => '', reportTimeline: vi.fn().mockResolvedValue({}), stopTranscode: vi.fn(), transcodeUrl: () => '' }));
|
||||||
|
vi.mock('../plex/api', () => ({ allLeaves: vi.fn(async () => harness.next), metadata: vi.fn(), setWatched: vi.fn().mockResolvedValue(undefined) }));
|
||||||
|
|
||||||
|
import { usePlayer } from './store';
|
||||||
|
import { useSettings } from '../app/settings';
|
||||||
|
import { parseItem } from '../plex/parse';
|
||||||
|
import { mpv } from './engine';
|
||||||
|
import * as api from '../plex/api';
|
||||||
|
|
||||||
|
const episode = (id = '1') => parseItem({ ratingKey: id, type: 'episode', title: `Episode ${id}`, grandparentRatingKey: 'show', duration: 100000,
|
||||||
|
Marker: [{ id: 'credits', type: 'credits', startTimeOffset: 80000, endTimeOffset: 90000 }],
|
||||||
|
Media: [{ Part: [{ key: '/video', Stream: [{ id: 'audio', streamType: 2 }] }] }],
|
||||||
|
});
|
||||||
|
const time = (position: number) => harness.event({ type: 'property', name: 'time-pos', value: position });
|
||||||
|
/** The stream ending at `position` (by default the real end of the 100 s episode). */
|
||||||
|
const eof = (position = 99.6) => {
|
||||||
|
usePlayer.setState({ position });
|
||||||
|
harness.event({ type: 'end-file', reason: 'eof' });
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
vi.stubGlobal('performance', { now: () => Date.now() });
|
||||||
|
Object.assign(document, { hidden: false, hasFocus: () => harness.focused });
|
||||||
|
harness.focused = true;
|
||||||
|
useSettings.setState({ autoplayNext: true, countdownSeconds: 5, skipCredits: 'auto', watchedPercent: 95 });
|
||||||
|
const current = episode();
|
||||||
|
harness.next = [current, episode('2')];
|
||||||
|
vi.mocked(api.metadata).mockResolvedValue(current);
|
||||||
|
await usePlayer.getState().play(current, { resume: false });
|
||||||
|
await Promise.resolve();
|
||||||
|
usePlayer.setState({ firstFrame: true });
|
||||||
|
});
|
||||||
|
afterEach(async () => {
|
||||||
|
await usePlayer.getState().close();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Up Next playback lifecycle', () => {
|
||||||
|
it('opens immediately at any episode credits marker with a single countdown', () => {
|
||||||
|
time(81);
|
||||||
|
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: 5, countdownTotal: 5 });
|
||||||
|
});
|
||||||
|
it.each(['button', 'off', 'auto'] as const)('opens at the first credits frame with movie credit skipping set to %s', (skipCredits) => {
|
||||||
|
useSettings.setState({ skipCredits });
|
||||||
|
time(79.9);
|
||||||
|
expect(usePlayer.getState().postPlay).toBe(false);
|
||||||
|
time(80);
|
||||||
|
expect(usePlayer.getState().postPlay).toBe(true);
|
||||||
|
});
|
||||||
|
it('counts while the native video owns focus instead of the webview', () => {
|
||||||
|
harness.focused = false;
|
||||||
|
time(81);
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(usePlayer.getState().countdown).toBeCloseTo(4);
|
||||||
|
});
|
||||||
|
it('counts elapsed time even when the webview delivers timer callbacks late', () => {
|
||||||
|
time(81);
|
||||||
|
vi.setSystemTime(Date.now() + 2000);
|
||||||
|
vi.advanceTimersByTime(50);
|
||||||
|
expect(usePlayer.getState().countdown).toBeCloseTo(2.95);
|
||||||
|
});
|
||||||
|
it('opens at EOF even when automatic credit skipping is off', () => {
|
||||||
|
useSettings.setState({ skipCredits: 'off' });
|
||||||
|
eof();
|
||||||
|
expect(usePlayer.getState()).toMatchObject({ postPlay: true, ended: true, countdown: 5 });
|
||||||
|
});
|
||||||
|
it('plays the next episode exactly once after the configured delay', () => {
|
||||||
|
const next = vi.fn().mockResolvedValue(undefined);
|
||||||
|
const original = usePlayer.getState().playNext;
|
||||||
|
usePlayer.setState({ playNext: next });
|
||||||
|
time(81);
|
||||||
|
vi.advanceTimersByTime(5100);
|
||||||
|
expect(next).toHaveBeenCalledOnce();
|
||||||
|
vi.advanceTimersByTime(5000);
|
||||||
|
expect(next).toHaveBeenCalledOnce();
|
||||||
|
usePlayer.setState({ playNext: original });
|
||||||
|
});
|
||||||
|
it('starts the next episode from the beginning, ignoring an earlier partial viewing', async () => {
|
||||||
|
const original = usePlayer.getState().play;
|
||||||
|
const spy = vi.fn().mockResolvedValue(undefined);
|
||||||
|
usePlayer.setState({ play: spy, nextUp: { ...episode('2'), viewOffset: 88000 } });
|
||||||
|
await usePlayer.getState().playNext();
|
||||||
|
expect(spy).toHaveBeenCalledWith(expect.objectContaining({ id: '2' }), expect.objectContaining({ resume: false }));
|
||||||
|
usePlayer.setState({ play: original });
|
||||||
|
});
|
||||||
|
it('cancels autoplay while keeping the screen open, including across EOF', () => {
|
||||||
|
time(81);
|
||||||
|
usePlayer.getState().cancelCountdown();
|
||||||
|
eof();
|
||||||
|
vi.advanceTimersByTime(10000);
|
||||||
|
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null, postPlayDismissed: true });
|
||||||
|
});
|
||||||
|
it('returns to credits without reopening while they play', () => {
|
||||||
|
time(81);
|
||||||
|
usePlayer.getState().dismissPostPlay();
|
||||||
|
time(82);
|
||||||
|
expect(usePlayer.getState()).toMatchObject({ postPlay: false, countdown: null });
|
||||||
|
});
|
||||||
|
it('reopens at the end after returning to the credits', () => {
|
||||||
|
time(81);
|
||||||
|
usePlayer.getState().dismissPostPlay();
|
||||||
|
eof();
|
||||||
|
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: 5 });
|
||||||
|
});
|
||||||
|
it('reopens when the credits start again after seeking back into the episode', () => {
|
||||||
|
time(81);
|
||||||
|
usePlayer.getState().dismissPostPlay();
|
||||||
|
usePlayer.getState().seek(40);
|
||||||
|
time(40);
|
||||||
|
expect(usePlayer.getState().postPlay).toBe(false);
|
||||||
|
time(80);
|
||||||
|
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: 5 });
|
||||||
|
});
|
||||||
|
it.each(['hidden', 'mini'] as const)('holds the countdown while %s', (reason) => {
|
||||||
|
time(81);
|
||||||
|
if (reason === 'hidden') Object.assign(document, { hidden: true });
|
||||||
|
if (reason === 'mini') usePlayer.setState({ mini: true });
|
||||||
|
vi.advanceTimersByTime(20000);
|
||||||
|
expect(usePlayer.getState().countdown).toBe(5);
|
||||||
|
Object.assign(document, { hidden: false });
|
||||||
|
harness.focused = true;
|
||||||
|
usePlayer.setState({ paused: false, mini: false });
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(usePlayer.getState().countdown).toBeCloseTo(4);
|
||||||
|
});
|
||||||
|
it('keeps counting at EOF even when mpv reports pause', () => {
|
||||||
|
eof();
|
||||||
|
usePlayer.setState({ paused: true });
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(usePlayer.getState().countdown).toBeCloseTo(4);
|
||||||
|
});
|
||||||
|
it('keeps counting while credits are paused, like Android Up Next', () => {
|
||||||
|
time(81);
|
||||||
|
usePlayer.setState({ paused: true });
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(usePlayer.getState().countdown).toBeCloseTo(4);
|
||||||
|
});
|
||||||
|
it('does not spend hidden time when the app returns before another timer tick', () => {
|
||||||
|
time(80);
|
||||||
|
Object.assign(document, { hidden: true });
|
||||||
|
document.dispatchEvent(new Event('visibilitychange'));
|
||||||
|
vi.setSystemTime(Date.now() + 60000);
|
||||||
|
Object.assign(document, { hidden: false });
|
||||||
|
document.dispatchEvent(new Event('visibilitychange'));
|
||||||
|
vi.advanceTimersByTime(50);
|
||||||
|
expect(usePlayer.getState().countdown).toBeCloseTo(4.95);
|
||||||
|
});
|
||||||
|
it('shows a finale without an autoplay target', () => {
|
||||||
|
usePlayer.setState({ nextUp: null });
|
||||||
|
eof();
|
||||||
|
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null });
|
||||||
|
});
|
||||||
|
it('respects autoplay off', () => {
|
||||||
|
useSettings.setState({ autoplayNext: false });
|
||||||
|
time(81);
|
||||||
|
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null });
|
||||||
|
});
|
||||||
|
it('opens when seeking into credits instead of suppressing Up Next', () => {
|
||||||
|
usePlayer.getState().seek(81);
|
||||||
|
time(81);
|
||||||
|
vi.advanceTimersByTime(2000);
|
||||||
|
time(83);
|
||||||
|
expect(usePlayer.getState().postPlay).toBe(true);
|
||||||
|
expect(mpv.command).toHaveBeenCalledWith('seek', '81.000', 'absolute+exact');
|
||||||
|
});
|
||||||
|
it.each(['ended', 'credits'] as const)('shows Up Next immediately and loads slow episode context after %s', async (reason) => {
|
||||||
|
let resolve!: (items: ReturnType<typeof episode>[]) => void;
|
||||||
|
vi.mocked(api.allLeaves).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
|
||||||
|
await usePlayer.getState().play(episode(), { resume: false });
|
||||||
|
usePlayer.setState({ firstFrame: true });
|
||||||
|
useSettings.setState({ skipCredits: 'button' });
|
||||||
|
if (reason === 'ended') eof();
|
||||||
|
else time(80);
|
||||||
|
expect(usePlayer.getState().postPlay).toBe(true);
|
||||||
|
expect(usePlayer.getState().countdown).toBeNull();
|
||||||
|
resolve([episode(), episode('2')]);
|
||||||
|
await vi.waitFor(() => expect(usePlayer.getState().episodeContextReady).toBe(true));
|
||||||
|
expect(usePlayer.getState().nextUp?.id).toBe('2');
|
||||||
|
expect(usePlayer.getState().countdownTotal).toBe(5);
|
||||||
|
expect(usePlayer.getState().countdown).toBeGreaterThan(4.9);
|
||||||
|
expect(usePlayer.getState().countdown).toBeLessThanOrEqual(5);
|
||||||
|
});
|
||||||
|
it('keeps autoplay cancelled when episode context arrives after interaction', async () => {
|
||||||
|
let resolve!: (items: ReturnType<typeof episode>[]) => void;
|
||||||
|
vi.mocked(api.allLeaves).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
|
||||||
|
await usePlayer.getState().play(episode(), { resume: false });
|
||||||
|
usePlayer.setState({ firstFrame: true });
|
||||||
|
time(80);
|
||||||
|
usePlayer.getState().cancelCountdown();
|
||||||
|
resolve([episode(), episode('2')]);
|
||||||
|
await vi.waitFor(() => expect(usePlayer.getState().episodeContextReady).toBe(true));
|
||||||
|
vi.advanceTimersByTime(10000);
|
||||||
|
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null, postPlayDismissed: true });
|
||||||
|
});
|
||||||
|
it('clears Up Next and its timer when playback closes', async () => {
|
||||||
|
time(81);
|
||||||
|
await usePlayer.getState().close();
|
||||||
|
vi.advanceTimersByTime(10000);
|
||||||
|
expect(usePlayer.getState()).toMatchObject({ open: false, postPlay: false, countdown: null });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Losing the server mid-stream', () => {
|
||||||
|
it('waits for the server instead of ending when the stream is cut off early', () => {
|
||||||
|
eof(42);
|
||||||
|
expect(usePlayer.getState()).toMatchObject({ reconnecting: true, ended: false, postPlay: false });
|
||||||
|
});
|
||||||
|
it('resumes from where it stopped once the server answers again', async () => {
|
||||||
|
const original = usePlayer.getState().play;
|
||||||
|
const play = vi.fn().mockResolvedValue(undefined);
|
||||||
|
usePlayer.setState({ play });
|
||||||
|
harness.identity.mockRejectedValueOnce(new Error('unreachable'));
|
||||||
|
eof(42);
|
||||||
|
await vi.advanceTimersByTimeAsync(2000);
|
||||||
|
expect(play).not.toHaveBeenCalled();
|
||||||
|
expect(usePlayer.getState().reconnecting).toBe(true);
|
||||||
|
harness.identity.mockResolvedValueOnce({});
|
||||||
|
await vi.advanceTimersByTimeAsync(3000);
|
||||||
|
expect(play).toHaveBeenCalledWith(expect.objectContaining({ id: '1' }), expect.objectContaining({ offsetMs: 42000, keepMini: true }));
|
||||||
|
expect(usePlayer.getState().reconnecting).toBe(false);
|
||||||
|
usePlayer.setState({ play: original });
|
||||||
|
});
|
||||||
|
it('tries straight away on Play instead of starting over', async () => {
|
||||||
|
const original = usePlayer.getState().play;
|
||||||
|
const play = vi.fn().mockResolvedValue(undefined);
|
||||||
|
usePlayer.setState({ play });
|
||||||
|
harness.identity.mockResolvedValueOnce({});
|
||||||
|
eof(42);
|
||||||
|
usePlayer.getState().togglePause();
|
||||||
|
await vi.waitFor(() => expect(play).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ offsetMs: 42000 })));
|
||||||
|
expect(mpv.command).not.toHaveBeenCalledWith('seek', '0.000', 'absolute+exact');
|
||||||
|
usePlayer.setState({ play: original });
|
||||||
|
});
|
||||||
|
it('treats a second cut-off at the same place as the real end of the file', async () => {
|
||||||
|
harness.identity.mockResolvedValueOnce({});
|
||||||
|
eof(42);
|
||||||
|
await vi.advanceTimersByTimeAsync(2000);
|
||||||
|
usePlayer.setState({ firstFrame: true });
|
||||||
|
eof(42.5);
|
||||||
|
expect(usePlayer.getState()).toMatchObject({ reconnecting: false, ended: true });
|
||||||
|
});
|
||||||
|
it('stops waiting when the player is closed', async () => {
|
||||||
|
eof(42);
|
||||||
|
await usePlayer.getState().close();
|
||||||
|
harness.identity.mockClear();
|
||||||
|
await vi.advanceTimersByTimeAsync(10000);
|
||||||
|
expect(harness.identity).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -11,7 +11,7 @@ function fadeTo(target: number, done?: () => void) {
|
||||||
if (fade) clearInterval(fade);
|
if (fade) clearInterval(fade);
|
||||||
const a = audio;
|
const a = audio;
|
||||||
fade = setInterval(() => {
|
fade = setInterval(() => {
|
||||||
const step = 0.02;
|
const step = Math.max(0.002, target / 25, a.volume / 25);
|
||||||
if (Math.abs(a.volume - target) <= step) {
|
if (Math.abs(a.volume - target) <= step) {
|
||||||
a.volume = target;
|
a.volume = target;
|
||||||
clearInterval(fade!);
|
clearInterval(fade!);
|
||||||
|
|
@ -21,17 +21,27 @@ function fadeTo(target: number, done?: () => void) {
|
||||||
}, 40);
|
}, 40);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Theme songs are mastered far louder than a film's dialogue, so the setting
|
||||||
|
* follows a square law and scales with the player's own volume: the default
|
||||||
|
* 30% sits around -21 dB, under the show it introduces.
|
||||||
|
*/
|
||||||
|
function themeGain() {
|
||||||
|
const { themeVolume, volume } = useSettings.getState();
|
||||||
|
return Math.pow(themeVolume / 100, 2) * Math.pow(Math.min(100, volume) / 100, 2);
|
||||||
|
}
|
||||||
|
|
||||||
export function playThemeMusic(path: string) {
|
export function playThemeMusic(path: string) {
|
||||||
const prefs = useSettings.getState();
|
const prefs = useSettings.getState();
|
||||||
const server = useSession.getState().server;
|
const server = useSession.getState().server;
|
||||||
if (!prefs.themeMusic || !path || !server || document.documentElement.classList.contains('player-open')) return;
|
if (!prefs.themeMusic || !path || !server || /player-(open|mini)/.test(document.documentElement.className)) return;
|
||||||
if (path === current && audio && !audio.paused) return;
|
if (path === current && audio && !audio.paused) return;
|
||||||
stopThemeMusic(true);
|
stopThemeMusic(true);
|
||||||
current = path;
|
current = path;
|
||||||
audio = new Audio(server.signed(path));
|
audio = new Audio(server.signed(path));
|
||||||
audio.volume = 0;
|
audio.volume = 0;
|
||||||
audio.loop = false;
|
audio.loop = false;
|
||||||
audio.play().then(() => fadeTo(prefs.themeVolume / 100), () => {});
|
audio.play().then(() => fadeTo(themeGain()), () => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function stopThemeMusic(immediate = false) {
|
export function stopThemeMusic(immediate = false) {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { arr, bool, num, str } from './parse';
|
import { arr, bool, num, str } from './parse';
|
||||||
import { clientIdentifier, PlexError, plexRequest, PRODUCT } from './client';
|
import { clientIdentifier, DEVICE, PLATFORM, PlexError, plexRequest, PRODUCT } from './client';
|
||||||
import type { HomeUser, PlexUser, ServerConnection, ServerResource } from './types';
|
import type { HomeUser, PlexUser, ServerConnection, ServerResource } from './types';
|
||||||
|
|
||||||
const TV = 'https://plex.tv/api/v2';
|
const TV = 'https://plex.tv/api/v2';
|
||||||
|
|
@ -26,8 +26,8 @@ export function authUrl(pin: Pin): string {
|
||||||
clientID: clientIdentifier(),
|
clientID: clientIdentifier(),
|
||||||
code: pin.code,
|
code: pin.code,
|
||||||
'context[device][product]': PRODUCT,
|
'context[device][product]': PRODUCT,
|
||||||
'context[device][platform]': 'Windows',
|
'context[device][platform]': PLATFORM,
|
||||||
'context[device][device]': 'Windows',
|
'context[device][device]': DEVICE,
|
||||||
});
|
});
|
||||||
return `https://app.plex.tv/auth#?${params.toString()}`;
|
return `https://app.plex.tv/auth#?${params.toString()}`;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -151,7 +151,7 @@ export interface BandwidthPoint {
|
||||||
wan: number;
|
wan: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Bandwidth samples grouped by time (bytes per sample interval). */
|
/** Bandwidth samples grouped by time (timespan 6: bytes in each second, idle seconds omitted). */
|
||||||
export async function bandwidth(s: PlexServer, timespan = 6): Promise<{ points: BandwidthPoint[]; devices: Record<number, string> }> {
|
export async function bandwidth(s: PlexServer, timespan = 6): Promise<{ points: BandwidthPoint[]; devices: Record<number, string> }> {
|
||||||
const mc = await s.container('/statistics/bandwidth', { timespan });
|
const mc = await s.container('/statistics/bandwidth', { timespan });
|
||||||
const byAt = new Map<number, BandwidthPoint>();
|
const byAt = new Map<number, BandwidthPoint>();
|
||||||
|
|
|
||||||
|
|
@ -94,6 +94,10 @@ export async function firstCharacters(s: PlexServer, sectionId: string, params:
|
||||||
return arr(mc.Directory).map((d: any) => ({ key: str(d.key), title: str(d.title), size: num(d.size) }));
|
return arr(mc.Directory).map((d: any) => ({ key: str(d.key), title: str(d.title), size: num(d.size) }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function genres(s: PlexServer, sectionId: string, type?: number): Promise<FilterOption[]> {
|
||||||
|
return filterOptions(s, `/library/sections/${sectionId}/genre`, type);
|
||||||
|
}
|
||||||
|
|
||||||
export async function collections(s: PlexServer, sectionId: string): Promise<Item[]> {
|
export async function collections(s: PlexServer, sectionId: string): Promise<Item[]> {
|
||||||
const mc = await s.container(`/library/sections/${sectionId}/collections`, { includeCollections: 1, sort: 'titleSort:asc' });
|
const mc = await s.container(`/library/sections/${sectionId}/collections`, { includeCollections: 1, sort: 'titleSort:asc' });
|
||||||
return items(mc);
|
return items(mc);
|
||||||
|
|
@ -221,10 +225,6 @@ export async function removeFromContinueWatching(s: PlexServer, id: string) {
|
||||||
await s.send('PUT', '/actions/removeFromContinueWatching', { ratingKey: id });
|
await s.send('PUT', '/actions/removeFromContinueWatching', { ratingKey: id });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function rate(s: PlexServer, id: string, rating: number) {
|
|
||||||
await s.send('PUT', '/:/rate', { key: id, identifier: 'com.plexapp.plugins.library', rating: rating < 0 ? -1 : rating });
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function selectStreams(s: PlexServer, partId: string, sel: { audioStreamID?: string; subtitleStreamID?: string }) {
|
export async function selectStreams(s: PlexServer, partId: string, sel: { audioStreamID?: string; subtitleStreamID?: string }) {
|
||||||
await s.send('PUT', `/library/parts/${partId}`, { allParts: 1, ...sel });
|
await s.send('PUT', `/library/parts/${partId}`, { allParts: 1, ...sel });
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
import { httpFetch } from '../platform/native';
|
import { hostOS, httpFetch } from '../platform/native';
|
||||||
|
|
||||||
export const PRODUCT = 'Kaleido';
|
export const PRODUCT = 'Kaleido';
|
||||||
export const PLATFORM = 'Windows';
|
/** How Plex lists this player (Plex's own names for each OS and device). */
|
||||||
|
export const PLATFORM = hostOS === 'macos' ? 'macOS' : hostOS === 'linux' ? 'Linux' : 'Windows';
|
||||||
|
export const DEVICE = hostOS === 'macos' ? 'Mac' : hostOS === 'linux' ? 'Linux' : 'Windows';
|
||||||
|
|
||||||
export class PlexError extends Error {
|
export class PlexError extends Error {
|
||||||
constructor(
|
constructor(
|
||||||
|
|
@ -14,7 +16,8 @@ export class PlexError extends Error {
|
||||||
|
|
||||||
let clientId = '';
|
let clientId = '';
|
||||||
let version = '0.1.0';
|
let version = '0.1.0';
|
||||||
let deviceName = 'Windows PC';
|
let deviceName = hostOS === 'macos' ? 'Mac' : 'Windows PC';
|
||||||
|
let platformVersion = hostOS === 'windows' ? '11' : '';
|
||||||
|
|
||||||
/** A stable, random identifier for this installation (not secret). */
|
/** A stable, random identifier for this installation (not secret). */
|
||||||
export function clientIdentifier(): string {
|
export function clientIdentifier(): string {
|
||||||
|
|
@ -27,9 +30,24 @@ export function clientIdentifier(): string {
|
||||||
return clientId;
|
return clientId;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function configureClient(opts: { version?: string; deviceName?: string }) {
|
export function configureClient(opts: { version?: string; deviceName?: string; platformVersion?: string }) {
|
||||||
if (opts.version) version = opts.version;
|
if (opts.version) version = opts.version;
|
||||||
if (opts.deviceName) deviceName = opts.deviceName;
|
if (opts.deviceName) deviceName = opts.deviceName;
|
||||||
|
if (opts.platformVersion) platformVersion = opts.platformVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP header values must be ASCII; Mac names usually aren't ("Elijah’s MacBook").
|
||||||
|
* Typographic punctuation becomes its plain form and accents are dropped.
|
||||||
|
*/
|
||||||
|
export function headerSafe(value: string): string {
|
||||||
|
return value
|
||||||
|
.replace(/[‘’]/g, "'")
|
||||||
|
.replace(/[“”]/g, '"')
|
||||||
|
.replace(/[–—]/g, '-')
|
||||||
|
.normalize('NFKD')
|
||||||
|
.replace(/[^\x20-\x7e]/g, '')
|
||||||
|
.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function plexHeaders(token?: string | null): Record<string, string> {
|
export function plexHeaders(token?: string | null): Record<string, string> {
|
||||||
|
|
@ -39,9 +57,9 @@ export function plexHeaders(token?: string | null): Record<string, string> {
|
||||||
'X-Plex-Version': version,
|
'X-Plex-Version': version,
|
||||||
'X-Plex-Client-Identifier': clientIdentifier(),
|
'X-Plex-Client-Identifier': clientIdentifier(),
|
||||||
'X-Plex-Platform': PLATFORM,
|
'X-Plex-Platform': PLATFORM,
|
||||||
'X-Plex-Platform-Version': '11',
|
'X-Plex-Platform-Version': platformVersion,
|
||||||
'X-Plex-Device': 'Windows',
|
'X-Plex-Device': DEVICE,
|
||||||
'X-Plex-Device-Name': `Kaleido (${deviceName})`,
|
'X-Plex-Device-Name': headerSafe(`Kaleido (${deviceName})`),
|
||||||
'X-Plex-Model': 'Desktop',
|
'X-Plex-Model': 'Desktop',
|
||||||
'X-Plex-Provides': 'player',
|
'X-Plex-Provides': 'player',
|
||||||
'X-Plex-Language': navigator.language || 'en',
|
'X-Plex-Language': navigator.language || 'en',
|
||||||
|
|
@ -57,7 +75,7 @@ export function plexQuery(token?: string | null): Record<string, string> {
|
||||||
'X-Plex-Version': version,
|
'X-Plex-Version': version,
|
||||||
'X-Plex-Client-Identifier': clientIdentifier(),
|
'X-Plex-Client-Identifier': clientIdentifier(),
|
||||||
'X-Plex-Platform': PLATFORM,
|
'X-Plex-Platform': PLATFORM,
|
||||||
'X-Plex-Device': 'Windows',
|
'X-Plex-Device': DEVICE,
|
||||||
'X-Plex-Device-Name': `Kaleido (${deviceName})`,
|
'X-Plex-Device-Name': `Kaleido (${deviceName})`,
|
||||||
};
|
};
|
||||||
if (token) q['X-Plex-Token'] = token;
|
if (token) q['X-Plex-Token'] = token;
|
||||||
|
|
@ -103,23 +121,41 @@ export async function plexRequest<T = any>(url: string, token: string | null | u
|
||||||
const timer = setTimeout(() => controller.abort(), opts.timeout ?? 30000);
|
const timer = setTimeout(() => controller.abort(), opts.timeout ?? 30000);
|
||||||
const onAbort = () => controller.abort();
|
const onAbort = () => controller.abort();
|
||||||
opts.signal?.addEventListener('abort', onAbort);
|
opts.signal?.addEventListener('abort', onAbort);
|
||||||
|
// The timeout and the caller's cancel cover the body as well as the headers: a reply
|
||||||
|
// that stalls part way must still end. (Rejects only once aborted.)
|
||||||
|
const aborted = new Promise<never>((_, reject) =>
|
||||||
|
controller.signal.addEventListener('abort', () => reject(opts.signal?.aborted ? opts.signal.reason : new PlexError('The server took too long to respond.', 0)), { once: true }),
|
||||||
|
);
|
||||||
|
aborted.catch(() => {});
|
||||||
|
if (opts.signal?.aborted) controller.abort();
|
||||||
let response: Response;
|
let response: Response;
|
||||||
|
let text: string;
|
||||||
try {
|
try {
|
||||||
response = await httpFetch(withParams(url, opts.params), {
|
try {
|
||||||
method: opts.method ?? 'GET',
|
response = await Promise.race([
|
||||||
headers: { ...plexHeaders(token), ...opts.headers },
|
httpFetch(withParams(url, opts.params), {
|
||||||
body: opts.body ?? undefined,
|
method: opts.method ?? 'GET',
|
||||||
signal: controller.signal,
|
headers: { ...plexHeaders(token), ...opts.headers },
|
||||||
});
|
body: opts.body ?? undefined,
|
||||||
} catch (e: any) {
|
signal: controller.signal,
|
||||||
if (opts.signal?.aborted) throw e;
|
}),
|
||||||
throw new PlexError(controller.signal.aborted ? 'The server took too long to respond.' : 'Could not reach the server.', 0);
|
aborted,
|
||||||
|
]);
|
||||||
|
} catch (e: any) {
|
||||||
|
if (opts.signal?.aborted) throw e;
|
||||||
|
throw new PlexError(controller.signal.aborted ? 'The server took too long to respond.' : 'Could not reach the server.', 0);
|
||||||
|
}
|
||||||
|
if (!response.ok) throw new PlexError(statusMessage(response.status), response.status);
|
||||||
|
try {
|
||||||
|
text = await Promise.race([response.text(), aborted]);
|
||||||
|
} catch (e: any) {
|
||||||
|
if (opts.signal?.aborted || e instanceof PlexError) throw e;
|
||||||
|
throw new PlexError('The connection to the server was lost.', 0);
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
opts.signal?.removeEventListener('abort', onAbort);
|
opts.signal?.removeEventListener('abort', onAbort);
|
||||||
}
|
}
|
||||||
if (!response.ok) throw new PlexError(statusMessage(response.status), response.status);
|
|
||||||
const text = await response.text();
|
|
||||||
if (opts.text) return text as unknown as T;
|
if (opts.text) return text as unknown as T;
|
||||||
if (!text.trim()) return {} as T;
|
if (!text.trim()) return {} as T;
|
||||||
try {
|
try {
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,10 @@ export function transcodeUrl(
|
||||||
path: `/library/metadata/${item.id}`,
|
path: `/library/metadata/${item.id}`,
|
||||||
mediaIndex: opts.mediaIndex,
|
mediaIndex: opts.mediaIndex,
|
||||||
partIndex: 0,
|
partIndex: 0,
|
||||||
|
// Plex converts the part's selected streams; callers save the selection first and
|
||||||
|
// name it here as well.
|
||||||
|
audioStreamID: opts.audioStreamID,
|
||||||
|
subtitleStreamID: opts.subtitleStreamID,
|
||||||
protocol: 'hls',
|
protocol: 'hls',
|
||||||
session: opts.session,
|
session: opts.session,
|
||||||
offset: (opts.offsetMs / 1000).toFixed(1),
|
offset: (opts.offsetMs / 1000).toFixed(1),
|
||||||
|
|
@ -80,6 +84,12 @@ export function previewUrl(server: PlexServer, media: Media | undefined, timeMs:
|
||||||
return server.signed(`/library/parts/${part.id}/indexes/sd/${Math.max(0, Math.floor(local / 5000) * 5000)}`);
|
return server.signed(`/library/parts/${part.id}/indexes/sd/${Math.max(0, Math.floor(local / 5000) * 5000)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Plex's reply to a timeline report; a stream the server owner stopped carries a termination. */
|
||||||
|
export interface TimelineReply {
|
||||||
|
terminationCode?: number;
|
||||||
|
terminationText?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export async function reportTimeline(
|
export async function reportTimeline(
|
||||||
server: PlexServer,
|
server: PlexServer,
|
||||||
item: Item,
|
item: Item,
|
||||||
|
|
@ -87,8 +97,8 @@ export async function reportTimeline(
|
||||||
timeMs: number,
|
timeMs: number,
|
||||||
session: string,
|
session: string,
|
||||||
extra: Record<string, string | number> = {},
|
extra: Record<string, string | number> = {},
|
||||||
) {
|
): Promise<TimelineReply> {
|
||||||
await server.get(
|
return server.container(
|
||||||
'/:/timeline',
|
'/:/timeline',
|
||||||
{
|
{
|
||||||
ratingKey: item.id,
|
ratingKey: item.id,
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,8 @@ import { describe, expect, it } from 'vitest';
|
||||||
import { parseItem, parseScores } from './parse';
|
import { parseItem, parseScores } from './parse';
|
||||||
import { isLocalAddress } from './account';
|
import { isLocalAddress } from './account';
|
||||||
import { partAt } from './playback';
|
import { partAt } from './playback';
|
||||||
import { duration, formatBadges, isWatched, remaining, washGradient } from '../app/format';
|
import { headerSafe } from './client';
|
||||||
|
import { duration, formatBadges, isWatched, remaining, resumable, washGradient } from '../app/format';
|
||||||
import { buildFeatures } from '../screens/discover';
|
import { buildFeatures } from '../screens/discover';
|
||||||
import type { Hub } from './types';
|
import type { Hub } from './types';
|
||||||
|
|
||||||
|
|
@ -64,10 +65,16 @@ describe('parsing', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('watched rules', () => {
|
describe('watched rules', () => {
|
||||||
it('treats a resumed title as watched only past the threshold', () => {
|
it('keeps a title watched while it is being rewatched', () => {
|
||||||
expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 90)).toBe(false);
|
expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 90)).toBe(true);
|
||||||
expect(isWatched(movie({ viewCount: 1, viewOffset: 5700000 }), 90)).toBe(true);
|
|
||||||
expect(isWatched(movie({ viewCount: 1 }), 90)).toBe(true);
|
expect(isWatched(movie({ viewCount: 1 }), 90)).toBe(true);
|
||||||
|
expect(resumable(movie({ viewCount: 1, viewOffset: 3000000 }))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts an unplayed title as watched only past the threshold', () => {
|
||||||
|
expect(isWatched(movie({ viewOffset: 3000000 }), 90)).toBe(false);
|
||||||
|
expect(isWatched(movie({ viewOffset: 5700000 }), 90)).toBe(true);
|
||||||
|
expect(isWatched(movie({}), 90)).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uses episode counts for shows', () => {
|
it('uses episode counts for shows', () => {
|
||||||
|
|
@ -112,3 +119,10 @@ describe('features', () => {
|
||||||
expect(washGradient(movie().ultraBlur)).toContain('rgba(48, 97, 143');
|
expect(washGradient(movie().ultraBlur)).toContain('rgba(48, 97, 143');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('headerSafe', () => {
|
||||||
|
it('turns Mac computer names into ASCII header values', () => {
|
||||||
|
expect(headerSafe('Elijah’s MacBook Pro')).toBe("Elijah's MacBook Pro");
|
||||||
|
expect(headerSafe('Zoë’s iMac — Studio')).toBe("Zoe's iMac - Studio");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -117,6 +117,15 @@ export default function Downloads({ offline }: { offline?: boolean }) {
|
||||||
const used = store.items.reduce((a, d) => a + (d.status === 'completed' ? d.total || d.received : d.received), 0);
|
const used = store.items.reduce((a, d) => a + (d.status === 'completed' ? d.total || d.received : d.received), 0);
|
||||||
const movies = done.filter((d) => d.meta.raw?.type !== 'episode');
|
const movies = done.filter((d) => d.meta.raw?.type !== 'episode');
|
||||||
const episodes = done.filter((d) => d.meta.raw?.type === 'episode');
|
const episodes = done.filter((d) => d.meta.raw?.type === 'episode');
|
||||||
|
const removeMany = async (list: Download[], what: string) => {
|
||||||
|
const ok = await confirmDialog({
|
||||||
|
title: `Remove ${what}?`,
|
||||||
|
message: `${list.length} download${list.length === 1 ? '' : 's'} will be deleted from this computer. ${list.length === 1 ? 'It stays' : 'They stay'} available on your Plex server.`,
|
||||||
|
confirm: 'Remove',
|
||||||
|
danger: true,
|
||||||
|
});
|
||||||
|
if (ok) await Promise.all(list.map((d) => store.remove(d.id)));
|
||||||
|
};
|
||||||
const shows = new Map<string, Download[]>();
|
const shows = new Map<string, Download[]>();
|
||||||
for (const e of episodes) {
|
for (const e of episodes) {
|
||||||
const k = e.meta.raw?.grandparentTitle ?? 'Episodes';
|
const k = e.meta.raw?.grandparentTitle ?? 'Episodes';
|
||||||
|
|
@ -127,9 +136,14 @@ export default function Downloads({ offline }: { offline?: boolean }) {
|
||||||
<div className={`downloads-page page-pad${offline ? '' : ' top'}`}>
|
<div className={`downloads-page page-pad${offline ? '' : ' top'}`}>
|
||||||
<div className="download-intro">
|
<div className="download-intro">
|
||||||
<div>
|
<div>
|
||||||
<div className="micro">Offline · This computer</div>
|
|
||||||
<h1 className="page-title">Downloads</h1>
|
<h1 className="page-title">Downloads</h1>
|
||||||
<p className="page-subtitle">Movies and episodes saved to this computer play without a connection. Progress syncs to Plex when you’re back online.</p>
|
{store.items.length > 0 && (
|
||||||
|
<div className="actions download-intro-actions">
|
||||||
|
<Button variant="ghost" size="sm" icon="trash" onClick={() => removeMany(store.items, 'all downloads')}>
|
||||||
|
Remove all
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{isNative && (
|
{isNative && (
|
||||||
<div className="storage-card">
|
<div className="storage-card">
|
||||||
|
|
@ -158,14 +172,16 @@ export default function Downloads({ offline }: { offline?: boolean }) {
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!isNative && (
|
{!isNative && (
|
||||||
<EmptyState icon="download" title="Downloads need the desktop app">
|
<div className="downloads-empty">
|
||||||
Install Kaleido for Windows to save movies and episodes for offline viewing.
|
<EmptyState icon="download" title="Downloads need the desktop app">
|
||||||
</EmptyState>
|
Install the Kaleido desktop app to save movies and episodes for offline viewing.
|
||||||
|
</EmptyState>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
{isNative && !store.items.length && (
|
{isNative && !store.items.length && (
|
||||||
<EmptyState icon="download" title="Nothing downloaded yet" action={!offline && <Button variant="ghost" icon="film" onClick={() => navigate({ name: 'section', kind: 'movie', tab: 'library' })}>Browse movies</Button>}>
|
<div className="downloads-empty">
|
||||||
Choose Download on a movie or episode, or download a whole season from its page.
|
<EmptyState icon="download" title="Nothing downloaded yet" />
|
||||||
</EmptyState>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{active.length > 0 && (
|
{active.length > 0 && (
|
||||||
|
|
@ -197,6 +213,11 @@ export default function Downloads({ offline }: { offline?: boolean }) {
|
||||||
<h2>
|
<h2>
|
||||||
Movies <small>{movies.length}</small>
|
Movies <small>{movies.length}</small>
|
||||||
</h2>
|
</h2>
|
||||||
|
{movies.length > 1 && (
|
||||||
|
<Button variant="text" onClick={() => removeMany(movies, 'all downloaded movies')}>
|
||||||
|
Remove all
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{movies.map((d) => (
|
{movies.map((d) => (
|
||||||
<DownloadRow key={d.id} d={d} />
|
<DownloadRow key={d.id} d={d} />
|
||||||
|
|
@ -209,6 +230,11 @@ export default function Downloads({ offline }: { offline?: boolean }) {
|
||||||
<h2>
|
<h2>
|
||||||
{show} <small>{list.length} episode{list.length === 1 ? '' : 's'}</small>
|
{show} <small>{list.length} episode{list.length === 1 ? '' : 's'}</small>
|
||||||
</h2>
|
</h2>
|
||||||
|
{list.length > 1 && (
|
||||||
|
<Button variant="text" onClick={() => removeMany(list, `all ${show} episodes`)}>
|
||||||
|
Remove all
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{list
|
{list
|
||||||
.sort((a, b) => (a.meta.raw.parentIndex - b.meta.raw.parentIndex) * 1000 + (a.meta.raw.index - b.meta.raw.index))
|
.sort((a, b) => (a.meta.raw.parentIndex - b.meta.raw.parentIndex) * 1000 + (a.meta.raw.index - b.meta.raw.index))
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { useMemo } from 'react';
|
import { useMemo } from 'react';
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import * as api from '../plex/api';
|
import * as api from '../plex/api';
|
||||||
import { useSections, useServerQuery } from '../app/queries';
|
import { PROGRESS, WATCH_STATE, useSections, useServerQuery } from '../app/queries';
|
||||||
import { useServer } from '../app/session';
|
import { useServer } from '../app/session';
|
||||||
import { navigate } from '../app/router';
|
import { navigate } from '../app/router';
|
||||||
import { Hero } from '../ui/Hero';
|
import { Hero } from '../ui/Hero';
|
||||||
|
|
@ -14,8 +14,8 @@ export function Home() {
|
||||||
const sections = useSections();
|
const sections = useSections();
|
||||||
const video = (sections.data ?? []).filter((s) => (s.type === 'movie' || s.type === 'show') && !s.hidden);
|
const video = (sections.data ?? []).filter((s) => (s.type === 'movie' || s.type === 'show') && !s.hidden);
|
||||||
|
|
||||||
const home = useServerQuery(['homeHubs'], (s) => api.homeHubs(s));
|
const home = useServerQuery(['homeHubs'], (s) => api.homeHubs(s), WATCH_STATE);
|
||||||
const continueWatching = useServerQuery(['continue'], (s) => api.continueWatching(s), { staleTime: 15_000 });
|
const continueWatching = useServerQuery(['continue'], (s) => api.continueWatching(s), PROGRESS);
|
||||||
// Section hubs feed the hero and the release shelves; shared with Discover.
|
// Section hubs feed the hero and the release shelves; shared with Discover.
|
||||||
const sectionHubs = useQuery({
|
const sectionHubs = useQuery({
|
||||||
queryKey: [server.machineId, 'sectionHubsAll', video.map((s) => s.id).join(',')],
|
queryKey: [server.machineId, 'sectionHubsAll', video.map((s) => s.id).join(',')],
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||||
import * as api from '../plex/api';
|
import * as api from '../plex/api';
|
||||||
import type { Item } from '../plex/types';
|
import type { Item } from '../plex/types';
|
||||||
import { invalidateLibrary, useChildren, useItem, useRelated, useServerQuery } from '../app/queries';
|
import { PROGRESS, useChildren, useItem, useRelated, useServerQuery } from '../app/queries';
|
||||||
import { useServer } from '../app/session';
|
import { useServer } from '../app/session';
|
||||||
import { useSettings } from '../app/settings';
|
import { useSettings } from '../app/settings';
|
||||||
import { goBack, navigate, useRouter } from '../app/router';
|
import { goBack, navigate } from '../app/router';
|
||||||
import { canManage, itemMenu, openDialog, openItem, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions';
|
import { canManage, itemMenu, openDialog, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions';
|
||||||
import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, resolutionLabel, technicalLine } from '../app/format';
|
import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, remainingEpisodes, resolutionLabel, resumable, technicalLine } from '../app/format';
|
||||||
import { Backdrop } from '../ui/Backdrop';
|
import { Backdrop } from '../ui/Backdrop';
|
||||||
import { Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media';
|
import { EpisodeCard, Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media';
|
||||||
import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader, Select } from '../ui/primitives';
|
import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader } from '../ui/primitives';
|
||||||
import { Icon } from '../ui/Icon';
|
import { Icon } from '../ui/Icon';
|
||||||
import { openMenu, toastError } from '../ui/overlays';
|
import { openMenu } from '../ui/overlays';
|
||||||
import { useDownloads } from '../downloads/store';
|
import { useDownloads } from '../downloads/store';
|
||||||
import { playThemeMusic, stopThemeMusic } from '../player/theme';
|
import { playThemeMusic, stopThemeMusic } from '../player/theme';
|
||||||
|
|
||||||
|
|
@ -40,24 +40,29 @@ export function ItemScreen({ id }: { id: string }) {
|
||||||
|
|
||||||
// —— Shared pieces ————————————————————————————————————————————————
|
// —— Shared pieces ————————————————————————————————————————————————
|
||||||
|
|
||||||
function Synopsis({ item, text }: { item: Item; text: string }) {
|
/** Long descriptions open in place when clicked, and close again the same way. */
|
||||||
|
function Synopsis({ text }: { item: Item; text: string }) {
|
||||||
const [clamped, setClamped] = useState(false);
|
const [clamped, setClamped] = useState(false);
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
useEffect(() => setOpen(false), [text]);
|
||||||
if (!text) return null;
|
if (!text) return null;
|
||||||
|
const toggle = () => (clamped || open) && setOpen(!open);
|
||||||
return (
|
return (
|
||||||
<div className="synopsis-wrap">
|
<div className="synopsis-wrap">
|
||||||
<p
|
<p
|
||||||
className="synopsis"
|
className={`synopsis${open ? ' open' : ''}${clamped || open ? ' expandable' : ''}`}
|
||||||
|
role={clamped || open ? 'button' : undefined}
|
||||||
|
tabIndex={clamped || open ? 0 : undefined}
|
||||||
|
aria-expanded={clamped || open ? open : undefined}
|
||||||
|
title={clamped && !open ? 'Show the full description' : undefined}
|
||||||
|
onClick={toggle}
|
||||||
|
onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && (e.preventDefault(), toggle())}
|
||||||
ref={(el) => {
|
ref={(el) => {
|
||||||
if (el) setClamped(el.scrollHeight > el.clientHeight + 2);
|
if (el && !open) setClamped(el.scrollHeight > el.clientHeight + 2);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{text}
|
{text}
|
||||||
</p>
|
</p>
|
||||||
{clamped && (
|
|
||||||
<button className="btn text synopsis-more" onClick={() => openDialog({ kind: 'synopsis', item })}>
|
|
||||||
More
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -180,33 +185,6 @@ function RelatedRows({ item }: { item: Item }) {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function StarRating({ item }: { item: Item }) {
|
|
||||||
const server = useServer();
|
|
||||||
const [value, setValue] = useState(item.userRating);
|
|
||||||
const [hover, setHover] = useState(0);
|
|
||||||
useEffect(() => setValue(item.userRating), [item.userRating]);
|
|
||||||
const set = async (stars: number) => {
|
|
||||||
const rating = stars * 2 === value ? -1 : stars * 2;
|
|
||||||
setValue(Math.max(0, rating));
|
|
||||||
try {
|
|
||||||
await api.rate(server, item.id, rating);
|
|
||||||
invalidateLibrary();
|
|
||||||
} catch (e) {
|
|
||||||
toastError(e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
const shown = hover || value / 2;
|
|
||||||
return (
|
|
||||||
<span className="star-rating" onMouseLeave={() => setHover(0)} aria-label="Your rating">
|
|
||||||
{[1, 2, 3, 4, 5].map((n) => (
|
|
||||||
<button key={n} onMouseEnter={() => setHover(n)} onClick={() => set(n)} aria-label={`${n} star${n > 1 ? 's' : ''}`}>
|
|
||||||
<Icon name={n <= shown ? 'starFill' : 'star'} size={15} />
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AboutPanel({ item }: { item: Item }) {
|
function AboutPanel({ item }: { item: Item }) {
|
||||||
const m = item.media[0];
|
const m = item.media[0];
|
||||||
const rows: [string, ReactNode][] = [];
|
const rows: [string, ReactNode][] = [];
|
||||||
|
|
@ -248,7 +226,6 @@ function AboutPanel({ item }: { item: Item }) {
|
||||||
<aside className="about-panel">
|
<aside className="about-panel">
|
||||||
<div className="about-head">
|
<div className="about-head">
|
||||||
<h3>About</h3>
|
<h3>About</h3>
|
||||||
{['movie', 'show', 'episode', 'season'].includes(item.type) && <StarRating item={item} />}
|
|
||||||
</div>
|
</div>
|
||||||
{item.tagline && <p className="about-tagline">“{item.tagline}”</p>}
|
{item.tagline && <p className="about-tagline">“{item.tagline}”</p>}
|
||||||
{rows.map(([k, v]) => (
|
{rows.map(([k, v]) => (
|
||||||
|
|
@ -278,11 +255,12 @@ function AboutPanel({ item }: { item: Item }) {
|
||||||
// —— Movie ——————————————————————————————————————————————————————————
|
// —— Movie ——————————————————————————————————————————————————————————
|
||||||
|
|
||||||
function MovieDetail({ item }: { item: Item }) {
|
function MovieDetail({ item }: { item: Item }) {
|
||||||
const resume = item.viewOffset > 0 && !isWatched(item);
|
const resume = resumable(item);
|
||||||
return (
|
return (
|
||||||
<div className="detail movie">
|
<div className="detail movie">
|
||||||
<DetailHero item={item}>
|
<DetailHero item={item}>
|
||||||
<Facts item={item} />
|
{/* The Resume button carries the time left; the facts give the runtime. */}
|
||||||
|
<Facts item={{ ...item, viewOffset: 0 }} />
|
||||||
<Synopsis item={item} text={item.summary} />
|
<Synopsis item={item} text={item.summary} />
|
||||||
<div className="actions detail-actions">
|
<div className="actions detail-actions">
|
||||||
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
||||||
|
|
@ -321,115 +299,75 @@ function MovieDetail({ item }: { item: Item }) {
|
||||||
|
|
||||||
// —— Shows and seasons ————————————————————————————————————————————
|
// —— Shows and seasons ————————————————————————————————————————————
|
||||||
|
|
||||||
function EpisodeRow({ ep }: { ep: Item }) {
|
function EpisodeGrid({ episodes, upNextId }: { episodes: Item[] | undefined; upNextId?: string }) {
|
||||||
const server = useServer();
|
if (!episodes) return <PageLoader />;
|
||||||
const percent = useSettings((s) => s.watchedPercent);
|
if (!episodes.length) return <EmptyState icon="tv" title="No episodes" />;
|
||||||
const watched = isWatched(ep, percent);
|
|
||||||
const p = ep.viewOffset && ep.duration ? ep.viewOffset / ep.duration : 0;
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div className="episode-grid">
|
||||||
className="episode-row"
|
{episodes.map((ep) => (
|
||||||
role="button"
|
<EpisodeCard key={ep.id} item={ep} upNext={ep.id === upNextId} />
|
||||||
tabIndex={0}
|
))}
|
||||||
onClick={() => openItem(ep)}
|
|
||||||
onKeyDown={(e) => e.key === 'Enter' && openItem(ep)}
|
|
||||||
onContextMenu={(e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
openMenu(itemMenu(ep), { x: e.clientX, y: e.clientY });
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div className="episode-index">{ep.index || '–'}</div>
|
|
||||||
<div className="episode-pic">
|
|
||||||
<Artwork src={server.image(ep.thumb, 320, 180)} />
|
|
||||||
<button
|
|
||||||
className="episode-play"
|
|
||||||
aria-label={`Play ${ep.title}`}
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
playWithVersion(ep);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Icon name="play" size={18} />
|
|
||||||
</button>
|
|
||||||
{p > 0 && !watched && (
|
|
||||||
<span className="progress-line">
|
|
||||||
<i style={{ width: `${p * 100}%` }} />
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="episode-text">
|
|
||||||
<h3>
|
|
||||||
{ep.title}
|
|
||||||
{watched && <Icon name="check" size={15} className="episode-watched" />}
|
|
||||||
</h3>
|
|
||||||
<div className="episode-meta">
|
|
||||||
{[duration(ep.duration), ep.originallyAvailableAt ? date(ep.originallyAvailableAt) : '', ep.viewOffset && !watched ? remaining(ep) : ''].filter(Boolean).join(' · ')}
|
|
||||||
</div>
|
|
||||||
{ep.summary && <p>{ep.summary}</p>}
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
className="icon-btn episode-more"
|
|
||||||
aria-label="More"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
openMenu(itemMenu(ep), e.currentTarget);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Icon name="dots" size={18} />
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Episodes({ seasons, initialSeason, showPicker = true }: { seasons: Item[]; initialSeason?: string; showPicker?: boolean }) {
|
function EpisodesSection({ episodes, subtitle, upNextId }: { episodes: Item[] | undefined; subtitle?: string; upNextId?: string }) {
|
||||||
const saved = useRouter((s) => s.current.state.season as string | undefined);
|
|
||||||
const [seasonId, setSeasonId] = useState(saved ?? initialSeason ?? seasons[0]?.id);
|
|
||||||
useEffect(() => {
|
|
||||||
if (!seasonId && seasons[0]) setSeasonId(initialSeason ?? seasons[0].id);
|
|
||||||
}, [seasons, initialSeason]);
|
|
||||||
const episodes = useChildren(seasonId);
|
|
||||||
const season = seasons.find((s) => s.id === seasonId);
|
|
||||||
if (!seasons.length) return null;
|
|
||||||
return (
|
return (
|
||||||
<section className="episodes">
|
<section className="episodes">
|
||||||
<div className="episodes-head">
|
<div className="shelf-head">
|
||||||
<h2>Episodes</h2>
|
<h2>
|
||||||
{showPicker && seasons.length > 1 && (
|
Episodes
|
||||||
<Select
|
{subtitle && <small>{subtitle}</small>}
|
||||||
value={seasonId!}
|
</h2>
|
||||||
label="Season"
|
|
||||||
options={seasons.map((s) => ({ value: s.id, label: s.title, hint: s.leafCount ? `${s.leafCount} ep` : undefined }))}
|
|
||||||
onChange={(v) => {
|
|
||||||
setSeasonId(v);
|
|
||||||
useRouter.getState().setState({ season: v });
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{season && (
|
|
||||||
<span className="episodes-sub">
|
|
||||||
{season.leafCount} episodes{season.year ? ` · ${season.year}` : ''}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{season?.summary && <p className="season-summary">{season.summary}</p>}
|
|
||||||
<div className="episode-list">
|
|
||||||
{episodes.isLoading && <PageLoader />}
|
|
||||||
{episodes.data?.map((ep) => <EpisodeRow key={ep.id} ep={ep} />)}
|
|
||||||
{episodes.data && !episodes.data.length && <EmptyState icon="tv" title="No episodes" />}
|
|
||||||
</div>
|
</div>
|
||||||
|
<EpisodeGrid episodes={episodes} upNextId={upNextId} />
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The season's name, which opens a menu of the show's other seasons. */
|
||||||
|
function SeasonSwitcher({ season, seasons }: { season: Item; seasons: Item[] }) {
|
||||||
|
if (seasons.length < 2) return <h1 className="detail-subtitle">{season.title}</h1>;
|
||||||
|
const choose = (e: React.MouseEvent<HTMLButtonElement>) =>
|
||||||
|
openMenu(
|
||||||
|
seasons.map((s) => ({
|
||||||
|
label: s.title,
|
||||||
|
hint: s.leafCount ? `${s.leafCount} episodes` : undefined,
|
||||||
|
checked: s.id === season.id,
|
||||||
|
// Replace, so Back still returns to the show rather than through each season.
|
||||||
|
onSelect: () => s.id !== season.id && navigate({ name: 'item', id: s.id, title: s.title }, { replace: true }),
|
||||||
|
})),
|
||||||
|
e.currentTarget,
|
||||||
|
{ minWidth: 240 },
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<h1 className="detail-subtitle">
|
||||||
|
<button className="season-switch" aria-haspopup="menu" title="Choose a season" onClick={choose}>
|
||||||
|
{season.title}
|
||||||
|
<Icon name="chevronDown" size={20} strokeWidth={2.4} />
|
||||||
|
</button>
|
||||||
|
</h1>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "24 episodes · 8 unwatched", by Plex's own counts so it agrees with the Watched button. */
|
||||||
|
function seasonSubtitle(season: Item) {
|
||||||
|
const count = season.leafCount;
|
||||||
|
if (!count) return '';
|
||||||
|
const left = remainingEpisodes(season);
|
||||||
|
return [`${count} episode${count === 1 ? '' : 's'}`, left > 0 && left < count ? `${left} unwatched` : ''].filter(Boolean).join(' · ');
|
||||||
|
}
|
||||||
|
|
||||||
function ShowDetail({ item }: { item: Item }) {
|
function ShowDetail({ item }: { item: Item }) {
|
||||||
const seasons = useChildren(item.id);
|
const seasons = useChildren(item.id);
|
||||||
const server = useServer();
|
const next = useServerQuery(['onDeck', item.id], (s) => api.onDeckFor(s, item), PROGRESS);
|
||||||
const next = useServerQuery(['onDeck', item.id], (s) => api.onDeckFor(s, item), { staleTime: 15_000 });
|
|
||||||
const nextEp = next.data;
|
const nextEp = next.data;
|
||||||
const seasonList = (seasons.data ?? []).filter((s) => s.type === 'season');
|
const seasonList = (seasons.data ?? []).filter((s) => s.type === 'season');
|
||||||
|
// A single-season show lists its episodes here instead of one lonely poster.
|
||||||
|
const only = seasonList.length === 1 ? seasonList[0] : undefined;
|
||||||
|
const onlyEpisodes = useChildren(only?.id);
|
||||||
const percent = useSettings((s) => s.watchedPercent);
|
const percent = useSettings((s) => s.watchedPercent);
|
||||||
const playLabel = nextEp ? (nextEp.viewOffset ? `Resume ${episodeLabel(nextEp)}` : isWatched(item, percent) ? 'Play' : item.viewedLeafCount ? `Watch ${episodeLabel(nextEp)}` : 'Play') : 'Play';
|
const playLabel = nextEp ? (resumable(nextEp) ? `Resume ${episodeLabel(nextEp)}` : isWatched(item, percent) ? 'Play' : item.viewedLeafCount ? `Watch ${episodeLabel(nextEp)}` : 'Play') : 'Play';
|
||||||
void server;
|
|
||||||
return (
|
return (
|
||||||
<div className="detail show">
|
<div className="detail show">
|
||||||
<DetailHero item={item}>
|
<DetailHero item={item}>
|
||||||
|
|
@ -447,14 +385,16 @@ function ShowDetail({ item }: { item: Item }) {
|
||||||
<DownloadButton item={item} />
|
<DownloadButton item={item} />
|
||||||
<MoreButton item={item} onDeleted={goBack} />
|
<MoreButton item={item} onDeleted={goBack} />
|
||||||
</div>
|
</div>
|
||||||
|
{/* The button names the episode number; this adds its title, and the time left when resuming. */}
|
||||||
{nextEp && (
|
{nextEp && (
|
||||||
<div className="detail-tech">
|
<div className="detail-tech">
|
||||||
Up next: {episodeLabel(nextEp)} · {nextEp.title}
|
Up next: {[nextEp.title, resumable(nextEp) ? remaining(nextEp) : ''].filter(Boolean).join(' · ')}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</DetailHero>
|
</DetailHero>
|
||||||
<div className="detail-body">
|
<div className="detail-body">
|
||||||
<div className="detail-main">
|
<div className="detail-main">
|
||||||
|
{seasons.isLoading && <PageLoader />}
|
||||||
{seasonList.length > 1 && (
|
{seasonList.length > 1 && (
|
||||||
<Shelf title="Seasons">
|
<Shelf title="Seasons">
|
||||||
{seasonList.map((s) => (
|
{seasonList.map((s) => (
|
||||||
|
|
@ -462,7 +402,7 @@ function ShowDetail({ item }: { item: Item }) {
|
||||||
))}
|
))}
|
||||||
</Shelf>
|
</Shelf>
|
||||||
)}
|
)}
|
||||||
{seasons.isLoading ? <PageLoader /> : <Episodes seasons={seasonList} initialSeason={nextEp?.parentId} />}
|
{only && <EpisodesSection episodes={onlyEpisodes.data} subtitle={seasonSubtitle(only)} upNextId={nextEp?.id} />}
|
||||||
<CastRow item={item} />
|
<CastRow item={item} />
|
||||||
<ExtrasRow item={item} />
|
<ExtrasRow item={item} />
|
||||||
<RelatedRows item={item} />
|
<RelatedRows item={item} />
|
||||||
|
|
@ -475,12 +415,21 @@ function ShowDetail({ item }: { item: Item }) {
|
||||||
|
|
||||||
function SeasonDetail({ item }: { item: Item }) {
|
function SeasonDetail({ item }: { item: Item }) {
|
||||||
const show = useItem(item.parentId);
|
const show = useItem(item.parentId);
|
||||||
|
const showItem = show.data;
|
||||||
|
const episodes = useChildren(item.id);
|
||||||
const siblings = useChildren(item.parentId);
|
const siblings = useChildren(item.parentId);
|
||||||
const seasonList = (siblings.data ?? []).filter((s) => s.type === 'season');
|
const seasonList = (siblings.data ?? []).filter((s) => s.type === 'season');
|
||||||
const episodes = useChildren(item.id);
|
const deck = useServerQuery(['onDeck', item.parentId], (s) => (showItem ? api.onDeckFor(s, showItem) : Promise.resolve(null)), { ...PROGRESS, enabled: !!showItem });
|
||||||
const percent = useSettings((s) => s.watchedPercent);
|
const percent = useSettings((s) => s.watchedPercent);
|
||||||
const next = (episodes.data ?? []).find((e) => !isWatched(e, percent)) ?? episodes.data?.[0];
|
const list = episodes.data ?? [];
|
||||||
const showItem = show.data;
|
// The show's up-next episode when it is in this season (so the season page and the
|
||||||
|
// show page agree), else the first one started but never finished, else the first
|
||||||
|
// unwatched, else the start of the season. Positions left by rewatches don't count.
|
||||||
|
const deckHere = deck.data?.parentId === item.id ? list.find((e) => e.id === deck.data!.id) : undefined;
|
||||||
|
const next = deckHere ?? list.find((e) => resumable(e) && !isWatched(e, percent)) ?? list.find((e) => !isWatched(e, percent)) ?? list[0];
|
||||||
|
const resumeNext = !!next && resumable(next) && (next === deckHere || !isWatched(next, percent));
|
||||||
|
const aired = list.find((e) => e.originallyAvailableAt)?.originallyAvailableAt;
|
||||||
|
const year = aired ? new Date(aired).getFullYear() : item.year;
|
||||||
return (
|
return (
|
||||||
<div className="detail season">
|
<div className="detail season">
|
||||||
<DetailHero
|
<DetailHero
|
||||||
|
|
@ -495,15 +444,15 @@ function SeasonDetail({ item }: { item: Item }) {
|
||||||
) : (
|
) : (
|
||||||
<h2 className="title-text small">{item.parentTitle}</h2>
|
<h2 className="title-text small">{item.parentTitle}</h2>
|
||||||
)}
|
)}
|
||||||
<h1 className="detail-subtitle">{item.title}</h1>
|
<SeasonSwitcher season={item} seasons={seasonList} />
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Facts item={{ ...item, contentRating: showItem?.contentRating ?? item.contentRating, genres: [] }} />
|
<Facts item={{ ...item, year, contentRating: showItem?.contentRating ?? item.contentRating, genres: [] }} />
|
||||||
<Synopsis item={item} text={item.summary || showItem?.summary || ''} />
|
<Synopsis item={item} text={item.summary || showItem?.summary || ''} />
|
||||||
<div className="actions detail-actions">
|
<div className="actions detail-actions">
|
||||||
<Button variant="primary" icon="play" disabled={!next} onClick={() => next && playWithVersion(next)}>
|
<Button variant="primary" icon="play" disabled={!next} onClick={() => next && playWithVersion(next, resumeNext ? {} : { offsetMs: 0, resume: false })}>
|
||||||
{next ? (next.viewOffset ? `Resume ${episodeLabel(next)}` : `Play ${episodeLabel(next)}`) : 'Play'}
|
{next ? `${resumeNext ? 'Resume' : 'Play'} ${episodeLabel(next)}` : 'Play'}
|
||||||
</Button>
|
</Button>
|
||||||
<WatchedButton item={item} />
|
<WatchedButton item={item} />
|
||||||
<DownloadButton item={item} />
|
<DownloadButton item={item} />
|
||||||
|
|
@ -512,7 +461,7 @@ function SeasonDetail({ item }: { item: Item }) {
|
||||||
</DetailHero>
|
</DetailHero>
|
||||||
<div className="detail-body single">
|
<div className="detail-body single">
|
||||||
<div className="detail-main">
|
<div className="detail-main">
|
||||||
<Episodes seasons={seasonList.length ? seasonList : [item]} initialSeason={item.id} />
|
<EpisodesSection episodes={episodes.data} subtitle={seasonSubtitle(item)} upNextId={resumeNext ? next?.id : undefined} />
|
||||||
{showItem && <CastRow item={showItem} />}
|
{showItem && <CastRow item={showItem} />}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -523,7 +472,7 @@ function SeasonDetail({ item }: { item: Item }) {
|
||||||
function EpisodeDetail({ item }: { item: Item }) {
|
function EpisodeDetail({ item }: { item: Item }) {
|
||||||
const show = useItem(item.grandparentId);
|
const show = useItem(item.grandparentId);
|
||||||
const siblings = useChildren(item.parentId);
|
const siblings = useChildren(item.parentId);
|
||||||
const resume = item.viewOffset > 0 && !isWatched(item);
|
const resume = resumable(item);
|
||||||
const showItem = show.data;
|
const showItem = show.data;
|
||||||
const others = (siblings.data ?? []).filter((e) => e.id !== item.id);
|
const others = (siblings.data ?? []).filter((e) => e.id !== item.id);
|
||||||
const startIndex = Math.max(0, (siblings.data ?? []).findIndex((e) => e.id === item.id));
|
const startIndex = Math.max(0, (siblings.data ?? []).findIndex((e) => e.id === item.id));
|
||||||
|
|
@ -546,7 +495,7 @@ function EpisodeDetail({ item }: { item: Item }) {
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Facts item={{ ...item, contentRating: item.contentRating || showItem?.contentRating || '' }} />
|
<Facts item={{ ...item, viewOffset: 0, contentRating: item.contentRating || showItem?.contentRating || '' }} />
|
||||||
<Synopsis item={item} text={item.summary} />
|
<Synopsis item={item} text={item.summary} />
|
||||||
<div className="actions detail-actions">
|
<div className="actions detail-actions">
|
||||||
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
||||||
|
|
|
||||||
|
|
@ -33,7 +33,8 @@ function useDebounced<T>(value: T, ms: number) {
|
||||||
return v;
|
return v;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function LibraryBrowser({ section, kind }: { section: Section; kind: SectionKind }) {
|
/** `lockedFilters` (e.g. a category's genre) always apply and aren't shown as removable. */
|
||||||
|
export function LibraryBrowser({ section, kind, lockedFilters }: { section: Section; kind: SectionKind; lockedFilters?: Record<string, string> }) {
|
||||||
const server = useServer();
|
const server = useServer();
|
||||||
const type = kind === 'movie' ? 1 : 2;
|
const type = kind === 'movie' ? 1 : 2;
|
||||||
const views = useSettings((s) => s.libraryViews);
|
const views = useSettings((s) => s.libraryViews);
|
||||||
|
|
@ -63,7 +64,7 @@ export function LibraryBrowser({ section, kind }: { section: Section; kind: Sect
|
||||||
const openFilters = async (anchor: HTMLElement) => {
|
const openFilters = async (anchor: HTMLElement) => {
|
||||||
const filters = meta.data?.filters ?? [];
|
const filters = meta.data?.filters ?? [];
|
||||||
const bools = filters.filter((f) => f.type === 'boolean');
|
const bools = filters.filter((f) => f.type === 'boolean');
|
||||||
const strings = filters.filter((f) => f.type !== 'boolean' && QUICK_FILTERS.includes(f.filter));
|
const strings = filters.filter((f) => f.type !== 'boolean' && QUICK_FILTERS.includes(f.filter) && !lockedFilters?.[f.filter]);
|
||||||
const options = await Promise.all(strings.map((f) => loadOptions(f).catch(() => [])));
|
const options = await Promise.all(strings.map((f) => loadOptions(f).catch(() => [])));
|
||||||
const items: MenuItem[] = [
|
const items: MenuItem[] = [
|
||||||
...bools.map((f) => ({
|
...bools.map((f) => ({
|
||||||
|
|
@ -117,7 +118,8 @@ export function LibraryBrowser({ section, kind }: { section: Section; kind: Sect
|
||||||
|
|
||||||
if (meta.isError && !meta.data) return <ErrorState error={meta.error} onRetry={() => meta.refetch()} />;
|
if (meta.isError && !meta.data) return <ErrorState error={meta.error} onRetry={() => meta.refetch()} />;
|
||||||
|
|
||||||
const activeFilters = Object.entries(view.filters);
|
const activeFilters = Object.entries(view.filters).filter(([k]) => !lockedFilters?.[k]);
|
||||||
|
const gridFilters = { ...view.filters, ...lockedFilters };
|
||||||
return (
|
return (
|
||||||
<div className="library">
|
<div className="library">
|
||||||
<div className="lib-toolbar">
|
<div className="lib-toolbar">
|
||||||
|
|
@ -182,7 +184,7 @@ export function LibraryBrowser({ section, kind }: { section: Section; kind: Sect
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<LibraryGrid key={`${section.id}|${view.sort}|${JSON.stringify(view.filters)}|${title}`} section={section} type={type} sort={view.sort} filters={view.filters} title={title} sortTitle={sortTitle} />
|
<LibraryGrid key={`${section.id}|${view.sort}|${JSON.stringify(gridFilters)}|${title}`} section={section} type={type} sort={view.sort} filters={gridFilters} title={title} sortTitle={sortTitle} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -234,6 +236,33 @@ function LibraryGrid({ section, type, sort, filters, title, sortTitle }: { secti
|
||||||
loadPage(0);
|
loadPage(0);
|
||||||
}, [loadPage]);
|
}, [loadPage]);
|
||||||
|
|
||||||
|
// Pages are copied out of the cache, so nothing re-renders when it is invalidated
|
||||||
|
// (watched state, edits, deletions, library changes): fetch the loaded ones again.
|
||||||
|
const loaded = useRef(pages);
|
||||||
|
loaded.current = pages;
|
||||||
|
useEffect(() => {
|
||||||
|
const prefix = JSON.stringify([server.machineId, 'libraryPage', section.id, params]);
|
||||||
|
const due = new Set<number>();
|
||||||
|
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
||||||
|
if (event.type !== 'updated' || event.action.type !== 'invalidate') return;
|
||||||
|
const key = event.query.queryKey;
|
||||||
|
const p = key[4];
|
||||||
|
if (typeof p !== 'number' || !loaded.current[p] || JSON.stringify(key.slice(0, 4)) !== prefix) return;
|
||||||
|
due.add(p);
|
||||||
|
// One pass after the whole invalidation, not one per page as it happens.
|
||||||
|
timer ??= setTimeout(() => {
|
||||||
|
timer = null;
|
||||||
|
for (const page of due) loadPage(page);
|
||||||
|
due.clear();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
unsubscribe();
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
};
|
||||||
|
}, [loadPage]);
|
||||||
|
|
||||||
const gap = 16;
|
const gap = 16;
|
||||||
const target = CARD_WIDTH[posterSize];
|
const target = CARD_WIDTH[posterSize];
|
||||||
const cols = Math.max(2, Math.floor((width + gap) / (target + gap)));
|
const cols = Math.max(2, Math.floor((width + gap) / (target + gap)));
|
||||||
|
|
@ -276,6 +305,22 @@ function LibraryGrid({ section, type, sort, filters, title, sortTitle }: { secti
|
||||||
virtualizer.scrollToIndex(Math.floor(offset / cols), { align: 'start' });
|
virtualizer.scrollToIndex(Math.floor(offset / cols), { align: 'start' });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// The letter of the first title in view, highlighted on the rail.
|
||||||
|
let current = '';
|
||||||
|
if (alpha && letters.data && vrows.length) {
|
||||||
|
const scrollTop = (scrollEl?.scrollTop ?? 0) - virtualizer.options.scrollMargin + 150;
|
||||||
|
const firstRow = vrows.find((r) => r.end > scrollTop) ?? vrows[0];
|
||||||
|
const list = sort.endsWith(':desc') ? [...letters.data].reverse() : letters.data;
|
||||||
|
let offset = 0;
|
||||||
|
for (const l of list) {
|
||||||
|
offset += l.size;
|
||||||
|
if (firstRow.index * cols < offset) {
|
||||||
|
current = l.title;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (error && total === null) return <ErrorState error={error} onRetry={() => (setError(null), loadPage(0))} />;
|
if (error && total === null) return <ErrorState error={error} onRetry={() => (setError(null), loadPage(0))} />;
|
||||||
return (
|
return (
|
||||||
<div className="library-body">
|
<div className="library-body">
|
||||||
|
|
@ -314,7 +359,7 @@ function LibraryGrid({ section, type, sort, filters, title, sortTitle }: { secti
|
||||||
{alpha && letters.data && letters.data.length > 3 && (
|
{alpha && letters.data && letters.data.length > 3 && (
|
||||||
<div className="alpha-rail" aria-label="Jump to letter">
|
<div className="alpha-rail" aria-label="Jump to letter">
|
||||||
{letters.data.map((l) => (
|
{letters.data.map((l) => (
|
||||||
<button key={l.title} onClick={() => jump(l.title)} title={`${l.title} · ${l.size}`}>
|
<button key={l.title} className={l.title === current ? 'current' : ''} onClick={() => jump(l.title)} title={`${l.title} · ${l.size}`}>
|
||||||
{l.title}
|
{l.title}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { keepPreviousData } from '@tanstack/react-query';
|
||||||
import * as api from '../plex/api';
|
import * as api from '../plex/api';
|
||||||
import { useServerQuery } from '../app/queries';
|
import { useServerQuery } from '../app/queries';
|
||||||
import { navigate, useRouter } from '../app/router';
|
import { navigate, useRouter } from '../app/router';
|
||||||
|
|
@ -40,12 +41,12 @@ export default function Search({ initial }: { initial?: string }) {
|
||||||
input.current?.focus();
|
input.current?.focus();
|
||||||
}, []);
|
}, []);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const t = setTimeout(() => setDebounced(query.trim()), 250);
|
const t = setTimeout(() => setDebounced(query.trim()), 160);
|
||||||
useRouter.getState().setState({ query });
|
useRouter.getState().setState({ query });
|
||||||
return () => clearTimeout(t);
|
return () => clearTimeout(t);
|
||||||
}, [query]);
|
}, [query]);
|
||||||
|
|
||||||
const results = useServerQuery(['search', debounced], (s) => api.search(s, debounced), { enabled: debounced.length > 0, staleTime: 60_000 });
|
const results = useServerQuery(['search', debounced], (s) => api.search(s, debounced), { enabled: debounced.length > 0, staleTime: 60_000, placeholderData: keepPreviousData });
|
||||||
const recentlyAdded = useServerQuery(['homeHubs'], (s) => api.homeHubs(s), { enabled: !debounced });
|
const recentlyAdded = useServerQuery(['homeHubs'], (s) => api.homeHubs(s), { enabled: !debounced });
|
||||||
|
|
||||||
const remember = (q: string) => {
|
const remember = (q: string) => {
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,22 @@
|
||||||
import { useMemo } from 'react';
|
import { useMemo } from 'react';
|
||||||
import * as api from '../plex/api';
|
import * as api from '../plex/api';
|
||||||
import { useSectionFor, useServerQuery } from '../app/queries';
|
import { PROGRESS, useSectionFor, useServerQuery } from '../app/queries';
|
||||||
import { navigate, type SectionKind, type SectionTab } from '../app/router';
|
import { navigate, useRouter, type SectionKind, type SectionTab } from '../app/router';
|
||||||
import { useSettings } from '../app/settings';
|
import { useSettings } from '../app/settings';
|
||||||
import type { Section } from '../plex/types';
|
import type { Section } from '../plex/types';
|
||||||
import { Hero } from '../ui/Hero';
|
import { Hero } from '../ui/Hero';
|
||||||
import { HubShelf, PosterCard } from '../ui/media';
|
import { HubShelf } from '../ui/media';
|
||||||
import { EmptyState, ErrorState, PageLoader, Select } from '../ui/primitives';
|
import { useServer } from '../app/session';
|
||||||
|
import { Icon } from '../ui/Icon';
|
||||||
|
import { categoryArtwork } from './categories';
|
||||||
|
import { Artwork, EmptyState, ErrorState, PageLoader, Select } from '../ui/primitives';
|
||||||
import { buildFeatures, HIDDEN_HUBS, recentSeasons } from './discover';
|
import { buildFeatures, HIDDEN_HUBS, recentSeasons } from './discover';
|
||||||
import { LibraryBrowser } from './LibraryBrowser';
|
import { LibraryBrowser } from './LibraryBrowser';
|
||||||
|
|
||||||
const TABS: { id: SectionTab; label: string }[] = [
|
const TABS: { id: SectionTab; label: string }[] = [
|
||||||
{ id: 'discover', label: 'Discover' },
|
{ id: 'discover', label: 'Discover' },
|
||||||
{ id: 'library', label: 'Library' },
|
{ id: 'library', label: 'Library' },
|
||||||
{ id: 'collections', label: 'Collections' },
|
{ id: 'categories', label: 'Categories' },
|
||||||
];
|
];
|
||||||
|
|
||||||
function SectionHeader({ kind, tab, section, all, overlay }: { kind: SectionKind; tab: SectionTab; section: Section; all: Section[]; overlay: boolean }) {
|
function SectionHeader({ kind, tab, section, all, overlay }: { kind: SectionKind; tab: SectionTab; section: Section; all: Section[]; overlay: boolean }) {
|
||||||
|
|
@ -43,7 +46,7 @@ function SectionHeader({ kind, tab, section, all, overlay }: { kind: SectionKind
|
||||||
|
|
||||||
function Discover({ kind, section }: { kind: SectionKind; section: Section }) {
|
function Discover({ kind, section }: { kind: SectionKind; section: Section }) {
|
||||||
const hubs = useServerQuery(['sectionHubs', section.id], (s) => api.sectionHubs(s, section.id));
|
const hubs = useServerQuery(['sectionHubs', section.id], (s) => api.sectionHubs(s, section.id));
|
||||||
const cw = useServerQuery(['continue', section.id], (s) => api.continueWatching(s, section.id), { staleTime: 15_000 });
|
const cw = useServerQuery(['continue', section.id], (s) => api.continueWatching(s, section.id), PROGRESS);
|
||||||
const seasons = useServerQuery(['recentSeasons', section.id], (s) => recentSeasons(s, section.id), { enabled: kind === 'show', staleTime: 120_000 });
|
const seasons = useServerQuery(['recentSeasons', section.id], (s) => recentSeasons(s, section.id), { enabled: kind === 'show', staleTime: 120_000 });
|
||||||
const features = useMemo(() => buildFeatures(hubs.data ?? [], 7, kind === 'movie' ? 1 : 2), [hubs.data, kind]);
|
const features = useMemo(() => buildFeatures(hubs.data ?? [], 7, kind === 'movie' ? 1 : 2), [hubs.data, kind]);
|
||||||
|
|
||||||
|
|
@ -67,29 +70,65 @@ function Discover({ kind, section }: { kind: SectionKind; section: Section }) {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Collections({ section }: { section: Section }) {
|
/** Genres as artwork tiles, as on Kaleido for TV; each opens the library filtered to it. */
|
||||||
const q = useServerQuery(['collections', section.id], (s) => api.collections(s, section.id));
|
function Categories({ kind, section }: { kind: SectionKind; section: Section }) {
|
||||||
if (q.isError) return <ErrorState error={q.error} onRetry={() => q.refetch()} />;
|
const server = useServer();
|
||||||
if (!q.data) return <PageLoader />;
|
const type = kind === 'movie' ? 1 : 2;
|
||||||
if (!q.data.length)
|
const genres = useServerQuery(['genres', section.id, type], (s) => api.genres(s, section.id, type), { staleTime: 30 * 60_000 });
|
||||||
|
const artwork = useServerQuery(['categoryArtwork', section.id, type, genres.data?.map((g) => g.key).join(',')], (s) => categoryArtwork(s, section.id, type, genres.data ?? []), {
|
||||||
|
enabled: !!genres.data?.length,
|
||||||
|
staleTime: 30 * 60_000,
|
||||||
|
});
|
||||||
|
if (genres.isError) return <ErrorState error={genres.error} onRetry={() => genres.refetch()} />;
|
||||||
|
if (!genres.data) return <PageLoader />;
|
||||||
|
if (!genres.data.length)
|
||||||
return (
|
return (
|
||||||
<EmptyState icon="collection" title="No collections yet">
|
<EmptyState icon="grid" title="No categories">
|
||||||
Collections created in Plex for {section.title} appear here.
|
{section.title} has no genres yet.
|
||||||
</EmptyState>
|
</EmptyState>
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<div className="page-pad">
|
<div className="page-pad">
|
||||||
<div className="grid-count">{q.data.length.toLocaleString()} collections</div>
|
<div className="category-grid">
|
||||||
<div className="poster-grid auto">
|
{genres.data.map((g) => {
|
||||||
{q.data.map((c) => (
|
const path = artwork.data?.[g.key];
|
||||||
<PosterCard key={c.id} item={c} />
|
return (
|
||||||
))}
|
<button key={g.key} className="category-tile" onClick={() => navigate({ name: 'section', kind, tab: 'categories', genre: g.key, genreTitle: g.title })}>
|
||||||
|
{path && <Artwork src={server.image(path, 540, 304)} />}
|
||||||
|
<span className="category-scrim" />
|
||||||
|
<span className="category-title">{g.title}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SectionScreen({ kind, tab }: { kind: SectionKind; tab: SectionTab }) {
|
/** Back to the grid: pop the history entry when that's where the genre was opened from. */
|
||||||
|
function backToCategories(kind: SectionKind) {
|
||||||
|
const { entries, index, back } = useRouter.getState();
|
||||||
|
const prev = entries[index - 1]?.route;
|
||||||
|
if (prev?.name === 'section' && prev.tab === 'categories' && !prev.genre) back();
|
||||||
|
else navigate({ name: 'section', kind, tab: 'categories' }, { replace: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
function CategoryLibrary({ kind, section, genre, title }: { kind: SectionKind; section: Section; genre: string; title: string }) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="category-head">
|
||||||
|
<button className="category-back" onClick={() => backToCategories(kind)}>
|
||||||
|
<Icon name="back" size={16} />
|
||||||
|
Categories
|
||||||
|
</button>
|
||||||
|
<h2>{title}</h2>
|
||||||
|
</div>
|
||||||
|
<LibraryBrowser section={section} kind={kind} lockedFilters={{ genre }} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SectionScreen({ kind, tab, genre, genreTitle }: { kind: SectionKind; tab: SectionTab; genre?: string; genreTitle?: string }) {
|
||||||
const { section, all, loading } = useSectionFor(kind);
|
const { section, all, loading } = useSectionFor(kind);
|
||||||
if (loading) return <PageLoader />;
|
if (loading) return <PageLoader />;
|
||||||
if (!section)
|
if (!section)
|
||||||
|
|
@ -105,7 +144,7 @@ export function SectionScreen({ kind, tab }: { kind: SectionKind; tab: SectionTa
|
||||||
<SectionHeader kind={kind} tab={tab} section={section} all={all} overlay={tab === 'discover'} />
|
<SectionHeader kind={kind} tab={tab} section={section} all={all} overlay={tab === 'discover'} />
|
||||||
{tab === 'discover' && <Discover kind={kind} section={section} />}
|
{tab === 'discover' && <Discover kind={kind} section={section} />}
|
||||||
{tab === 'library' && <LibraryBrowser section={section} kind={kind} />}
|
{tab === 'library' && <LibraryBrowser section={section} kind={kind} />}
|
||||||
{tab === 'collections' && <Collections section={section} />}
|
{tab === 'categories' && (genre ? <CategoryLibrary kind={kind} section={section} genre={genre} title={genreTitle ?? ''} /> : <Categories kind={kind} section={section} />)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,44 +1,303 @@
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
import { useSettings } from '../app/settings';
|
import { useSettings } from '../app/settings';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The cold-start brand sequence, kept short because desktop startup is quick:
|
||||||
|
* the mark's six facets spin in from a loose ring and snap together with a
|
||||||
|
* ring pulse. If startup is still going, small shards circle the mark. Once
|
||||||
|
* startup is ready the camera flies through the mark's open centre, revealing
|
||||||
|
* the app drawn beneath (which settles from a slight zoom, `html.splash-arrival`).
|
||||||
|
*/
|
||||||
|
|
||||||
|
type Point = { x: number; y: number };
|
||||||
|
|
||||||
|
/** CSS-style cubic-bezier easing (x → y). */
|
||||||
|
function bezier(x1: number, y1: number, x2: number, y2: number) {
|
||||||
|
const cx = 3 * x1;
|
||||||
|
const bx = 3 * (x2 - x1) - cx;
|
||||||
|
const ax = 1 - cx - bx;
|
||||||
|
const cy = 3 * y1;
|
||||||
|
const by = 3 * (y2 - y1) - cy;
|
||||||
|
const ay = 1 - cy - by;
|
||||||
|
const sx = (t: number) => ((ax * t + bx) * t + cx) * t;
|
||||||
|
const sy = (t: number) => ((ay * t + by) * t + cy) * t;
|
||||||
|
const dx = (t: number) => (3 * ax * t + 2 * bx) * t + cx;
|
||||||
|
return (x: number) => {
|
||||||
|
if (x <= 0) return 0;
|
||||||
|
if (x >= 1) return 1;
|
||||||
|
let t = x;
|
||||||
|
for (let i = 0; i < 8; i++) {
|
||||||
|
const err = sx(t) - x;
|
||||||
|
const d = dx(t);
|
||||||
|
if (Math.abs(err) < 1e-5 || Math.abs(d) < 1e-6) break;
|
||||||
|
t -= err / d;
|
||||||
|
}
|
||||||
|
t = Math.min(1, Math.max(0, t));
|
||||||
|
return sy(t);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const Emphasized = bezier(0.2, 0, 0, 1);
|
||||||
|
const EmphasizedDecelerate = bezier(0.05, 0.7, 0.1, 1);
|
||||||
|
const Standard = bezier(0.4, 0, 0.2, 1);
|
||||||
|
const InOut = bezier(0.45, 0, 0.55, 1);
|
||||||
|
// Applied in log space: a brief pull back, then an accelerating flight.
|
||||||
|
const Flight = bezier(0.55, -0.06, 0.8, 0.36);
|
||||||
|
|
||||||
|
const phase = (time: number, start: number, end: number) => Math.min(1, Math.max(0, (time - start) / (end - start)));
|
||||||
|
const mix = (from: number, to: number, amount: number) => from + (to - from) * amount;
|
||||||
|
const rad = (deg: number) => (deg * Math.PI) / 180;
|
||||||
|
|
||||||
|
const PALETTE = ['#C3E8D3', '#71B9B0', '#3D7C7B', '#D0A977', '#E9D8AE', '#EEF2DD'];
|
||||||
|
|
||||||
|
// The brand mark's facets, centred on its 64-unit viewport, each with the
|
||||||
|
// outward normal of its hexagon edge and its centroid.
|
||||||
const FACETS = [
|
const FACETS = [
|
||||||
{ fill: '#C3E8D3', d: 'M33,4 L55.5,17 L42.5,24.5 L33,19 Z' },
|
[33, 4, 55.5, 17, 42.5, 24.5, 33, 19],
|
||||||
{ fill: '#71B9B0', d: 'M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z' },
|
[56.5, 19, 56.5, 45, 43.5, 37.5, 43.5, 26.5],
|
||||||
{ fill: '#3D7C7B', d: 'M55.5,47 L33,60 L33,45 L42.5,39.5 Z' },
|
[55.5, 47, 33, 60, 33, 45, 42.5, 39.5],
|
||||||
{ fill: '#D0A977', d: 'M31,60 L8.5,47 L21.5,39.5 L31,45 Z' },
|
[31, 60, 8.5, 47, 21.5, 39.5, 31, 45],
|
||||||
{ fill: '#E9D8AE', d: 'M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z' },
|
[7.5, 45, 7.5, 19, 20.5, 26.5, 20.5, 37.5],
|
||||||
{ fill: '#EEF2DD', d: 'M8.5,17 L31,4 L31,19 L21.5,24.5 Z' },
|
[8.5, 17, 31, 4, 31, 19, 21.5, 24.5],
|
||||||
];
|
].map((pts, i) => {
|
||||||
|
const points: Point[] = [];
|
||||||
|
for (let k = 0; k < pts.length; k += 2) points.push({ x: pts[k] - 32, y: pts[k + 1] - 32 });
|
||||||
|
const centroid = { x: points.reduce((s, p) => s + p.x, 0) / 4, y: points.reduce((s, p) => s + p.y, 0) / 4 };
|
||||||
|
const angle = rad(-60 + 60 * i);
|
||||||
|
return { points, centroid, color: PALETTE[i], normal: { x: Math.cos(angle), y: Math.sin(angle) } };
|
||||||
|
});
|
||||||
|
type Facet = (typeof FACETS)[number];
|
||||||
|
|
||||||
|
// The inner hexagon traced by the facets' inner edges: the aperture the exit flies through.
|
||||||
|
const INNER_RADIUS = 13.6;
|
||||||
|
const MARK_BOX = 140;
|
||||||
|
// Timeline (ms): the last facet locks at INTRO_END; the sequence then idles until startup is ready.
|
||||||
|
const FACET_STAGGER = 18;
|
||||||
|
const FACET_MS = 350;
|
||||||
|
const INTRO_END = FACET_STAGGER * 5 + FACET_MS;
|
||||||
|
// Still waiting at this point: shards start circling and a sheen crosses the mark.
|
||||||
|
const IDLE_START = 1100;
|
||||||
|
// Keep in step with the `splash-arrival` animation in app.css.
|
||||||
|
const EXIT_MS = 540;
|
||||||
|
const FLIGHT_ZOOM = 30;
|
||||||
|
|
||||||
|
const INK = '#090a0c';
|
||||||
|
const SEA_GLASS = [113, 185, 176];
|
||||||
|
const rgba = (c: number[], a: number) => `rgba(${c[0]}, ${c[1]}, ${c[2]}, ${Math.max(0, a)})`;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The cold-start aperture: the six facets twist open around the dark center,
|
* Facet `f` around mark centre `o`, `unit` px per grid unit: pushed `out` along its
|
||||||
* hold until startup data is ready, then the view flies through the aperture.
|
* normal, shrunk and spun about its own centroid, then turned `rot` about the mark centre.
|
||||||
*/
|
*/
|
||||||
|
function facetPath(ctx: CanvasRenderingContext2D, f: Facet, o: Point, unit: number, out = 0, scale = 1, spin = 0, rot = 0) {
|
||||||
|
const cr = Math.cos(rot);
|
||||||
|
const sr = Math.sin(rot);
|
||||||
|
const cs = Math.cos(spin);
|
||||||
|
const ss = Math.sin(spin);
|
||||||
|
const cx = f.centroid.x + f.normal.x * out;
|
||||||
|
const cy = f.centroid.y + f.normal.y * out;
|
||||||
|
f.points.forEach((p, i) => {
|
||||||
|
const rx = p.x + f.normal.x * out - cx;
|
||||||
|
const ry = p.y + f.normal.y * out - cy;
|
||||||
|
const x = cx + (rx * cs - ry * ss) * scale;
|
||||||
|
const y = cy + (rx * ss + ry * cs) * scale;
|
||||||
|
const px = o.x + (x * cr - y * sr) * unit;
|
||||||
|
const py = o.y + (x * sr + y * cr) * unit;
|
||||||
|
if (i === 0) ctx.moveTo(px, py);
|
||||||
|
else ctx.lineTo(px, py);
|
||||||
|
});
|
||||||
|
ctx.closePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A loose facet shape with its centroid at `pos`. */
|
||||||
|
function shardPath(ctx: CanvasRenderingContext2D, f: Facet, pos: Point, size: number, angle: number) {
|
||||||
|
const c = Math.cos(angle);
|
||||||
|
const s = Math.sin(angle);
|
||||||
|
f.points.forEach((p, i) => {
|
||||||
|
const x = p.x - f.centroid.x;
|
||||||
|
const y = p.y - f.centroid.y;
|
||||||
|
const px = pos.x + (x * c - y * s) * size;
|
||||||
|
const py = pos.y + (x * s + y * c) * size;
|
||||||
|
if (i === 0) ctx.moveTo(px, py);
|
||||||
|
else ctx.lineTo(px, py);
|
||||||
|
});
|
||||||
|
ctx.closePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
function hexagon(ctx: CanvasRenderingContext2D, o: Point, radius: number) {
|
||||||
|
for (let i = 0; i < 6; i++) {
|
||||||
|
const a = rad(-90 + 60 * i);
|
||||||
|
const x = o.x + Math.cos(a) * radius;
|
||||||
|
const y = o.y + Math.sin(a) * radius;
|
||||||
|
if (i === 0) ctx.moveTo(x, y);
|
||||||
|
else ctx.lineTo(x, y);
|
||||||
|
}
|
||||||
|
ctx.closePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw(ctx: CanvasRenderingContext2D, w: number, h: number, time: number, q: number) {
|
||||||
|
const o = { x: w / 2, y: h / 2 };
|
||||||
|
ctx.clearRect(0, 0, w, h);
|
||||||
|
const zoom = q > 0 ? Math.exp(Math.log(FLIGHT_ZOOM) * Flight(q)) : 1;
|
||||||
|
const unit = (MARK_BOX / 64) * zoom;
|
||||||
|
|
||||||
|
// The surface: ink everywhere, with the aperture's centre cut away on exit.
|
||||||
|
const hole = InOut(phase(q, 0.12, 0.5));
|
||||||
|
ctx.globalCompositeOperation = 'source-over';
|
||||||
|
ctx.globalAlpha = 1;
|
||||||
|
ctx.fillStyle = INK;
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.rect(0, 0, w, h);
|
||||||
|
if (hole > 0) hexagon(ctx, o, INNER_RADIUS * unit);
|
||||||
|
ctx.fill('evenodd');
|
||||||
|
if (hole > 0 && hole < 1) {
|
||||||
|
ctx.globalAlpha = 1 - hole;
|
||||||
|
ctx.beginPath();
|
||||||
|
hexagon(ctx, o, INNER_RADIUS * unit);
|
||||||
|
ctx.fill();
|
||||||
|
ctx.globalAlpha = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bloom = 0.09 * InOut(phase(time, 0, 260)) * (1 - Standard(phase(time, 420, 1100)));
|
||||||
|
if (bloom > 0.001) {
|
||||||
|
ctx.globalCompositeOperation = 'lighter';
|
||||||
|
const g = ctx.createRadialGradient(o.x, o.y, 0, o.x, o.y, 300);
|
||||||
|
g.addColorStop(0, rgba(SEA_GLASS, bloom));
|
||||||
|
g.addColorStop(0.45, rgba(SEA_GLASS, bloom * 0.3));
|
||||||
|
g.addColorStop(1, rgba(SEA_GLASS, 0));
|
||||||
|
ctx.fillStyle = g;
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(o.x, o.y, 300, 0, Math.PI * 2);
|
||||||
|
ctx.fill();
|
||||||
|
ctx.globalCompositeOperation = 'source-over';
|
||||||
|
}
|
||||||
|
|
||||||
|
// The six facets spin in from a loose ring and lock into the mark.
|
||||||
|
FACETS.forEach((f, s) => {
|
||||||
|
const start = s * FACET_STAGGER;
|
||||||
|
const p = Emphasized(phase(time, start, start + FACET_MS));
|
||||||
|
ctx.globalAlpha = Standard(phase(time, start, start + 160));
|
||||||
|
ctx.fillStyle = f.color;
|
||||||
|
ctx.beginPath();
|
||||||
|
facetPath(ctx, f, o, unit, 7 * (1 - p), mix(0.5, 1, p), rad(-45) * (1 - p), rad(-60) * (1 - p));
|
||||||
|
ctx.fill();
|
||||||
|
});
|
||||||
|
ctx.globalAlpha = 1;
|
||||||
|
|
||||||
|
// A ring pulses out as the facets lock.
|
||||||
|
const pulse = phase(time, 340, 900);
|
||||||
|
if (pulse > 0 && pulse < 1) {
|
||||||
|
ctx.strokeStyle = rgba(SEA_GLASS, 0.45 * (1 - pulse) * (1 - phase(q, 0, 0.3)));
|
||||||
|
ctx.lineWidth = 1.5;
|
||||||
|
ctx.beginPath();
|
||||||
|
hexagon(ctx, o, (30 + 22 * EmphasizedDecelerate(pulse)) * unit);
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Still starting: small shards circle the mark.
|
||||||
|
const idle = Standard(phase(time, IDLE_START, IDLE_START + 600)) * (1 - phase(q, 0, 0.25));
|
||||||
|
if (idle > 0) {
|
||||||
|
ctx.globalCompositeOperation = 'screen';
|
||||||
|
ctx.globalAlpha = 0.4 * idle;
|
||||||
|
for (let s = 0; s < 6; s++) {
|
||||||
|
for (const side of [-1, 1]) {
|
||||||
|
const a = rad(-60 + 60 * s) + side * rad(11) + (time - IDLE_START) * 0.00032;
|
||||||
|
ctx.fillStyle = PALETTE[(s + (side > 0 ? 2 : 4)) % 6];
|
||||||
|
ctx.beginPath();
|
||||||
|
shardPath(ctx, FACETS[s], { x: o.x + Math.cos(a) * 50 * unit, y: o.y + Math.sin(a) * 50 * unit }, unit * 0.16, a * 2);
|
||||||
|
ctx.fill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctx.globalAlpha = 1;
|
||||||
|
ctx.globalCompositeOperation = 'source-over';
|
||||||
|
}
|
||||||
|
|
||||||
|
// While it waits, a band of light crosses the mark every few seconds.
|
||||||
|
const sheen = time < IDLE_START ? 0 : ((time - IDLE_START) % 3600) / 900;
|
||||||
|
if (q === 0 && sheen > 0 && sheen < 1) {
|
||||||
|
ctx.save();
|
||||||
|
ctx.beginPath();
|
||||||
|
FACETS.forEach((f) => facetPath(ctx, f, o, unit));
|
||||||
|
ctx.clip();
|
||||||
|
const reach = 40 * unit;
|
||||||
|
const a = rad(36);
|
||||||
|
const d = { x: Math.cos(a), y: Math.sin(a) };
|
||||||
|
const pos = mix(-1.25, 1.25, InOut(sheen)) * reach;
|
||||||
|
const width = 10 * unit;
|
||||||
|
const peak = 0.42 * Math.sin(Math.min(1, sheen * 1.1) * Math.PI);
|
||||||
|
const g = ctx.createLinearGradient(o.x + d.x * (pos - width), o.y + d.y * (pos - width), o.x + d.x * (pos + width), o.y + d.y * (pos + width));
|
||||||
|
g.addColorStop(0, 'rgba(255, 255, 255, 0)');
|
||||||
|
g.addColorStop(0.5, `rgba(255, 255, 255, ${peak})`);
|
||||||
|
g.addColorStop(1, 'rgba(255, 255, 255, 0)');
|
||||||
|
ctx.fillStyle = g;
|
||||||
|
ctx.fillRect(o.x - reach, o.y - reach, reach * 2, reach * 2);
|
||||||
|
ctx.restore();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function Splash({ ready, onDone }: { ready: boolean; onDone: () => void }) {
|
export function Splash({ ready, onDone }: { ready: boolean; onDone: () => void }) {
|
||||||
const reduced = useSettings((s) => s.reducedMotion);
|
const reduced = useSettings((s) => s.reducedMotion);
|
||||||
const [phase, setPhase] = useState<'opening' | 'held' | 'leaving'>('opening');
|
const canvas = useRef<HTMLCanvasElement>(null);
|
||||||
|
const readyRef = useRef(ready);
|
||||||
|
readyRef.current = ready;
|
||||||
|
const done = useRef(onDone);
|
||||||
|
done.current = onDone;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const t = setTimeout(() => setPhase('held'), reduced ? 0 : 1100);
|
const el = canvas.current;
|
||||||
return () => clearTimeout(t);
|
if (!el) return;
|
||||||
|
if (reduced) {
|
||||||
|
// No sequence: wait for startup, then hand straight over.
|
||||||
|
const t = setInterval(() => readyRef.current && (clearInterval(t), done.current()), 50);
|
||||||
|
return () => clearInterval(t);
|
||||||
|
}
|
||||||
|
const ctx = el.getContext('2d')!;
|
||||||
|
let raf = 0;
|
||||||
|
let stopped = false;
|
||||||
|
const size = () => {
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
el.width = Math.round(window.innerWidth * dpr);
|
||||||
|
el.height = Math.round(window.innerHeight * dpr);
|
||||||
|
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||||
|
};
|
||||||
|
size();
|
||||||
|
window.addEventListener('resize', size);
|
||||||
|
|
||||||
|
let last = 0;
|
||||||
|
let time = 0;
|
||||||
|
let exitStart = 0;
|
||||||
|
const frame = (now: number) => {
|
||||||
|
if (stopped) return;
|
||||||
|
// Clamp long frames so a stall doesn't skip the gather.
|
||||||
|
time += last ? Math.min(64, now - last) : 0;
|
||||||
|
last = now;
|
||||||
|
if (!exitStart && time >= INTRO_END && readyRef.current) {
|
||||||
|
exitStart = now;
|
||||||
|
document.documentElement.classList.add('splash-arrival');
|
||||||
|
}
|
||||||
|
const q = exitStart ? Math.min(1, (now - exitStart) / EXIT_MS) : 0;
|
||||||
|
draw(ctx, window.innerWidth, window.innerHeight, time, q);
|
||||||
|
if (q >= 1) {
|
||||||
|
done.current();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
raf = requestAnimationFrame(frame);
|
||||||
|
};
|
||||||
|
// Draw the first (dark) frame at once so the app never shows through.
|
||||||
|
draw(ctx, window.innerWidth, window.innerHeight, 0, 0);
|
||||||
|
raf = requestAnimationFrame(frame);
|
||||||
|
return () => {
|
||||||
|
stopped = true;
|
||||||
|
cancelAnimationFrame(raf);
|
||||||
|
window.removeEventListener('resize', size);
|
||||||
|
// Let the arrival settle finish after the splash is gone.
|
||||||
|
setTimeout(() => document.documentElement.classList.remove('splash-arrival'), EXIT_MS + 60);
|
||||||
|
};
|
||||||
}, [reduced]);
|
}, [reduced]);
|
||||||
useEffect(() => {
|
|
||||||
if (phase === 'held' && ready) setPhase('leaving');
|
|
||||||
}, [phase, ready]);
|
|
||||||
useEffect(() => {
|
|
||||||
if (phase !== 'leaving') return;
|
|
||||||
const t = setTimeout(onDone, reduced ? 0 : 620);
|
|
||||||
return () => clearTimeout(t);
|
|
||||||
}, [phase]);
|
|
||||||
return (
|
return (
|
||||||
<div className={`splash ${phase}`} data-tauri-drag-region>
|
<div className="splash" data-tauri-drag-region aria-label="Kaleido starting" role="img">
|
||||||
<div className="splash-mark">
|
<canvas ref={canvas} />
|
||||||
<svg viewBox="0 0 64 64" width="92" height="92" aria-hidden="true">
|
|
||||||
{FACETS.map((f, i) => (
|
|
||||||
<path key={i} d={f.d} fill={f.fill} style={{ ['--i' as string]: i }} />
|
|
||||||
))}
|
|
||||||
</svg>
|
|
||||||
<span className="splash-word">KALEIDO</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,22 +1,12 @@
|
||||||
import { isNative, win } from '../platform/native';
|
import { isNative } from '../platform/native';
|
||||||
import { Icon } from '../ui/Icon';
|
import { WindowControls } from '../app/TopBar';
|
||||||
|
|
||||||
/** A draggable strip with window controls for full-screen states without the top bar. */
|
/** A draggable strip with window controls for full-screen states without the top bar. */
|
||||||
export function WindowDrag() {
|
export function WindowDrag() {
|
||||||
if (!isNative) return null;
|
if (!isNative) return null;
|
||||||
return (
|
return (
|
||||||
<div className="window-drag" data-tauri-drag-region>
|
<div className="window-drag" data-tauri-drag-region>
|
||||||
<div className="window-controls">
|
<WindowControls />
|
||||||
<button aria-label="Minimize" onClick={() => win.minimize()}>
|
|
||||||
<Icon name="minimize" size={15} strokeWidth={1.4} />
|
|
||||||
</button>
|
|
||||||
<button aria-label="Maximize" onClick={() => win.toggleMaximize()}>
|
|
||||||
<Icon name="maximize" size={13} strokeWidth={1.4} />
|
|
||||||
</button>
|
|
||||||
<button aria-label="Close" className="close" onClick={() => win.close()}>
|
|
||||||
<Icon name="x" size={15} strokeWidth={1.4} />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
78
src/screens/categories.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
||||||
|
import * as api from '../plex/api';
|
||||||
|
import type { PlexServer } from '../plex/client';
|
||||||
|
import type { Item } from '../plex/types';
|
||||||
|
|
||||||
|
/** Plex timestamps or query strings don't make a refreshed image a different picture. */
|
||||||
|
export function artworkIdentity(path: string): string {
|
||||||
|
return path.split('?')[0].replace(/(\/(?:art|thumb))\/\d+$/, '$1');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Matches genres to distinct artwork, moving an earlier choice when a later
|
||||||
|
* genre needs it (augmenting paths), so two tiles never share a picture.
|
||||||
|
* Narrow genres choose first so a broad one can't take their only source.
|
||||||
|
*/
|
||||||
|
export function selectCategoryArtwork<T>(candidates: Map<string, T[]>, identity: (t: T) => string): Map<string, T> {
|
||||||
|
const options = new Map<string, T[]>();
|
||||||
|
for (const [genre, items] of candidates) {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
options.set(
|
||||||
|
genre,
|
||||||
|
items.filter((i) => {
|
||||||
|
const id = identity(i);
|
||||||
|
if (!id || seen.has(id)) return false;
|
||||||
|
seen.add(id);
|
||||||
|
return true;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const owners = new Map<string, string>();
|
||||||
|
const selected = new Map<string, T>();
|
||||||
|
const assign = (genre: string, visited: Set<string>): boolean => {
|
||||||
|
const choices = options.get(genre) ?? [];
|
||||||
|
const free = choices.find((i) => !owners.has(identity(i)) && !visited.has(identity(i)));
|
||||||
|
if (free) {
|
||||||
|
owners.set(identity(free), genre);
|
||||||
|
selected.set(genre, free);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
for (const item of choices) {
|
||||||
|
const key = identity(item);
|
||||||
|
if (visited.has(key)) continue;
|
||||||
|
visited.add(key);
|
||||||
|
const previous = owners.get(key);
|
||||||
|
if (previous && assign(previous, visited)) {
|
||||||
|
owners.set(key, genre);
|
||||||
|
selected.set(genre, item);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
[...options.keys()].sort((a, b) => options.get(a)!.length - options.get(b)!.length).forEach((g) => assign(g, new Set()));
|
||||||
|
return selected;
|
||||||
|
}
|
||||||
|
|
||||||
|
const backdropOf = (i: Item) => i.art || i.thumb;
|
||||||
|
|
||||||
|
/** One distinct, well-liked title's artwork per genre, fetched a few genres at a time. */
|
||||||
|
export async function categoryArtwork(s: PlexServer, sectionId: string, type: number, genres: { key: string; title: string }[]): Promise<Record<string, string>> {
|
||||||
|
const candidates = new Map<string, Item[]>();
|
||||||
|
const queue = [...genres];
|
||||||
|
const worker = async () => {
|
||||||
|
for (let g = queue.shift(); g; g = queue.shift()) {
|
||||||
|
const page = await api
|
||||||
|
.libraryPage(s, sectionId, { type, sort: 'audienceRating:desc', filters: { genre: g.key }, start: 0, size: 24 })
|
||||||
|
.catch(() => api.libraryPage(s, sectionId, { type, filters: { genre: g.key }, start: 0, size: 24 }))
|
||||||
|
.catch(() => null);
|
||||||
|
candidates.set(g.key, (page?.items ?? []).filter((i) => i.art));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
await Promise.all(Array.from({ length: 4 }, worker));
|
||||||
|
const chosen = selectCategoryArtwork(candidates, (i) => artworkIdentity(backdropOf(i)));
|
||||||
|
const out: Record<string, string> = {};
|
||||||
|
for (const [genre, item] of chosen) out[genre] = backdropOf(item);
|
||||||
|
// Genres whose only titles were all taken still get a picture.
|
||||||
|
for (const [genre, items] of candidates) if (!out[genre] && items[0]) out[genre] = backdropOf(items[0]);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
@ -16,26 +16,21 @@ function shuffled<T>(list: T[], salt = 0): T[] {
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
const FEATURE_SOURCES: [RegExp, string][] = [
|
/** Recently released, highly rated, recently added, start watching, recommended. */
|
||||||
[/recentlyreleased|recentlyaired/, 'Recently released'],
|
const FEATURE_SOURCES: RegExp[] = [/recentlyreleased|recentlyaired/, /topunwatched|toprated/, /recentlyadded/, /startwatching/, /curated|genre|by\.actor|moreingenre/];
|
||||||
[/topunwatched|toprated/, 'Highly rated'],
|
|
||||||
[/recentlyadded/, 'Recently added'],
|
|
||||||
[/startwatching/, 'Start watching'],
|
|
||||||
[/curated|genre|by\.actor|moreingenre/, 'Recommended'],
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Features interleave recently released, highly rated unwatched and
|
* Features interleave recently released, highly rated unwatched and
|
||||||
* Plex-recommended titles; they need artwork and skip in-progress titles.
|
* Plex-recommended titles; they need artwork and skip in-progress titles.
|
||||||
*/
|
*/
|
||||||
export function buildFeatures(hubs: Hub[], limit = 8, salt = 0): Feature[] {
|
export function buildFeatures(hubs: Hub[], limit = 8, salt = 0): Feature[] {
|
||||||
const pools: Feature[][] = FEATURE_SOURCES.map(([re, eyebrow]) =>
|
const pools: Feature[][] = FEATURE_SOURCES.map((re) =>
|
||||||
shuffled(
|
shuffled(
|
||||||
hubs
|
hubs
|
||||||
.filter((h) => re.test(h.id))
|
.filter((h) => re.test(h.id))
|
||||||
.flatMap((h) => h.items)
|
.flatMap((h) => h.items)
|
||||||
.filter((i) => (i.type === 'movie' || i.type === 'show') && i.art && !i.viewOffset && i.summary)
|
.filter((i) => (i.type === 'movie' || i.type === 'show') && i.art && !i.viewOffset && i.summary)
|
||||||
.map((item) => ({ item, eyebrow })),
|
.map((item) => ({ item })),
|
||||||
salt,
|
salt,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,13 @@
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useSettings, QUALITY_LABEL, type Quality, type SkipMode, type SubtitleMode } from '../../app/settings';
|
import { useSettings, QUALITY_LABEL, SUBTITLE_COLORS, SUBTITLE_MARGIN, type Preferences, type Quality, type SkipMode, type SubtitleBox, type SubtitleEdge, type SubtitleMode, type SubtitlePosition } from '../../app/settings';
|
||||||
import { useSession } from '../../app/session';
|
import { useSession } from '../../app/session';
|
||||||
import { useSections } from '../../app/queries';
|
import { useSections, useServerQuery } from '../../app/queries';
|
||||||
|
import * as api from '../../plex/api';
|
||||||
|
import { art } from '../../app/format';
|
||||||
import { useDownloads } from '../../downloads/store';
|
import { useDownloads } from '../../downloads/store';
|
||||||
import { appInfo, isNative, openExternal, pickFolder, revealPath, type AppInfo } from '../../platform/native';
|
import { appInfo, fullscreenShortcut, isMac, isNative, openExternal, pickFolder, revealPath, shortcut, type AppInfo } from '../../platform/native';
|
||||||
import { checkForUpdate, installUpdate, useUpdater } from '../../app/updater';
|
import { checkForUpdate, installUpdate, useUpdater } from '../../app/updater';
|
||||||
import { Button, Select, Switch } from '../../ui/primitives';
|
import { Button, Segmented, Select, Switch } from '../../ui/primitives';
|
||||||
import { confirmDialog } from '../../ui/overlays';
|
import { confirmDialog } from '../../ui/overlays';
|
||||||
import { Pref, SettingsSection } from './parts';
|
import { Pref, SettingsSection } from './parts';
|
||||||
import { KaleidoMark } from '../../ui/primitives';
|
import { KaleidoMark } from '../../ui/primitives';
|
||||||
|
|
@ -40,14 +42,16 @@ const skipOptions: { value: SkipMode; label: string }[] = [
|
||||||
{ value: 'off', label: 'Off' },
|
{ value: 'off', label: 'Off' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const OS_NAMES: Record<string, string> = { windows: 'Windows', macos: 'macOS', linux: 'Linux' };
|
||||||
|
|
||||||
const SHORTCUTS: [string, string][][] = [
|
const SHORTCUTS: [string, string][][] = [
|
||||||
[
|
[
|
||||||
['Ctrl + K', 'Search'],
|
[shortcut('K'), 'Search'],
|
||||||
['Alt + ← / Mouse back', 'Go back'],
|
[isMac ? '⌘[ / Mouse back' : 'Alt + ← / Mouse back', 'Go back'],
|
||||||
['Alt + → / Mouse forward', 'Go forward'],
|
[isMac ? '⌘] / Mouse forward' : 'Alt + → / Mouse forward', 'Go forward'],
|
||||||
['Esc', 'Go back or close a dialog'],
|
['Esc', 'Go back or close a dialog'],
|
||||||
['F11', 'Full screen'],
|
[fullscreenShortcut, 'Full screen'],
|
||||||
['Ctrl + ,', 'Settings'],
|
[shortcut(','), 'Settings'],
|
||||||
['Right-click a title', 'Title actions'],
|
['Right-click a title', 'Title actions'],
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
|
|
@ -59,12 +63,49 @@ const SHORTCUTS: [string, string][][] = [
|
||||||
['M', 'Mute'],
|
['M', 'Mute'],
|
||||||
['F or double-click', 'Full screen'],
|
['F or double-click', 'Full screen'],
|
||||||
['C', 'Next subtitle track'],
|
['C', 'Next subtitle track'],
|
||||||
['Shift + N', 'Next episode'],
|
['U', 'Cycle upscaling'],
|
||||||
|
['B', 'Compare with enhancement off'],
|
||||||
|
['Shift + P / N', 'Previous / next episode'],
|
||||||
['0–9', 'Jump to 0–90%'],
|
['0–9', 'Jump to 0–90%'],
|
||||||
['Esc', 'Exit full screen, then the player'],
|
['Esc or Backspace', 'Exit full screen, then keep playing in the corner'],
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A frame from the library with a sample line drawn the way mpv will draw it:
|
||||||
|
* sizes are in mpv's scaled pixels, where the frame height is 720.
|
||||||
|
*/
|
||||||
|
function SubtitlePreview({ prefs }: { prefs: Preferences }) {
|
||||||
|
const session = useSession();
|
||||||
|
const cw = useServerQuery(['continue'], (srv) => api.continueWatching(srv), { enabled: !!session.server, staleTime: 15_000 });
|
||||||
|
const still = cw.data?.find((i) => art.backdrop(i));
|
||||||
|
const px = (n: number) => `calc(${n} / 720 * 100cqh)`;
|
||||||
|
const edge = prefs.subtitleBox === 'none' ? prefs.subtitleEdge : 'none';
|
||||||
|
const outline = edge === 'outline' ? 1.8 : edge === 'raised' ? 1.3 : 0;
|
||||||
|
const shadow = edge === 'shadow' ? 2.2 : edge === 'raised' ? 1.6 : 0;
|
||||||
|
return (
|
||||||
|
<div className="subtitle-preview">
|
||||||
|
{still && session.server && <img src={session.server.image(art.backdrop(still), 960, 540)} alt="" draggable={false} />}
|
||||||
|
<div className="subtitle-preview-line" style={{ bottom: px(SUBTITLE_MARGIN[prefs.subtitlePosition]) }}>
|
||||||
|
<span
|
||||||
|
className={prefs.subtitleBox}
|
||||||
|
style={{
|
||||||
|
color: prefs.subtitleColor,
|
||||||
|
fontSize: px(38 * prefs.subtitleScale),
|
||||||
|
fontWeight: prefs.subtitleBold ? 700 : 400,
|
||||||
|
WebkitTextStroke: outline ? `${px(outline * 2)} #000` : undefined,
|
||||||
|
textShadow: shadow ? `${px(shadow)} ${px(shadow)} 0 rgba(0, 0, 0, 0.7)` : undefined,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
The night is darkest just before the dawn.
|
||||||
|
<br />
|
||||||
|
And I promise you, the dawn is coming.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function AppSettings({ tab }: { tab: string }) {
|
export function AppSettings({ tab }: { tab: string }) {
|
||||||
const s = useSettings();
|
const s = useSettings();
|
||||||
const set = s.set;
|
const set = s.set;
|
||||||
|
|
@ -143,7 +184,7 @@ export function AppSettings({ tab }: { tab: string }) {
|
||||||
<Pref label="Hardware decoding" description="Uses your graphics card to decode video. Turn off only if you see artifacts. Applies after restarting Kaleido.">
|
<Pref label="Hardware decoding" description="Uses your graphics card to decode video. Turn off only if you see artifacts. Applies after restarting Kaleido.">
|
||||||
<Switch checked={s.hwdec} onChange={(v) => set('hwdec', v)} />
|
<Switch checked={s.hwdec} onChange={(v) => set('hwdec', v)} />
|
||||||
</Pref>
|
</Pref>
|
||||||
<Pref label="HDR passthrough" description="Sends HDR video to HDR-capable displays when Windows HDR is on. Applies after restarting Kaleido.">
|
<Pref label="HDR passthrough" description={`Sends HDR video to HDR-capable displays${isMac ? '' : ' when Windows HDR is on'}. Applies after restarting Kaleido.`}>
|
||||||
<Switch checked={s.hdrPassthrough} onChange={(v) => set('hdrPassthrough', v)} />
|
<Switch checked={s.hdrPassthrough} onChange={(v) => set('hdrPassthrough', v)} />
|
||||||
</Pref>
|
</Pref>
|
||||||
</SettingsSection>
|
</SettingsSection>
|
||||||
|
|
@ -151,14 +192,27 @@ export function AppSettings({ tab }: { tab: string }) {
|
||||||
<Pref label="Skip intros">
|
<Pref label="Skip intros">
|
||||||
<Select value={s.skipIntro} onChange={(v) => set('skipIntro', v)} options={skipOptions} />
|
<Select value={s.skipIntro} onChange={(v) => set('skipIntro', v)} options={skipOptions} />
|
||||||
</Pref>
|
</Pref>
|
||||||
<Pref label="Skip credits">
|
<Pref label="Skip movie credits" description="Episodes open Up Next when their credits begin.">
|
||||||
<Select value={s.skipCredits} onChange={(v) => set('skipCredits', v)} options={skipOptions} />
|
<Select value={s.skipCredits} onChange={(v) => set('skipCredits', v)} options={skipOptions} />
|
||||||
</Pref>
|
</Pref>
|
||||||
<Pref label="Play the next episode automatically">
|
<Pref label="Automatic skip delay" description="How long the button counts down before skipping automatically. Pause, seek or press any key to keep watching instead.">
|
||||||
<Switch checked={s.autoplayNext} onChange={(v) => set('autoplayNext', v)} />
|
<Select
|
||||||
|
value={s.autoSkipDelay}
|
||||||
|
disabled={s.skipIntro !== 'auto' && s.skipCredits !== 'auto'}
|
||||||
|
onChange={(v) => set('autoSkipDelay', v)}
|
||||||
|
options={[0, 3, 5, 10].map((v) => ({ value: v, label: v ? `${v} seconds` : 'Skip straight away' }))}
|
||||||
|
/>
|
||||||
</Pref>
|
</Pref>
|
||||||
<Pref label="Countdown" description="Seconds before the next episode starts.">
|
<Pref label="Autoplay next episode">
|
||||||
<Select value={s.countdownSeconds} disabled={!s.autoplayNext} onChange={(v) => set('countdownSeconds', v)} options={[5, 8, 10, 15, 20, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />
|
<Select
|
||||||
|
label="Autoplay next episode"
|
||||||
|
value={s.autoplayNext ? s.countdownSeconds : 0}
|
||||||
|
onChange={(seconds) => {
|
||||||
|
set('autoplayNext', seconds > 0);
|
||||||
|
if (seconds > 0) set('countdownSeconds', seconds);
|
||||||
|
}}
|
||||||
|
options={[{ value: 0, label: 'Off' }, ...[5, 8, 10, 15, 20, 30].map((v) => ({ value: v, label: `After ${v} seconds` }))]}
|
||||||
|
/>
|
||||||
</Pref>
|
</Pref>
|
||||||
<Pref label="Arrow-key seek">
|
<Pref label="Arrow-key seek">
|
||||||
<Select value={s.seekStep} onChange={(v) => set('seekStep', v)} options={[5, 10, 15, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />
|
<Select value={s.seekStep} onChange={(v) => set('seekStep', v)} options={[5, 10, 15, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />
|
||||||
|
|
@ -190,6 +244,9 @@ export function AppSettings({ tab }: { tab: string }) {
|
||||||
<Pref label="Subtitle language" description="Automatic uses the language of the audio track.">
|
<Pref label="Subtitle language" description="Automatic uses the language of the audio track.">
|
||||||
<Select value={s.subtitleLanguage} onChange={(v) => set('subtitleLanguage', v)} options={LANGUAGES.map(([value, label]) => ({ value, label }))} />
|
<Select value={s.subtitleLanguage} onChange={(v) => set('subtitleLanguage', v)} options={LANGUAGES.map(([value, label]) => ({ value, label }))} />
|
||||||
</Pref>
|
</Pref>
|
||||||
|
</SettingsSection>
|
||||||
|
<SettingsSection title="Subtitle style" description="How text subtitles look. Image subtitles (Blu-ray, DVD) and styled ASS subtitles keep their own look. Changes apply to a playing video straight away.">
|
||||||
|
<SubtitlePreview prefs={s} />
|
||||||
<Pref label="Size">
|
<Pref label="Size">
|
||||||
<Select
|
<Select
|
||||||
value={s.subtitleScale}
|
value={s.subtitleScale}
|
||||||
|
|
@ -202,8 +259,58 @@ export function AppSettings({ tab }: { tab: string }) {
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
</Pref>
|
</Pref>
|
||||||
<Pref label="Background box" description="Draws text subtitles on a dark box for contrast.">
|
<Pref label="Text colour">
|
||||||
<Switch checked={s.subtitleBackground} onChange={(v) => set('subtitleBackground', v)} />
|
<div className="swatches" role="radiogroup" aria-label="Text colour">
|
||||||
|
{SUBTITLE_COLORS.map((c) => (
|
||||||
|
<button
|
||||||
|
key={c.value}
|
||||||
|
role="radio"
|
||||||
|
aria-checked={s.subtitleColor === c.value}
|
||||||
|
aria-label={c.label}
|
||||||
|
title={c.label}
|
||||||
|
className={s.subtitleColor === c.value ? 'selected' : ''}
|
||||||
|
style={{ background: c.value }}
|
||||||
|
onClick={() => set('subtitleColor', c.value)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Pref>
|
||||||
|
<Pref label="Edge">
|
||||||
|
<Segmented<SubtitleEdge>
|
||||||
|
value={s.subtitleEdge}
|
||||||
|
onChange={(v) => set('subtitleEdge', v)}
|
||||||
|
options={[
|
||||||
|
{ value: 'outline', label: 'Outline' },
|
||||||
|
{ value: 'shadow', label: 'Shadow' },
|
||||||
|
{ value: 'raised', label: 'Both' },
|
||||||
|
{ value: 'none', label: 'None' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Pref>
|
||||||
|
<Pref label="Background">
|
||||||
|
<Segmented<SubtitleBox>
|
||||||
|
value={s.subtitleBox}
|
||||||
|
onChange={(v) => set('subtitleBox', v)}
|
||||||
|
options={[
|
||||||
|
{ value: 'none', label: 'None' },
|
||||||
|
{ value: 'translucent', label: 'Translucent' },
|
||||||
|
{ value: 'solid', label: 'Solid' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Pref>
|
||||||
|
<Pref label="Bold">
|
||||||
|
<Switch checked={s.subtitleBold} onChange={(v) => set('subtitleBold', v)} />
|
||||||
|
</Pref>
|
||||||
|
<Pref label="Position">
|
||||||
|
<Segmented<SubtitlePosition>
|
||||||
|
value={s.subtitlePosition}
|
||||||
|
onChange={(v) => set('subtitlePosition', v)}
|
||||||
|
options={[
|
||||||
|
{ value: 'low', label: 'Low' },
|
||||||
|
{ value: 'normal', label: 'Normal' },
|
||||||
|
{ value: 'high', label: 'Raised' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
</Pref>
|
</Pref>
|
||||||
</SettingsSection>
|
</SettingsSection>
|
||||||
</>
|
</>
|
||||||
|
|
@ -214,7 +321,7 @@ export function AppSettings({ tab }: { tab: string }) {
|
||||||
<Pref label="Artwork colour wash" description="Tints pages with colors from the title’s artwork.">
|
<Pref label="Artwork colour wash" description="Tints pages with colors from the title’s artwork.">
|
||||||
<Switch checked={s.colorWash} onChange={(v) => set('colorWash', v)} />
|
<Switch checked={s.colorWash} onChange={(v) => set('colorWash', v)} />
|
||||||
</Pref>
|
</Pref>
|
||||||
<Pref label="Rotate featured titles" description="Cycles the featured title on Home and Discover every 12 seconds.">
|
<Pref label="Rotate featured titles" description="Cycles the featured title on Home and Discover every 8 seconds.">
|
||||||
<Switch checked={s.heroRotation} onChange={(v) => set('heroRotation', v)} />
|
<Switch checked={s.heroRotation} onChange={(v) => set('heroRotation', v)} />
|
||||||
</Pref>
|
</Pref>
|
||||||
<Pref label="Poster size" description="Card size in library grids.">
|
<Pref label="Poster size" description="Card size in library grids.">
|
||||||
|
|
@ -282,7 +389,7 @@ export function AppSettings({ tab }: { tab: string }) {
|
||||||
<div>
|
<div>
|
||||||
<h2>Kaleido</h2>
|
<h2>Kaleido</h2>
|
||||||
<p className="muted">
|
<p className="muted">
|
||||||
Version {info?.version ?? '—'} · {info?.platform === 'windows' ? 'Windows' : info?.platform}
|
Version {info?.version ?? '—'} · {OS_NAMES[info?.platform ?? ''] ?? info?.platform}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -52,6 +52,28 @@ function AreaChart({ series, height = 150, max, format }: { series: { values: nu
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Seconds of bandwidth the chart shows. */
|
||||||
|
const BANDWIDTH_WINDOW = 120;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plex's real-time bandwidth samples are bytes per second, and seconds with
|
||||||
|
* no traffic are left out; lay them on a gap-free per-second axis in Mbps.
|
||||||
|
*/
|
||||||
|
function perSecond(points: admin.BandwidthPoint[]) {
|
||||||
|
const latest = points.length ? points[points.length - 1].at : 0;
|
||||||
|
// Ends at the newest sample, or now when nothing has been sent lately.
|
||||||
|
const end = Math.max(latest, Math.floor(Date.now() / 1000) - 2);
|
||||||
|
const lan = new Array<number>(BANDWIDTH_WINDOW).fill(0);
|
||||||
|
const wan = new Array<number>(BANDWIDTH_WINDOW).fill(0);
|
||||||
|
for (const p of points) {
|
||||||
|
const i = BANDWIDTH_WINDOW - 1 - (end - p.at);
|
||||||
|
if (i < 0 || i >= BANDWIDTH_WINDOW) continue;
|
||||||
|
lan[i] = (p.lan * 8) / 1e6;
|
||||||
|
wan[i] = (p.wan * 8) / 1e6;
|
||||||
|
}
|
||||||
|
return { lan, wan };
|
||||||
|
}
|
||||||
|
|
||||||
function NowPlaying({ session, onStop }: { session: admin.Session; onStop: () => void }) {
|
function NowPlaying({ session, onStop }: { session: admin.Session; onStop: () => void }) {
|
||||||
const server = useServer();
|
const server = useServer();
|
||||||
const item = session.item;
|
const item = session.item;
|
||||||
|
|
@ -99,7 +121,7 @@ function NowPlaying({ session, onStop }: { session: admin.Session; onStop: () =>
|
||||||
function Dashboard() {
|
function Dashboard() {
|
||||||
const server = useServer();
|
const server = useServer();
|
||||||
const sessions = useServerQuery(['sessions'], (s) => admin.sessions(s), { refetchInterval: 5000, staleTime: 0 });
|
const sessions = useServerQuery(['sessions'], (s) => admin.sessions(s), { refetchInterval: 5000, staleTime: 0 });
|
||||||
const bw = useServerQuery(['bandwidth'], (s) => admin.bandwidth(s, 6), { refetchInterval: 6000, staleTime: 0 });
|
const bw = useServerQuery(['bandwidth'], (s) => admin.bandwidth(s, 6), { refetchInterval: 1000, staleTime: 0 });
|
||||||
const res = useServerQuery(['resources'], (s) => admin.resources(s, 6), { refetchInterval: 6000, staleTime: 0 });
|
const res = useServerQuery(['resources'], (s) => admin.resources(s, 6), { refetchInterval: 6000, staleTime: 0 });
|
||||||
const info = useServerQuery(['serverInfo'], (s) => api.serverInfo(s), { staleTime: 60_000 });
|
const info = useServerQuery(['serverInfo'], (s) => api.serverInfo(s), { staleTime: 60_000 });
|
||||||
const sections = useServerQuery(['sections'], (s) => api.sections(s));
|
const sections = useServerQuery(['sections'], (s) => api.sections(s));
|
||||||
|
|
@ -107,10 +129,7 @@ function Dashboard() {
|
||||||
|
|
||||||
const list = sessions.data ?? [];
|
const list = sessions.data ?? [];
|
||||||
const transcodes = list.filter((s) => s.decision?.video === 'transcode').length;
|
const transcodes = list.filter((s) => s.decision?.video === 'transcode').length;
|
||||||
const points = (bw.data?.points ?? []).slice(-40);
|
const { lan, wan } = perSecond(bw.data?.points ?? []);
|
||||||
const toMbps = (bytes: number) => (bytes * 8) / 6 / 1e6;
|
|
||||||
const lan = points.map((p) => toMbps(p.lan));
|
|
||||||
const wan = points.map((p) => toMbps(p.wan));
|
|
||||||
const r = (res.data ?? []).slice(-40);
|
const r = (res.data ?? []).slice(-40);
|
||||||
const cpu = r[r.length - 1];
|
const cpu = r[r.length - 1];
|
||||||
const totalBandwidth = list.reduce((a, s) => a + s.bandwidth, 0);
|
const totalBandwidth = list.reduce((a, s) => a + s.bandwidth, 0);
|
||||||
|
|
@ -150,7 +169,7 @@ function Dashboard() {
|
||||||
))}
|
))}
|
||||||
</Card>
|
</Card>
|
||||||
<div className="admin-2-col">
|
<div className="admin-2-col">
|
||||||
<Card title="Bandwidth" actions={<span className="note">Last few minutes · live</span>}>
|
<Card title="Bandwidth" actions={<span className="note">Last 2 minutes · live</span>}>
|
||||||
<AreaChart
|
<AreaChart
|
||||||
series={[
|
series={[
|
||||||
{ values: wan, color: '#6797f5', label: 'Remote' },
|
{ values: wan, color: '#6797f5', label: 'Remote' },
|
||||||
|
|
|
||||||
|
|
@ -57,14 +57,12 @@ function PrefsEditor({ tab }: { tab: string }) {
|
||||||
const server = useServer();
|
const server = useServer();
|
||||||
const cfg = GROUPS[tab];
|
const cfg = GROUPS[tab];
|
||||||
const q = useServerQuery(['serverPrefs'], (s) => admin.prefs(s), { staleTime: 0 });
|
const q = useServerQuery(['serverPrefs'], (s) => admin.prefs(s), { staleTime: 0 });
|
||||||
const [advanced, setAdvanced] = useState(false);
|
|
||||||
const [edits, setEdits] = useState<Record<string, string | number | boolean>>({});
|
const [edits, setEdits] = useState<Record<string, string | number | boolean>>({});
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const settings = useMemo(
|
const settings = useMemo(
|
||||||
() => (q.data ?? []).filter((x) => cfg.groups.includes(x.group) && !x.hidden && (advanced || !x.advanced) && !(cfg.exclude && cfg.exclude.test(x.id))),
|
() => (q.data ?? []).filter((x) => cfg.groups.includes(x.group) && !x.hidden && !(cfg.exclude && cfg.exclude.test(x.id))),
|
||||||
[q.data, tab, advanced],
|
[q.data, tab],
|
||||||
);
|
);
|
||||||
const advancedCount = (q.data ?? []).filter((x) => cfg.groups.includes(x.group) && !x.hidden && x.advanced).length;
|
|
||||||
const dirty = Object.keys(edits).length > 0;
|
const dirty = Object.keys(edits).length > 0;
|
||||||
|
|
||||||
const save = async () => {
|
const save = async () => {
|
||||||
|
|
@ -85,18 +83,7 @@ function PrefsEditor({ tab }: { tab: string }) {
|
||||||
if (!q.data) return <PageLoader />;
|
if (!q.data) return <PageLoader />;
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SettingsSection
|
<SettingsSection title={cfg.title} description={cfg.description}>
|
||||||
title={cfg.title}
|
|
||||||
description={cfg.description}
|
|
||||||
actions={
|
|
||||||
advancedCount > 0 && (
|
|
||||||
<label className="inline-toggle">
|
|
||||||
Show advanced
|
|
||||||
<Switch checked={advanced} onChange={setAdvanced} />
|
|
||||||
</label>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{settings.map((s) => (
|
{settings.map((s) => (
|
||||||
<Pref key={s.id} label={s.label} description={s.summary}>
|
<Pref key={s.id} label={s.label} description={s.summary}>
|
||||||
<SettingControl setting={s} value={s.id in edits ? edits[s.id] : s.value} onChange={(v) => setEdits((e) => (v === s.value ? (({ [s.id]: _, ...rest }) => rest)(e) : { ...e, [s.id]: v }))} />
|
<SettingControl setting={s} value={s.id in edits ? edits[s.id] : s.value} onChange={(v) => setEdits((e) => (v === s.value ? (({ [s.id]: _, ...rest }) => rest)(e) : { ...e, [s.id]: v }))} />
|
||||||
|
|
|
||||||
|
|
@ -66,8 +66,7 @@
|
||||||
gap: 20px;
|
gap: 20px;
|
||||||
transition:
|
transition:
|
||||||
background var(--t) var(--ease),
|
background var(--t) var(--ease),
|
||||||
box-shadow var(--t) var(--ease),
|
box-shadow var(--t) var(--ease);
|
||||||
backdrop-filter var(--t);
|
|
||||||
}
|
}
|
||||||
.topbar::before {
|
.topbar::before {
|
||||||
content: '';
|
content: '';
|
||||||
|
|
@ -78,9 +77,9 @@
|
||||||
z-index: -1;
|
z-index: -1;
|
||||||
transition: opacity var(--t);
|
transition: opacity var(--t);
|
||||||
}
|
}
|
||||||
|
/* No backdrop blur: it re-renders the page behind the bar on every scroll frame. */
|
||||||
.topbar.solid {
|
.topbar.solid {
|
||||||
background: rgba(11, 12, 14, 0.86);
|
background: rgba(11, 12, 14, 0.95);
|
||||||
backdrop-filter: blur(22px) saturate(1.2);
|
|
||||||
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.05);
|
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.05);
|
||||||
}
|
}
|
||||||
.topbar.solid::before {
|
.topbar.solid::before {
|
||||||
|
|
@ -163,19 +162,21 @@
|
||||||
.nav-item::after {
|
.nav-item::after {
|
||||||
content: '';
|
content: '';
|
||||||
position: absolute;
|
position: absolute;
|
||||||
left: 50%;
|
left: 0;
|
||||||
right: 50%;
|
right: 0;
|
||||||
bottom: 14px;
|
bottom: 14px;
|
||||||
height: 2px;
|
height: 2px;
|
||||||
border-radius: 2px;
|
border-radius: 2px;
|
||||||
background: #e2e8e5;
|
background: #e2e8e5;
|
||||||
|
opacity: 0;
|
||||||
|
transform: scaleX(0);
|
||||||
transition:
|
transition:
|
||||||
left var(--t) var(--ease-out),
|
transform var(--t) var(--ease-out),
|
||||||
right var(--t) var(--ease-out);
|
opacity var(--t) var(--ease-out);
|
||||||
}
|
}
|
||||||
.nav-item.active::after {
|
.nav-item.active::after {
|
||||||
left: 0;
|
opacity: 1;
|
||||||
right: 0;
|
transform: none;
|
||||||
}
|
}
|
||||||
.nav-count {
|
.nav-count {
|
||||||
min-width: 17px;
|
min-width: 17px;
|
||||||
|
|
@ -247,62 +248,46 @@
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
}
|
}
|
||||||
|
/* macOS draws its traffic lights at the top left (tauri.macos.conf.json places
|
||||||
|
them in the bar's centre line); keep the bar's content clear of them. */
|
||||||
|
html.os-macos:not(.window-fullscreen) {
|
||||||
|
--traffic-lights: 92px;
|
||||||
|
}
|
||||||
|
html.os-macos:not(.window-fullscreen) .topbar {
|
||||||
|
padding-left: max(calc(var(--gutter) - 10px), var(--traffic-lights));
|
||||||
|
}
|
||||||
|
|
||||||
/* —— Splash ————————————————————————————————————————————————— */
|
/* —— Splash ————————————————————————————————————————————————— */
|
||||||
.splash {
|
.splash {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
z-index: 2000;
|
z-index: 2000;
|
||||||
background: radial-gradient(ellipse at 70% 20%, #16302c 0%, transparent 55%), radial-gradient(ellipse at 20% 90%, #2a2118 0%, transparent 50%), #08090b;
|
|
||||||
display: grid;
|
|
||||||
place-items: center;
|
|
||||||
transition:
|
|
||||||
opacity 600ms var(--ease) 80ms,
|
|
||||||
transform 640ms var(--ease);
|
|
||||||
}
|
}
|
||||||
.splash-mark {
|
.splash canvas {
|
||||||
display: flex;
|
display: block;
|
||||||
flex-direction: column;
|
width: 100%;
|
||||||
align-items: center;
|
height: 100%;
|
||||||
gap: 22px;
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
.splash-mark path {
|
/* The app beneath settles from a slight zoom as the camera flies through the
|
||||||
transform-origin: 32px 32px;
|
aperture (held for the first quarter of the exit, then decelerating).
|
||||||
animation: facet-open 1000ms var(--ease-out) both;
|
The duration matches EXIT_MS in Splash.tsx. */
|
||||||
animation-delay: calc(var(--i) * 45ms);
|
html.splash-arrival .app-shell,
|
||||||
|
html.splash-arrival .auth-screen {
|
||||||
|
animation: splash-arrival 540ms linear both;
|
||||||
}
|
}
|
||||||
@keyframes facet-open {
|
@keyframes splash-arrival {
|
||||||
0% {
|
0% {
|
||||||
opacity: 0;
|
transform: scale(1.14);
|
||||||
transform: rotate(-44deg) scale(0.55);
|
|
||||||
}
|
}
|
||||||
70% {
|
25% {
|
||||||
opacity: 1;
|
transform: scale(1.14);
|
||||||
transform: rotate(3deg) scale(1.03);
|
animation-timing-function: cubic-bezier(0.05, 0.7, 0.1, 1);
|
||||||
}
|
}
|
||||||
100% {
|
100% {
|
||||||
transform: none;
|
transform: none;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.splash-word {
|
|
||||||
font-weight: 760;
|
|
||||||
letter-spacing: 0.42em;
|
|
||||||
font-size: 15px;
|
|
||||||
color: #e9eeec;
|
|
||||||
animation: rise-in 700ms 420ms var(--ease-out) both;
|
|
||||||
margin-right: -0.42em;
|
|
||||||
}
|
|
||||||
.splash.leaving {
|
|
||||||
opacity: 0;
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
|
||||||
.splash.leaving .splash-mark {
|
|
||||||
transform: scale(1.4);
|
|
||||||
opacity: 0;
|
|
||||||
transition:
|
|
||||||
transform 600ms var(--ease),
|
|
||||||
opacity 400ms var(--ease);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* —— Sign-in and server picker ———————————————————————————————— */
|
/* —— Sign-in and server picker ———————————————————————————————— */
|
||||||
.auth-screen {
|
.auth-screen {
|
||||||
|
|
@ -526,15 +511,66 @@
|
||||||
position: absolute;
|
position: absolute;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
transition: opacity 560ms var(--ease);
|
transition: opacity 420ms var(--ease);
|
||||||
}
|
}
|
||||||
.backdrop-layer.ready {
|
.backdrop-layer.ready {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
/* The outgoing art fades too, a beat behind the incoming, so nothing of it is
|
||||||
|
left to vanish through the new art's faded edges. */
|
||||||
|
.backdrop-layer.ready.leaving {
|
||||||
|
opacity: 0;
|
||||||
|
transition-delay: 180ms;
|
||||||
|
}
|
||||||
|
/* The colour wash lives outside the clipped backdrop so it can carry on down
|
||||||
|
the page behind the rows, fading out as it goes. */
|
||||||
|
.backdrop-tint {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
height: calc(100% + 70vh);
|
||||||
|
z-index: -1;
|
||||||
|
pointer-events: none;
|
||||||
|
-webkit-mask-image: linear-gradient(180deg, #000 0%, rgba(0, 0, 0, 0.75) 45%, transparent 100%);
|
||||||
|
mask-image: linear-gradient(180deg, #000 0%, rgba(0, 0, 0, 0.75) 45%, transparent 100%);
|
||||||
|
}
|
||||||
|
/* Registered as colours so a change of title blends the wash from one set of
|
||||||
|
colours to the next, instead of swapping the gradient outright. */
|
||||||
|
@property --wash-tr {
|
||||||
|
syntax: '<color>';
|
||||||
|
inherits: false;
|
||||||
|
initial-value: transparent;
|
||||||
|
}
|
||||||
|
@property --wash-tl {
|
||||||
|
syntax: '<color>';
|
||||||
|
inherits: false;
|
||||||
|
initial-value: transparent;
|
||||||
|
}
|
||||||
|
@property --wash-br {
|
||||||
|
syntax: '<color>';
|
||||||
|
inherits: false;
|
||||||
|
initial-value: transparent;
|
||||||
|
}
|
||||||
|
@property --wash-bl {
|
||||||
|
syntax: '<color>';
|
||||||
|
inherits: false;
|
||||||
|
initial-value: transparent;
|
||||||
|
}
|
||||||
.backdrop-wash {
|
.backdrop-wash {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
opacity: 0.62;
|
opacity: 0.5;
|
||||||
|
background:
|
||||||
|
radial-gradient(ellipse at 100% 0%, var(--wash-tr) 0%, transparent 62%),
|
||||||
|
radial-gradient(ellipse at 0% 0%, var(--wash-tl) 0%, transparent 55%),
|
||||||
|
radial-gradient(ellipse at 100% 100%, var(--wash-br) 0%, transparent 60%),
|
||||||
|
radial-gradient(ellipse at 0% 100%, var(--wash-bl) 0%, transparent 60%);
|
||||||
|
transition:
|
||||||
|
--wash-tr 700ms var(--ease),
|
||||||
|
--wash-tl 700ms var(--ease),
|
||||||
|
--wash-br 700ms var(--ease),
|
||||||
|
--wash-bl 700ms var(--ease);
|
||||||
}
|
}
|
||||||
.backdrop-art {
|
.backdrop-art {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
|
|
@ -565,20 +601,30 @@
|
||||||
linear-gradient(90deg, rgba(9, 10, 12, 0.92) 0%, rgba(9, 10, 12, 0.6) 30%, rgba(9, 10, 12, 0.08) 62%, transparent 100%),
|
linear-gradient(90deg, rgba(9, 10, 12, 0.92) 0%, rgba(9, 10, 12, 0.6) 30%, rgba(9, 10, 12, 0.08) 62%, transparent 100%),
|
||||||
linear-gradient(0deg, var(--bg) 0%, rgba(9, 10, 12, 0.6) 14%, transparent 40%);
|
linear-gradient(0deg, var(--bg) 0%, rgba(9, 10, 12, 0.6) 14%, transparent 40%);
|
||||||
}
|
}
|
||||||
|
/* With the wash, the art's own mask fades it into the tinted page; the scrim
|
||||||
|
only keeps the copy legible instead of painting the page back to black. */
|
||||||
|
.backdrop.washed .backdrop-scrim {
|
||||||
|
background: linear-gradient(90deg, rgba(9, 10, 12, 0.55) 0%, rgba(9, 10, 12, 0.25) 34%, transparent 60%);
|
||||||
|
}
|
||||||
|
|
||||||
/* —— Hero ———————————————————————————————————————————————————— */
|
/* —— Hero ———————————————————————————————————————————————————— */
|
||||||
.hero {
|
.hero {
|
||||||
position: relative;
|
position: relative;
|
||||||
height: clamp(430px, 64vh, 760px);
|
/* A minimum, not a fixed height: long copy grows the hero instead of
|
||||||
|
running up under the navigation. */
|
||||||
|
min-height: clamp(430px, 64vh, 760px);
|
||||||
|
padding-top: calc(var(--nav-h) + 36px);
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: flex-end;
|
align-items: flex-end;
|
||||||
isolation: isolate;
|
isolation: isolate;
|
||||||
}
|
}
|
||||||
.hero.section {
|
.hero.section {
|
||||||
height: clamp(400px, 56vh, 660px);
|
min-height: clamp(400px, 56vh, 660px);
|
||||||
|
/* Clear of the overlaid section header (title and tabs). */
|
||||||
|
padding-top: calc(var(--nav-h) + 96px);
|
||||||
}
|
}
|
||||||
.hero.empty {
|
.hero.empty {
|
||||||
height: clamp(240px, 30vh, 320px);
|
min-height: clamp(240px, 30vh, 320px);
|
||||||
}
|
}
|
||||||
.hero-content {
|
.hero-content {
|
||||||
position: relative;
|
position: relative;
|
||||||
|
|
@ -601,11 +647,9 @@
|
||||||
transform: none;
|
transform: none;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.hero-eyebrow {
|
/* Scoped so the later `.title-art { margin: 0 }` can't cancel the gap above the facts. */
|
||||||
margin-bottom: 16px;
|
.hero-content .hero-title {
|
||||||
}
|
margin: 0 0 22px;
|
||||||
.hero-title {
|
|
||||||
margin: 0 0 18px;
|
|
||||||
}
|
}
|
||||||
.hero-episode {
|
.hero-episode {
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
|
|
@ -659,7 +703,7 @@
|
||||||
inset: 0;
|
inset: 0;
|
||||||
background: #eef3f1;
|
background: #eef3f1;
|
||||||
transform-origin: left;
|
transform-origin: left;
|
||||||
animation: dot-fill 12s linear both;
|
animation: dot-fill 8s linear both;
|
||||||
}
|
}
|
||||||
.hero-dots button.active:not(:has(.hero-dot-progress)) {
|
.hero-dots button.active:not(:has(.hero-dot-progress)) {
|
||||||
background: #eef3f1;
|
background: #eef3f1;
|
||||||
|
|
@ -810,6 +854,7 @@
|
||||||
overflow-y: hidden;
|
overflow-y: hidden;
|
||||||
scroll-snap-type: x proximity;
|
scroll-snap-type: x proximity;
|
||||||
scroll-padding: 0 var(--gutter);
|
scroll-padding: 0 var(--gutter);
|
||||||
|
overflow-anchor: none;
|
||||||
padding: 4px var(--gutter) 10px;
|
padding: 4px var(--gutter) 10px;
|
||||||
scrollbar-width: none;
|
scrollbar-width: none;
|
||||||
}
|
}
|
||||||
|
|
@ -966,9 +1011,8 @@
|
||||||
display: grid;
|
display: grid;
|
||||||
place-items: center;
|
place-items: center;
|
||||||
color: #fff;
|
color: #fff;
|
||||||
background: rgba(30, 33, 36, 0.6);
|
background: rgba(24, 27, 30, 0.78);
|
||||||
box-shadow: inset 0 0 0 1.4px rgba(255, 255, 255, 0.45);
|
box-shadow: inset 0 0 0 1.4px rgba(255, 255, 255, 0.45);
|
||||||
backdrop-filter: blur(6px);
|
|
||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
}
|
}
|
||||||
.card-more:hover {
|
.card-more:hover {
|
||||||
|
|
@ -1049,6 +1093,23 @@
|
||||||
.card.landscape .card-title {
|
.card.landscape .card-title {
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
.card-title-link {
|
||||||
|
max-width: 100%;
|
||||||
|
font: inherit;
|
||||||
|
color: inherit;
|
||||||
|
text-align: left;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
text-decoration: underline;
|
||||||
|
text-decoration-color: transparent;
|
||||||
|
text-underline-offset: 3px;
|
||||||
|
transition: text-decoration-color var(--t-fast);
|
||||||
|
}
|
||||||
|
.card-title-link:hover {
|
||||||
|
color: #fff;
|
||||||
|
text-decoration-color: rgba(255, 255, 255, 0.5);
|
||||||
|
}
|
||||||
.card-meta {
|
.card-meta {
|
||||||
font-size: 11.5px;
|
font-size: 11.5px;
|
||||||
color: #8a9196;
|
color: #8a9196;
|
||||||
|
|
@ -1073,9 +1134,8 @@
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
display: grid;
|
display: grid;
|
||||||
place-items: center;
|
place-items: center;
|
||||||
background: rgba(20, 22, 24, 0.55);
|
background: rgba(20, 22, 24, 0.72);
|
||||||
box-shadow: inset 0 0 0 1.5px rgba(255, 255, 255, 0.6);
|
box-shadow: inset 0 0 0 1.5px rgba(255, 255, 255, 0.6);
|
||||||
backdrop-filter: blur(6px);
|
|
||||||
color: #fff;
|
color: #fff;
|
||||||
transition: transform var(--t-fast);
|
transition: transform var(--t-fast);
|
||||||
}
|
}
|
||||||
|
|
|
||||||