Compare commits

..

No commits in common. "main" and "v0.1.0-beta.5" have entirely different histories.

99 changed files with 1610 additions and 5191 deletions

View file

@ -1,8 +1,8 @@
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.
# push. Releases can instead be built with scripts/build.ps1 and published with
# scripts/publish-release.mjs.
on:
workflow_dispatch:
@ -29,14 +29,11 @@ jobs:
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'
- 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/build.sh
- name: Build (Linux)
if: matrix.os == 'linux'
run: |
sh scripts/fetch-libmpv.sh
npm ci

1
.gitignore vendored
View file

@ -10,6 +10,5 @@ vendor/mpv/*/
.env
.env.*
evidence/
.DS_Store
*.log
.claude/

View file

@ -11,7 +11,7 @@
- Keep the interface restrained: no redundant buttons or navigation.
- `.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
replace it. `.tools/macos-signing.*` backs up the macOS signing certificate; same rules.
replace it.
- 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`.
@ -19,20 +19,19 @@
- `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`).
- Native: `npm run tauri dev` (on Windows with `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`);
`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`).
- Native: `npm run tauri dev` with `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`;
`window.__kaleido` exposes the stores in development.
- Mute before playback tests (`__kaleido.useSettings.getState().set('volume', 0)`).
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
Built and published locally (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, `.\scripts\build.ps1`, commit + tag `vX.Y.Z` + push,
`node scripts/publish-release.mjs X.Y.Z [--prerelease]`, then
`node scripts/update-manifest.mjs X.Y.Z <release download URL>` 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`.

View file

@ -1,155 +1,5 @@
# 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.

View file

@ -4,10 +4,9 @@ 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
mouse and keyboard.
Kaleido runs on Windows and macOS (Apple silicon) with the same interface and features;
each release carries both, and installed copies update themselves. The interface and
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.
Windows is supported today. The repository is structured for Windows, macOS and Linux:
the interface and nearly all of the native core are shared, and each platform's
differences live in one place (see [Architecture](docs/architecture.md)).
## What's in the app
@ -62,20 +61,18 @@ place (see [Architecture](docs/architecture.md)). Linux builds browse but don't
| Browsing | | Player | |
| --- | --- | --- | --- |
| Ctrl+K (⌘K) | Search | Space / K | Play/pause |
| Ctrl+K | Search | Space / K | Play/pause |
| Arrow keys | Move between titles | ← / → | Seek (Shift: 1 min) |
| Enter / Space | Open / play | ↑ / ↓, wheel | Volume |
| Menu or Shift+F10 | Title actions | F, double-click | Full screen |
| Alt+← (⌘[) / mouse back | Back | C | Next subtitle |
| / | Focus search | Shift+P / N | Previous / next episode |
| F11 (⌃⌘F) | Full screen | Esc | Exit full screen, then player |
Keys in brackets are the macOS equivalents.
| Alt+← / mouse back | Back | C | Next subtitle |
| / | Focus search | Shift+N | Next episode |
| F11 | Full screen | Esc | Exit full screen, then player |
## Build from source
Requirements: Node 22+, Rust (stable); on Windows the Visual Studio C++ build tools and
7-Zip, on macOS the Xcode command line tools and Homebrew.
Requirements: Node 22+, Rust (stable), and on Windows the Visual Studio C++ build tools
and 7-Zip.
```powershell
npm ci
@ -84,13 +81,6 @@ npm run tauri dev # development app
.\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
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

View file

@ -35,34 +35,21 @@ 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`.
Each exposes the same items:
| 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. 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` | `libmpv.2.dylib` (in `Contents/Frameworks` with the libraries it links) |
| `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 |
| Item | Windows implementation |
| --- | --- |
| `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_LIBRARIES` | `libmpv-2.dll` |
| `hold_awake` | `SetThreadExecutionState` while video plays |
Linux provides stubs for `VideoSurface` (browsing, downloads, settings and updates
work; playback reports that it is unavailable); the macOS approach (render API beneath
the web view) applies there with an OpenGL surface under WebKitGTK. Per-OS bundling
(libmpv, targets, window style) lives in `tauri.<os>.conf.json`. Credentials use the
platform's 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.
macOS and Linux currently provide stubs for `VideoSurface` (browsing, downloads,
settings and updates work; playback reports that it is unavailable). To add playback
there, render through mpv's render API into a layer beneath the web view and implement
the same methods (`set_rect` places the video in part of the window for the miniplayer). Per-OS bundling (libmpv, targets, dependencies) lives in
`tauri.macos.conf.json` and `tauri.linux.conf.json`. Credentials use the platform's
keychain through the `keyring` crate with per-OS features in `Cargo.toml`.
The page background turns transparent only while video is visible
(`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.
On Windows the main window is created transparent and the page background turns
transparent only while video is visible (`html.video-active`), so browsing is opaque.
## Interface
@ -79,33 +66,17 @@ into the display's HDR headroom; SDR video returns both to their defaults.
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.
Plex streams are matched to mpv tracks by stream index; external subtitles are added
on demand. Timeline reports every 10 seconds (and when playback stalls) make the session appear in
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
on demand. Timeline reports every 10 seconds make the session appear in Plex, and the
title is marked watched at the configured percentage. The player's back arrow (or Esc)
shrinks playback into a miniplayer: the video is drawn in a corner rectangle and the
interface stays visible around it, 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
- **Upscaling** (`player/enhance.ts`): tiers set mpv's scalers and debanding and load
shaders bundled from `src-tauri/shaders/` (FSRCNNX, nlmeans, KrigBilateral, AMD CAS);
each shader's `WHEN` condition decides whether it runs for the current video and size.
The chosen tier and the running one are tracked separately: shader errors in mpv's log
or missing network passes in `vo-passes` 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
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`).
user's confirmation and then relaunch.

View file

@ -11,22 +11,6 @@
debug builds and the Vite dev server. Never commit or print it.
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
layout work; playback, downloads and native dialogs need the desktop app. In development
builds the stores are available as `window.__kaleido` for debugging.
@ -47,107 +31,45 @@ 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
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 are built and published locally: Windows on the Windows machine, macOS on the
Mac. CI only validates; it never builds installers on push (there are no Windows/macOS
runners). Versions follow SemVer; betas use a prerelease suffix (`0.1.0-beta.1`) and are
published as pre-releases. **Each release carries both platforms**, and the update feed
is written only once both are uploaded.
Releases are built and published from this Windows machine. CI only validates; it never
builds installers on push (there are no Windows/macOS runners). Versions follow SemVer;
betas use a prerelease suffix (`0.1.0-beta.1`) and are published as pre-releases.
Checklist for version `X.Y.Z` (run from the repository root):
1. **Version** (either machine): set `X.Y.Z` in `package.json`, `src-tauri/Cargo.toml`
and `src-tauri/tauri.conf.json`, then `npm install --package-lock-only` to update
1. **Version**: set `X.Y.Z` in `package.json`, `src-tauri/Cargo.toml` 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
4. **Build**: `.\scripts\build.ps1` → `src-tauri/target/release/bundle/nsis/Kaleido_X.Y.Z_x64-setup.exe`
and its `.sig`. The updater key is read from `.tools/updater.key` (ignored; keep it
safe — replacing it breaks in-app updates for existing installs) or from
`TAURI_SIGNING_PRIVATE_KEY`.
5. **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.
(SSH remote `origin`, already configured).
6. **Publish**: `node scripts/publish-release.mjs X.Y.Z` (add `--prerelease` for betas)
creates the Forgejo release with the notes from `CHANGELOG.md` and uploads the
installer and `.sig`. It reads `FORGEJO_TOKEN` (repository read/write) from the
environment or the ignored `.env`, and never prints it. Re-running it replaces the
assets.
7. **Update feed**: `node scripts/update-manifest.mjs X.Y.Z https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/vX.Y.Z`
rewrites `updates/latest.json`; commit it (`Publish the X.Y.Z update feed`) and push.
Installed copies offer the update on their next start. Publish the feed only after
the release assets exist, or clients would be sent to a missing file.
8. **Verify**: download the installer from the release URL and compare its SHA-256 with
the local file; `https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/raw/branch/main/updates/latest.json`
should show 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.
The installer is per user (`%LOCALAPPDATA%\Kaleido`, no admin) and is not code-signed,
so SmartScreen warns on first run. In-app updates run it in passive mode and relaunch.
**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;
For macOS and Linux, build on those systems (`scripts/fetch-libmpv.sh`, then
`npx tauri build`) and merge their bundles into the same feed with `KALEIDO_BUNDLES`.
`.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.

View file

@ -1,12 +0,0 @@
<!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
View file

@ -1,12 +1,12 @@
{
"name": "kaleido-desktop",
"version": "1.0.1",
"version": "0.1.0-beta.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaleido-desktop",
"version": "1.0.1",
"version": "0.1.0-beta.5",
"dependencies": {
"@fontsource-variable/inter": "^5.3.0",
"@tanstack/react-query": "^5.105.0",

View file

@ -1,7 +1,7 @@
{
"name": "kaleido-desktop",
"private": true,
"version": "1.0.1",
"version": "0.1.0-beta.5",
"type": "module",
"scripts": {
"dev": "vite",

View file

@ -21,25 +21,10 @@ if (-not $env:TAURI_SIGNING_PRIVATE_KEY) {
}
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")
if ($Debug) { $buildArgs += "--debug" }
npx @buildArgs
if ($LASTEXITCODE -ne 0) { throw "Build failed" }
$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

View file

@ -1,54 +0,0 @@
#!/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"

View file

@ -1,39 +1,14 @@
#!/usr/bin/env sh
# 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.
# macOS: copies Homebrew's libmpv into vendor/mpv/macos for bundling.
# Linux: libmpv comes from the system package (libmpv2); nothing to copy.
set -eu
root=$(cd "$(dirname "$0")/.." && pwd)
case "$(uname -s)" in
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
command -v dylibbundler >/dev/null 2>&1 || brew install dylibbundler
rm -rf "$out" && mkdir -p "$out"
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)" ;;
mkdir -p "$root/vendor/mpv/macos"
cp "$(brew --prefix mpv)/lib/libmpv.2.dylib" "$root/vendor/mpv/macos/"
echo "libmpv copied to vendor/mpv/macos" ;;
Linux)
echo "Install libmpv from your distribution (e.g. apt install libmpv2 libmpv-dev)." ;;
*) echo "Use scripts/fetch-libmpv.ps1 on Windows." ;;

View file

@ -1,12 +1,11 @@
// 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.
// Creates (or reuses) a Forgejo release for a tag and uploads the Windows installer and
// its updater signature. 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 API = 'https://git.elijahkuntz.com/api/v1/repos/Elijah/Kaleido-Desktop';
const root = path.resolve(import.meta.dirname, '..');
const version = process.argv[2];
const prerelease = process.argv.includes('--prerelease');
if (!version) {
@ -14,38 +13,43 @@ if (!version) {
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.');
let token = process.env.FORGEJO_TOKEN;
if (!token && fs.existsSync(path.join(root, '.env'))) {
token = fs.readFileSync(path.join(root, '.env'), 'utf8').match(/^FORGEJO_TOKEN=(.*)$/m)?.[1]?.trim().replace(/^"|"$/g, '');
}
if (!token) {
console.error('FORGEJO_TOKEN is not set.');
process.exit(1);
}
const headers = { Authorization: `token ${token}`, Accept: 'application/json' };
token(true);
const files = builtFiles();
for (const file of files) {
if (!fs.existsSync(file)) throw new Error(`Missing ${file}; build this version first.`);
async function api(method, url, body) {
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;
}
const tag = `v${version}`;
const changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8');
const section = changelog.split(/^## /m).find((s) => s.startsWith(version));
const notes = section ? section.slice(version.length).trim() : '';
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 });
release = await api('POST', '/releases', { tag_name: tag, name: `Kaleido Desktop ${version}`, body: notes, 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 dir = path.join(root, 'src-tauri/target/release/bundle/nsis');
const files = [`Kaleido_${version}_x64-setup.exe`, `Kaleido_${version}_x64-setup.exe.sig`];
for (const name of files) {
const file = path.join(dir, name);
if (!fs.existsSync(file)) throw new Error(`Missing ${file}; run scripts/build.ps1 first.`);
const existing = release.assets?.find((a) => a.name === name);
if (existing) await api('DELETE', `/releases/${release.id}/assets/${existing.id}`);
const form = new FormData();

View file

@ -1,49 +0,0 @@
// 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() : '';
}

View file

@ -1,56 +1,53 @@
// Writes updates/latest.json, the feed Kaleido's updater reads, from a published release:
// each platform's updater artifact and signature are taken from the release's assets, so
// the feed only ever points at this version's files, whichever machine runs it.
// 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.
// Writes updates/latest.json, the feed Kaleido's updater reads, from built bundles.
// Usage: node scripts/update-manifest.mjs <version> <baseDownloadUrl> [notesFile]
// Notes come from the version's CHANGELOG.md section unless a notes file is given.
// Each platform's signed artifact (and its .sig) must be in src-tauri/target/release/bundle,
// or pass several bundle folders via KALEIDO_BUNDLES (path;path) when collecting CI outputs.
import fs from 'node:fs';
import path from 'node:path';
import { api, download, releaseNotes, root } from './release-common.mjs';
const args = process.argv.slice(2);
const allowMissing = args.includes('--allow-missing');
const [version, notesFile] = args.filter((a) => !a.startsWith('--'));
if (!version) {
console.error('usage: node scripts/update-manifest.mjs <version> [--allow-missing] [notesFile]');
const [version, baseUrl, notesFile] = process.argv.slice(2);
if (!version || !baseUrl) {
console.error('usage: node scripts/update-manifest.mjs <version> <baseDownloadUrl> [notesFile]');
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 release asset each one installs. */
/** Tauri updater platform keys and the artifact each one installs. */
const PLATFORMS = [
{ key: 'windows-x86_64', match: (f) => f === `Kaleido_${version}_x64-setup.exe` },
{ key: 'darwin-aarch64', match: (f) => f === `Kaleido_${version}_aarch64.app.tar.gz` },
{ key: 'windows-x86_64', dir: 'nsis', match: /-setup\.exe$/ },
{ key: 'darwin-aarch64', dir: 'macos', match: /aarch64.*\.app\.tar\.gz$/ },
{ key: 'darwin-x86_64', dir: 'macos', match: /x64.*\.app\.tar\.gz$/ },
{ key: 'linux-x86_64', dir: 'appimage', match: /\.AppImage$/ },
];
const release = await api('GET', `/releases/tags/v${version}`).catch(() => null);
if (!release) throw new Error(`No release v${version}; publish it with scripts/publish-release.mjs first.`);
const assets = release.assets ?? [];
const platforms = {};
const missing = [];
for (const p of PLATFORMS) {
const artifact = assets.find((a) => p.match(a.name));
const sig = artifact && assets.find((a) => a.name === `${artifact.name}.sig`);
if (!artifact || !sig) {
missing.push(p.key);
continue;
}
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.`);
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');
const manifest = fs.existsSync(manifestPath) ? JSON.parse(fs.readFileSync(manifestPath, 'utf8')) : { platforms: {} };
manifest.version = version;
// Notes default to this version's section of CHANGELOG.md.
const changelogNotes = () => {
const section = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8').split(/^## /m).find((x) => x.startsWith(version));
return section ? section.slice(version.length).trim() : '';
};
manifest.notes = notesFile ? fs.readFileSync(notesFile, 'utf8').trim() : changelogNotes();
manifest.pub_date = new Date().toISOString();
manifest.platforms ??= {};
for (const bundle of bundles) {
for (const p of PLATFORMS) {
const dir = path.join(bundle, p.dir);
if (!fs.existsSync(dir)) continue;
const file = fs.readdirSync(dir).find((f) => p.match.test(f) && f.includes(version));
if (!file || !fs.existsSync(path.join(dir, `${file}.sig`))) continue;
manifest.platforms[p.key] = {
signature: fs.readFileSync(path.join(dir, `${file}.sig`), 'utf8').trim(),
url: `${baseUrl.replace(/\/$/, '')}/${encodeURIComponent(file)}`,
};
console.log(`${p.key}: ${file}`);
}
}
fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
console.log(`Wrote ${path.relative(root, manifestPath)}${missing.length ? ` (without ${missing.join(', ')})` : ''}`);
console.log(`Wrote ${path.relative(root, manifestPath)}`);

57
src-tauri/Cargo.lock generated
View file

@ -2173,21 +2173,13 @@ dependencies = [
[[package]]
name = "kaleido"
version = "1.0.1"
version = "0.1.0-beta.5"
dependencies = [
"fs2",
"futures-util",
"keyring",
"libloading 0.8.9",
"log",
"objc2",
"objc2-app-kit",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-core-video",
"objc2-foundation",
"objc2-open-gl",
"objc2-quartz-core",
"once_cell",
"parking_lot",
"reqwest 0.12.28",
@ -2613,15 +2605,8 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
dependencies = [
"bitflags 2.13.2",
"block2",
"libc",
"objc2",
"objc2-cloud-kit",
"objc2-core-data",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-core-image",
"objc2-core-text",
"objc2-core-video",
"objc2-foundation",
"objc2-quartz-core",
]
@ -2643,7 +2628,6 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"
dependencies = [
"bitflags 2.13.2",
"objc2",
"objc2-foundation",
]
@ -2704,19 +2688,6 @@ dependencies = [
"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]]
name = "objc2-encode"
version = "4.1.0"
@ -2756,26 +2727,6 @@ dependencies = [
"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]]
name = "objc2-osa-kit"
version = "0.3.2"
@ -2795,15 +2746,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
dependencies = [
"bitflags 2.13.2",
"block2",
"libc",
"objc2",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-core-video",
"objc2-foundation",
"objc2-metal",
"objc2-open-gl",
]
[[package]]

View file

@ -1,6 +1,6 @@
[package]
name = "kaleido"
version = "1.0.1"
version = "0.1.0-beta.5"
description = "Kaleido — a Plex client for Windows"
authors = ["Elijah"]
edition = "2021"
@ -34,14 +34,6 @@ log = "0.4"
# Credentials use each OS's native store: Credential Manager, Keychain, Secret Service.
[target.'cfg(target_os = "macos")'.dependencies]
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]
keyring = { version = "3", features = ["sync-secret-service", "crypto-rust"] }
@ -62,13 +54,6 @@ windows = { version = "0.61", features = [
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D11",
"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]

View file

@ -1,10 +1,9 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Kaleido main window and miniplayer window",
"description": "Kaleido main window",
"windows": [
"main",
"mini"
"main"
],
"permissions": [
"core:default",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 4.7 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 9.9 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 37 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

After

Width:  |  Height:  |  Size: 7.6 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 447 KiB

After

Width:  |  Height:  |  Size: 153 KiB

Before After
Before After

View file

@ -1,35 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 43 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

After

Width:  |  Height:  |  Size: 67 KiB

Before After
Before After

View file

@ -0,0 +1,426 @@
// Copyright (C) 2017-2021 igv
//
// This program 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 program 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 program. If not, see <https://www.gnu.org/licenses/>.
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC feature map 1
//!BIND LUMA
//!SAVE FEATURE1
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(-0.1572492271661758,-0.0120896836742759,0.0061487639322877,-0.2852848768234253);
res += vec4(-0.0047900392673910,0.0537447109818459,-0.0000247144635068,0.0066653941757977) * float(LUMA_texOff(vec2(-2,-2)));
res += vec4(0.0073144687339664,-0.0309004038572311,-0.0109181385487318,-0.0092840325087309) * float(LUMA_texOff(vec2(-2,-1)));
res += vec4(0.0591700896620750,0.1974907070398331,-0.0197357516735792,-0.0546554848551750) * float(LUMA_texOff(vec2(-2,0)));
res += vec4(-0.0011764382943511,-0.0299451071768999,0.0229587312787771,0.0021908886265010) * float(LUMA_texOff(vec2(-2,1)));
res += vec4(0.0098101310431957,0.0080995410680771,-0.0030452020000666,-0.0132035519927740) * float(LUMA_texOff(vec2(-2,2)));
res += vec4(-0.0168330334126949,-0.0743711441755295,-0.0259261634200811,0.0234480481594801) * float(LUMA_texOff(vec2(-1,-2)));
res += vec4(0.0239933785051107,0.1896541714668274,0.0207756329327822,-0.0370332375168800) * float(LUMA_texOff(vec2(-1,-1)));
res += vec4(0.0094799501821399,-0.0652511194348335,-0.0004292793164495,-0.0726212188601494) * float(LUMA_texOff(vec2(-1,0)));
res += vec4(0.0297284796833992,-0.1210186630487442,-0.0202929321676493,-0.0574462898075581) * float(LUMA_texOff(vec2(-1,1)));
res += vec4(-0.0318185277283192,0.0840775370597839,0.0110451309010386,0.0415569432079792) * float(LUMA_texOff(vec2(-1,2)));
res += vec4(-0.0253141783177853,0.1168256178498268,0.1159729585051537,0.0963164269924164) * float(LUMA_texOff(vec2(0,-2)));
res += vec4(-0.1103615835309029,-0.0276833958923817,-0.4999594092369080,0.1053867191076279) * float(LUMA_texOff(vec2(0,-1)));
res += vec4(1.1100435256958008,0.0646764487028122,0.0154005717486143,0.8891586661338806) * float(LUMA_texOff(vec2(0,0)));
res += vec4(0.1229330673813820,0.1719468832015991,0.5730338096618652,-0.1645544171333313) * float(LUMA_texOff(vec2(0,1)));
res += vec4(-0.0090442728251219,-0.3023961782455444,-0.1589493155479431,0.0418574027717113) * float(LUMA_texOff(vec2(0,2)));
res += vec4(0.0031942036002874,-0.1310926079750061,0.0075543406419456,-0.0016449346439913) * float(LUMA_texOff(vec2(1,-2)));
res += vec4(-0.0995150282979012,-0.0701921209692955,-0.0130895879119635,0.1344170123338699) * float(LUMA_texOff(vec2(1,-1)));
res += vec4(0.0060519003309309,-0.1533465683460236,0.0114194005727768,0.0264683905988932) * float(LUMA_texOff(vec2(1,0)));
res += vec4(0.0244008023291826,0.1881769001483917,-0.0206351149827242,-0.0628309547901154) * float(LUMA_texOff(vec2(1,1)));
res += vec4(0.0075713125988841,0.0508594363927841,0.0430423170328140,-0.0124188791960478) * float(LUMA_texOff(vec2(1,2)));
res += vec4(-0.0166875869035721,-0.0047865519300103,0.0006719123339280,0.0316803231835365) * float(LUMA_texOff(vec2(2,-2)));
res += vec4(-0.0058461269363761,0.0990798473358154,-0.0177743826061487,-0.0066122291609645) * float(LUMA_texOff(vec2(2,-1)));
res += vec4(-0.0972401946783066,-0.0225446373224258,-0.0037693574558944,0.1953062713146210) * float(LUMA_texOff(vec2(2,0)));
res += vec4(-0.0216837190091610,-0.1824268400669098,0.0069816261529922,0.0283037684857845) * float(LUMA_texOff(vec2(2,1)));
res += vec4(-0.0025767991319299,0.0459827110171318,-0.0080216089263558,0.0084134787321091) * float(LUMA_texOff(vec2(2,2)));
return res;
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC feature map 2
//!BIND LUMA
//!SAVE FEATURE2
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(0.0541447550058365,0.0088306749239564,-0.0112389577552676,-0.0127860950306058);
res += vec4(0.0142660010606050,0.0137931071221828,0.0061188107356429,-0.0104134222492576) * float(LUMA_texOff(vec2(-2,-2)));
res += vec4(0.0147292809560895,-0.0289912857115269,0.0266769435256720,0.0933856964111328) * float(LUMA_texOff(vec2(-2,-1)));
res += vec4(-0.1734338253736496,0.1116316691040993,-0.1973157376050949,-0.0581855811178684) * float(LUMA_texOff(vec2(-2,0)));
res += vec4(0.0347507223486900,-0.0341566652059555,0.0061667622067034,0.0075258882716298) * float(LUMA_texOff(vec2(-2,1)));
res += vec4(0.0069884369149804,-0.0194250214844942,0.0080830128863454,-0.0036874092184007) * float(LUMA_texOff(vec2(-2,2)));
res += vec4(0.0233764201402664,0.0344744995236397,0.0162145942449570,0.0979529991745949) * float(LUMA_texOff(vec2(-1,-2)));
res += vec4(0.1280796974897385,-0.1018339172005653,-0.0132977198809385,-0.0019474622095004) * float(LUMA_texOff(vec2(-1,-1)));
res += vec4(0.4286882579326630,0.1222677752375603,0.7046694159507751,0.0945475697517395) * float(LUMA_texOff(vec2(-1,0)));
res += vec4(0.1107441782951355,-0.0134433070197701,-0.0174900908023119,-0.1686445474624634) * float(LUMA_texOff(vec2(-1,1)));
res += vec4(0.0321478620171547,0.0065357843413949,0.0300805997103453,0.0420113280415535) * float(LUMA_texOff(vec2(-1,2)));
res += vec4(-0.1240341588854790,0.0950303301215172,-0.0129648456349969,-0.2681856453418732) * float(LUMA_texOff(vec2(0,-2)));
res += vec4(0.4846960902214050,0.0351924635469913,0.0223043337464333,-0.1273630708456039) * float(LUMA_texOff(vec2(0,-1)));
res += vec4(-1.9379507303237915,-0.2444442063570023,0.0291962660849094,-0.3835578560829163) * float(LUMA_texOff(vec2(0,0)));
res += vec4(0.6396278142929077,-0.0765938311815262,-0.0552659817039967,0.4393545985221863) * float(LUMA_texOff(vec2(0,1)));
res += vec4(-0.1969728022813797,-0.0607173256576061,0.0131113547831774,0.0542017817497253) * float(LUMA_texOff(vec2(0,2)));
res += vec4(0.0091696009039879,-0.0031533432193100,-0.0368777588009834,-0.0459998287260532) * float(LUMA_texOff(vec2(1,-2)));
res += vec4(0.1096992492675781,0.2597902715206146,0.0304869692772627,-0.0195200722664595) * float(LUMA_texOff(vec2(1,-1)));
res += vec4(0.2889648377895355,-0.4275591969490051,-0.7414156794548035,0.2695442438125610) * float(LUMA_texOff(vec2(1,0)));
res += vec4(0.0892018377780914,-0.0229137558490038,0.0244414471089840,-0.1926898956298828) * float(LUMA_texOff(vec2(1,1)));
res += vec4(0.0576358586549759,0.0027846973389387,-0.0036861505359411,-0.0253547113388777) * float(LUMA_texOff(vec2(1,2)));
res += vec4(0.0159624069929123,0.0319602824747562,0.0019470085389912,0.0089780492708087) * float(LUMA_texOff(vec2(2,-2)));
res += vec4(0.0552792511880398,0.0543054342269897,0.0134062822908163,0.0545728243887424) * float(LUMA_texOff(vec2(2,-1)));
res += vec4(-0.1170092225074768,0.1963327825069427,0.1503890156745911,0.1891828328371048) * float(LUMA_texOff(vec2(2,0)));
res += vec4(-0.0084421783685684,0.1297017931938171,-0.0330600887537003,-0.0942063704133034) * float(LUMA_texOff(vec2(2,1)));
res += vec4(0.0118440408259630,-0.0337875857949257,0.0055063469335437,0.0254479162395000) * float(LUMA_texOff(vec2(2,2)));
return res;
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC mapping 1_1
//!BIND FEATURE1
//!BIND FEATURE2
//!SAVE MODEL21
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(-0.0445119962096214,-0.7632357478141785,0.0156328510493040,-0.2424548566341400);
res += mat4(0.1279004216194153,-0.0275541823357344,0.2275633513927460,0.2241709381341934,0.0197204202413559,-0.0456816256046295,-0.1296672523021698,0.0564568229019642,-0.0241488646715879,-0.0237508192658424,-0.1899632662534714,0.4177669584751129,-0.1814560592174530,-0.0526473335921764,0.1154382973909378,-0.0715614855289459) * FEATURE1_texOff(vec2(-1,-1));
res += mat4(-0.0660311505198479,0.0416736751794815,0.3146112561225891,0.1472041457891464,-0.3456672728061676,-0.0055983816273510,0.0022350433282554,0.0819796621799469,0.0057485047727823,0.1532524228096008,0.0204557459801435,-0.2500547170639038,-0.0524359568953514,-0.1911625266075134,-0.1078366711735725,-0.1296254843473434) * FEATURE2_texOff(vec2(-1,-1));
res += mat4(0.0904538556933403,-0.0150672039017081,0.3322310745716095,0.0638923197984695,0.5975797176361084,-0.2452044337987900,-0.4947478473186493,-0.0783191770315170,0.5771877169609070,-0.0870653912425041,-0.8966570496559143,-0.2140965163707733,-0.0493861362338066,-0.0380848757922649,-0.1345319598913193,-0.0186063013970852) * FEATURE1_texOff(vec2(-1,0));
res += mat4(-0.2523841261863708,0.1387074738740921,0.7878478765487671,-0.2251627445220947,0.2277439534664154,0.5417668819427490,0.0866540968418121,-0.1707777529954910,-0.0598246827721596,-0.4717158675193787,-1.2242834568023682,0.0454643070697784,-0.3503442704677582,0.0573085807263851,0.2530198395252228,-0.0207283068448305) * FEATURE2_texOff(vec2(-1,0));
res += mat4(0.0168380383402109,-0.2142438590526581,-0.0207892972975969,0.3628533780574799,0.2431225180625916,0.3098322153091431,0.4073205888271332,-0.2762102782726288,-0.0197229012846947,0.1305596232414246,-0.5697882771492004,-0.2976251542568207,-0.0551432967185974,0.2614036500453949,-0.1410341411828995,-0.2906406223773956) * FEATURE1_texOff(vec2(-1,1));
res += mat4(-0.0498303361237049,0.0224859956651926,0.1952174901962280,-0.0311204437166452,0.2501715123653412,-0.5893352627754211,-1.0793941020965576,0.0160885509103537,0.5081620812416077,0.0482814386487007,0.0546359121799469,-0.0501569248735905,0.1400523334741592,-0.0106841633096337,-0.0940591320395470,-0.1791856139898300) * FEATURE2_texOff(vec2(-1,1));
res += mat4(0.0393299944698811,0.2232691347599030,-0.1055066883563995,-0.1607919186353683,-0.1567825973033905,-0.0042221010662615,-0.0548228211700916,0.2352052628993988,0.1483389288187027,0.7503526806831360,0.0797731876373291,-0.0049001369625330,-0.0242983382195234,-0.0308702979236841,0.0828925222158432,0.0561857633292675) * FEATURE1_texOff(vec2(0,-1));
res += mat4(0.0926392748951912,-0.0418718457221985,-0.3060409128665924,-0.1883587390184402,0.0284292586147785,-0.3584854304790497,-0.7909982800483704,-0.0187337957322598,-0.2496993243694305,-0.7520986795425415,0.3771523833274841,-0.0259053874760866,0.0337998159229755,0.2209153026342392,0.0708771497011185,-0.2814430892467499) * FEATURE2_texOff(vec2(0,-1));
res += mat4(-0.5287809371948242,0.5777525901794434,0.0880500450730324,-0.8452472090721130,-0.3393408954143524,-0.2273543328046799,-0.1298527419567108,0.4990308582782745,1.2613251209259033,-0.7636719942092896,1.5694186687469482,-0.4087363779544830,0.0874531939625740,0.7067158818244934,-0.3419588804244995,-0.3265531957149506) * FEATURE1_texOff(vec2(0,0));
res += mat4(0.8229957222938538,-0.1236215904355049,-0.1859253048896790,1.6684840917587280,0.2000777721405029,-0.1239093989133835,1.5623438358306885,0.1779983490705490,0.1017884835600853,-0.3707404434680939,1.0626678466796875,-0.3124029338359833,0.0659058541059494,-0.3585464656352997,-0.1866402775049210,0.6733445525169373) * FEATURE2_texOff(vec2(0,0));
res += mat4(-0.5544115900993347,-0.1892931908369064,0.2460739761590958,-0.1056193932890892,-0.4318082630634308,0.1257930994033813,-0.2672747671604156,-0.1690235435962677,0.0018221997888759,-0.4397548139095306,-0.3007801771163940,0.1068472340703011,0.3506655991077423,0.1143834441900253,0.1363849341869354,-0.1417382210493088) * FEATURE1_texOff(vec2(0,1));
res += mat4(-0.0505668744444847,0.1831464916467667,0.3957343697547913,-0.2295413911342621,-0.3892803490161896,0.5436951518058777,0.1217770799994469,0.0223295800387859,-0.4462866187095642,-0.4055982232093811,-0.3771279454231262,0.0807068347930908,0.2116729617118835,0.0281026475131512,-0.0229265503585339,0.2868605256080627) * FEATURE2_texOff(vec2(0,1));
res += mat4(0.1962712109088898,-0.2373334914445877,-2.5208437442779541,-0.1988540291786194,0.2224564403295517,-0.1783192902803421,-0.3962321281433105,-0.1685980409383774,0.1910390257835388,0.2554391324520111,0.4586416482925415,0.2779130041599274,-0.2002453953027725,-0.0061091855168343,1.3808131217956543,0.0434907525777817) * FEATURE1_texOff(vec2(1,-1));
res += mat4(-0.0307611189782619,-0.0524470545351505,-0.5897512435913086,-0.0816674903035164,0.4052906930446625,0.2542210817337036,-1.9041002988815308,0.0835462361574173,-0.2484460622072220,-0.0184739269316196,0.4510098397731781,0.2587619423866272,0.1537084281444550,0.1503131389617920,-0.0742949545383453,0.0613216012716293) * FEATURE2_texOff(vec2(1,-1));
res += mat4(0.1772638261318207,0.0948876664042473,0.0083848545327783,-0.2919732332229614,0.2566950321197510,0.0288751143962145,-0.4624863862991333,-0.0608786940574646,0.3310996592044830,-0.0104284398257732,0.6334818005561829,-0.0027201652992517,-0.0342350602149963,0.1938806027173996,-0.2464301586151123,0.0125883584842086) * FEATURE1_texOff(vec2(1,0));
res += mat4(0.4839433431625366,-0.0502159744501114,-1.1114163398742676,-0.3965759575366974,0.2117286175489426,0.0414481423795223,-0.1332397013902664,-0.0549883767962456,-0.1275007277727127,0.7844302654266357,-0.0095163453370333,0.0961041301488876,-0.4759134948253632,-0.4284025132656097,-0.2072399407625198,-0.3953579664230347) * FEATURE2_texOff(vec2(1,0));
res += mat4(0.1605869531631470,-0.1715892106294632,0.0865620598196983,-0.0464400537312031,-0.2688548862934113,0.1722514480352402,0.0167612321674824,-0.0032994034700096,-0.3451044559478760,-0.2280300110578537,-0.0029796555172652,-0.1597652435302734,0.0500137843191624,0.1023071259260178,-0.0407028235495090,0.2228624969720840) * FEATURE1_texOff(vec2(1,1));
res += mat4(0.6999920010566711,0.0839441940188408,0.0815469548106194,-0.1509176045656204,-0.0690853074193001,-0.3200871348381042,0.0780162736773491,-0.1449639797210693,0.2868815064430237,0.3962450027465820,-0.3439113497734070,0.2657423913478851,0.0988137871026993,0.3471299111843109,-0.2186402678489685,-0.0648017078638077) * FEATURE2_texOff(vec2(1,1));
res = max(res, vec4(0.0)) + vec4(1.0311057567596436,0.1051208898425102,0.1158760935068130,0.0466635078191757) * min(res, vec4(0.0));
return res;
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC mapping 1_2
//!BIND FEATURE1
//!BIND FEATURE2
//!SAVE MODEL22
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(0.0713458731770515,-0.1403961777687073,-0.0019562745001167,0.0153338573873043);
res += mat4(-0.0950641855597496,-0.1496641039848328,-0.0653550028800964,0.0655386000871658,-0.0118882004171610,0.2012491524219513,-0.2844599783420563,-0.4794720113277435,0.1128025799989700,-0.0173030979931355,-0.0558849945664406,-0.2957552075386047,0.0128202112391591,0.0199047476053238,-0.0091027505695820,-0.0789640173316002) * FEATURE1_texOff(vec2(-1,-1));
res += mat4(0.1597457975149155,-0.0476507246494293,0.1466529071331024,0.0859163030982018,0.0797316282987595,-0.3380981683731079,0.2370245009660721,-0.1145931258797646,-0.0352988094091415,-0.0444888733327389,-0.2100716233253479,0.1305520236492157,-0.1359029710292816,0.1097442805767059,0.0449938289821148,-0.1155664771795273) * FEATURE2_texOff(vec2(-1,-1));
res += mat4(-0.0333916284143925,0.2415594160556793,0.0520512908697128,0.1228107511997223,-0.0491011217236519,0.4408806562423706,0.4631956815719604,0.2014560103416443,-0.3688595592975616,0.0367180295288563,0.2484581321477890,-0.1113442853093147,0.1283355057239532,0.0418004281818867,-0.0171243026852608,-0.1231943219900131) * FEATURE1_texOff(vec2(-1,0));
res += mat4(0.3493446409702301,0.4550022482872009,0.0368724688887596,0.0748724937438965,0.5001406073570251,0.0145555436611176,0.1236629858613014,0.3143120706081390,-0.1951988488435745,-0.0157914645969868,0.0937998965382576,-0.2233840376138687,0.5033411383628845,-0.3183194100856781,-0.2259195148944855,0.3639536798000336) * FEATURE2_texOff(vec2(-1,0));
res += mat4(-0.0742707476019859,-0.1287801116704941,-0.2533137500286102,0.0666435658931732,-0.0185621567070484,0.1427449285984039,-0.0724751204252243,-0.0781485065817833,-0.2270648330450058,-0.2314778864383698,0.3814929425716400,-0.1655400246381760,0.0408568829298019,-0.1139645278453827,0.1797397136688232,-0.0245632305741310) * FEATURE1_texOff(vec2(-1,1));
res += mat4(0.1184135973453522,0.0439366139471531,0.0225226897746325,-0.0038526873104274,0.1292685419321060,0.0629177838563919,0.3455114960670471,-0.1857204884290695,-0.4921502172946930,-0.1171003505587578,0.0188624169677496,-0.1101682260632515,0.0676844567060471,0.5154085755348206,-0.0898379907011986,0.3413280248641968) * FEATURE2_texOff(vec2(-1,1));
res += mat4(-0.2631838321685791,0.0215514600276947,0.3092688918113708,-0.0200904365628958,0.0678770467638969,0.1769931465387344,-0.3653681278228760,-0.3274513185024261,0.4608019888401031,-0.1544784456491470,0.1189439669251442,0.7015876173973083,0.2732816934585571,-0.0545057803392410,-0.3474545478820801,-0.0253226496279240) * FEATURE1_texOff(vec2(0,-1));
res += mat4(0.0994316861033440,0.0642566010355949,0.2031503319740295,0.2276959568262100,-0.1094077304005623,0.4463521838188171,0.0921792611479759,-0.3033096492290497,-0.0953373983502388,-0.1331395804882050,0.2615413069725037,-0.2874414622783661,-0.0389687754213810,0.0338272154331207,0.2804331183433533,-0.3443813025951385) * FEATURE2_texOff(vec2(0,-1));
res += mat4(-0.1806042939424515,-0.4840798676013947,0.4222546219825745,0.1238701492547989,0.0117481639608741,-0.5986865758895874,0.3057619929313660,0.1934896260499954,-0.7086342573165894,-0.8567376136779785,0.6944998502731323,-1.4599204063415527,0.0886754393577576,-0.4293498098850250,-0.1524195969104767,0.2418079674243927) * FEATURE1_texOff(vec2(0,0));
res += mat4(2.1706113815307617,0.3525652289390564,-0.7008359432220459,-0.4825965166091919,-0.3203429281711578,0.8500943183898926,-0.7993509769439697,0.4329842329025269,0.2106771767139435,1.1103280782699585,1.2092385292053223,1.4814503192901611,-0.4147390127182007,-0.7046836614608765,-0.1443170011043549,-0.6811133027076721) * FEATURE2_texOff(vec2(0,0));
res += mat4(-0.1489356607198715,0.1400019824504852,0.2425604313611984,-0.2098473459482193,-0.1580564379692078,0.1463224738836288,-0.2187854647636414,0.5174596905708313,-0.0143817225471139,-0.0362622961401939,-0.0068237944506109,0.4749472737312317,0.2914732992649078,-0.3306328952312469,-0.2444777786731720,-0.1171946674585342) * FEATURE1_texOff(vec2(0,1));
res += mat4(0.0455239675939083,0.3496046066284180,0.1297491937875748,-0.2541095912456512,0.3605501055717468,0.2339573651552200,-0.0188565086573362,-0.0526181310415268,0.1471424549818039,0.8212822079658508,0.0819099843502045,-0.0851665437221527,0.3739568293094635,0.1304695755243301,0.1481167376041412,-0.2134698331356049) * FEATURE2_texOff(vec2(0,1));
res += mat4(-0.2076720446348190,-0.0932599306106567,0.0648527294397354,-0.2374770641326904,-0.0927826911211014,0.1848200261592865,0.4131188094615936,0.3280069231987000,-0.2099185734987259,0.2130926996469498,-0.0362745784223080,0.0191331822425127,0.1590368449687958,0.0303016249090433,0.1207325309514999,0.2451425045728683) * FEATURE1_texOff(vec2(1,-1));
res += mat4(-0.0135009605437517,-0.0101303057745099,0.0752487555146217,0.0533373840153217,-0.0253537259995937,0.1318614929914474,-0.1263181120157242,0.0249524712562561,-0.1477261483669281,0.3236559033393860,0.0773291289806366,-0.1439673304557800,-0.2005890905857086,0.0892757251858711,0.0398719944059849,0.3675192892551422) * FEATURE2_texOff(vec2(1,-1));
res += mat4(-0.0193535499274731,-0.2256918102502823,0.0341436080634594,0.0795947611331940,0.1496857404708862,-0.2784725725650787,-0.0582313314080238,-0.2786065340042114,-0.1666128039360046,-0.6534121036529541,0.2695854306221008,-0.0179719906300306,0.0015976354479790,0.0139929885044694,-0.1706486046314240,-0.3274765610694885) * FEATURE1_texOff(vec2(1,0));
res += mat4(-0.7170836329460144,0.0868831276893616,0.1829078495502472,-0.0076045366004109,0.1525912433862686,-0.2558896839618683,0.0893209800124168,-0.3426039516925812,-0.2871107757091522,-0.2445062994956970,0.1676304638385773,0.2116415053606033,0.0883995518088341,-0.3880331516265869,0.2636835277080536,-0.2514505982398987) * FEATURE2_texOff(vec2(1,0));
res += mat4(-0.1861270815134048,0.2000686377286911,-0.1501186788082123,0.1525203883647919,0.1969228833913803,0.1174068301916122,-0.1281060427427292,-0.0854888409376144,0.0290613435208797,-0.0538076497614384,-0.0251582786440849,0.0692845508456230,0.0384319014847279,0.2888138592243195,0.1151804402470589,0.0990421250462532) * FEATURE1_texOff(vec2(1,1));
res += mat4(-0.0344385802745819,0.1270371377468109,0.0922426953911781,-0.0426749102771282,-0.1656492203474045,-0.3273328542709351,-0.0282224025577307,0.1099396124482155,-0.1113230437040329,0.2943290174007416,-0.2181112915277481,-0.3177657723426819,-0.1096536740660667,-0.0508293099701405,-0.0256164856255054,-0.0388228967785835) * FEATURE2_texOff(vec2(1,1));
res = max(res, vec4(0.0)) + vec4(0.7142407894134521,0.0686190053820610,0.3999933302402496,-1.0247212648391724) * min(res, vec4(0.0));
return res;
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC mapping 2_1
//!BIND MODEL21
//!BIND MODEL22
//!SAVE MODEL1
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(0.0203563515096903,0.1902436912059784,-0.0757935121655464,0.0393617525696754);
res += mat4(-0.1080558672547340,-0.0400269515812397,0.1042881682515144,-0.1994346678256989,0.0172465778887272,-0.0829331055283546,-0.1278677284717560,-0.0762506872415543,-0.0593080408871174,-0.0305212251842022,0.1326192617416382,-0.3380933105945587,-0.0722763314843178,-0.1975518912076950,-0.0223602931946516,0.2251029163599014) * MODEL21_texOff(vec2(-1,-1));
res += mat4(0.1747678220272064,0.0297168865799904,0.1054855734109879,0.0803295820951462,-0.0338115766644478,-0.3885377943515778,-0.3540246784687042,-0.0719623491168022,-0.0656022280454636,-0.0469004511833191,0.1379419565200806,0.0319863893091679,0.0799935683608055,-0.0099127553403378,0.1698455959558487,-0.0108015276491642) * MODEL22_texOff(vec2(-1,-1));
res += mat4(0.1587898135185242,0.3995443880558014,-0.0333226583898067,0.2373267263174057,-0.1616930961608887,0.0659186244010925,0.0141129801049829,-0.0541022196412086,-0.5743742585182190,0.1121487766504288,0.4259817600250244,0.0280795227736235,-0.3721714317798615,-0.3496374189853668,0.0997273251414299,-0.0079920450225472) * MODEL21_texOff(vec2(-1,0));
res += mat4(0.0928084030747414,0.3107658624649048,0.1375299990177155,0.1550617516040802,-0.0780353918671608,-0.0102957757189870,-0.2056752145290375,-0.3927979469299316,-1.2112152576446533,0.0213295854628086,0.1396545022726059,0.0492016039788723,-0.0569122135639191,-0.1691886335611343,-0.1535325646400452,0.2800904810428619) * MODEL22_texOff(vec2(-1,0));
res += mat4(0.2494744062423706,-0.0363066755235195,0.0959179550409317,-0.0048101749271154,-0.0195793900638819,0.0451166369020939,0.1470773071050644,-0.0050059854984283,0.2886958122253418,-0.3221147954463959,-0.7062104344367981,0.1646659970283508,-0.0092520527541637,-0.1254461258649826,0.0217506736516953,-0.0678806379437447) * MODEL21_texOff(vec2(-1,1));
res += mat4(-0.0686557441949844,-0.0414490625262260,-0.1855954080820084,0.0264346338808537,-0.0296857114881277,-0.0431593284010887,0.0669397041201591,-0.0946076661348343,-0.2036914378404617,-0.1336101740598679,-0.2099903970956802,-0.1327936947345734,-0.1002155169844627,-0.0368575826287270,-0.1660962998867035,0.0728288888931274) * MODEL22_texOff(vec2(-1,1));
res += mat4(0.5504320859909058,0.2939232587814331,0.4704743027687073,0.2129514217376709,0.0843106731772423,-0.1978624463081360,-0.3298224806785583,0.1919094175100327,0.1980742365121841,-0.0644423812627792,0.0091170109808445,-0.2124856859445572,0.0804558470845222,-0.1130188927054405,-0.6276652812957764,0.1861163526773453) * MODEL21_texOff(vec2(0,-1));
res += mat4(-0.3357668519020081,0.2093413323163986,0.4355416595935822,0.1550502777099609,-0.6510964035987854,-0.1751857399940491,-0.2060168534517288,-0.1710205078125000,-0.1202360317111015,-0.2500316798686981,0.1074745431542397,-0.2418434321880341,0.0133954072371125,-0.0555886104702950,0.1514673978090286,0.2739115655422211) * MODEL22_texOff(vec2(0,-1));
res += mat4(-0.3006273508071899,-0.2699472010135651,-0.1982013583183289,-0.0032952548936009,0.0307833012193441,0.3671586215496063,-0.0966020002961159,-0.2836556434631348,0.4297264218330383,0.6171903610229492,0.6723483800888062,0.2705117464065552,-0.1438141316175461,-0.0873940736055374,-0.7001031041145325,-0.2052250355482101) * MODEL21_texOff(vec2(0,0));
res += mat4(-0.2875024676322937,-1.6230558156967163,-0.6733398437500000,-0.9642448425292969,-0.1964960694313049,0.2485812455415726,0.1236900389194489,-1.1423941850662231,-0.0412602946162224,0.3412002623081207,0.3962794244289398,-0.2490761876106262,-0.0058065578341484,-0.4578708708286285,-0.2418260127305984,0.5357795953750610) * MODEL22_texOff(vec2(0,0));
res += mat4(0.0062361713498831,0.1925230026245117,0.0824977159500122,0.0561275146901608,0.0929671525955200,0.0698546022176743,0.3816939592361450,0.0395248420536518,-0.0719512030482292,0.0564917400479317,-0.1297784000635147,0.1245511695742607,0.0012355837970972,-0.0990515723824501,0.4213519692420959,-0.1645816713571548) * MODEL21_texOff(vec2(0,1));
res += mat4(-0.0611936338245869,-0.0220258161425591,-0.0040935277938843,-0.1060328409075737,-0.0583154149353504,-0.0171997752040625,0.1058546081185341,0.2793170809745789,-0.2339317053556442,-0.1972009539604187,-0.0600687190890312,-0.0684379041194916,0.0243016034364700,-0.2111079394817352,-0.2042971849441528,0.0724857896566391) * MODEL22_texOff(vec2(0,1));
res += mat4(-0.0833447948098183,-0.0533220991492271,0.0767802372574806,0.1182348504662514,-0.0223299078643322,-0.0479344800114632,-0.0119727496057749,0.0524821877479553,-0.0334780365228653,0.0719002187252045,0.0439689308404922,0.0475181229412556,0.0764308497309685,0.0086713796481490,-0.1700707823038101,0.0657354295253754) * MODEL21_texOff(vec2(1,-1));
res += mat4(0.1391696482896805,0.0739523395895958,0.0565792545676231,-0.0430364646017551,0.0943084582686424,0.0102064209058881,0.0120795257389545,-0.0841303989291191,0.1573246121406555,0.0164279472082853,0.0988841354846954,-0.1430613398551941,-0.0572808869183064,-0.0844292491674423,0.0621565617620945,0.0923799052834511) * MODEL22_texOff(vec2(1,-1));
res += mat4(-0.1223107874393463,-0.2441930323839188,-0.2410650849342346,-0.0162935722619295,0.0695567727088928,-0.0028583710081875,-0.0059417244046926,0.0715164169669151,-0.0668491795659065,-0.1499572396278381,0.0869924053549767,0.0553652904927731,0.2729566097259521,0.1370039582252502,-0.1282183527946472,-0.1451860070228577) * MODEL21_texOff(vec2(1,0));
res += mat4(0.1331952214241028,0.0021079662255943,-0.1116734445095062,-0.4168601930141449,0.0534659475088120,0.0037860786542296,-0.0366065911948681,0.1047701835632324,0.1491260826587677,0.0782341659069061,0.0949895009398460,-0.1160908639431000,-0.1057133302092552,-0.2699718773365021,-0.1193305626511574,0.2142304331064224) * MODEL22_texOff(vec2(1,0));
res += mat4(0.0041565205901861,-0.1065499857068062,-0.0629659667611122,-0.1144768893718719,0.0318886637687683,-0.0562519319355488,0.0043422472663224,0.0226082988083363,-0.1456198990345001,-0.2398656159639359,-0.2625046670436859,-0.0710547044873238,0.0067904205061495,0.0018544088816270,0.1019348874688148,-0.0186133962124586) * MODEL21_texOff(vec2(1,1));
res += mat4(0.0732532218098640,0.1516859829425812,0.0580205544829369,0.1968977004289627,-0.0066619524732232,-0.1597842127084732,-0.0990600511431694,-0.1059188917279243,0.0718481168150902,-0.2222738713026047,-0.1675696671009064,-0.1500017195940018,-0.0568779110908508,-0.0582777932286263,-0.0844587534666061,-0.0263266414403915) * MODEL22_texOff(vec2(1,1));
res = max(res, vec4(0.0)) + vec4(-0.2459529191255569,0.7563464641571045,-0.0705636814236641,-0.0094820559024811) * min(res, vec4(0.0));
return res;
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC mapping 2_2
//!BIND MODEL21
//!BIND MODEL22
//!SAVE MODEL2
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(-0.0448397286236286,-0.1649267971515656,-0.1192543581128120,-0.0061073559336364);
res += mat4(0.0724840760231018,-0.0480341166257858,-0.1082391515374184,-0.1447021961212158,0.0723197236657143,0.0481830574572086,0.0009448126656935,0.0353565886616707,-0.0653375908732414,0.0029647622723132,-0.0016588598955423,-0.2075651884078979,0.0403469167649746,0.3929971158504486,0.0342363268136978,0.1427230089902878) * MODEL21_texOff(vec2(-1,-1));
res += mat4(-0.0743464827537537,0.1844420731067657,0.0256296340376139,-0.2808582782745361,0.0351609662175179,0.3277008235454559,-0.0205841138958931,-0.5355809330940247,0.0681906566023827,0.2058052271604538,-0.0479847639799118,-0.3735262751579285,-0.0261550359427929,-0.1148884072899818,-0.2329017966985703,0.0728458985686302) * MODEL22_texOff(vec2(-1,-1));
res += mat4(-0.1236097738146782,0.1251334398984909,-0.1339431256055832,0.0198749266564846,-0.1325920224189758,-2.2431972026824951,-0.0680834427475929,-0.5671764612197876,-0.3431925177574158,-0.0983135104179382,-0.2207138091325760,-0.2374879121780396,0.0127309206873178,1.3076044321060181,0.0848151743412018,-0.1928595900535583) * MODEL21_texOff(vec2(-1,0));
res += mat4(-0.0471093133091927,-0.1513628512620926,-0.0134263765066862,-0.1519252359867096,-0.5260242223739624,0.2291621714830399,0.4088975787162781,-0.4315340518951416,0.0933236032724380,-1.0386694669723511,0.0015958193689585,-0.2737887501716614,-0.0246253963559866,-0.2722961604595184,-0.1770633459091187,-0.2291279733181000) * MODEL22_texOff(vec2(-1,0));
res += mat4(-0.0017552347853780,0.1903935521841049,-0.0740704238414764,-0.0917679518461227,0.0323882810771465,-0.3029108047485352,0.0532565414905548,-0.0651542618870735,0.4868686199188232,0.8539272546768188,0.4151960313320160,0.2619662582874298,-0.0413270294666290,0.1404227763414383,0.1027320474386215,0.3274228572845459) * MODEL21_texOff(vec2(-1,1));
res += mat4(0.1828346252441406,0.0274682324379683,-0.1169882863759995,0.0327291004359722,0.1786244213581085,-0.6569546461105347,-0.0609031207859516,-0.1676601022481918,-0.1481092721223831,0.2889067530632019,0.1246089115738869,0.2203597426414490,-0.0366856977343559,0.1539470851421356,0.0069492300972342,-0.1544002443552017) * MODEL22_texOff(vec2(-1,1));
res += mat4(0.2073992937803268,-0.0717074573040009,-0.0196173377335072,-0.0956910699605942,0.0728898122906685,0.0484567955136299,0.3063069283962250,-0.3200540542602539,0.0291527546942234,-0.0265460256487131,0.1168476045131683,-0.2479970753192902,0.1224220171570778,0.0745823010802269,0.1868897676467896,-0.1958049237728119) * MODEL21_texOff(vec2(0,-1));
res += mat4(0.0019954447634518,-0.0225235987454653,0.0812198966741562,0.0295672398060560,-0.2016931176185608,-0.2239151000976562,-0.2481262385845184,-0.2381946444511414,-0.0520484372973442,-0.1200495883822441,0.2121954560279846,-0.1573531329631805,-0.0198472067713737,0.1001087054610252,-0.1084884032607079,-0.3126969039440155) * MODEL22_texOff(vec2(0,-1));
res += mat4(0.3838330209255219,0.1678779572248459,0.6496244072914124,0.3783606290817261,-0.2198582738637924,-0.2351343184709549,-0.2852248847484589,0.6310021877288818,0.8083020448684692,0.0039323624223471,-0.0901831910014153,0.0797894075512886,-0.2271467447280884,0.7082978487014771,0.1513756662607193,0.2188975960016251) * MODEL21_texOff(vec2(0,0));
res += mat4(-0.2871031761169434,0.2316448241472244,0.4947948157787323,0.3308620452880859,-0.0623455122113228,-0.1314185708761215,-0.2664661705493927,0.8725078701972961,0.4541083276271820,0.1433589160442352,-1.1269453763961792,0.6427971124649048,-0.1016561388969421,0.3418317139148712,-0.0991155728697777,-1.0508837699890137) * MODEL22_texOff(vec2(0,0));
res += mat4(-0.2179604172706604,0.1258949041366577,-0.1155700981616974,-0.0536149404942989,-0.0140614463016391,-0.0091438721865416,-0.0501774959266186,-0.3570724725723267,-0.5832386016845703,0.2004123181104660,0.2986239194869995,-0.8139168024063110,0.0142666567116976,0.0681498944759369,0.1293468028306961,-0.1001938357949257) * MODEL21_texOff(vec2(0,1));
res += mat4(0.1952836811542511,-0.3092494010925293,0.3063779771327972,0.1934849917888641,0.0746696740388870,-0.3533902466297150,-0.1269576102495193,-0.2237875163555145,0.2470717132091522,-0.2640363574028015,-0.2862776815891266,0.1740108281373978,-0.0963631942868233,0.2631850540637970,0.0400718413293362,-0.3590607047080994) * MODEL22_texOff(vec2(0,1));
res += mat4(-0.5299927592277527,0.0979989692568779,0.1666737496852875,-0.1547524333000183,-0.0043443185277283,0.1540203243494034,0.0594348423182964,-0.0167275425046682,-0.1043610796332359,0.0504250898957253,0.0456700921058655,0.2525034546852112,0.2241353541612625,-0.1678503304719925,0.1532667279243469,0.2901742458343506) * MODEL21_texOff(vec2(1,-1));
res += mat4(0.0998796448111534,0.0385462641716003,-0.0762400180101395,-0.1255892217159271,0.0281430184841156,-0.0304958485066891,-0.1440480053424835,-0.1001605167984962,-0.2257689833641052,0.2056092917919159,0.0248535349965096,-0.1383949518203735,-0.0951708629727364,0.0997417271137238,0.0275330394506454,-0.5728432536125183) * MODEL22_texOff(vec2(1,-1));
res += mat4(0.4256163835525513,0.1745115518569946,-0.2409395426511765,0.3139856457710266,-0.0036795330233872,0.1819283962249756,-0.0864531323313713,0.0102691333740950,-0.3397279977798462,0.1107075437903404,-0.0035228815395385,-0.2207705229520798,-0.1779139339923859,-0.2106117755174637,0.0352664291858673,0.3615589439868927) * MODEL21_texOff(vec2(1,0));
res += mat4(-0.0345224253833294,-0.0669926702976227,0.0907212942838669,-0.3758732676506042,-0.0452554710209370,-0.1134464666247368,-0.0358871109783649,-0.1858227252960205,-0.0233245138078928,-0.0495684742927551,0.1976234614849091,-0.1165761798620224,-0.0340447537600994,0.1095624342560768,0.0110175255686045,-0.8269239664077759) * MODEL22_texOff(vec2(1,0));
res += mat4(-0.1379280686378479,0.1004267781972885,0.0723998174071312,-0.1510958224534988,0.0610648579895496,0.0451720170676708,-0.0231927260756493,-0.0251553766429424,0.2306085377931595,0.1033207178115845,-0.1316205114126205,0.1130664870142937,-0.0458516106009483,-0.1152514070272446,-0.0088650323450565,-0.0214479379355907) * MODEL21_texOff(vec2(1,1));
res += mat4(-0.0545783303678036,-0.0620098188519478,0.0347074456512928,0.1096799224615097,0.0036664425861090,-0.0413107499480247,0.1443250179290771,-0.1161036714911461,-0.0061624986119568,-0.0252977479249239,0.3230019211769104,-0.2536626160144806,-0.0565439648926258,0.0827583819627762,-0.0071726376190782,-0.1983329951763153) * MODEL22_texOff(vec2(1,1));
res = max(res, vec4(0.0)) + vec4(-0.6312188506126404,-0.1215368881821632,0.2487443536520004,0.4051703512668610) * min(res, vec4(0.0));
return res;
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC mapping 3_1
//!BIND MODEL1
//!BIND MODEL2
//!SAVE MODEL21
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(-0.0410279631614685,-0.1111723631620407,-0.0406232848763466,-0.0939496159553528);
res += mat4(0.1221675798296928,0.0083215842023492,-0.0162804014980793,0.0316714197397232,-0.2205813378095627,0.1500435769557953,0.2109555304050446,0.2741867899894714,0.0956874340772629,-0.0896854698657990,-0.1657065600156784,-0.1349759399890900,0.0601499564945698,-0.1523845940828323,-0.1828087568283081,-0.2727653682231903) * MODEL1_texOff(vec2(-1,-1));
res += mat4(-0.0918163508176804,0.1564485579729080,0.1133174449205399,0.2215953171253204,-0.0623677000403404,-0.0497728772461414,-0.0372809022665024,-0.0258478187024593,-0.1364922970533371,0.1053884625434875,0.3292874991893768,0.2693256139755249,-0.0347631797194481,-0.1470523178577423,0.0096792401745915,-0.0542853325605392) * MODEL2_texOff(vec2(-1,-1));
res += mat4(0.1331177949905396,-0.0964357852935791,-0.0706946700811386,0.1593225002288818,-0.4815943241119385,0.1224092170596123,-0.0870430991053581,0.0005010276800022,-0.0242684502154589,-0.2256436049938202,0.1367238312959671,0.0474774017930031,0.6886650323867798,-0.0065326127223670,0.1841574758291245,-0.1354993879795074) * MODEL1_texOff(vec2(-1,0));
res += mat4(-0.1049591675400734,0.0515934228897095,0.1128631457686424,0.1688040047883987,-0.0084041170775890,-0.0006375144002959,-0.0598374009132385,0.1424416452646255,-0.0048398924991488,0.1832167655229568,0.0231959503144026,0.0816788375377655,-0.1321710795164108,0.0397678017616272,-0.0058345394209027,0.5784573554992676) * MODEL2_texOff(vec2(-1,0));
res += mat4(0.1438693851232529,-0.0694608166813850,-0.0428275354206562,0.1599996536970139,-0.1651254445314407,0.1388883888721466,-0.0895452573895454,0.2569831907749176,0.3150432109832764,-0.0910519883036613,0.0367441214621067,0.1903669685125351,0.2805841267108917,-0.0444608181715012,0.0059385276399553,-0.2585869431495667) * MODEL1_texOff(vec2(-1,1));
res += mat4(-0.1217494234442711,0.0191769022494555,-0.0065453462302685,0.1391217857599258,0.0998920649290085,-0.0162798929959536,0.0502282194793224,0.0370145924389362,0.0290782172232866,-0.0099554909393191,0.0142515478655696,0.1248661577701569,-0.0076912571676075,0.0251651499420404,0.2190572917461395,0.0020069130696356) * MODEL2_texOff(vec2(-1,1));
res += mat4(0.2666685581207275,-0.1625511497259140,-0.3938800692558289,-0.0253848694264889,0.0987015441060066,0.2033616453409195,0.3128099143505096,0.4608893990516663,0.0620003379881382,-0.1389972567558289,-0.3095863461494446,-0.4023511111736298,-0.1105777546763420,0.1115406602621078,0.3639950752258301,0.0645622834563255) * MODEL1_texOff(vec2(0,-1));
res += mat4(-0.2135885655879974,-0.1035343706607819,0.1795026361942291,0.1828210204839706,0.0780984908342361,0.0656728670001030,0.0033678691834211,0.1361345648765564,0.1712654232978821,-0.0172833092510700,-0.0502183400094509,0.2910411655902863,0.0691247656941414,0.1935720741748810,0.0652214139699936,0.1608240753412247) * MODEL2_texOff(vec2(0,-1));
res += mat4(0.8243460655212402,-0.0979344248771667,-0.0366373993456364,0.1692261099815369,0.5517869591712952,0.3282494544982910,-0.7905511856079102,-0.4462923705577850,-0.0803156569600105,0.1172509342432022,0.1864327639341354,0.1471016854047775,0.1296005547046661,-0.1004103720188141,0.3174172043800354,-0.1181766316294670) * MODEL1_texOff(vec2(0,0));
res += mat4(0.0259374529123306,-0.0934808850288391,0.3008874654769897,0.3957927823066711,-0.4048821926116943,0.1461934000253677,-0.1819096356630325,-0.1908810287714005,0.3193186521530151,-0.7438099980354309,0.1919509470462799,-0.2065188735723495,0.1752236187458038,-0.6840037107467651,0.1588519066572189,-0.3956064879894257) * MODEL2_texOff(vec2(0,0));
res += mat4(0.1574442386627197,-0.0114925103262067,-0.1208277940750122,0.2058266401290894,0.2879209220409393,-0.0419875606894493,-0.1902059614658356,-0.2723863720893860,-0.1086223348975182,-0.0870924964547157,0.8605937957763672,0.2656622231006622,-0.1653763055801392,0.0816384851932526,-0.0137870563194156,0.1433854848146439) * MODEL1_texOff(vec2(0,1));
res += mat4(-0.1565909236669540,-0.0307490080595016,-0.1055604666471481,0.2573592662811279,-0.1186821162700653,0.1141471788287163,-0.0272745657712221,-0.1049114838242531,0.2445316016674042,-0.0027864547446370,-0.1759569346904755,-0.1556979566812515,0.0550616309046745,0.1704383641481400,0.0853662937879562,0.3280856907367706) * MODEL2_texOff(vec2(0,1));
res += mat4(0.1460669338703156,0.4202052652835846,-0.3638312816619873,-0.0958623066544533,-0.0492525361478329,-0.3664234280586243,0.0794373303651810,0.0399017669260502,0.0629198029637337,0.1662959158420563,-0.1001493930816650,-0.0587460733950138,-0.0396478697657585,0.0017320754704997,0.0314909480512142,-0.0202700830996037) * MODEL1_texOff(vec2(1,-1));
res += mat4(-0.0964399129152298,0.0380319654941559,0.0396055467426777,0.0265473183244467,-0.0161637403070927,-0.1872924566268921,0.1670000404119492,0.0029466480482370,-0.1093841269612312,-0.3629201948642731,-0.0562992505729198,0.1792684197425842,-0.0203859098255634,0.0983991250395775,0.0058611719869077,0.1627455651760101) * MODEL2_texOff(vec2(1,-1));
res += mat4(-0.1117974221706390,0.7562329173088074,-0.2046248912811279,0.1677842289209366,-0.2063486129045486,-0.6023545265197754,-0.5739209651947021,0.5110496878623962,-0.0715268924832344,-0.1373793482780457,0.1251420378684998,-0.0477442294359207,0.4961377978324890,0.2688887119293213,0.3146316707134247,-0.5197153687477112) * MODEL1_texOff(vec2(1,0));
res += mat4(-0.1314805448055267,0.0746279135346413,0.3457699418067932,0.2564856410026550,0.0839370116591454,-0.6136511564254761,-0.4646295011043549,0.0612256154417992,-0.1910563558340073,-0.0935136750340462,-0.2426030039787292,0.2102959007024765,0.1575350016355515,0.6145061254501343,0.3368154168128967,-0.0974092856049538) * MODEL2_texOff(vec2(1,0));
res += mat4(0.0565315335988998,0.2393359094858170,-0.0932938233017921,0.1555283814668655,0.0123879108577967,-0.1247719228267670,-0.0564610138535500,-0.1125799044966698,-0.0104600470513105,0.0482629500329494,0.2316472232341766,0.1083717569708824,-0.0525921434164047,0.0643989592790604,-0.0525734610855579,-0.0503251366317272) * MODEL1_texOff(vec2(1,1));
res += mat4(-0.1835366338491440,0.0978360474109650,-0.1111819595098495,0.2109299153089523,0.0509372949600220,-0.1992686837911606,0.0677929744124413,-0.0870024710893631,-0.0412262082099915,-0.0697719156742096,-0.0967373847961426,0.0137308547273278,0.0195730421692133,0.0410240143537521,0.1157210171222687,0.2283479571342468) * MODEL2_texOff(vec2(1,1));
res = max(res, vec4(0.0)) + vec4(0.1991519331932068,-0.1275756657123566,-0.0622864030301571,0.1586369574069977) * min(res, vec4(0.0));
return res;
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC mapping 3_2
//!BIND MODEL1
//!BIND MODEL2
//!SAVE MODEL22
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(-0.0089084329083562,-0.0336172059178352,0.0177190825343132,0.0529975406825542);
res += mat4(-0.0275970958173275,0.0141968233510852,0.1181544512510300,-0.0572245270013809,0.1161347925662994,-0.1156444773077965,-0.2549640238285065,0.0882879272103310,-0.0715355500578880,0.0151285668835044,0.1079384386539459,0.0650847703218460,-0.1597152203321457,0.0669793561100960,0.2084401696920395,-0.0951152443885803) * MODEL1_texOff(vec2(-1,-1));
res += mat4(0.0404323227703571,-0.0206144321709871,-0.1080420613288879,-0.2038477361202240,0.0248847268521786,-0.0064681121148169,0.0389525443315506,0.0011026862775907,0.0885242074728012,0.0295896343886852,-0.3323790132999420,0.1935138553380966,-0.0466548874974251,0.1023886054754257,0.1257870644330978,-0.1541756242513657) * MODEL2_texOff(vec2(-1,-1));
res += mat4(-0.0076520540751517,0.0361139886081219,0.1749804913997650,-0.2051989138126373,0.0022692133206874,-0.0282937753945589,-0.2039019316434860,-0.2343468815088272,-0.0357327871024609,-0.0570764988660812,0.2925858795642853,-0.1988349705934525,-0.0584560707211494,-0.0341510921716690,0.1300961822271347,0.5184492468833923) * MODEL1_texOff(vec2(-1,0));
res += mat4(0.0884973928332329,0.0333527140319347,0.0180535931140184,-0.2655122876167297,0.0433661043643951,0.0104369185864925,0.0010909073753282,-0.0705273598432541,-0.0602585524320602,0.2420269846916199,-0.4731841087341309,-0.8040290474891663,0.3066828548908234,-0.2466925680637360,0.0938910692930222,-0.2002603262662888) * MODEL2_texOff(vec2(-1,0));
res += mat4(0.0549152903258801,0.0291299298405647,0.0946277007460594,-0.0581608228385448,0.0669180899858475,-0.0635575056076050,-0.2427970170974731,-0.2677550315856934,0.2226776182651520,0.1301570236682892,-0.1519709974527359,0.0671724304556847,-0.0526433289051056,0.1898351758718491,0.2383745312690735,0.2191711813211441) * MODEL1_texOff(vec2(-1,1));
res += mat4(-0.0234222635626793,0.0238620284944773,0.0427630320191383,-0.1080563366413116,0.0332126952707767,-0.0039051575586200,0.0293126031756401,0.0161924213171005,0.0453971028327942,0.0131999952718616,-0.0689036697149277,0.2349009960889816,0.1013344153761864,0.2706570029258728,0.1191426888108253,-0.2830821871757507) * MODEL2_texOff(vec2(-1,1));
res += mat4(0.0181465242058039,-0.0571886636316776,0.4875229001045227,-0.4244020283222198,0.4331104159355164,0.1066712513566017,-0.5277034044265747,0.1110567077994347,-0.1179447323083878,-0.0273578558117151,0.1798476576805115,-0.2829602360725403,0.1012385115027428,-0.2528488039970398,0.1697608679533005,0.1121710017323494) * MODEL1_texOff(vec2(0,-1));
res += mat4(-0.1404130905866623,-0.0984055623412132,-0.0279541295021772,-0.1321212500333786,-0.0841855704784393,0.1336171030998230,-0.1458790600299835,-0.0044095455668867,0.2203754037618637,0.1455714553594589,-0.2362042963504791,-0.0329121425747871,-0.1683547794818878,0.0289597529917955,0.3424547612667084,0.0143845872953534) * MODEL2_texOff(vec2(0,-1));
res += mat4(0.0287246014922857,0.1948280781507492,0.5998955368995667,0.1192114129662514,-0.6269109249114990,0.8724324703216553,-0.6399638652801514,-0.4201497733592987,-0.3355066180229187,-0.1566904038190842,-0.4396412074565887,0.1525828838348389,0.5573399066925049,0.2324324846267700,0.2762884795665741,0.0406046211719513) * MODEL1_texOff(vec2(0,0));
res += mat4(0.3890096545219421,-0.0574061162769794,-0.1468243300914764,-0.5953360199928284,-0.1363215148448944,-0.2224670499563217,-0.2237723320722580,0.2738097012042999,-0.4868114292621613,-0.5029351711273193,-0.3570256233215332,-0.1776263266801834,-0.0176672954112291,-0.4318660795688629,1.0395888090133667,0.1728395074605942) * MODEL2_texOff(vec2(0,0));
res += mat4(0.1337304115295410,-0.0809440389275551,0.1600498855113983,-0.1108811497688293,-0.2376178801059723,-0.1532768607139587,-0.0447455830872059,0.2515332102775574,0.4848278462886810,-0.0915748402476311,-0.0336527302861214,-0.2141884714365005,0.2125129699707031,0.3237875998020172,0.0022272330243140,-0.0167857185006142) * MODEL1_texOff(vec2(0,1));
res += mat4(0.0457934997975826,0.0510537698864937,-0.0519523508846760,-0.4506326615810394,-0.1029204949736595,0.0116113182157278,-0.1750748157501221,-0.0048758201301098,0.1506977379322052,0.0633068457245827,-0.1628549993038177,-0.0144928665831685,0.1408756822347641,0.2896180152893066,0.0803691521286964,-0.4930096566677094) * MODEL2_texOff(vec2(0,1));
res += mat4(-0.0484248884022236,0.1371297985315323,-0.1235475391149521,-0.2618594765663147,-0.0280395895242691,0.0248795989900827,0.1204105168581009,0.3246576189994812,0.0426272377371788,-0.0520061068236828,0.0575957447290421,-0.2613646090030670,0.1165295541286469,-0.0390013493597507,-0.0470846109092236,-0.0014663023175672) * MODEL1_texOff(vec2(1,-1));
res += mat4(-0.1066762879490852,-0.0869804695248604,-0.0099332248792052,-0.1355892717838287,-0.0760413780808449,0.1377770304679871,-0.0263407956808805,0.0880135521292686,0.1496269851922989,-0.0487459264695644,0.1286851912736893,0.2218491584062576,0.1723349541425705,-0.0165541302412748,-0.0690477639436722,-0.2388458102941513) * MODEL2_texOff(vec2(1,-1));
res += mat4(-0.4236431121826172,0.0465179122984409,-0.1526456624269485,0.1426440477371216,0.5913932919502258,-0.1082349196076393,0.2731275856494904,-0.2687640488147736,-0.4628683030605316,-0.0537119321525097,-0.1597615629434586,0.0528527684509754,-0.3485085070133209,0.1395110934972763,0.0642972290515900,0.0323829315602779) * MODEL1_texOff(vec2(1,0));
res += mat4(0.0066713397391140,-0.0482029877603054,-0.1707276403903961,-0.1001396998763084,0.0539822019636631,-0.1624453216791153,0.4913550019264221,0.3687861263751984,0.0491421781480312,0.1311376541852951,0.0992425829172134,-0.4636098444461823,-0.3415873646736145,-0.0153833786025643,-0.0270162131637335,-0.0935514941811562) * MODEL2_texOff(vec2(1,0));
res += mat4(-0.1738258153200150,0.0458541549742222,-0.0653749182820320,-0.0156540926545858,-0.0357586294412613,-0.1486178338527679,0.1798035055398941,-0.1310307979583740,0.0783249065279961,-0.0261360015720129,-0.1047066971659660,0.3385537564754486,-0.0339452810585499,0.2299628853797913,-0.1408322304487228,-0.0352708548307419) * MODEL1_texOff(vec2(1,1));
res += mat4(0.0463018082082272,0.0565674640238285,-0.0538956597447395,-0.2354862987995148,0.0297824125736952,0.0307939313352108,0.1271791011095047,-0.1025698855519295,0.1060482114553452,-0.0703211054205894,-0.0083062350749969,0.0474255047738552,0.0442508421838284,0.1569559425115585,-0.0442709513008595,-0.1188704669475555) * MODEL2_texOff(vec2(1,1));
res = max(res, vec4(0.0)) + vec4(0.7366524934768677,1.0013850927352905,-0.0276311747729778,0.0734841898083687) * min(res, vec4(0.0));
return res;
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC mapping 4_1
//!BIND MODEL21
//!BIND MODEL22
//!SAVE MODEL1
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(-0.1306160986423492,-0.0808217376470566,-0.2880123555660248,0.0099629526957870);
res += mat4(-0.1033539846539497,0.0541300140321255,-0.0804840475320816,-0.0334571413695812,-0.0264753755182028,0.1118840202689171,0.1186013221740723,-0.0127575425431132,0.2236593365669250,0.0025286162272096,0.0985530614852905,0.0685181617736816,-0.1884875595569611,0.0530862808227539,-0.0482063069939613,0.0375233069062233) * MODEL21_texOff(vec2(-1,-1));
res += mat4(0.1837068796157837,-0.0632847175002098,0.0016613919287920,0.0392861217260361,0.2923883199691772,-0.1713902205228806,0.1907587945461273,0.0550456829369068,0.0644215345382690,-0.1046456992626190,0.0187383033335209,0.0770180150866508,0.1933846622705460,-0.0455715768039227,0.0375007353723049,-0.1053109914064407) * MODEL22_texOff(vec2(-1,-1));
res += mat4(-0.0972480997443199,0.2820451855659485,0.0114549007266760,-0.0954328626394272,0.0706252008676529,0.4829064607620239,-0.6371517181396484,0.0005180989392102,0.3280143439769745,0.0665246024727821,-0.0503116399049759,-0.1261110603809357,0.1114177703857422,-0.2053108513355255,0.1428771317005157,0.3926100134849548) * MODEL21_texOff(vec2(-1,0));
res += mat4(-0.2571723163127899,0.1627264618873596,-0.4940335154533386,-0.1361546218395233,0.0804422944784164,-0.4231885373592377,0.0650202706456184,0.0518481098115444,-0.0502478554844856,-0.1305799931287766,0.1814480125904083,0.0090866927057505,-0.0510044656693935,-0.1691461503505707,0.0922467112541199,-0.0314207412302494) * MODEL22_texOff(vec2(-1,0));
res += mat4(0.1270498335361481,0.0563284493982792,-0.0435525141656399,0.1569847911596298,0.0576847903430462,0.3461692929267883,-0.0325655154883862,-0.2688976824283600,-0.1341977864503860,-0.1382253766059875,0.2293784171342850,-0.1111817285418510,-0.1402447521686554,-0.3257531225681305,0.0598510466516018,0.1008039116859436) * MODEL21_texOff(vec2(-1,1));
res += mat4(0.1698816716670990,0.3491003513336182,-0.1367681026458740,-0.1165873408317566,-0.2091718912124634,-0.1487034261226654,-0.0569749698042870,-0.2100717276334763,0.0404917001724243,-0.1372035890817642,0.0689046755433083,-0.0367818064987659,-0.0325474888086319,-0.0114965448155999,-0.0137249026447535,-0.0279692262411118) * MODEL22_texOff(vec2(-1,1));
res += mat4(-0.0563433989882469,0.0132494345307350,-0.2434540390968323,0.0796563774347305,-0.2109155058860779,0.0387088693678379,-0.0591037571430206,0.0955820381641388,0.4660535752773285,-0.1204202473163605,0.1332369595766068,-0.0285425651818514,-0.3886952698230743,-0.0434980578720570,-0.0849134400486946,0.0802380964159966) * MODEL21_texOff(vec2(0,-1));
res += mat4(0.0412235632538795,0.1571959257125854,0.2050069272518158,-0.1138664111495018,0.1962715685367584,0.0594439841806889,0.0351715497672558,-0.0129811102524400,0.2055217623710632,-0.0647534057497978,0.0373471938073635,0.0877277255058289,-0.5734645724296570,0.1188675239682198,-0.1145943328738213,-0.1182733029127121) * MODEL22_texOff(vec2(0,-1));
res += mat4(-0.2004909217357635,-0.4817073047161102,0.5596802830696106,-0.0327854752540588,0.0989314392209053,0.4127818942070007,0.7265836596488953,-0.2692042589187622,0.5195841789245605,-0.2357539832592010,-0.3819393217563629,0.1755530238151550,0.6578183770179749,0.1075539961457253,-0.2688144743442535,0.3242723941802979) * MODEL21_texOff(vec2(0,0));
res += mat4(-0.3221310675144196,0.2978510260581970,0.2269985526800156,-0.3184116482734680,0.4845580160617828,0.4407236874103546,0.0099756307899952,-0.3121858239173889,-0.3810067176818848,-0.0553649961948395,0.0202834140509367,0.0409953594207764,0.2532750964164734,0.2731618583202362,0.1237529441714287,0.0134243080392480) * MODEL22_texOff(vec2(0,0));
res += mat4(0.1835541725158691,0.0549701862037182,-0.1749316602945328,-0.2030028849840164,0.0263462308794260,0.2781440317630768,0.0372458845376968,0.3643021881580353,-0.4047883749008179,0.0660117194056511,0.4863115549087524,-0.2024163603782654,-0.6403482556343079,0.2765505611896515,0.1417075097560883,0.5064445734024048) * MODEL21_texOff(vec2(0,1));
res += mat4(0.6106975078582764,-0.1570862233638763,-0.3223383128643036,-0.2497926801443100,-0.4854303300380707,0.0132978223264217,-0.0609334111213684,0.1285556703805923,-0.1412864029407501,-0.1379042416810989,-0.0258826259523630,0.1357705891132355,-0.1285902857780457,-0.0577826797962189,0.0550044551491737,0.1717510819435120) * MODEL22_texOff(vec2(0,1));
res += mat4(0.1389609426259995,0.0835867226123810,0.0309768319129944,-0.0278116948902607,-0.0390677824616432,-0.0111810686066747,-0.0025318188127130,0.0069569633342326,0.0347319357097149,0.0191543344408274,0.0314339138567448,-0.0228427499532700,0.0416300334036350,0.0249234102666378,0.1210031509399414,0.1142473593354225) * MODEL21_texOff(vec2(1,-1));
res += mat4(0.0607251487672329,0.0386395826935768,-0.0219341218471527,-0.1102298423647881,0.1487188935279846,0.0602982006967068,-0.0280748903751373,-0.0211924221366644,0.0042894422076643,-0.0269144997000694,0.0814756453037262,-0.0314031280577183,-0.0213186051696539,-0.1362965404987335,0.0382767543196678,-0.0669511556625366) * MODEL22_texOff(vec2(1,-1));
res += mat4(-0.2397561967372894,0.3023172020912170,-0.2398054003715515,0.0041919997893274,-0.1016605198383331,-0.1521034836769104,-0.1526568531990051,0.0272433310747147,0.0741761848330498,0.1116370111703873,0.1149727106094360,-0.0809784531593323,-0.1448147594928741,-0.0943927690386772,-0.0086280042305589,0.1243222951889038) * MODEL21_texOff(vec2(1,0));
res += mat4(-0.0469366572797298,-0.1655988991260529,-0.1029584184288979,-0.1347874104976654,0.2064601778984070,0.0521226711571217,-0.1366733759641647,-0.0041872998699546,0.1077186539769173,0.0184442866593599,-0.2309073060750961,-0.1637075096368790,-0.0417953692376614,-0.3190860450267792,-0.1593534499406815,0.0136412177234888) * MODEL22_texOff(vec2(1,0));
res += mat4(0.1698798984289169,0.0232755411416292,-0.0876034423708916,-0.3008348643779755,0.0789884999394417,0.0034748215693980,-0.0064704762771726,0.0057828431017697,-0.0190630126744509,-0.0334153175354004,-0.0195646341890097,0.0105131156742573,0.0995147302746773,-0.3130289018154144,-0.0724022984504700,0.0113303456455469) * MODEL21_texOff(vec2(1,1));
res += mat4(-0.0027791252359748,-0.0193455871194601,-0.0415000133216381,0.0568981170654297,-0.2745247483253479,0.1222846284508705,0.1899162530899048,0.1067754998803139,-0.0561975166201591,-0.1500336527824402,0.0526139959692955,-0.3491798937320709,-0.0692384615540504,-0.0307095069438219,0.0498757846653461,0.0019003645284101) * MODEL22_texOff(vec2(1,1));
res = max(res, vec4(0.0)) + vec4(0.1552927196025848,0.0782765746116638,0.7966942191123962,-1.1619627475738525) * min(res, vec4(0.0));
return res;
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC mapping 4_2
//!BIND MODEL21
//!BIND MODEL22
//!SAVE MODEL2
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(-0.1443098634481430,-0.1343899369239807,-0.0624338127672672,-0.1094277128577232);
res += mat4(-0.0689977407455444,-0.1693786680698395,0.0109281269833446,0.0609922930598259,0.0296908002346754,0.1195700988173485,-0.0694077461957932,0.0971287414431572,0.0253518298268318,0.1213042959570885,0.0703809782862663,0.0055739870294929,-0.1595942378044128,-0.1336689442396164,-0.0622441768646240,-0.0428023114800453) * MODEL21_texOff(vec2(-1,-1));
res += mat4(0.0860001668334007,-0.0226618759334087,0.1602241247892380,0.0431661494076252,0.1526461094617844,0.2752982378005981,0.0960300788283348,-0.0536719262599945,-0.0171773489564657,0.0457364916801453,-0.0360932648181915,-0.0397153608500957,-0.0277090407907963,0.0729821547865868,-0.0145150292664766,0.0252893269062042) * MODEL22_texOff(vec2(-1,-1));
res += mat4(-0.1407091915607452,-0.4007499516010284,-0.0302001200616360,-0.0606933943927288,-0.2960600554943085,-0.2263117432594299,0.0721478462219238,-0.4578711986541748,0.0960150733590126,-0.1606502830982208,0.2444226741790771,0.0000882153908606,0.1472496986389160,0.3256779909133911,-0.2132861614227295,0.0339313484728336) * MODEL21_texOff(vec2(-1,0));
res += mat4(-0.1477648764848709,-0.1487885862588882,-0.1973863691091537,0.0717295333743095,0.0843430235981941,0.6259996294975281,-0.1214931011199951,-0.1274987608194351,0.2359549105167389,0.3002171218395233,-0.0825233608484268,-0.0157950688153505,0.0706149637699127,0.1762917637825012,-0.0611497573554516,-0.0859689489006996) * MODEL22_texOff(vec2(-1,0));
res += mat4(0.0174895934760571,-0.0567042417824268,0.0409146919846535,0.0258173532783985,0.1421577036380768,0.1234543323516846,-0.1721662431955338,0.1492216140031815,0.1100751459598541,0.0501539446413517,0.1100447699427605,-0.1086079254746437,-0.0608497932553291,0.0087817469611764,0.0714464113116264,-0.1285197436809540) * MODEL21_texOff(vec2(-1,1));
res += mat4(-0.0017177806003019,-0.1463395059108734,-0.1085453778505325,0.1650195866823196,0.0813829153776169,0.1102061793208122,-0.0578421875834465,-0.0232036896049976,-0.1239888817071915,0.0155465165153146,0.1079114526510239,-0.0420837886631489,-0.0775837749242783,0.0148941157385707,-0.0502299368381500,-0.0654754191637039) * MODEL22_texOff(vec2(-1,1));
res += mat4(0.0918162539601326,0.0440697595477104,-0.0515748932957649,0.0417411290109158,0.0353216230869293,0.1535954177379608,0.0439723692834377,-0.1288845241069794,0.1076577678322792,-0.1306740194559097,0.0715952813625336,-0.0681907683610916,-0.3798767924308777,0.1023928597569466,-0.0970670804381371,0.0077168666757643) * MODEL21_texOff(vec2(0,-1));
res += mat4(0.0634560957551003,-0.0550306066870689,0.2073986232280731,0.0520241297781467,0.1162287592887878,-0.2218665480613708,0.3199682831764221,0.0606246069073677,-0.0058511858806014,-0.0667045339941978,-0.0449917949736118,0.0707788690924644,-0.3323366343975067,-0.0763893201947212,-0.0997853428125381,-0.1181001588702202) * MODEL22_texOff(vec2(0,-1));
res += mat4(-0.3101258873939514,0.2616009712219238,0.0584651045501232,0.1656491309404373,-0.0069236233830452,0.2573371529579163,-0.1793291717767715,-0.2718756198883057,0.0953581258654594,0.0524105131626129,0.1183085516095161,0.0583294369280338,0.5036848187446594,-0.5763167142868042,-0.2119628041982651,-0.3140562772750854) * MODEL21_texOff(vec2(0,0));
res += mat4(-0.2497755438089371,-0.0146329319104552,-0.2741575539112091,0.2459975033998489,0.3562706708908081,-0.6528629064559937,-0.4287456274032593,0.2055913358926773,0.1739019453525543,-0.3855968713760376,-0.0958273336291313,-0.7066691517829895,0.2365748286247253,-0.3046728968620300,-0.2590373754501343,-0.0496727414429188) * MODEL22_texOff(vec2(0,0));
res += mat4(-0.0844531357288361,-0.0321611948311329,-0.0951840654015541,0.0577518045902252,-0.1606003493070602,0.2776086628437042,-0.1355003118515015,-0.0880064144730568,-0.1277643740177155,-0.0514567233622074,0.1522682905197144,-0.1040910631418228,-0.2767944037914276,-0.1452194601297379,0.0089118303731084,0.0231996178627014) * MODEL21_texOff(vec2(0,1));
res += mat4(0.2603267133235931,0.0167464651167393,-0.2064073234796524,0.1782064288854599,0.4890212416648865,0.0559245310723782,0.1221160590648651,-0.0202587731182575,-0.4056585729122162,-0.1839511841535568,0.2775998413562775,0.0024275144096464,-0.2624500989913940,-0.0619418807327747,0.0153478365391493,0.0123427547514439) * MODEL22_texOff(vec2(0,1));
res += mat4(0.0816635638475418,-0.0134946266189218,0.0594766475260258,-0.0551253929734230,0.0134431896731257,-0.0652195811271667,-0.0563635528087616,-0.0066532371565700,-0.0004114551993553,0.0105680683627725,0.1324467360973358,0.0467248968780041,0.0301312971860170,-0.1073397025465965,-0.0363437235355377,-0.0474153012037277) * MODEL21_texOff(vec2(1,-1));
res += mat4(0.0199097190052271,0.0901319086551666,0.0448978282511234,0.0505443066358566,0.0438878424465656,-0.0494784042239189,0.0724927335977554,-0.0070675504393876,-0.0012125011999160,0.0295279901474714,0.0705125033855438,0.0555334389209747,-0.0403393507003784,-0.1271172016859055,0.0017914215568453,0.1462216079235077) * MODEL22_texOff(vec2(1,-1));
res += mat4(-0.2827299833297729,0.2052399665117264,0.0042732120491564,-0.3969024717807770,-0.0782120972871780,0.1960176974534988,-0.0675340741872787,0.0027962317690253,0.0516129024326801,-0.0352642722427845,0.0546326488256454,0.0065340655855834,-0.1062376946210861,0.1364430636167526,-0.0536947809159756,0.2098117172718048) * MODEL21_texOff(vec2(1,0));
res += mat4(0.0045875865034759,0.2162927240133286,-0.2158576399087906,-0.0047327815555036,0.1251590698957443,0.1279677897691727,-0.1188964918255806,0.0328494384884834,0.0076038073748350,-0.0561547242105007,0.0335608273744583,0.4332321286201477,0.0021786799188703,0.0844521671533585,-0.2102309316396713,-0.0189208015799522) * MODEL22_texOff(vec2(1,0));
res += mat4(0.0933093801140785,0.1548244059085846,-0.0598701611161232,0.0357220247387886,-0.1141726672649384,0.0536412484943867,-0.0159156844019890,-0.0445508137345314,0.1883231997489929,-0.1547038406133652,0.0530619807541370,0.0059371814131737,0.0602529086172581,-0.0435577929019928,0.0083390390500426,0.0191930737346411) * MODEL21_texOff(vec2(1,1));
res += mat4(-0.0351041629910469,0.2119503468275070,-0.0841927304863930,0.0079463515430689,0.0683520361781120,-0.1657009869813919,0.0611055232584476,-0.0063667562790215,0.0330024957656860,-0.1810818463563919,0.0872574150562286,0.1485669612884521,-0.1305806934833527,0.0041402997449040,0.0223289318382740,-0.0141495745629072) * MODEL22_texOff(vec2(1,1));
res = max(res, vec4(0.0)) + vec4(0.5769761204719543,0.1716064810752869,-0.0821026712656021,0.2092144042253494) * min(res, vec4(0.0));
return res;
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC sub-band residuals 1
//!BIND MODEL1
//!BIND MODEL2
//!BIND FEATURE1
//!SAVE RES1
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(0.0245648548007011,-0.4467784762382507,0.0197526942938566,-0.0110000418499112);
res += mat4(0.0302665308117867,-0.9262221455574036,-0.1161134764552116,-0.0506900474429131,0.2716045379638672,-0.0485871583223343,0.0044713355600834,-0.4274623394012451,0.0749531090259552,-0.3700785338878632,0.0350039415061474,-0.0540786534547806,-0.0607390031218529,-0.8019900321960449,0.0923245251178741,0.1258827745914459) * MODEL1_texOff(0);
res += mat4(-0.0649135261774063,0.0815236791968346,0.0067334296181798,0.1277425885200500,-0.0051357815973461,-0.1485908329486847,0.0074226572178304,0.0050623500719666,0.0588018335402012,-0.0692552924156189,0.1288725286722183,-0.0989386290311813,0.0427936837077141,0.0967708528041840,-0.0455632135272026,-0.0711275041103363) * MODEL2_texOff(0);
res += FEATURE1_texOff(0);
res = max(res, vec4(0.0)) + vec4(0.9927186965942383,0.0570580027997494,1.3226752281188965,1.0069466829299927) * min(res, vec4(0.0));
return res;
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC sub-band residuals 2
//!BIND MODEL1
//!BIND MODEL2
//!BIND FEATURE2
//!SAVE RES2
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(-0.0425243787467480,-0.3715015351772308,-0.0256227850914001,-0.2774516046047211);
res += mat4(0.0238118842244148,0.0295480657368898,-0.0066418983042240,0.1021223962306976,-0.0568209178745747,-0.4355100393295288,-0.2700522541999817,-0.2060186564922333,-0.0689613372087479,-0.1689691990613937,-0.0306748505681753,-0.2461252212524414,-0.0057375836186111,-0.1892303228378296,-0.0285871494561434,-0.5032613277435303) * MODEL1_texOff(0);
res += mat4(0.5463213324546814,0.0972800329327583,0.0307560767978430,0.0678058937191963,-0.0356063023209572,-0.7013865113258362,0.1890443563461304,-0.1036657467484474,-0.1745826154947281,-0.2942218780517578,-0.0485423319041729,-0.2983124554157257,-0.0524431839585304,-0.3261034786701202,0.3217246532440186,0.1958018541336060) * MODEL2_texOff(0);
res += FEATURE2_texOff(0);
res = max(res, vec4(0.0)) + vec4(0.1391339898109436,0.0960328355431557,0.6235341429710388,0.1177272796630859) * min(res, vec4(0.0));
return res;
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!DESC sub-pixel convolution 1
//!BIND RES1
//!BIND RES2
//!SAVE SUBCONV1
//!COMPONENTS 4
vec4 hook()
{
vec4 res = vec4(0.2010385394096375,0.2058132737874985,0.1918809115886688,0.1961363703012466);
res += mat4x4(-0.0005980331334285,-0.0095877395942807,-0.0149448839947581,-0.0026380482595414,0.0320665836334229,-0.0706205591559410,-0.0054677254520357,0.0215112231671810,-0.0025710910558701,-0.0000433265340689,0.0044494951143861,-0.0034823501482606,-0.0050858515314758,0.0109513988718390,0.0208286065608263,-0.0032168829347938) * RES1_texOff(vec2(-1,-1));
res += mat4x4(-0.0145305208861828,0.0246876608580351,-0.0038286084309220,-0.0033089490607381,-0.0920709222555161,-0.0767898634076118,0.0012083095498383,-0.0751532614231110,0.0001302754972130,-0.0107085108757019,-0.0010383903281763,-0.0059571005403996,0.0809685289859772,0.0414833538234234,0.0227938480675220,-0.0211347509175539) * RES2_texOff(vec2(-1,-1));
res += mat4x4(0.0160999298095703,0.0364215746521950,-0.0377063788473606,-0.0449111759662628,-0.0476365163922310,0.1522845029830933,-0.0131391752511263,-0.0476671792566776,-0.0378389135003090,0.0235454943031073,0.0224007442593575,-0.0010372076649219,-0.0089435689151287,-0.0293026417493820,0.0274190884083509,0.0469092652201653) * RES1_texOff(vec2(-1,0));
res += mat4x4(0.0297575183212757,-0.0132508194074035,-0.0044682323932648,-0.0096222748979926,0.2525918781757355,0.1873829364776611,-0.5599535703659058,-0.2372044622898102,0.0033207221422344,0.0256173480302095,0.0294605866074562,0.0323960892856121,-0.1679904460906982,-0.1278967708349228,0.3168168365955353,0.1978507637977600) * RES2_texOff(vec2(-1,0));
res += mat4x4(-0.0047590560279787,-0.0149335600435734,0.0033453819341958,-0.0012247267877683,0.1112466752529144,0.0147760482504964,0.0031189601868391,0.0391573049128056,-0.0028154491446912,-0.0036881719715893,-0.0116015253588557,-0.0037573333829641,0.0047581391409039,0.0071071563288569,-0.0033221673220396,0.0004882142529823) * RES1_texOff(vec2(-1,1));
res += mat4x4(-0.0025197160430253,-0.0018677815096453,0.0038254233077168,0.0041981274262071,-0.1321131736040115,-0.0494364202022552,0.0760654658079147,-0.1386690139770508,-0.0016222692793235,-0.0060105528682470,0.0010201989207417,0.0092753591015935,-0.0194614846259356,0.0087382243946195,-0.0606758072972298,0.0156162241473794) * RES2_texOff(vec2(-1,1));
res += mat4x4(-0.0073722628876567,0.0012844242155552,0.0241398401558399,-0.0075527969747782,-0.0865194946527481,-0.0610522404313087,0.0289319511502981,-0.0994452014565468,0.0281447004526854,-0.0250582899898291,0.0044891634024680,-0.0246205236762762,0.0112307453528047,-0.0010844616917893,-0.0223584957420826,0.0177635718137026) * RES1_texOff(vec2(0,-1));
res += mat4x4(-0.0585863515734673,0.0953190475702286,-0.0555586628615856,0.1033507287502289,0.1560877263545990,-0.0690897777676582,-0.0341389514505863,-0.0661668032407761,0.0531073249876499,-0.0266165956854820,-0.0203275382518768,0.0017760475166142,-0.1300747394561768,0.1810652017593384,0.0381597876548767,0.1397419273853302) * RES2_texOff(vec2(0,-1));
res += mat4x4(0.6259804368019104,0.6062518954277039,0.5450409054756165,0.5966195464134216,-0.0423948727548122,0.0760537460446358,-0.0113651463761926,0.3007817566394806,-0.3218322694301605,0.2713021934032440,-0.3143473267555237,0.2303840517997742,0.3493050038814545,0.3590726852416992,0.4138027429580688,0.3391666412353516) * RES1_texOff(vec2(0,0));
res += mat4x4(0.0790478289127350,-0.0978994593024254,0.0779844969511032,-0.0823706611990929,0.0094470111653209,0.1671760678291321,0.1201528310775757,-0.2016288936138153,0.3667598366737366,0.3651430010795593,-0.3612343966960907,-0.2978236973285675,-0.4231655597686768,0.0091423410922289,-0.1918412446975708,0.4224558770656586) * RES2_texOff(vec2(0,0));
res += mat4x4(-0.0186564289033413,0.0274957418441772,-0.0064405309967697,0.0056951809674501,0.4864942431449890,-0.2563461959362030,0.4357284605503082,-0.2976118028163910,0.0374982468783855,0.0167757049202919,0.0305800959467888,0.0232830215245485,0.0138373551890254,-0.0191283021122217,0.0032355054281652,0.0055057541467249) * RES1_texOff(vec2(0,1));
res += mat4x4(-0.0276355985552073,0.0048149987123907,-0.0251619722694159,-0.0057246969081461,0.0271473955363035,-0.0042668608948588,-0.0594691745936871,0.2255926281213760,-0.0203660242259502,0.0721646770834923,0.0137230781838298,-0.0650938376784325,-0.3049557507038116,0.2035628110170364,-0.2509683668613434,0.1962853819131851) * RES2_texOff(vec2(0,1));
res += mat4x4(0.0109980758279562,-0.0053752651438117,-0.0112550277262926,0.0024017230607569,0.0362104885280132,0.0084348218515515,-0.0106990104541183,-0.0207723993808031,-0.0014961160486564,0.0066790678538382,0.0028113177977502,0.0025022011250257,-0.0093937022611499,0.0016421369509771,0.0035362334456295,-0.0058064293116331) * RES1_texOff(vec2(1,-1));
res += mat4x4(0.0138889988884330,-0.0078343702480197,0.0061464929021895,0.0202130675315857,-0.0257590841501951,-0.0366640128195286,0.0250097587704659,-0.0498071312904358,-0.0103149358183146,-0.0001786737266229,-0.0099909817799926,0.0062733208760619,0.0131437368690968,-0.0005469865864143,-0.0388854071497917,0.0612070746719837) * RES2_texOff(vec2(1,-1));
res += mat4x4(0.0052813654765487,0.0215748809278011,0.0107395220547915,-0.0079439217224717,0.0382786765694618,0.0697424262762070,-0.0415962152183056,0.0657853558659554,0.0209470037370920,-0.0218399092555046,-0.0447359494864941,0.0407319553196430,-0.0040902681648731,-0.0196106657385826,-0.0018554026028141,0.0203906055539846) * RES1_texOff(vec2(1,0));
res += mat4x4(-0.0106181986629963,0.0084018819034100,0.0131329754367471,-0.0198754761368036,0.1117177084088326,0.0990846082568169,-0.0732304081320763,0.0163581725209951,-0.0648830309510231,-0.0451613292098045,0.0206844564527273,0.0031441387254745,-0.0106161693111062,-0.0567689687013626,0.0782861113548279,-0.0306094046682119) * RES2_texOff(vec2(1,0));
res += mat4x4(0.0012452082009986,-0.0026056850329041,-0.0096226977184415,-0.0037850935477763,-0.0190967041999102,0.0534373670816422,0.1599360853433609,0.0834670960903168,-0.0070255175232887,0.0012873009545729,0.0030876772943884,-0.0093916896730661,-0.0033529615029693,0.0043485122732818,0.0089034689590335,-0.0067489291541278) * RES1_texOff(vec2(1,1));
res += mat4x4(0.0004713654634543,-0.0034161377698183,-0.0026913962792605,0.0053522582165897,-0.0040974905714393,0.0273330621421337,-0.0333138220012188,-0.0701237097382545,0.0082997502759099,-0.0183656588196754,-0.0122841577976942,-0.0052855615504086,-0.0023795007728040,-0.0438593104481697,-0.1101513057947159,-0.0182559806853533) * RES2_texOff(vec2(1,1));
return vec4(res);
}
//!HOOK LUMA
//!WHEN OUTPUT.w LUMA.w / 1.300 > OUTPUT.h LUMA.h / 1.300 > *
//!WIDTH LUMA.w 2 *
//!HEIGHT LUMA.h 2 *
//!DESC aggregation
//!BIND SUBCONV1
vec4 hook()
{
vec2 fcoord = fract(SUBCONV1_pos * SUBCONV1_size);
vec2 base = SUBCONV1_pos + (vec2(0.5) - fcoord) * SUBCONV1_pt;
ivec2 index = ivec2(fcoord * vec2(2));
vec4 res = SUBCONV1_tex(base);
return vec4(res[index.x * 2 + index.y], 0, 0, 1);
}

View file

@ -19,9 +19,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// Description: nlmeans_light.glsl: Tuned for light noise.
// Kaleido: the luma denoising factor (S) of both passes is 60% of upstream's,
// so compressed streams keep their texture after upscaling.
// Description: nlmeans.glsl: Default profile, general purpose, tuned for low noise
// The following is shader code injected from ./nlmeans_template
/* vi: ft=c
@ -62,9 +60,9 @@
// Denoising factor (sigma, higher means more blur)
#ifdef LUMA_raw
#define S 0.5613045774507373
#define S 2.171842300643018
#else
#define S 0.9403666624779301
#define S 3.472706940155897
#endif
/* Noise resistant adaptive sharpening
@ -102,9 +100,9 @@
* AKA the center weight, the weight of the pixel-of-interest.
*/
#ifdef LUMA_raw
#define SW 1.4862663328498773
#define SW 0.874631892412684
#else
#define SW 0.9819103409433417
#define SW 0.3493678781214755
#endif
/* Spatial kernel
@ -121,12 +119,12 @@
*/
#ifdef LUMA_raw
#define SST 1
#define SS 0.07583364754930425
#define SS 0.1786363425615082
#define PST 0
#define PSS 0.0
#else
#define SST 1
#define SS 0.10671055546360571
#define SS 0.3241999209926485
#define PST 0
#define PSS 0.0
#endif
@ -237,8 +235,8 @@
*/
#ifdef LUMA_raw
#define WD 1
#define WDT 0.16487506042732236
#define WDP 1.9555360378310291
#define WDT 0.2935708849017379
#define WDP 1.2788519721382683
#define WDS 1.0
#else
#define WD 0
@ -1397,7 +1395,7 @@ vec4 hook()
//!BIND HOOKED
//!BIND G
//!BIND GC
//!DESC Non-local means (nlmeans_light.glsl)
//!DESC Non-local means (nlmeans.glsl)
@ -1408,9 +1406,9 @@ vec4 hook()
// Denoising factor (sigma, higher means more blur)
#ifdef LUMA_raw
#define S 1.624252283929877
#define S 3.559719405746641
#else
#define S 1.3439787380682449
#define S 0.644044031464058
#endif
/* Noise resistant adaptive sharpening
@ -1448,9 +1446,9 @@ vec4 hook()
* AKA the center weight, the weight of the pixel-of-interest.
*/
#ifdef LUMA_raw
#define SW 0.42869267982902737
#define SW 0.5211292610050897
#else
#define SW 2.0240674571497026
#define SW 0.32722815587389364
#endif
/* Spatial kernel
@ -1467,12 +1465,12 @@ vec4 hook()
*/
#ifdef LUMA_raw
#define SST 1
#define SS 1.5736089799792439
#define SS 1.3662208603933492
#define PST 0
#define PSS 0.0
#else
#define SST 1
#define SS 0.17327451303505204
#define SS 0.07604576880459668
#define PST 0
#define PSS 0.0
#endif
@ -1583,7 +1581,7 @@ vec4 hook()
*/
#ifdef LUMA_raw
#define WD 2
#define WDT 0.5035442429806473
#define WDT 0.6302678350888067
#define WDP 0.0
#define WDS 1.0
#else

View file

@ -1,158 +0,0 @@
//! 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));
}
}
}

View file

@ -5,9 +5,8 @@
//! server-relative source path; resuming after a restart asks the interface for
//! a freshly signed URL.
use std::collections::{HashMap, HashSet};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
@ -48,19 +47,10 @@ pub struct Item {
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 {
items: Mutex<Vec<Item>>,
dir: Mutex<Option<PathBuf>>,
workers: Mutex<HashMap<String, Worker>>,
generation: AtomicU64,
cancels: Mutex<HashMap<String, watch::Sender<bool>>>,
permits: Arc<Semaphore>,
client: reqwest::Client,
}
@ -70,8 +60,7 @@ impl Default for Downloads {
Downloads {
items: Mutex::new(Vec::new()),
dir: Mutex::new(None),
workers: Mutex::new(HashMap::new()),
generation: AtomicU64::new(0),
cancels: Mutex::new(HashMap::new()),
permits: Arc::new(Semaphore::new(MAX_ACTIVE)),
client: reqwest::Client::builder()
.connect_timeout(Duration::from_secs(20))
@ -179,11 +168,8 @@ pub async fn download_start<R: Runtime>(app: AppHandle<R>, request: StartRequest
let mut meta = request.meta.clone();
if let Value::Object(map) = &mut meta {
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 {
let target = folder.join(format!(".{stem}.{}.jpg", sanitize(name)));
let target = folder.join(format!(".{}.jpg", sanitize(name)));
if fetch_to(&state.client, url, &target).await.is_ok() {
local.insert(name.clone(), Value::String(target.display().to_string()));
}
@ -218,48 +204,21 @@ async fn fetch_to(client: &reqwest::Client, url: &str, target: &Path) -> Result<
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) {
let state = app.state::<Downloads>();
let generation = state.generation.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = watch::channel(false);
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
});
app.state::<Downloads>().cancels.lock().insert(id.clone(), tx);
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 _permit = tokio::select! {
p = permits.acquire_owned() => p,
_ = cancelled(rx.clone()) => { release(&app, &id, generation); return; }
_ = cancelled(rx.clone()) => return,
};
// The task it replaced may have finished the file just as it was stopped.
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;
}
let result = transfer(&app, &id, &url, rx).await;
app.state::<Downloads>().cancels.lock().remove(&id);
match result {
Ok(true) => {
update(&app, &id, |i| {
i.status = Status::Completed;
i.error = None;
i.speed = 0;
i.received = i.total.max(i.received);
});
@ -277,30 +236,6 @@ 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>) {
while !*rx.borrow() {
if rx.changed().await.is_err() {
@ -313,7 +248,10 @@ 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> {
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 part_path = part_path(&final_path);
let part_path = final_path.with_extension(format!(
"{}.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 client = app.state::<Downloads>().client.clone();
@ -321,10 +259,7 @@ async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch
if existing > 0 {
request = request.header("Range", format!("bytes={existing}-"));
}
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 response = request.send().await.map_err(|e| format!("Could not reach the server: {e}"))?;
let status = response.status();
if status.as_u16() == 401 || status.as_u16() == 403 {
return Err("The server does not allow downloads for this account.".into());
@ -401,14 +336,10 @@ async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch
Ok(true)
}
/// Stops the transfer for `id`, if one is running; the receiver closes once it has exited.
/// The entry stays until then, so a task started meanwhile knows to wait for it.
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())
fn cancel<R: Runtime>(app: &AppHandle<R>, id: &str) {
if let Some(tx) = app.state::<Downloads>().cancels.lock().remove(id) {
let _ = tx.send(true);
}
}
#[tauri::command]
@ -425,7 +356,7 @@ pub fn download_pause<R: Runtime>(app: AppHandle<R>, id: String) {
#[tauri::command]
pub fn download_resume<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
// `spawn` takes over from a transfer still winding down.
cancel(&app, &id);
update(&app, &id, |i| {
i.status = Status::Queued;
i.error = None;
@ -435,7 +366,7 @@ pub fn download_resume<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
#[tauri::command]
pub async fn download_remove<R: Runtime>(app: AppHandle<R>, id: String, delete_files: bool) -> Result<(), String> {
let running = cancel(&app, &id);
cancel(&app, &id);
let removed = {
let state = app.state::<Downloads>();
let mut items = state.items.lock();
@ -444,24 +375,14 @@ pub async fn download_remove<R: Runtime>(app: AppHandle<R>, id: String, delete_f
};
if let (Some(item), true) = (removed, delete_files) {
let path = PathBuf::from(&item.file_path);
// Let the cancelled transfer release its file handle first.
if let Some(done) = running {
let _ = tokio::time::timeout(Duration::from_secs(10), exited(done)).await;
}
// Give the cancelled transfer a moment to release its file handle.
tokio::time::sleep(Duration::from_millis(150)).await;
let _ = tokio::fs::remove_file(&path).await;
let _ = tokio::fs::remove_file(part_path(&path)).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();
let part = path.with_extension(format!("{}.part", path.extension().and_then(|e| e.to_str()).unwrap_or("bin")));
let _ = tokio::fs::remove_file(&part).await;
if let Value::Object(assets) = &item.meta["localAssets"] {
for v in assets.values() {
if let Some(p) = v.as_str().filter(|p| !in_use.contains(*p)) {
if let Some(p) = v.as_str() {
let _ = tokio::fs::remove_file(p).await;
}
}

View file

@ -1,6 +1,4 @@
mod diagnostics;
mod downloads;
mod mini;
mod mpv;
mod platform;
mod player;
@ -17,8 +15,6 @@ pub fn run() {
.plugin(tauri_plugin_process::init())
.plugin(
tauri_plugin_window_state::Builder::default()
// The miniplayer window is always placed from the main window (mini.rs).
.with_denylist(&["mini"])
.with_state_flags(
tauri_plugin_window_state::StateFlags::SIZE
| tauri_plugin_window_state::StateFlags::POSITION
@ -27,24 +23,15 @@ pub fn run() {
.build(),
)
.manage(player::PlayerState::default())
.manage(mini::MiniState::default())
.manage(downloads::Downloads::default())
.setup(|app| {
let handle = app.handle().clone();
diagnostics::start(&handle);
downloads::restore(&handle);
if let Some(window) = app.get_webview_window("main") {
let w = window.clone();
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 {
// 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));
player::on_resize(&w);
}
});
}
@ -57,7 +44,6 @@ pub fn run() {
player::player_command,
player::player_set,
player::player_get,
player::window_buttons,
system::secret_get,
system::secret_set,
system::secret_delete,
@ -73,13 +59,6 @@ pub fn run() {
downloads::download_list,
downloads::download_set_dir,
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!())
.expect("error while running Kaleido");

View file

@ -1,334 +0,0 @@
//! 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));
}

View file

@ -192,21 +192,6 @@ 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 {
unsafe { CStr::from_ptr((self.api.error_string)(code)).to_string_lossy().into_owned() }
}

View file

@ -1,5 +1,5 @@
//! Linux: render mpv through its render API (OpenGL) beneath the WebKitGTK
//! view, then implement `VideoSurface` here (see macos.rs for the same idea).
//! view, then implement `VideoSurface` here.
//!
//! Browsing, downloads, settings and updates already work here; only native
//! video composition remains to be written.
@ -20,61 +20,13 @@ impl VideoSurface {
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
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 show<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: bool) {}
pub fn show(&mut self, _: bool) {}
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<()>) {
// TODO(Linux): org.freedesktop.ScreenSaver.Inhibit over D-Bus.
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) {}

View file

@ -1,568 +1,32 @@
//! macOS: libmpv's render API (OpenGL) draws into a CAOpenGLLayer hosted by a
//! view placed beneath the WKWebView; libmpv names, power assertions, window
//! buttons and host details.
//! macOS: render mpv through its render API (libplacebo) into a CAMetalLayer
//! placed beneath the WKWebView, then implement `VideoSurface` here.
//!
//! OpenGL is deprecated on macOS but still supported (on Metal); it is the
//! render API libmpv offers, and what IINA and other mpv front ends use.
#![allow(deprecated)]
//! Browsing, downloads, settings and updates already work here; only native
//! video composition remains to be written.
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 crate::mpv::Mpv;
// —— OpenGL ————————————————————————————————————————————————————————————
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 {
pub fn create<R: Runtime>(window: &WebviewWindow<R>) -> Result<VideoSurface, String> {
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)> {
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(())
}
}
/// mpv properties the surface needs to observe.
pub const SURFACE_PROPERTIES: &[&str] = &["video-params/gamma"];
/// File names libmpv may have on this platform.
pub const SURFACE_PROPERTIES: &[&str] = &[];
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()
}
pub struct VideoSurface;
/// 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)
impl VideoSurface {
pub fn create<R: Runtime>(_: &WebviewWindow<R>) -> Result<VideoSurface, String> {
Err("Video playback is not available on this platform yet.".into())
}
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
Vec::new()
}
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 set_rect<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: Option<&Mpv>, _: Option<(i32, i32, i32, i32)>) {}
}
/// 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;
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
// TODO(macOS): IOPMAssertionCreateWithName(PreventUserIdleDisplaySleep).
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) {}

View file

@ -2,14 +2,10 @@
//! Each platform file exposes the same items:
//!
//! - `VideoSurface`: composes mpv's output beneath the web view
//! (`create`, `mpv_options`, `start`, `on_property`, `show`, `fit`, `set_rect`).
//! (`create`, `mpv_options`, `on_property`, `show`, `fit`, `set_rect`).
//! - `SURFACE_PROPERTIES`: mpv properties the surface observes.
//! - `MPV_LIBRARIES`: libmpv file names to look for.
//! - `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")]
mod windows;

View file

@ -10,15 +10,9 @@ use ::windows::Win32::UI::WindowsAndMessaging::GetClientRect;
use crate::mpv::Mpv;
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,
device: IDCompositionDevice,
/// One composition target per window the video has been shown in.
targets: Vec<(isize, IDCompositionTarget)>,
_target: IDCompositionTarget,
root: IDCompositionVisual,
visible: bool,
/// Where the video is drawn, in client pixels; `None` fills the window.
@ -50,12 +44,11 @@ impl VideoSurface {
let root = device.CreateVisual().map_err(|e| e.to_string())?;
let (width, height) = client_size(hwnd);
device.Commit().map_err(|e| e.to_string())?;
let _ = &target;
Ok(VideoSurface {
hwnd,
main: hwnd,
attached: 0,
device,
targets: vec![(hwnd.0 as isize, target)],
_target: target,
root,
visible: false,
rect: None,
@ -76,11 +69,6 @@ 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) {
if name == "display-swapchain" {
self.attach(value.as_i64().unwrap_or(0) as usize);
@ -106,60 +94,22 @@ impl VideoSurface {
}
}
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) {
pub fn show(&mut self, visible: bool) {
if self.visible == visible {
return;
}
self.visible = visible;
if let Some(target) = self.target(self.hwnd) {
unsafe {
let _ = if visible { target.SetRoot(&self.root) } else { target.SetRoot(None::<&IDCompositionVisual>) };
let _ = self.device.Commit();
}
}
}
/// Moves the video to another window (the miniplayer's, a raw `HWND`), or
/// back to the main window with `None`, filling its client area. Both
/// 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);
}
}
let _ = if visible { self._target.SetRoot(&self.root) } else { self._target.SetRoot(None::<&IDCompositionVisual>) };
let _ = self.device.Commit();
}
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);
pub fn fit<R: Runtime>(&mut self, window: &WebviewWindow<R>, mpv: Option<&Mpv>) {
let Ok(h) = window.hwnd() else { return };
let (cw, ch) = client_size(HWND(h.0 as _));
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),
@ -191,188 +141,6 @@ pub const SURFACE_PROPERTIES: &[&str] = &["display-swapchain"];
/// File names libmpv may have on this platform.
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.
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
use ::windows::Win32::System::Power::*;

View file

@ -14,10 +14,6 @@ use tauri::{AppHandle, Emitter, Manager, Runtime, WebviewWindow};
use crate::mpv::{self, Event, Mpv};
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)]
pub struct PlayerState {
mpv: Mutex<Option<Arc<Mpv>>>,
@ -64,8 +60,6 @@ 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> {
let resource_dir = app.path().resource_dir().ok();
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 render_options = surface.mpv_options();
*app.state::<PlayerState>().surface.lock() = Some(surface);
@ -77,9 +71,7 @@ fn create_player<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindow<R>, opts
set("hwdec", opts.hwdec.as_deref().unwrap_or("auto-safe"))?;
set("keep-open", "yes")?;
set("idle", "yes")?;
if !render_options.iter().any(|(k, _)| *k == "force-window") {
set("force-window", "yes")?;
}
set("force-window", "yes")?;
set("osc", "no")?;
set("osd-level", "0")?;
set("input-default-bindings", "no")?;
@ -115,9 +107,6 @@ fn create_player<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindow<R>, opts
}
mpv.request_log_messages("warn");
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() {
mpv.observe(i as u64 + 1, name);
}
@ -180,29 +169,13 @@ fn player<R: Runtime>(app: &AppHandle<R>) -> Result<Arc<Mpv>, String> {
#[tauri::command]
pub async fn player_init<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, options: Option<InitOptions>) -> Result<(), String> {
let state = app.state::<PlayerState>();
{
let mut guard = state.mpv.lock();
if guard.is_none() {
*guard = Some(create_player(&app, &window, &options.unwrap_or_default())?);
}
let mut guard = state.mpv.lock();
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(())
}
/// 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]
pub async fn player_show<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, visible: bool) -> Result<(), String> {
let state = app.state::<PlayerState>();
@ -210,7 +183,7 @@ pub async fn player_show<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>
let mut surface = state.surface.lock();
if let Some(surface) = surface.as_mut() {
surface.fit(&window, mpv.as_deref());
surface.show(&window, visible);
surface.show(visible);
}
Ok(())
}
@ -252,13 +225,6 @@ pub async fn player_get<R: Runtime>(app: AppHandle<R>, name: String) -> Result<V
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.
pub fn on_resize<R: Runtime>(window: &WebviewWindow<R>) {
let app = window.app_handle();

View file

@ -13,14 +13,9 @@ fn entry(key: &str) -> Result<keyring::Entry, String> {
keyring::Entry::new(SERVICE, key).map_err(|e| e.to_string())
}
/// 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`.
/// Secrets (Plex tokens) live in Windows Credential Manager, never in plain files.
#[tauri::command]
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));
}
pub fn secret_get(key: String) -> Result<Option<String>, String> {
match entry(&key)?.get_password() {
Ok(v) => Ok(Some(v)),
Err(keyring::Error::NoEntry) => Ok(None),
@ -29,66 +24,18 @@ pub fn secret_get<R: Runtime>(app: AppHandle<R>, key: String) -> Result<Option<S
}
#[tauri::command]
pub fn secret_set<R: Runtime>(app: AppHandle<R>, key: String, value: String) -> Result<(), 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()),
}
pub fn secret_set(key: String, value: String) -> Result<(), String> {
entry(&key)?.set_password(&value).map_err(|e| e.to_string())
}
#[tauri::command]
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);
}
pub fn secret_delete(key: String) -> Result<(), String> {
match entry(&key)?.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
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)]
#[serde(rename_all = "camelCase")]
pub struct AppInfo {
@ -96,10 +43,7 @@ pub struct AppInfo {
data_dir: String,
default_download_dir: String,
platform: String,
os_version: String,
device_name: String,
/// Graphics adapters by name (decides which upscaling tiers are offered).
gpus: Vec<String>,
}
#[tauri::command]
@ -117,9 +61,7 @@ pub fn app_info<R: Runtime>(app: AppHandle<R>) -> AppInfo {
data_dir: data,
default_download_dir: downloads,
platform: std::env::consts::OS.to_string(),
os_version: crate::platform::os_version(),
device_name: crate::platform::device_name(),
gpus: crate::platform::gpu_names(),
device_name: std::env::var("COMPUTERNAME").unwrap_or_else(|_| "Windows PC".into()),
}
}

View file

@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Kaleido",
"version": "1.0.1",
"version": "0.1.0-beta.5",
"identifier": "tv.kaleido.desktop",
"build": {
"beforeDevCommand": "npm run dev",
@ -31,12 +31,9 @@
"csp": null,
"assetProtocol": {
"enable": true,
"scope": {
"allow": [
"**"
],
"requireLiteralLeadingDot": false
}
"scope": [
"**"
]
}
}
},
@ -61,7 +58,7 @@
},
"plugins": {
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEUxQjk1OTExMzBCRTRENEUKUldST1RiNHdFVm01NFFMQ1EvYm9CYlhhNU9jNTZXb254dVZOQW8relJYRlQ4ZjdLQll3cHR3VE4K",
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEU0MTA2RjI0OUFFQzU1QzUKUldURlZleWFKRzhRNUlqTTR3U095STFYS3BsUXd2UnZMYlRrQmt3aUk5YU5WSjdqcUxVcHllU1EK",
"endpoints": [
"https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/raw/branch/main/updates/latest.json"
]

View file

@ -1,39 +1,15 @@
{
"$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": {
"targets": [
"app",
"dmg"
],
"macOS": {
"minimumSystemVersion": "26.0",
"signingIdentity": "-",
"hardenedRuntime": false,
"files": {
"Frameworks": "../vendor/mpv/macos"
}
"minimumSystemVersion": "12.0",
"frameworks": [
"../vendor/mpv/macos/libmpv.2.dylib"
]
}
}
}
}

View file

@ -11,7 +11,7 @@ import { PageLoader } from '../ui/primitives';
import { Splash } from '../screens/Splash';
import { SignIn } from '../screens/SignIn';
import { ServerPicker } from '../screens/ServerPicker';
import { isMac, isNative, win } from '../platform/native';
import { win } from '../platform/native';
import { usePlayer } from '../player/store';
import { PlayerOverlay } from '../player/PlayerOverlay';
import { DialogHost } from '../screens/dialogs/DialogHost';
@ -100,20 +100,18 @@ function useGlobalShortcuts() {
if ((e.ctrlKey || e.metaKey) && (e.key === 'k' || e.key === 'f')) {
e.preventDefault();
navigate({ name: 'search' });
} else if ((e.altKey && e.key === 'ArrowLeft') || (isMac && e.metaKey && e.key === '[')) {
} else if (e.altKey && e.key === 'ArrowLeft') {
e.preventDefault();
useRouter.getState().back();
} else if ((e.altKey && e.key === 'ArrowRight') || (isMac && e.metaKey && e.key === ']')) {
} else if (e.altKey && e.key === 'ArrowRight') {
e.preventDefault();
useRouter.getState().forward();
} else if (e.key === 'F11' || (isMac && e.metaKey && e.ctrlKey && e.key.toLowerCase() === 'f')) {
} else if (e.key === 'F11') {
e.preventDefault();
win.isFullscreen().then((fs) => win.setFullscreen(!fs));
} else if ((e.key === 'Escape' || e.key === 'Backspace') && !isTyping(e.target) && !document.querySelector('.menu-layer, .dialog-layer')) {
if (e.key === 'Escape' && document.fullscreenElement) return;
// 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();
useRouter.getState().back();
} else if ((e.ctrlKey || e.metaKey) && e.key === ',') {
e.preventDefault();
navigate({ name: 'settings', mode: 'app', tab: 'general' });
@ -227,16 +225,7 @@ export function App() {
useEffect(() => {
useSession.getState().init();
// The window appears once the first frame is painted (no white flash).
// 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);
requestAnimationFrame(() => win.show());
}, []);
useEffect(() => {

View file

@ -5,7 +5,7 @@ import { useSettings } from './settings';
import { Icon } from '../ui/Icon';
import { KaleidoMark } from '../ui/primitives';
import { openMenu, type MenuItem } from '../ui/overlays';
import { isMac, isNative, shortcut, win } from '../platform/native';
import { isNative, win } from '../platform/native';
import { useDownloads } from '../downloads/store';
import { useHomeUsers } from './useHomeUsers';
@ -16,40 +16,25 @@ const NAV = [
{ id: 'downloads', label: 'Downloads', route: { name: 'downloads' } as const },
];
/** Caption buttons drawn by the page; macOS shows its own traffic lights instead. */
export function WindowControls() {
const [maximized, setMaximized] = useState(false);
const [fullscreen, setFullscreen] = useState(false);
useEffect(() => {
if (!isNative || isMac) return;
if (!isNative) return;
let off: (() => void) | undefined;
let gone = false;
const sync = () => {
win.isMaximized().then((m) => !gone && setMaximized(m));
win.isFullscreen().then((f) => !gone && setFullscreen(f));
};
const sync = () => win.isMaximized().then(setMaximized);
sync();
win.onResized(sync).then((u) => (gone ? u() : (off = u)));
return () => {
gone = true;
off?.();
};
win.onResized(sync).then((u) => (off = u));
return () => off?.();
}, []);
if (!isNative || isMac) return null;
if (!isNative) return null;
return (
<div className="window-controls">
<button aria-label="Minimize" onClick={() => win.minimize()}>
<Icon name="minimize" size={15} strokeWidth={1.4} />
</button>
{fullscreen ? (
<button aria-label="Exit full screen" title="Exit full screen (Esc)" onClick={() => win.setFullscreen(false)}>
<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={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()}>
<Icon name="x" size={15} strokeWidth={1.4} />
</button>
@ -124,7 +109,7 @@ export function TopBar({ solid }: { solid: boolean }) {
</nav>
</div>
<div className="topbar-right" data-tauri-drag-region>
<button className={`icon-btn${active === 'search' ? ' on' : ''}`} aria-label="Search" title={`Search (${shortcut('K')})`} onClick={() => navigate({ name: 'search' })}>
<button className={`icon-btn${active === 'search' ? ' on' : ''}`} aria-label="Search" title="Search (Ctrl+K)" onClick={() => navigate({ name: 'search' })}>
<Icon name="search" size={19} />
</button>
<button className={`icon-btn${active === 'settings' ? ' on' : ''}`} aria-label="Settings" title="Settings" onClick={() => navigate({ name: 'settings', mode: 'app', tab: 'general' })}>

View file

@ -36,19 +36,10 @@ export function progress(item: Item): number {
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 {
if (item.type === 'show' || item.type === 'season') return item.leafCount > 0 && item.viewedLeafCount >= item.leafCount;
if (item.viewCount > 0) return true;
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;
if (item.viewOffset > 0 && item.duration > 0) return item.viewCount > 0 && item.viewOffset / item.duration >= percent / 100;
return item.viewCount > 0;
}
export function remainingEpisodes(item: Item): number {
@ -183,24 +174,17 @@ export function plural(n: number, word: string, pluralWord = `${word}s`) {
return `${n.toLocaleString()} ${n === 1 ? word : pluralWord}`;
}
/** Hex UltraBlur colors → the wash's four corner colours, each at its own strength. */
export function washColors(u: Item['ultraBlur'], strength = 1) {
if (!u) return null;
/** Hex UltraBlur colors → CSS gradient layers for the artwork colour wash. */
export function washGradient(u: Item['ultraBlur'], strength = 1): string {
if (!u) return '';
const c = (hex: string, a: number) => {
const n = parseInt(hex, 16);
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 [
`radial-gradient(ellipse at 100% 0%, ${c.topRight} 0%, transparent 62%)`,
`radial-gradient(ellipse at 0% 0%, ${c.topLeft} 0%, transparent 55%)`,
`radial-gradient(ellipse at 100% 100%, ${c.bottomRight} 0%, transparent 60%)`,
`radial-gradient(ellipse at 0% 100%, ${c.bottomLeft} 0%, transparent 60%)`,
`radial-gradient(ellipse at 100% 0%, ${c(u.topRight, 0.95)} 0%, transparent 62%)`,
`radial-gradient(ellipse at 0% 0%, ${c(u.topLeft, 0.7)} 0%, transparent 55%)`,
`radial-gradient(ellipse at 100% 100%, ${c(u.bottomRight, 0.55)} 0%, transparent 60%)`,
`radial-gradient(ellipse at 0% 100%, ${c(u.bottomLeft, 0.45)} 0%, transparent 60%)`,
].join(', ');
}

View file

@ -1,9 +1,9 @@
/**
* 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
* the same across shelves, grids and people rows.
* the same across shelves, grids, episode lists and people rows.
*/
const TARGETS = '.card, .person-card:not(:disabled), .shelf-title-link';
const TARGETS = '.card, .person-card:not(:disabled), .episode-row, .shelf-title-link';
function center(r: DOMRect) {
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };

View file

@ -1,7 +1,7 @@
import { QueryClient, useQuery, type UseQueryOptions } from '@tanstack/react-query';
import * as api from '../plex/api';
import type { Item, Section } from '../plex/types';
import { useServer, useSession } from './session';
import { useServer } from './session';
import { useSettings } from './settings';
export const queryClient = new QueryClient({
@ -15,25 +15,6 @@ 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. */
export function useKey(...parts: unknown[]) {
const server = useServer();
@ -56,9 +37,9 @@ export function useSectionFor(kind: 'movie' | 'show'): { section: Section | null
}
export const useItem = (id: string | undefined, opts: Partial<UseQueryOptions<Item>> = {}) =>
useServerQuery(['item', id], (s) => api.metadata(s, id!), { enabled: !!id, staleTime: 30_000, ...WATCH_STATE, ...opts });
useServerQuery(['item', id], (s) => api.metadata(s, id!), { enabled: !!id, staleTime: 30_000, ...opts });
export const useChildren = (id: string | undefined) => useServerQuery(['children', id], (s) => api.children(s, id!), { enabled: !!id, staleTime: 30_000, ...WATCH_STATE });
export const useChildren = (id: string | undefined) => useServerQuery(['children', id], (s) => api.children(s, id!), { enabled: !!id, staleTime: 30_000 });
export const useRelated = (id: string | undefined) => useServerQuery(['related', id], (s) => api.related(s, id!), { enabled: !!id, staleTime: 10 * 60_000 });

View file

@ -54,7 +54,7 @@ export const useSession = create<SessionState>((set, get) => ({
async init() {
const info = await appInfo();
configureClient({ version: info.version, deviceName: info.deviceName, platformVersion: info.osVersion });
configureClient({ version: info.version, deviceName: info.deviceName });
let token = await secrets.get('account-token');
const stored = loadStoredServer();

View file

@ -19,8 +19,6 @@ export interface Preferences {
countdownSeconds: number;
skipIntro: SkipMode;
skipCredits: SkipMode;
/** Seconds a "Skip automatically" marker waits, so it can be cancelled; 0 skips at once. */
autoSkipDelay: number;
watchedPercent: number;
audioLanguage: string;
subtitleMode: SubtitleMode;
@ -64,7 +62,6 @@ export const defaults: Preferences = {
countdownSeconds: 8,
skipIntro: 'button',
skipCredits: 'button',
autoSkipDelay: 5,
watchedPercent: 90,
audioLanguage: '',
subtitleMode: 'auto',
@ -152,6 +149,6 @@ export const SUBTITLE_MARGIN: Record<SubtitlePosition, number> = { low: 14, norm
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' },
balanced: { label: 'Balanced', detail: 'Neural upscaling (FSRCNNX), colour reconstruction, debanding and sharpening' },
quality: { label: 'Quality', detail: 'nlmeans denoising, larger neural upscaler (FSRCNNX 16), colour reconstruction, debanding and sharpening. Needs a capable GPU' },
};

View file

@ -52,16 +52,12 @@ function sanitize(s: string) {
return s.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').trim() || 'Untitled';
}
/**
* 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) {
/** Trims metadata kept for offline display: no extras, related hubs or raw blobs. */
function slim(raw: any) {
const { Extras, Related, OnDeck, ...rest } = raw ?? {};
void Extras;
void Related;
void OnDeck;
if (Array.isArray(rest.Media) && rest.Media[mediaIndex]) rest.Media = [rest.Media[mediaIndex]];
return rest;
}
@ -106,12 +102,9 @@ export const useDownloads = create<DownloadsState>((set, get) => ({
try {
await get().init();
const item = await api.metadata(server, input.id);
// 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 media = item.media[0];
const part = media?.parts[0];
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);
if (get().items.some((d) => d.id === id && d.status !== 'failed')) {
toast('This title is already in Downloads.');
@ -136,7 +129,7 @@ export const useDownloads = create<DownloadsState>((set, get) => ({
url: server.signed(part.key, { download: 1 }),
folder,
fileName: sanitize(baseName),
meta: { serverId: server.machineId, serverName: server.name, ratingKey: item.id, partKey: part.key, raw: slim(item.raw, item.media.indexOf(media)) } satisfies DownloadMeta,
meta: { serverId: server.machineId, serverName: server.name, ratingKey: item.id, partKey: part.key, raw: slim(item.raw) } satisfies DownloadMeta,
assets,
},
});

View file

@ -13,7 +13,6 @@ import { useRouter } from './app/router';
import { usePlayer } from './player/store';
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, useDownloads };
@ -25,15 +24,6 @@ window.addEventListener('contextmenu', (e) => {
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(
<StrictMode>
<App />

View file

@ -1,153 +0,0 @@
/**
* 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>,
);

View file

@ -1,32 +0,0 @@
/* 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;
}

View file

@ -1,17 +0,0 @@
/** 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';

View file

@ -7,16 +7,6 @@ import type { UnlistenFn } from '@tauri-apps/api/event';
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> {
if (!isNative) throw new Error(`${cmd} is only available in the desktop app.`);
const { invoke } = await import('@tauri-apps/api/core');
@ -57,10 +47,7 @@ export interface AppInfo {
dataDir: string;
defaultDownloadDir: string;
platform: string;
osVersion: string;
deviceName: string;
/** Graphics adapters by name (empty where not reported). */
gpus: string[];
}
let info: AppInfo | null = null;
@ -68,7 +55,7 @@ export async function appInfo(): Promise<AppInfo> {
if (info) return info;
info = isNative
? await invoke<AppInfo>('app_info')
: { version: '0.1.0-dev', dataDir: '', defaultDownloadDir: '', platform: 'browser', osVersion: '', deviceName: 'Browser preview', gpus: [] };
: { version: '0.1.0-dev', dataDir: '', defaultDownloadDir: '', platform: 'browser', deviceName: 'Browser preview' };
return info;
}
@ -118,10 +105,6 @@ export const win = {
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> {
if (!isNative) {
window.addEventListener('resize', cb);

View file

@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react';
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { usePlayer } from './store';
import { useSession } from '../app/session';
import { useSettings, QUALITY_LABEL, UPSCALING, type Quality, type SubtitleBox, type Upscaling } from '../app/settings';
@ -10,11 +10,9 @@ 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 { PREPARING_NOTICE_MS, UPSCALING_ORDER, hasFailed, readDiagnostics, requestEnhancement, toggleBypass, type Diagnostics } from './enhance';
import { toast } from '../ui/overlays';
import type { Item } from '../plex/types';
import { PostPlay } from './PostPlay';
const HIDE_AFTER = 3000;
@ -175,9 +173,9 @@ function Panel({ title, onClose, onBack, children, className = '' }: { title: st
);
}
function Option({ selected, label, detail, disabled, onClick }: { selected: boolean; label: string; detail?: string; disabled?: boolean; onClick: () => void }) {
function Option({ selected, label, detail, onClick }: { selected: boolean; label: string; detail?: string; onClick: () => void }) {
return (
<button className={`panel-option${selected ? ' selected' : ''}`} disabled={disabled} onClick={onClick}>
<button className={`panel-option${selected ? ' selected' : ''}`} onClick={onClick}>
<span className="panel-check">{selected && <Icon name="check" size={16} />}</span>
<span className="panel-label">
{label}
@ -330,19 +328,12 @@ function SettingsPanel({ onClose }: { onClose: () => void }) {
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)}
/>
<Option key={m} selected={prefs.upscaling === m} label={UPSCALING[m].label} detail={hasFailed(m) ? 'Couldn’t start on this computer' : UPSCALING[m].detail} 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)} />
<Option selected={prefs.enhanceDenoise} label="Denoising" detail="Non-local means, at any size · Quality 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>
@ -493,103 +484,69 @@ 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() {
const item = usePlayer((s) => s.item);
const position = usePlayer((s) => s.position);
const seek = usePlayer((s) => s.seek);
const nextUp = usePlayer((s) => s.nextUp);
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 skipCredits = useSettings((s) => s.skipCredits);
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 autoSkipped = useRef(new Set<string>());
const ms = position * 1000;
const marker = item?.markers.find((m) => (m.type === 'intro' || m.type === 'credits') && ms >= m.start && ms < m.end - 1000);
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.
const mode = marker?.type === 'intro' ? skipIntro : skipCredits;
useEffect(() => {
if (!auto || !ready || paused || settled.current.has(key) || pending?.key === key) return;
if (Date.now() - usePlayer.getState().lastSeek < SEEK_GRACE_MS) {
settled.current.add(key);
return;
if (marker && mode === 'auto' && !autoSkipped.current.has(marker.id + marker.start) && !(marker.type === 'credits' && nextUp)) {
autoSkipped.current.add(marker.id + marker.start);
seek(marker.end / 1000);
}
if (delay <= 0) return skip();
setPending({ key, from: usePlayer.getState().position });
}, [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;
}, [marker?.id, marker?.start, mode]);
if (!marker || mode === 'off' || countdown !== null) return null;
if (marker.type === 'credits' && nextUp) return null;
return (
<button
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>
<button className="skip-button" onClick={() => seek(marker.end / 1000)}>
{marker.type === 'intro' ? 'Skip intro' : 'Skip credits'}
<Icon name="skipNext" size={16} />
</button>
);
}
function PostPlay() {
const server = useSession((s) => s.server);
const nextUp = usePlayer((s) => s.nextUp);
const countdown = usePlayer((s) => s.countdown);
const playNext = usePlayer((s) => s.playNext);
const cancel = usePlayer((s) => s.cancelCountdown);
if (!nextUp || countdown === null || !server) return null;
return (
<div className="post-play" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
<div className="post-play-art">
<img src={server.image(nextUp.thumb, 360, 202)} alt="" draggable={false} />
{countdown > 0 && (
<svg className="post-play-ring" viewBox="0 0 40 40">
<circle cx="20" cy="20" r="17" />
</svg>
)}
</div>
<div className="post-play-text">
<span className="micro">Next episode{countdown > 0 ? ` in ${countdown}` : ''}</span>
<b>
{episodeLabel(nextUp)} · {nextUp.title}
</b>
<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>
);
}
/** The title opens its show or movie page, with playback moving to the miniplayer. */
function openFromPlayer(id: string | undefined) {
if (!id) return;
@ -619,62 +576,18 @@ 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`).
* Playing in the corner while browsing. 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(() => {
@ -690,64 +603,23 @@ function MiniPlayer() {
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();
place();
const ro = new ResizeObserver(place);
ro.observe(el);
window.addEventListener('resize', onResize);
window.addEventListener('resize', place);
return () => {
cancelAnimationFrame(frame);
ro.disconnect();
window.removeEventListener('resize', onResize);
window.removeEventListener('resize', place);
};
}, []);
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 (
<div ref={box} className={`mini-player${loading || st.error ? ' loading' : ''}`} onPointerDown={startDrag} onDoubleClick={() => st.expand()}>
<div ref={box} className={`mini-player${loading || st.error ? ' loading' : ''}`} onDoubleClick={() => st.expand()}>
<div className="mini-scrim" />
<div className="mini-top">
<button className="mini-icon" aria-label="Back to full screen player" title="Expand" onClick={() => st.expand()}>
@ -758,7 +630,7 @@ function MiniPlayer() {
</button>
</div>
<div className="mini-center">
{(loading || st.buffering || st.reconnecting) && !st.error ? (
{(loading || st.buffering) && !st.error ? (
<Spinner size={30} />
) : st.error ? (
<span className="mini-error">Playback stopped</span>
@ -811,9 +683,6 @@ export function PlayerOverlay() {
useEffect(() => {
if (!st.open || st.mini) return;
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;
const p = usePlayer.getState();
let handled = true;
@ -856,16 +725,10 @@ export function PlayerOverlay() {
if (e.shiftKey && p.nextUp) p.playNext();
else handled = false;
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];
const next = UPSCALING_ORDER[(UPSCALING_ORDER.indexOf(prefs.upscaling) + 1) % UPSCALING_ORDER.length];
prefs.set('upscaling', next);
// Confirm what is actually running once it's applied.
requestEnhancement().then(() => {
@ -910,18 +773,8 @@ export function PlayerOverlay() {
return () => window.removeEventListener('keydown', onKey);
}, [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;
// 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} />;
if (st.mini) return <MiniPlayer />;
const item = st.item;
const loading = !st.firstFrame && !st.error;
const art = item.type === 'episode' ? item.grandparentArt || item.art : item.art;
@ -965,12 +818,10 @@ export function PlayerOverlay() {
{!st.fullscreen && <WindowControls />}
</div>
{(loading || st.buffering || st.seeking || preparing || st.reconnecting) && !st.error && (
{(loading || st.buffering || st.seeking || preparing) && !st.error && (
<div className="player-center">
<Spinner size={44} />
{st.reconnecting ? (
<p className="player-preparing">Lost connection to {server?.name ?? 'the server'}</p>
) : preparing && (
{preparing && (
<p className="player-preparing">
Preparing {UPSCALING[st.enhance.active].label} upscaling
<small>First time on this computer only</small>
@ -990,25 +841,18 @@ export function PlayerOverlay() {
<h2>Playback stopped</h2>
<p>{st.error}</p>
<div className="actions">
{st.terminated ? (
<Button variant="primary" onClick={() => st.close()}>
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>
</>
)}
<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>
)}
<SkipButton />
<PostPlay />
{!st.error && (
<div className="player-bottom" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
@ -1019,49 +863,24 @@ export function PlayerOverlay() {
<Timeline onScrub={setScrubbing} />
<div className="player-controls">
<div className="player-controls-left">
<Volume />
<span className="player-time">
{clock(st.position, st.duration >= 3600)} <span className="dim">/ {clock(st.duration, st.duration >= 3600)}</span>
</span>
</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 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 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()}
>
{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>
)}
<button className="player-icon" aria-label="Stop playback" title="Stop" onClick={() => st.close()}>
<Icon name="stop" size={19} />
</button>
<Volume />
<span className="player-time">
{clock(st.position, st.duration >= 3600)} <span className="dim">/ {clock(st.duration, st.duration >= 3600)}</span>
</span>
</div>
<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')}>

View file

@ -1,334 +0,0 @@
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>
);
}

View file

@ -1,28 +1,19 @@
/**
* 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.
* Video enhancement: upscaling tiers built from mpv's scalers, debanding and
* the shaders bundled in src-tauri/shaders. Each shader's WHEN condition
* decides whether it runs for the current video and window size, so one list
* covers every case: FSRCNNX doubles luma when the video is enlarged (the
* small model above 1.3×, the large one at any enlargement, so 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 at any size.
*
* 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.
* state) are kept apart: a tier whose shaders fail 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 { isNative, resourcePath } from '../platform/native';
import { toast } from '../ui/overlays';
import { mpv } from './engine';
import { usePlayer } from './store';
@ -34,63 +25,47 @@ const SCALER_PROPS = ['scale', 'cscale', 'dscale', 'sigmoid-upscaling', 'deband'
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';
/** The enlargement above which each tier's network runs (its shaders' WHEN condition). */
const NETWORK_MIN_SCALE: Partial<Record<Upscaling, number>> = { balanced: 1.3, quality: 1.0 };
const runsNetwork = async (mode: Upscaling) => mode in NETWORK_MIN_SCALE && (await scaleFactor()) > NETWORK_MIN_SCALE[mode]!;
/** 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;
const NEURAL: Partial<Record<Upscaling, string>> = { balanced: 'FSRCNNX_x2_8-0-4-1.glsl', quality: 'FSRCNNX_x2_16-0-4-1.glsl' };
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.
* Quality denoises first, so the network enlarges the picture rather than
* the compression noise. Both FSRCNNX models are trained on general imagery,
* which suits live action.
*/
function plan(mode: Upscaling, hdr: boolean, scale: number): Plan {
function plan(mode: Upscaling, hdr: boolean): 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'] : [])];
props = { scale: 'ewa_lanczossharp', cscale: 'ewa_lanczossharp', dscale: 'mitchell', 'sigmoid-upscaling': true, deband: true, 'deband-iterations': 2, 'deband-grain': 16 };
shaders = [NEURAL.balanced!, '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)}`;
props = { scale: 'ewa_lanczossharp', cscale: 'ewa_lanczossharp', dscale: 'mitchell', 'sigmoid-upscaling': true, deband: true, 'deband-iterations': 2, 'deband-grain': 12 };
shaders = [...(enhanceDenoise && !hdr ? ['nlmeans.glsl'] : []), NEURAL.quality!, 'KrigBilateral.glsl', ...(sharpen ? ['CAS.glsl'] : [])];
break;
default:
return { props: { ...scalerDefaults }, shaders: [], vsr };
return { props: { ...scalerDefaults }, shaders: [] };
}
if (!enhanceDeband) props.deband = false;
return { props, shaders, vsr };
return { props, shaders };
}
/** HDR as decoded (a converted stream may already be SDR), else Plex's metadata. */
@ -104,12 +79,8 @@ function isHdr() {
const shaderErrors: { at: number; text: string }[] = [];
/** Fed every mpv log line; keeps the ones that mean a user shader or RTX Video failed. */
/** Fed every mpv log line; keeps the ones that mean a user shader 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))) {
@ -148,40 +119,22 @@ export async function scaleFactor(): Promise<number> {
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.
* After a tier is applied: wait for frames, then look for shader errors in
* mpv's log, and for the passes that should be running at this size (the
* denoiser always, the network when enlarging). Either failing drops to the
* tier below.
*/
async function verify(id: number, mode: Upscaling, appliedAt: number, signature: string, { shaders, vsr }: Plan) {
async function verify(id: number, mode: Upscaling, appliedAt: number, signature: string, shaders: string[]) {
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/);
if (shaders.includes('nlmeans.glsl')) expected.push(/Non-local means/);
if (NEURAL[mode] && (await runsNetwork(mode))) 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) {
if (!error && 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.
@ -207,7 +160,7 @@ async function verify(id: number, mode: Upscaling, appliedAt: number, signature:
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'));
console.warn('[upscaling]', mode, 'failed:', error?.text ?? 'network passes not running');
toast(`${UPSCALING[mode].label} upscaling couldn’t start. Using ${UPSCALING[fallback].label}.`, 'error');
requestEnhancement();
}
@ -246,14 +199,14 @@ function markWarm(signature: string) {
}
if (usePlayer.getState().enhance.preparing) usePlayer.setState({ enhance: { ...usePlayer.getState().enhance, preparing: false } });
}
/** Tiers that failed this session. */
/** Tiers whose shaders 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. */
/** The chosen tier, or the nearest one below it that 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--;
while (i > 0 && failed.has(UPSCALING_ORDER[i])) i--;
return UPSCALING_ORDER[i];
}
@ -271,8 +224,7 @@ async function apply(id: number, requested: Upscaling) {
}
const bypass = usePlayer.getState().enhance.bypass;
let mode = usable(requested);
const scale = await scaleFactor();
let { props, shaders, vsr } = plan(bypass ? 'off' : mode, isHdr(), scale);
let { props, shaders } = plan(bypass ? 'off' : mode, isHdr());
const dir = await (shaderDir ??= resourcePath('shaders').catch(() => ''));
if (shaders.length && !dir) {
// No shaders at all: keep the scaler and debanding settings only.
@ -280,7 +232,7 @@ async function apply(id: number, requested: Upscaling) {
missingWarned = true;
shaders = [];
if (mode !== 'performance') mode = 'performance';
({ props, vsr } = plan(mode, isHdr(), scale));
({ props } = plan(mode, isHdr()));
}
// Decided before touching mpv: while a shader compiles, mpv holds option
// changes until it finishes, so a notice set afterwards would come too late.
@ -294,7 +246,7 @@ async function apply(id: number, requested: Upscaling) {
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 });
const settings = JSON.stringify({ props, shaders });
if (settings !== lastApplied) {
lastApplied = settings;
lastAppliedAt = Date.now();
@ -305,13 +257,10 @@ async function apply(id: number, requested: Upscaling) {
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 });
if (!bypass && shaders.length) verify(id, mode, lastAppliedAt, signature, shaders);
}
/**
@ -360,8 +309,6 @@ const STAGES: [RegExp, string][] = [
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;
@ -408,23 +355,3 @@ 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));
}

View file

@ -1,99 +0,0 @@
/**
* 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();
});
}

View file

@ -1,280 +0,0 @@
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();
});
});

View file

@ -2,18 +2,15 @@ import { create } from 'zustand';
import * as api from '../plex/api';
import { directUrl, previewUrl, reportTimeline, stopTranscode, transcodeUrl, type Delivery } from '../plex/playback';
import type { Item, Stream } from '../plex/types';
import type { PlexServer } from '../plex/client';
import { useSession } from '../app/session';
import { useDownloads, type Download } from '../downloads/store';
import { useSettings, SUBTITLE_MARGIN, type Preferences, type Quality, type Upscaling } from '../app/settings';
import { followVideoSize, noteMpvLog, requestEnhancement, watchPerformance } from './enhance';
import { noteMpvLog, requestEnhancement, watchPerformance } from './enhance';
import { channelLabel } from '../app/format';
import { invalidateLibrary } from '../app/queries';
import { invoke, keepAwake, isNative, win } from '../platform/native';
import { keepAwake, isNative, win } from '../platform/native';
import { mpv, type MpvEvent, type MpvTrack } from './engine';
import { toast } from '../ui/overlays';
import { stopThemeMusic } from './theme';
import { bridgeMiniWindow, hideMiniWindow, separateMini, showMiniWindow } from './miniWindow';
export interface Track {
key: string; // stable UI key
@ -34,10 +31,6 @@ export interface PlayOptions {
/** A local file path (offline download). */
localFile?: string;
quality?: Quality;
/** Keep these track choices (UI keys) instead of applying the preferences again. */
tracks?: { audioKey: string; subKey: string };
/** Reloading the same title in place (after an outage): stay in the miniplayer if it's there. */
keepMini?: boolean;
}
interface PlayerState {
@ -48,18 +41,12 @@ interface PlayerState {
quality: Quality;
firstFrame: boolean;
error: string;
/** The server owner stopped this stream (error holds their message). */
terminated: boolean;
/** The stream was cut off before the end (the server went away); waiting for it to come back. */
reconnecting: boolean;
position: number;
duration: number;
cacheTime: number;
paused: boolean;
buffering: boolean;
seeking: boolean;
/** When the last seek was asked for (Date.now()), so a pending auto-skip can step aside. */
lastSeek: number;
volume: number;
muted: boolean;
speed: number;
@ -72,12 +59,7 @@ interface PlayerState {
video: { width: number; height: number; hwdec: string; codec: string } | null;
ended: boolean;
nextUp: Item | null;
/** The episode before this one, for the previous-episode button. */
prevUp: Item | null;
episodeContextReady: boolean;
countdown: number | null;
countdownTotal: number;
postPlay: boolean;
postPlayDismissed: boolean;
fullscreen: boolean;
/** Playing in the corner while browsing. */
@ -105,10 +87,7 @@ interface PlayerState {
setQuality(q: Quality): Promise<void>;
selectVersion(index: number): Promise<void>;
playNext(): Promise<void>;
playPrevious(): Promise<void>;
cancelCountdown(): void;
showPostPlay(): void;
dismissPostPlay(): void;
toggleFullscreen(): Promise<void>;
previewAt(seconds: number): string;
}
@ -116,27 +95,15 @@ interface PlayerState {
let session = '';
let startOffsetMs = 0;
let lastReport = 0;
/** Plex has answered a report for this session without a termination. */
let sessionAnswered = false;
let reportTimer: ReturnType<typeof setInterval> | null = null;
let countdownTimer: ReturnType<typeof setInterval> | null = null;
let unwatchCountdown: (() => void) | null = null;
let scrobbled = false;
let unlisten: (() => void) | null = null;
let loadToken = 0;
let wasFullscreenBeforePlay = false;
let pendingExternal: Track | null = null;
/**
* The server this playback belongs to, fixed when it starts. Progress, watched state
* and transcodes always go there, never to whichever server is selected later. A
* download plays without one unless its own server is the one connected.
*/
let playServer: PlexServer | null = null;
/** The download being played, whose saved metadata keeps the offline resume point. */
let playDownload: Download | null = null;
const server = () => playServer;
const server = () => useSession.getState().server;
/**
* mpv applies its volume on a cubic curve, so halfway on a linear slider was
@ -241,85 +208,22 @@ async function applySubtitleStyle(prefs: Preferences = useSettings.getState()) {
}
}
/** A download's watch was counted this session; its resume point stays cleared. */
let localScrobbled = false;
/**
* Keeps a download's resume point (or, once watched, its watch count) in its saved
* metadata, which is all an offline title has to resume from.
*/
function saveLocalProgress(watched = false) {
const d = playDownload;
const { item, position, delivery, firstFrame } = usePlayer.getState();
// Before the first frame the position is only where it was asked to start.
if (!d || !item || delivery?.mode !== 'local' || !firstFrame || (localScrobbled && !watched)) return;
const raw = { ...(d.meta.raw ?? {}) };
if (watched) {
if (localScrobbled) return;
localScrobbled = true;
raw.viewOffset = 0;
raw.viewCount = (Number(raw.viewCount) || 0) + 1;
raw.lastViewedAt = Math.floor(Date.now() / 1000);
} else raw.viewOffset = Math.max(0, Math.round(position * 1000));
const meta = { ...d.meta, raw };
playDownload = { ...d, meta };
invoke('download_write_meta', { id: d.id, meta }).catch(() => {});
}
/** Reports progress to Plex; resolves true if the reply says the stream was stopped. */
function report(state: 'playing' | 'paused' | 'buffering' | 'stopped'): Promise<boolean> {
if (state === 'paused' || state === 'stopped') saveLocalProgress();
function report(state: 'playing' | 'paused' | 'buffering' | 'stopped') {
const s = server();
const { item, position, delivery } = usePlayer.getState();
if (!s || !item || !session || item.type === 'clip') return Promise.resolve(false);
if (!s || !item || !session || item.type === 'clip') return;
lastReport = Date.now();
const extra: Record<string, string | number> = {};
if (delivery?.mode === 'transcode' && delivery.session) extra['X-Plex-Session-Identifier'] = delivery.session;
const reported = session;
return reportTimeline(s, item, state, position * 1000, session, extra)
.then((reply) => {
if (reported !== session) return false;
if (!reply.terminationText) {
sessionAnswered = true;
return false;
}
// Plex repeats a termination to this client until it reports a stop.
// On a session's first reply it is left over from an earlier stream
// (this one can't have been stopped yet): clear it and carry on.
reportTimeline(s, item, 'stopped', position * 1000, session, extra).catch(() => {});
if (!sessionAnswered) return false;
onTerminated(reply.terminationText);
return true;
})
.catch(() => false);
}
/**
* The server owner stopped this stream. Plex cuts the connection, so mpv would
* play out its buffer and then wait forever; stop it and show their message.
*/
function onTerminated(text: string) {
const st = usePlayer.getState();
if (!st.open || st.terminated) return;
if (reportTimer) clearInterval(reportTimer);
reportTimer = null;
stopCountdown();
keepAwake(false);
watchPerformance(false);
const s = server();
if (st.delivery?.session && s) stopTranscode(s, st.delivery.session);
usePlayer.setState({ error: text, terminated: true, buffering: false, countdown: null });
if (isNative) mpv.command('stop').catch(() => {});
reportTimeline(s, item, state, position * 1000, session, extra).catch(() => {});
}
function checkScrobble() {
const { item, position, duration } = usePlayer.getState();
const s = server();
if (!item || scrobbled || !duration || item.type === 'clip') return;
if (!item || !s || scrobbled || !duration || item.type === 'clip') return;
const percent = useSettings.getState().watchedPercent;
if (position / duration >= percent / 100) {
saveLocalProgress(true);
if (!s) return;
scrobbled = true;
api
.setWatched(s, item.id, true)
@ -328,156 +232,42 @@ function checkScrobble() {
}
}
/** The episodes either side of this one in the show. */
async function findNeighbours(item: Item): Promise<{ prevUp: Item | null; nextUp: Item | null }> {
const none = { prevUp: null, nextUp: null };
async function findNext(item: Item): Promise<Item | null> {
const s = server();
if (!s || item.type !== 'episode' || !item.grandparentId) return none;
if (!s || item.type !== 'episode' || !item.grandparentId) return null;
try {
const leaves = await api.allLeaves(s, item.grandparentId);
const i = leaves.findIndex((e) => e.id === item.id);
return i >= 0 ? { prevUp: leaves[i - 1] ?? null, nextUp: leaves[i + 1] ?? null } : none;
return i >= 0 ? (leaves[i + 1] ?? null) : null;
} catch {
return none;
return null;
}
}
function openPostPlay() {
const st = usePlayer.getState();
if (!st.open || st.error || st.item?.type !== 'episode' || st.postPlay || st.postPlayDismissed) return;
usePlayer.setState({ postPlay: true });
startCountdown();
}
function startCountdown() {
const st = usePlayer.getState();
if (!st.open || !st.postPlay || st.error || !st.nextUp || st.postPlayDismissed || st.countdown !== null) return;
if (!st.nextUp || st.countdown !== null || st.postPlayDismissed) return;
const settings = useSettings.getState();
const total = settings.autoplayNext ? settings.countdownSeconds : 0;
if (total <= 0) return;
stopCountdown();
usePlayer.setState({ countdown: total, countdownTotal: total });
let lastTick = performance.now();
const visibilityChanged = () => { lastTick = performance.now(); };
document.addEventListener('visibilitychange', visibilityChanged);
unwatchCountdown = () => document.removeEventListener('visibilitychange', visibilityChanged);
if (!settings.autoplayNext) {
usePlayer.setState({ countdown: -1 });
return;
}
usePlayer.setState({ countdown: settings.countdownSeconds });
countdownTimer && clearInterval(countdownTimer);
countdownTimer = setInterval(() => {
const now = performance.now();
const elapsed = Math.max(0, (now - lastTick) / 1000);
lastTick = now;
const current = usePlayer.getState();
if (!current.open || !current.postPlay || current.error || current.countdown === null) return stopCountdown();
// Native video can own keyboard focus while the webview is still on screen.
if (document.hidden || current.mini) return;
const remaining = Math.max(0, current.countdown - elapsed);
usePlayer.setState({ countdown: remaining });
if (remaining === 0) {
stopCountdown();
current.playNext();
}
}, 50);
const c = usePlayer.getState().countdown;
if (c === null || c < 0) return;
if (c <= 1) {
clearInterval(countdownTimer!);
countdownTimer = null;
usePlayer.getState().playNext();
} else usePlayer.setState({ countdown: c - 1 });
}, 1000);
}
function stopCountdown() {
if (countdownTimer) clearInterval(countdownTimer);
countdownTimer = null;
unwatchCountdown?.();
unwatchCountdown = null;
}
/**
* The tracks to play: a choice already made is kept ('' audio and '__init' subtitles
* mean none yet), otherwise the preferred audio language, then Plex's selection, then
* the file default; subtitles follow the subtitle mode.
*/
function preferredTracks(audio: Track[], subs: Track[], prefs: Preferences, audioKey = '', subKey = '__init') {
if (!audioKey) {
const lang = prefs.audioLanguage;
audioKey =
(lang && audio.find((t) => t.language === lang)?.key) ||
audio.find((t) => t.stream?.selected)?.key ||
audio.find((t) => t.stream?.default)?.key ||
audio[0]?.key ||
'';
}
if (subKey === '__init') {
const lang = prefs.subtitleLanguage || audio.find((t) => t.key === audioKey)?.language || '';
const inLang = subs.filter((t) => !lang || t.language === lang);
switch (prefs.subtitleMode) {
case 'off':
subKey = '';
break;
case 'always':
subKey = (inLang.find((t) => !t.forced) ?? inLang[0] ?? subs[0])?.key ?? '';
break;
case 'forced':
subKey = inLang.find((t) => t.forced)?.key ?? '';
break;
default:
subKey = subs.find((t) => t.stream?.selected)?.key ?? inLang.find((t) => t.forced)?.key ?? '';
}
}
return { audioKey, subKey };
}
type Selection = { audioStreamID?: string; subtitleStreamID?: string };
/** The item with Plex's stream selection updated locally to match `sel`. */
function withSelection(item: Item, mediaIndex: number, sel: Selection): Item {
const media = item.media.map((m, i) =>
i !== mediaIndex
? m
: {
...m,
parts: m.parts.map((p) => ({
...p,
streams: p.streams.map((x) =>
x.streamType === 2 && sel.audioStreamID !== undefined
? { ...x, selected: x.id === sel.audioStreamID }
: x.streamType === 3 && sel.subtitleStreamID !== undefined
? { ...x, selected: x.id === sel.subtitleStreamID }
: x,
),
})),
},
);
return { ...item, media };
}
const streamId = (tracks: Track[], key: string) => tracks.find((t) => t.key === key)?.stream?.id;
/**
* What Plex must be told so its selection on this media matches the given streams
* (subtitle '' is none, undefined leaves either as it is). Empty if it already does.
*/
function selectionFor(item: Item, mediaIndex: number, audioId: string | undefined, subId: string | undefined): Selection {
const streams = item.media[mediaIndex]?.parts.flatMap((p) => p.streams) ?? [];
const sel: Selection = {};
if (audioId && !streams.some((x) => x.streamType === 2 && x.selected && x.id === audioId)) sel.audioStreamID = audioId;
if (subId !== undefined && (streams.find((x) => x.streamType === 3 && x.selected)?.id ?? '') !== subId) sel.subtitleStreamID = subId || '0';
return sel;
}
/** Saves a track choice on the server; resolves to the item with that selection. */
async function saveSelection(s: PlexServer, item: Item, mediaIndex: number, sel: Selection): Promise<Item> {
const part = item.media[mediaIndex]?.parts[0];
if (!part || (sel.audioStreamID === undefined && sel.subtitleStreamID === undefined)) return item;
await api.selectStreams(s, part.id, sel);
return withSelection(item, mediaIndex, sel);
}
/** Saves a choice made during direct play, so other Plex apps (and a later conversion) use it too. */
function rememberSelection(st: PlayerState, audioId: string | undefined, subId: string | undefined) {
const s = server();
const { item, mediaIndex } = st;
if (!s || !item) return;
const sel = selectionFor(item, mediaIndex, audioId, subId);
saveSelection(s, item, mediaIndex, sel)
.then(() => {
const now = usePlayer.getState();
if (now.item?.id === item.id && now.mediaIndex === mediaIndex) usePlayer.setState({ item: withSelection(now.item, mediaIndex, sel) });
})
.catch(() => {});
}
/** Applies Plex/user track preferences once mpv has loaded the file. */
@ -497,7 +287,36 @@ async function applyInitialTracks(tracks: MpvTrack[]) {
if (!subs.length) subs = tracks.filter((t) => t.type === 'sub').map(mpvTrackLabel);
}
const { audioKey, subKey } = preferredTracks(audio, subs, prefs, st.audioKey, st.subKey);
// Audio: preferred language, else Plex's selection, else the file default.
let audioKey = st.audioKey;
if (!audioKey) {
const lang = prefs.audioLanguage;
audioKey =
(lang && audio.find((t) => t.language === lang)?.key) ||
audio.find((t) => t.stream?.selected)?.key ||
audio.find((t) => t.stream?.default)?.key ||
audio[0]?.key ||
'';
}
// Subtitles: follow the subtitle mode.
let subKey = st.subKey;
if (subKey === '__init') {
const lang = prefs.subtitleLanguage || audio.find((t) => t.key === audioKey)?.language || '';
const inLang = subs.filter((t) => !lang || t.language === lang);
switch (prefs.subtitleMode) {
case 'off':
subKey = '';
break;
case 'always':
subKey = (inLang.find((t) => !t.forced) ?? inLang[0] ?? subs[0])?.key ?? '';
break;
case 'forced':
subKey = inLang.find((t) => t.forced)?.key ?? '';
break;
default:
subKey = subs.find((t) => t.stream?.selected)?.key ?? inLang.find((t) => t.forced)?.key ?? '';
}
}
usePlayer.setState({ audioTracks: audio, subTracks: subs, audioKey, subKey });
if (direct) {
const a = audio.find((t) => t.key === audioKey);
@ -547,8 +366,6 @@ function onEvent(e: MpvEvent) {
break;
case 'paused-for-cache':
usePlayer.setState({ buffering: !!v });
// A stall can mean the server stopped the stream; its reply says so.
if (v && Date.now() - lastReport > 2000) report('buffering');
break;
case 'seeking':
usePlayer.setState({ seeking: !!v });
@ -601,7 +418,7 @@ function onEvent(e: MpvEvent) {
}
break;
case 'eof-reached':
if (v === true) onStreamEnd();
if (v === true) onEnded();
break;
}
break;
@ -618,18 +435,9 @@ function onEvent(e: MpvEvent) {
break;
case 'end-file':
if (e.reason === 'error') {
// A stream the server owner stopped can fail outright; don't retry that.
// (Briefly: an unreachable server shouldn't hold up the error.)
const failed = session;
Promise.race([report('buffering'), new Promise<boolean>((r) => setTimeout(() => r(false), 3000))]).then((terminated) => {
const now = usePlayer.getState();
if (terminated || !now.open || session !== failed) return;
// Partway through a stream that was playing, it's the connection that failed.
if (cutShort(now)) return onStreamEnd();
usePlayer.setState({ error: e.error ? `Playback failed: ${e.error}` : 'This video could not be played.' });
fallbackAfterError();
});
} else if (e.reason === 'eof') onStreamEnd();
usePlayer.setState({ error: e.error ? `Playback failed: ${e.error}` : 'This video could not be played.' });
fallbackAfterError();
} else if (e.reason === 'eof') onEnded();
break;
case 'log':
noteMpvLog(e.level, e.prefix, e.text);
@ -638,9 +446,6 @@ function onEvent(e: MpvEvent) {
}
}
/** The tracks playing now, to carry over when the same media restarts (a choice not made yet stays open). */
const currentTracks = (st: PlayerState) => ({ audioKey: st.audioKey, subKey: st.subKey });
/** Direct play failed: retry once through Plex's converter. */
let triedFallback = false;
function fallbackAfterError() {
@ -649,74 +454,14 @@ function fallbackAfterError() {
triedFallback = true;
toast('Direct playback failed. Asking Plex to convert this video.');
usePlayer.setState({ error: '' });
st.play(st.item, { offsetMs: st.position * 1000 || startOffsetMs, mediaIndex: st.mediaIndex, quality: '1080', tracks: currentTracks(st) });
st.play(st.item, { offsetMs: st.position * 1000 || startOffsetMs, mediaIndex: st.mediaIndex, quality: '1080' });
}
function maybeCredits(pos: number) {
const st = usePlayer.getState();
if (st.item?.type !== 'episode' || !st.firstFrame) return;
const inCredits = st.item.markers.some((m) => m.type === 'credits' && pos * 1000 >= m.start && pos * 1000 < m.end);
// Leaving the credits (seeking back into the episode) re-arms Up Next for the next time they start.
if (!inCredits) {
if (st.postPlayDismissed && !st.postPlay && !st.ended) usePlayer.setState({ postPlayDismissed: false });
} else if (!st.postPlayDismissed) openPostPlay();
}
/**
* A streamed title stopping well short of its end means the connection went
* (mpv plays out its buffer, then sees the cut-off stream as the end of the file).
*/
const CUT_SHORT_MARGIN = 15;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
/** Where the last cut-off happened, so a file that really does end early isn't retried forever. */
let lastCutAt: number | null = null;
function cutShort(st: PlayerState) {
return st.delivery?.mode !== 'local' && st.firstFrame && st.duration > 0 && st.position < st.duration - CUT_SHORT_MARGIN;
}
/** The stream ran out: a real ending, or a lost connection to wait out. */
function onStreamEnd() {
const st = usePlayer.getState();
if (!cutShort(st)) return onEnded();
if (st.reconnecting || st.ended) return;
// Cut off at the same place again once the server answered: the file itself ends there.
if (lastCutAt !== null && Math.abs(st.position - lastCutAt) < 5) return onEnded();
lastCutAt = st.position;
usePlayer.setState({ reconnecting: true, buffering: false });
keepAwake(false);
scheduleReconnect(2000);
}
function stopReconnecting() {
if (reconnectTimer) clearTimeout(reconnectTimer);
reconnectTimer = null;
}
function scheduleReconnect(delay: number) {
stopReconnecting();
reconnectTimer = setTimeout(() => void tryReconnect(), delay);
}
/** Resumes where the stream was cut off if the server answers; otherwise checks again shortly. */
async function tryReconnect(): Promise<boolean> {
stopReconnecting();
const st = usePlayer.getState();
const s = server();
if (!st.open || !st.reconnecting || !st.item || !s) return false;
const reachable = await s.get('/identity', undefined, { timeout: 4000 }).then(
() => true,
() => false,
);
const now = usePlayer.getState();
if (!now.open || !now.reconnecting || now.item?.id !== st.item.id) return false;
if (!reachable) {
scheduleReconnect(3000);
return false;
}
usePlayer.setState({ reconnecting: false });
await now.play(now.item, { offsetMs: now.position * 1000, mediaIndex: now.mediaIndex, quality: now.quality, tracks: currentTracks(now), keepMini: true });
return true;
if (st.item?.type !== 'episode' || !st.nextUp || st.countdown !== null) return;
const credits = st.item.markers.find((m) => m.type === 'credits' && (m.final || m.end >= st.item!.duration - 5000));
if (credits && pos * 1000 >= credits.start && pos * 1000 < credits.end && useSettings.getState().skipCredits !== 'off') startCountdown();
}
function onEnded() {
@ -725,11 +470,7 @@ function onEnded() {
usePlayer.setState({ ended: true });
report('stopped');
checkScrobble();
// Reaching the end always offers Up Next, as on Android, even after watching the credits.
if (st.item?.type === 'episode' && !st.postPlay) {
usePlayer.setState({ postPlayDismissed: false });
openPostPlay();
}
if (st.nextUp) startCountdown();
}
export const usePlayer = create<PlayerState>((set, get) => ({
@ -740,15 +481,12 @@ export const usePlayer = create<PlayerState>((set, get) => ({
quality: 'original',
firstFrame: false,
error: '',
terminated: false,
reconnecting: false,
position: 0,
duration: 0,
cacheTime: 0,
paused: false,
buffering: false,
seeking: false,
lastSeek: 0,
volume: 100,
muted: false,
speed: 1,
@ -761,11 +499,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
video: null,
ended: false,
nextUp: null,
prevUp: null,
episodeContextReady: false,
countdown: null,
countdownTotal: 0,
postPlay: false,
postPlayDismissed: false,
fullscreen: false,
mini: false,
@ -775,8 +509,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
async play(input, opts = {}) {
const token = ++loadToken;
// Closing or starting something else while this one is still setting up wins.
const stale = () => token !== loadToken;
const s = server();
const prefs = useSettings.getState();
stopThemeMusic();
stopCountdown();
@ -785,59 +518,36 @@ export const usePlayer = create<PlayerState>((set, get) => ({
return;
}
const previous = get();
stopReconnecting();
if (previous.item?.id !== input.id) lastCutAt = null;
// The previous title's reporting ends here, against its own server.
if (reportTimer) clearInterval(reportTimer);
reportTimer = null;
if (previous.open && previous.item) {
report('stopped');
const ps = server();
if (previous.delivery?.session && ps) stopTranscode(ps, previous.delivery.session);
if (previous.delivery?.session && s) stopTranscode(s, previous.delivery.session);
}
session = '';
const current = useSession.getState().server;
const download = opts.localFile ? (useDownloads.getState().items.find((d) => d.filePath === opts.localFile) ?? null) : null;
const s = opts.localFile ? (current && download && current.machineId === download.meta.serverId ? current : null) : current;
playServer = s;
playDownload = download;
localScrobbled = false;
// From the miniplayer the window may have gone full screen (or left it) since.
const fullscreenNow = await win.isFullscreen().catch(() => false);
if (stale()) return;
if (!previous.open) {
triedFallback = false;
wasFullscreenBeforePlay = fullscreenNow;
wasFullscreenBeforePlay = await win.isFullscreen().catch(() => false);
}
set({
open: true,
item: input,
firstFrame: false,
error: '',
terminated: false,
reconnecting: false,
position: (opts.offsetMs ?? 0) / 1000,
lastSeek: 0,
duration: input.duration / 1000,
cacheTime: 0,
paused: false,
buffering: true,
ended: false,
nextUp: null,
prevUp: null,
episodeContextReady: false,
countdown: null,
countdownTotal: 0,
postPlay: false,
postPlayDismissed: false,
chapters: [],
audioTracks: [],
subTracks: [],
audioKey: opts.tracks?.audioKey ?? '',
subKey: opts.tracks?.subKey ?? '__init',
audioKey: '',
subKey: '__init',
video: null,
fullscreen: fullscreenNow,
mini: opts.keepMini ? previous.open && previous.mini : false,
fullscreen: wasFullscreenBeforePlay,
mini: false,
videoGamma: '',
enhance: { ...previous.enhance, bypass: false, preparing: false },
});
@ -848,16 +558,15 @@ export const usePlayer = create<PlayerState>((set, get) => ({
if (!opts.localFile && s && (!input.media.length || !input.media[0].parts[0]?.streams.length || !input.raw?.Marker)) {
item = await api.metadata(s, input.id).catch(() => input);
}
if (stale()) return;
if (token !== loadToken) return;
const mediaIndex = Math.min(opts.mediaIndex ?? 0, Math.max(0, item.media.length - 1));
let media = item.media[mediaIndex];
const media = item.media[mediaIndex];
let offsetMs = opts.offsetMs ?? (opts.resume !== false && item.viewOffset && item.viewOffset < item.duration * 0.97 ? item.viewOffset : 0);
startOffsetMs = offsetMs;
const local = useSession.getState().connection?.local ?? true;
const quality: Quality = opts.quality ?? (local ? prefs.quality : prefs.remoteQuality);
const streams = media?.parts.flatMap((p) => p.streams) ?? [];
const audioTracks = streams.filter((x) => x.streamType === 2).map(audioTrackFromStream);
const subTracks = streams.filter((x) => x.streamType === 3).map(subTrackFromStream);
let tracks: { audioKey: string; subKey: string } | null = null;
session = crypto.randomUUID();
scrobbled = false;
let delivery: Delivery;
if (opts.localFile) {
@ -867,77 +576,44 @@ export const usePlayer = create<PlayerState>((set, get) => ({
} else if (quality === 'original') {
delivery = { url: directUrl(s, media), mode: 'direct', label: 'Original', absoluteTime: false };
} else {
// Plex converts (and burns in) the tracks selected on the server, so the chosen
// ones are saved there before the conversion starts, not after.
tracks = preferredTracks(audioTracks, subTracks, prefs, opts.tracks?.audioKey, opts.tracks?.subKey);
const audioStreamID = streamId(audioTracks, tracks.audioKey);
const subtitleStreamID = streamId(subTracks, tracks.subKey) ?? '';
const base = item;
item = await saveSelection(s, base, mediaIndex, selectionFor(base, mediaIndex, audioStreamID, subtitleStreamID)).catch(() => base);
if (stale()) return;
media = item.media[mediaIndex];
const tsession = crypto.randomUUID();
delivery = {
url: transcodeUrl(s, item, { mediaIndex, quality, offsetMs, session: tsession, local, audioStreamID, subtitleStreamID: subtitleStreamID || undefined }),
url: transcodeUrl(s, item, { mediaIndex, quality, offsetMs, session: tsession, local }),
mode: 'transcode',
session: tsession,
label: quality === '2160' ? '4K' : `${quality}p`,
absoluteTime: true,
};
}
startOffsetMs = offsetMs;
session = crypto.randomUUID();
sessionAnswered = false;
scrobbled = false;
const streams = media?.parts.flatMap((p) => p.streams) ?? [];
set({
item,
delivery,
mediaIndex,
quality,
duration: (item.duration || media?.duration || 0) / 1000,
audioTracks,
subTracks,
...(tracks ?? {}),
});
findNeighbours(item).then((n) => {
if (token !== loadToken) return;
set({ ...n, episodeContextReady: true });
const current = get();
if (current.postPlay) startCountdown();
else if (current.ended) openPostPlay();
else maybeCredits(current.position);
audioTracks: streams.filter((x) => x.streamType === 2).map(audioTrackFromStream),
subTracks: streams.filter((x) => x.streamType === 3).map(subTrackFromStream),
});
await mpv.init({ hwdec: prefs.hwdec, hdr: prefs.hdrPassthrough });
if (!unlisten) unlisten = await mpv.on(onEvent);
if (stale()) return;
// mpv keeps pause across files: a title paused and closed would start paused.
await mpv.set('pause', false);
if (token !== loadToken) return;
await mpv.set('mute', false);
await mpv.set('volume', sliderToMpv(prefs.volume));
await mpv.set('speed', 1);
await mpv.set('audio-delay', 0);
await applySubtitleStyle(prefs);
if (stale()) return;
followVideoSize();
await requestEnhancement();
if (stale()) return;
watchPerformance(true);
await mpv.set('force-media-title', item.type === 'episode' ? `${item.grandparentTitle} — ${item.title}` : item.title);
if (stale()) return;
await mpv.show(true);
if (stale()) return;
const fileOpts = [
delivery.mode === 'transcode' ? 'rebase-start-time=no' : 'rebase-start-time=yes',
offsetMs > 0 && delivery.mode !== 'transcode' ? `start=${(offsetMs / 1000).toFixed(2)}` : 'start=none',
].join(',');
await mpv.command('loadfile', delivery.url, 'replace', -1, fileOpts);
// A file left paused at its end (keep-open) re-pauses as soon as it's unpaused
// above, so a reload in place (after an outage) would open paused: unpause again.
await mpv.set('pause', false);
if (stale()) return;
keepAwake(true);
report('buffering');
reportTimer && clearInterval(reportTimer);
@ -945,6 +621,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
const st = get();
if (st.open && !st.ended) report(st.paused ? 'paused' : st.buffering ? 'buffering' : 'playing');
}, 10000);
findNext(item).then((next) => token === loadToken && set({ nextUp: next }));
} catch (e: any) {
if (token !== loadToken) return;
set({ error: e?.message ?? String(e), buffering: false });
@ -955,44 +632,25 @@ export const usePlayer = create<PlayerState>((set, get) => ({
loadToken++;
const st = get();
stopCountdown();
stopReconnecting();
lastCutAt = null;
if (reportTimer) clearInterval(reportTimer);
reportTimer = null;
if (st.item && !st.error) report('stopped');
const s = server();
if (st.delivery?.session && s) stopTranscode(s, st.delivery.session);
// Nothing more is reported for this playback, whatever mpv says while it stops.
session = '';
playServer = null;
playDownload = null;
keepAwake(false);
watchPerformance(false);
if (isNative) {
// From the miniplayer window, the video goes home first (and stays hidden).
if (separateMini && st.mini) await hideMiniWindow();
await mpv.command('stop').catch(() => {});
await mpv.show(false).catch(() => {});
}
set({ open: false, mini: false, postPlay: false, item: null, delivery: null, error: '', terminated: false, reconnecting: false, countdown: null, nextUp: null, prevUp: null, firstFrame: false });
// Closing the full player hands back the window it found; closing the
// miniplayer leaves browsing as it is, full screen or not.
if (!st.mini) {
const fs = await win.isFullscreen().catch(() => false);
if (fs && !wasFullscreenBeforePlay) win.setFullscreen(false);
}
set({ open: false, mini: false, item: null, delivery: null, error: '', countdown: null, nextUp: null, firstFrame: false });
const fs = await win.isFullscreen().catch(() => false);
if (fs && !wasFullscreenBeforePlay) win.setFullscreen(false);
if (st.item) invalidateLibrary();
},
togglePause() {
const st = get();
// Play while the server is away: try it now rather than at the next check.
if (st.reconnecting) {
tryReconnect().then((resumed) => {
if (!resumed && get().reconnecting) toast(`Still can’t reach ${server()?.name ?? 'the server'}.`);
});
return;
}
if (st.ended) {
st.seek(0);
set({ ended: false });
@ -1003,8 +661,11 @@ export const usePlayer = create<PlayerState>((set, get) => ({
seek(seconds) {
const st = get();
const target = Math.max(0, Math.min(seconds, (st.duration || seconds) - 0.5));
set({ position: target, ended: false, lastSeek: Date.now() });
if (st.postPlay) st.dismissPostPlay();
set({ position: target, ended: false });
if (st.countdown !== null) {
stopCountdown();
set({ countdown: null });
}
mpv.command('seek', target.toFixed(3), 'absolute+exact').catch(() => {});
},
@ -1040,22 +701,16 @@ export const usePlayer = create<PlayerState>((set, get) => ({
async minimize() {
const st = get();
if (!st.open || st.mini) return;
if (st.postPlay) st.dismissPostPlay();
// Full screen stays for browsing; Esc or the window controls leave it.
set({ mini: true });
if (separateMini) {
// Once the page is opaque again (no video in it), the video moves into
// the miniplayer's own window (miniWindow.ts).
await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
if (get().open && get().mini) await showMiniWindow().catch((e) => console.warn('[mini]', e));
// Full screen was for the video; browsing goes back to the window.
if (st.fullscreen && !wasFullscreenBeforePlay) {
await win.setFullscreen(false).catch(() => {});
set({ fullscreen: false });
}
},
expand() {
if (!get().mini) return;
// The video comes back behind the still-opaque page before it turns transparent.
if (separateMini) hideMiniWindow().finally(() => set({ mini: false }));
else set({ mini: false });
if (get().mini) set({ mini: false });
},
async selectAudio(key) {
@ -1063,30 +718,35 @@ export const usePlayer = create<PlayerState>((set, get) => ({
const t = st.audioTracks.find((x) => x.key === key);
if (!t) return;
set({ audioKey: key });
const s = server();
const part = st.item?.media[st.mediaIndex]?.parts[0];
if (s && part && t.stream) api.selectStreams(s, part.id, { audioStreamID: t.stream.id }).catch(() => {});
if (st.delivery?.mode === 'transcode' && st.item) {
// The restart saves the choice on the server before converting with it.
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality, tracks: { ...currentTracks(st), audioKey: key } });
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality });
return;
}
if (t.mpvId) await mpv.set('aid', t.mpvId).catch(() => {});
rememberSelection(st, t.stream?.id, undefined);
},
async selectSubtitle(key) {
const st = get();
set({ subKey: key });
const s = server();
const part = st.item?.media[st.mediaIndex]?.parts[0];
const t = st.subTracks.find((x) => x.key === key);
if (s && part) api.selectStreams(s, part.id, { subtitleStreamID: t?.stream?.id ?? '0' }).catch(() => {});
if (st.delivery?.mode === 'transcode' && st.item) {
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality, tracks: { ...currentTracks(st), subKey: key } });
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality });
usePlayer.setState({ subKey: key });
return;
}
await setMpvSubtitle(key);
rememberSelection(st, undefined, streamId(st.subTracks, key) ?? '');
},
async setQuality(q) {
const st = get();
if (!st.item || q === st.quality) return;
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: q, tracks: currentTracks(st) });
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: q });
},
async selectVersion(index) {
@ -1099,15 +759,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
const st = get();
stopCountdown();
if (!st.nextUp) return;
// Watching on through a season starts each episode from the top, never at a
// stale position left by an earlier, unfinished viewing.
await st.play(st.nextUp, { resume: false, quality: st.quality });
},
async playPrevious() {
const st = get();
if (!st.prevUp) return;
await st.play(st.prevUp, { resume: false, quality: st.quality });
await st.play(st.nextUp, { resume: true, quality: st.quality });
},
cancelCountdown() {
@ -1115,17 +767,6 @@ export const usePlayer = create<PlayerState>((set, get) => ({
set({ countdown: null, postPlayDismissed: true });
},
showPostPlay() {
// A deliberate Skip credits can reopen a screen previously dismissed.
set({ postPlayDismissed: false });
openPostPlay();
},
dismissPostPlay() {
stopCountdown();
set({ countdown: null, postPlay: false, postPlayDismissed: true });
},
async toggleFullscreen() {
const fs = await win.isFullscreen().catch(() => false);
await win.setFullscreen(!fs);
@ -1147,44 +788,13 @@ export const usePlayer = create<PlayerState>((set, get) => ({
usePlayer.subscribe((st, prev) => {
if (st.firstFrame !== prev.firstFrame || st.open !== prev.open || st.error !== prev.error || st.mini !== prev.mini) {
const html = document.documentElement.classList;
// With a miniplayer window, the video has left this page entirely.
html.toggle('video-active', st.open && st.firstFrame && !st.error && !(st.mini && separateMini));
html.toggle('video-active', st.open && st.firstFrame && !st.error);
html.toggle('player-open', st.open && !st.mini);
html.toggle('player-mini', st.open && st.mini);
}
// However the miniplayer is left (expanding, playing another title, closing),
// the video returns to the whole window.
if (prev.mini && !st.mini && isNative) {
if (separateMini) hideMiniWindow();
else mpv.rect(null).catch(() => {});
}
});
bridgeMiniWindow(usePlayer);
// Full screen can change outside the player (Esc or the window controls while
// browsing with the miniplayer, the OS): the player's controls follow it.
win.onResized(() => {
if (!usePlayer.getState().open) return;
win.isFullscreen().then((fs) => usePlayer.getState().fullscreen !== fs && usePlayer.setState({ fullscreen: fs }), () => {});
});
/**
* Signing out, or switching server or profile, ends a stream from the old one: its
* progress belongs to that account. A download keeps playing, without reporting.
* A reconnect to the same server with the same credentials carries on.
*/
useSession.subscribe((st, prev) => {
const old = prev.server;
if (!old || st.server === old) return;
const same = !!st.server && st.server.machineId === old.machineId && st.server.token === old.token;
if (playServer !== old) return;
if (same) {
playServer = st.server;
return;
}
if (usePlayer.getState().open && !playDownload) usePlayer.getState().close();
playServer = null;
if (prev.mini && !st.mini && isNative) mpv.rect(null).catch(() => {});
});
/** Subtitle look changes apply to the playing video straight away. */

View file

@ -1,5 +1,5 @@
import { arr, bool, num, str } from './parse';
import { clientIdentifier, DEVICE, PLATFORM, PlexError, plexRequest, PRODUCT } from './client';
import { clientIdentifier, PlexError, plexRequest, PRODUCT } from './client';
import type { HomeUser, PlexUser, ServerConnection, ServerResource } from './types';
const TV = 'https://plex.tv/api/v2';
@ -26,8 +26,8 @@ export function authUrl(pin: Pin): string {
clientID: clientIdentifier(),
code: pin.code,
'context[device][product]': PRODUCT,
'context[device][platform]': PLATFORM,
'context[device][device]': DEVICE,
'context[device][platform]': 'Windows',
'context[device][device]': 'Windows',
});
return `https://app.plex.tv/auth#?${params.toString()}`;
}

View file

@ -151,7 +151,7 @@ export interface BandwidthPoint {
wan: number;
}
/** Bandwidth samples grouped by time (timespan 6: bytes in each second, idle seconds omitted). */
/** Bandwidth samples grouped by time (bytes per sample interval). */
export async function bandwidth(s: PlexServer, timespan = 6): Promise<{ points: BandwidthPoint[]; devices: Record<number, string> }> {
const mc = await s.container('/statistics/bandwidth', { timespan });
const byAt = new Map<number, BandwidthPoint>();

View file

@ -1,9 +1,7 @@
import { hostOS, httpFetch } from '../platform/native';
import { httpFetch } from '../platform/native';
export const PRODUCT = 'Kaleido';
/** 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 const PLATFORM = 'Windows';
export class PlexError extends Error {
constructor(
@ -16,8 +14,7 @@ export class PlexError extends Error {
let clientId = '';
let version = '0.1.0';
let deviceName = hostOS === 'macos' ? 'Mac' : 'Windows PC';
let platformVersion = hostOS === 'windows' ? '11' : '';
let deviceName = 'Windows PC';
/** A stable, random identifier for this installation (not secret). */
export function clientIdentifier(): string {
@ -30,24 +27,9 @@ export function clientIdentifier(): string {
return clientId;
}
export function configureClient(opts: { version?: string; deviceName?: string; platformVersion?: string }) {
export function configureClient(opts: { version?: string; deviceName?: string }) {
if (opts.version) version = opts.version;
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> {
@ -57,9 +39,9 @@ export function plexHeaders(token?: string | null): Record<string, string> {
'X-Plex-Version': version,
'X-Plex-Client-Identifier': clientIdentifier(),
'X-Plex-Platform': PLATFORM,
'X-Plex-Platform-Version': platformVersion,
'X-Plex-Device': DEVICE,
'X-Plex-Device-Name': headerSafe(`Kaleido (${deviceName})`),
'X-Plex-Platform-Version': '11',
'X-Plex-Device': 'Windows',
'X-Plex-Device-Name': `Kaleido (${deviceName})`,
'X-Plex-Model': 'Desktop',
'X-Plex-Provides': 'player',
'X-Plex-Language': navigator.language || 'en',
@ -75,7 +57,7 @@ export function plexQuery(token?: string | null): Record<string, string> {
'X-Plex-Version': version,
'X-Plex-Client-Identifier': clientIdentifier(),
'X-Plex-Platform': PLATFORM,
'X-Plex-Device': DEVICE,
'X-Plex-Device': 'Windows',
'X-Plex-Device-Name': `Kaleido (${deviceName})`,
};
if (token) q['X-Plex-Token'] = token;
@ -121,41 +103,23 @@ export async function plexRequest<T = any>(url: string, token: string | null | u
const timer = setTimeout(() => controller.abort(), opts.timeout ?? 30000);
const onAbort = () => controller.abort();
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 text: string;
try {
try {
response = await Promise.race([
httpFetch(withParams(url, opts.params), {
method: opts.method ?? 'GET',
headers: { ...plexHeaders(token), ...opts.headers },
body: opts.body ?? undefined,
signal: controller.signal,
}),
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);
}
response = await httpFetch(withParams(url, opts.params), {
method: opts.method ?? 'GET',
headers: { ...plexHeaders(token), ...opts.headers },
body: opts.body ?? undefined,
signal: controller.signal,
});
} 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);
} finally {
clearTimeout(timer);
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 (!text.trim()) return {} as T;
try {

View file

@ -39,10 +39,6 @@ export function transcodeUrl(
path: `/library/metadata/${item.id}`,
mediaIndex: opts.mediaIndex,
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',
session: opts.session,
offset: (opts.offsetMs / 1000).toFixed(1),
@ -84,12 +80,6 @@ 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)}`);
}
/** 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(
server: PlexServer,
item: Item,
@ -97,8 +87,8 @@ export async function reportTimeline(
timeMs: number,
session: string,
extra: Record<string, string | number> = {},
): Promise<TimelineReply> {
return server.container(
) {
await server.get(
'/:/timeline',
{
ratingKey: item.id,

View file

@ -2,8 +2,7 @@ import { describe, expect, it } from 'vitest';
import { parseItem, parseScores } from './parse';
import { isLocalAddress } from './account';
import { partAt } from './playback';
import { headerSafe } from './client';
import { duration, formatBadges, isWatched, remaining, resumable, washGradient } from '../app/format';
import { duration, formatBadges, isWatched, remaining, washGradient } from '../app/format';
import { buildFeatures } from '../screens/discover';
import type { Hub } from './types';
@ -65,16 +64,10 @@ describe('parsing', () => {
});
describe('watched rules', () => {
it('keeps a title watched while it is being rewatched', () => {
expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 90)).toBe(true);
it('treats a resumed title as watched only past the threshold', () => {
expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 90)).toBe(false);
expect(isWatched(movie({ viewCount: 1, viewOffset: 5700000 }), 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', () => {
@ -119,10 +112,3 @@ describe('features', () => {
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");
});
});

View file

@ -174,7 +174,7 @@ export default function Downloads({ offline }: { offline?: boolean }) {
{!isNative && (
<div className="downloads-empty">
<EmptyState icon="download" title="Downloads need the desktop app">
Install the Kaleido desktop app to save movies and episodes for offline viewing.
Install Kaleido for Windows to save movies and episodes for offline viewing.
</EmptyState>
</div>
)}

View file

@ -1,7 +1,7 @@
import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import * as api from '../plex/api';
import { PROGRESS, WATCH_STATE, useSections, useServerQuery } from '../app/queries';
import { useSections, useServerQuery } from '../app/queries';
import { useServer } from '../app/session';
import { navigate } from '../app/router';
import { Hero } from '../ui/Hero';
@ -14,8 +14,8 @@ export function Home() {
const sections = useSections();
const video = (sections.data ?? []).filter((s) => (s.type === 'movie' || s.type === 'show') && !s.hidden);
const home = useServerQuery(['homeHubs'], (s) => api.homeHubs(s), WATCH_STATE);
const continueWatching = useServerQuery(['continue'], (s) => api.continueWatching(s), PROGRESS);
const home = useServerQuery(['homeHubs'], (s) => api.homeHubs(s));
const continueWatching = useServerQuery(['continue'], (s) => api.continueWatching(s), { staleTime: 15_000 });
// Section hubs feed the hero and the release shelves; shared with Discover.
const sectionHubs = useQuery({
queryKey: [server.machineId, 'sectionHubsAll', video.map((s) => s.id).join(',')],

View file

@ -1,15 +1,15 @@
import { useEffect, useMemo, useState, type ReactNode } from 'react';
import * as api from '../plex/api';
import type { Item } from '../plex/types';
import { PROGRESS, useChildren, useItem, useRelated, useServerQuery } from '../app/queries';
import { useChildren, useItem, useRelated, useServerQuery } from '../app/queries';
import { useServer } from '../app/session';
import { useSettings } from '../app/settings';
import { goBack, navigate } from '../app/router';
import { canManage, itemMenu, openDialog, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions';
import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, remainingEpisodes, resolutionLabel, resumable, technicalLine } from '../app/format';
import { goBack, navigate, useRouter } from '../app/router';
import { canManage, itemMenu, openDialog, openItem, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions';
import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, resolutionLabel, technicalLine } from '../app/format';
import { Backdrop } from '../ui/Backdrop';
import { EpisodeCard, Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media';
import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader } from '../ui/primitives';
import { Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media';
import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader, Select } from '../ui/primitives';
import { Icon } from '../ui/Icon';
import { openMenu } from '../ui/overlays';
import { useDownloads } from '../downloads/store';
@ -255,12 +255,11 @@ function AboutPanel({ item }: { item: Item }) {
// —— Movie ——————————————————————————————————————————————————————————
function MovieDetail({ item }: { item: Item }) {
const resume = resumable(item);
const resume = item.viewOffset > 0 && !isWatched(item);
return (
<div className="detail movie">
<DetailHero item={item}>
{/* The Resume button carries the time left; the facts give the runtime. */}
<Facts item={{ ...item, viewOffset: 0 }} />
<Facts item={item} />
<Synopsis item={item} text={item.summary} />
<div className="actions detail-actions">
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
@ -299,75 +298,115 @@ function MovieDetail({ item }: { item: Item }) {
// —— Shows and seasons ————————————————————————————————————————————
function EpisodeGrid({ episodes, upNextId }: { episodes: Item[] | undefined; upNextId?: string }) {
if (!episodes) return <PageLoader />;
if (!episodes.length) return <EmptyState icon="tv" title="No episodes" />;
function EpisodeRow({ ep }: { ep: Item }) {
const server = useServer();
const percent = useSettings((s) => s.watchedPercent);
const watched = isWatched(ep, percent);
const p = ep.viewOffset && ep.duration ? ep.viewOffset / ep.duration : 0;
return (
<div className="episode-grid">
{episodes.map((ep) => (
<EpisodeCard key={ep.id} item={ep} upNext={ep.id === upNextId} />
))}
<div
className="episode-row"
role="button"
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>
);
}
function EpisodesSection({ episodes, subtitle, upNextId }: { episodes: Item[] | undefined; subtitle?: string; upNextId?: string }) {
function Episodes({ seasons, initialSeason, showPicker = true }: { seasons: Item[]; initialSeason?: string; showPicker?: boolean }) {
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 (
<section className="episodes">
<div className="shelf-head">
<h2>
Episodes
{subtitle && <small>{subtitle}</small>}
</h2>
<div className="episodes-head">
<h2>Episodes</h2>
{showPicker && seasons.length > 1 && (
<Select
value={seasonId!}
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>
<EpisodeGrid episodes={episodes} upNextId={upNextId} />
</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 }) {
const seasons = useChildren(item.id);
const next = useServerQuery(['onDeck', item.id], (s) => api.onDeckFor(s, item), PROGRESS);
const server = useServer();
const next = useServerQuery(['onDeck', item.id], (s) => api.onDeckFor(s, item), { staleTime: 15_000 });
const nextEp = next.data;
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 playLabel = nextEp ? (resumable(nextEp) ? `Resume ${episodeLabel(nextEp)}` : isWatched(item, percent) ? 'Play' : item.viewedLeafCount ? `Watch ${episodeLabel(nextEp)}` : 'Play') : 'Play';
const playLabel = nextEp ? (nextEp.viewOffset ? `Resume ${episodeLabel(nextEp)}` : isWatched(item, percent) ? 'Play' : item.viewedLeafCount ? `Watch ${episodeLabel(nextEp)}` : 'Play') : 'Play';
void server;
return (
<div className="detail show">
<DetailHero item={item}>
@ -385,16 +424,14 @@ function ShowDetail({ item }: { item: Item }) {
<DownloadButton item={item} />
<MoreButton item={item} onDeleted={goBack} />
</div>
{/* The button names the episode number; this adds its title, and the time left when resuming. */}
{nextEp && (
<div className="detail-tech">
Up next: {[nextEp.title, resumable(nextEp) ? remaining(nextEp) : ''].filter(Boolean).join(' · ')}
Up next: {episodeLabel(nextEp)} · {nextEp.title}
</div>
)}
</DetailHero>
<div className="detail-body">
<div className="detail-main">
{seasons.isLoading && <PageLoader />}
{seasonList.length > 1 && (
<Shelf title="Seasons">
{seasonList.map((s) => (
@ -402,7 +439,7 @@ function ShowDetail({ item }: { item: Item }) {
))}
</Shelf>
)}
{only && <EpisodesSection episodes={onlyEpisodes.data} subtitle={seasonSubtitle(only)} upNextId={nextEp?.id} />}
{seasons.isLoading ? <PageLoader /> : <Episodes seasons={seasonList} initialSeason={nextEp?.parentId} />}
<CastRow item={item} />
<ExtrasRow item={item} />
<RelatedRows item={item} />
@ -415,21 +452,12 @@ function ShowDetail({ item }: { item: Item }) {
function SeasonDetail({ item }: { item: Item }) {
const show = useItem(item.parentId);
const showItem = show.data;
const episodes = useChildren(item.id);
const siblings = useChildren(item.parentId);
const seasonList = (siblings.data ?? []).filter((s) => s.type === 'season');
const deck = useServerQuery(['onDeck', item.parentId], (s) => (showItem ? api.onDeckFor(s, showItem) : Promise.resolve(null)), { ...PROGRESS, enabled: !!showItem });
const episodes = useChildren(item.id);
const percent = useSettings((s) => s.watchedPercent);
const list = episodes.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;
const next = (episodes.data ?? []).find((e) => !isWatched(e, percent)) ?? episodes.data?.[0];
const showItem = show.data;
return (
<div className="detail season">
<DetailHero
@ -444,15 +472,15 @@ function SeasonDetail({ item }: { item: Item }) {
) : (
<h2 className="title-text small">{item.parentTitle}</h2>
)}
<SeasonSwitcher season={item} seasons={seasonList} />
<h1 className="detail-subtitle">{item.title}</h1>
</>
}
>
<Facts item={{ ...item, year, contentRating: showItem?.contentRating ?? item.contentRating, genres: [] }} />
<Facts item={{ ...item, contentRating: showItem?.contentRating ?? item.contentRating, genres: [] }} />
<Synopsis item={item} text={item.summary || showItem?.summary || ''} />
<div className="actions detail-actions">
<Button variant="primary" icon="play" disabled={!next} onClick={() => next && playWithVersion(next, resumeNext ? {} : { offsetMs: 0, resume: false })}>
{next ? `${resumeNext ? 'Resume' : 'Play'} ${episodeLabel(next)}` : 'Play'}
<Button variant="primary" icon="play" disabled={!next} onClick={() => next && playWithVersion(next)}>
{next ? (next.viewOffset ? `Resume ${episodeLabel(next)}` : `Play ${episodeLabel(next)}`) : 'Play'}
</Button>
<WatchedButton item={item} />
<DownloadButton item={item} />
@ -461,7 +489,7 @@ function SeasonDetail({ item }: { item: Item }) {
</DetailHero>
<div className="detail-body single">
<div className="detail-main">
<EpisodesSection episodes={episodes.data} subtitle={seasonSubtitle(item)} upNextId={resumeNext ? next?.id : undefined} />
<Episodes seasons={seasonList.length ? seasonList : [item]} initialSeason={item.id} />
{showItem && <CastRow item={showItem} />}
</div>
</div>
@ -472,7 +500,7 @@ function SeasonDetail({ item }: { item: Item }) {
function EpisodeDetail({ item }: { item: Item }) {
const show = useItem(item.grandparentId);
const siblings = useChildren(item.parentId);
const resume = resumable(item);
const resume = item.viewOffset > 0 && !isWatched(item);
const showItem = show.data;
const others = (siblings.data ?? []).filter((e) => e.id !== item.id);
const startIndex = Math.max(0, (siblings.data ?? []).findIndex((e) => e.id === item.id));
@ -495,7 +523,7 @@ function EpisodeDetail({ item }: { item: Item }) {
</>
}
>
<Facts item={{ ...item, viewOffset: 0, contentRating: item.contentRating || showItem?.contentRating || '' }} />
<Facts item={{ ...item, contentRating: item.contentRating || showItem?.contentRating || '' }} />
<Synopsis item={item} text={item.summary} />
<div className="actions detail-actions">
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>

View file

@ -236,33 +236,6 @@ function LibraryGrid({ section, type, sort, filters, title, sortTitle }: { secti
loadPage(0);
}, [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 target = CARD_WIDTH[posterSize];
const cols = Math.max(2, Math.floor((width + gap) / (target + gap)));

View file

@ -1,6 +1,6 @@
import { useMemo } from 'react';
import * as api from '../plex/api';
import { PROGRESS, useSectionFor, useServerQuery } from '../app/queries';
import { useSectionFor, useServerQuery } from '../app/queries';
import { navigate, useRouter, type SectionKind, type SectionTab } from '../app/router';
import { useSettings } from '../app/settings';
import type { Section } from '../plex/types';
@ -46,7 +46,7 @@ function SectionHeader({ kind, tab, section, all, overlay }: { kind: SectionKind
function Discover({ kind, section }: { kind: SectionKind; section: Section }) {
const hubs = useServerQuery(['sectionHubs', section.id], (s) => api.sectionHubs(s, section.id));
const cw = useServerQuery(['continue', section.id], (s) => api.continueWatching(s, section.id), PROGRESS);
const cw = useServerQuery(['continue', section.id], (s) => api.continueWatching(s, section.id), { staleTime: 15_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]);

View file

@ -2,11 +2,11 @@ import { useEffect, useRef } from 'react';
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`).
* The cold-start brand sequence, the same as Kaleido for TV: a closed iris lit
* from behind twists open, light catches the facets and the wordmark slides out
* of the mark. Once startup is ready the camera flies through the aperture's
* dark centre, revealing the app drawn beneath (which settles from a slight
* zoom, `html.splash-arrival`).
*/
type Point = { x: number; y: number };
@ -41,83 +41,73 @@ 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);
// A mechanical iris: the blades gather, snap open and overshoot slightly as they lock.
const IrisOpen = bezier(0.55, 0, 0.15, 1);
const IrisTwist = bezier(0.5, 0, 0.18, 1.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 = [
[33, 4, 55.5, 17, 42.5, 24.5, 33, 19],
[56.5, 19, 56.5, 45, 43.5, 37.5, 43.5, 26.5],
[55.5, 47, 33, 60, 33, 45, 42.5, 39.5],
[31, 60, 8.5, 47, 21.5, 39.5, 31, 45],
[7.5, 45, 7.5, 19, 20.5, 26.5, 20.5, 37.5],
[8.5, 17, 31, 4, 31, 19, 21.5, 24.5],
].map((pts, i) => {
// outward normal of its hexagon edge for the iris motion.
const FACETS = (
[
[[33, 4, 55.5, 17, 42.5, 24.5, 33, 19], '#C3E8D3'],
[[56.5, 19, 56.5, 45, 43.5, 37.5, 43.5, 26.5], '#71B9B0'],
[[55.5, 47, 33, 60, 33, 45, 42.5, 39.5], '#3D7C7B'],
[[31, 60, 8.5, 47, 21.5, 39.5, 31, 45], '#D0A977'],
[[7.5, 45, 7.5, 19, 20.5, 26.5, 20.5, 37.5], '#E9D8AE'],
[[8.5, 17, 31, 4, 31, 19, 21.5, 24.5], '#EEF2DD'],
] as [number[], string][]
).map(([pts, color], i) => {
const angle = ((-60 + 60 * i) * Math.PI) / 180;
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) } };
return { points, color, 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 INNER_APOTHEM = 11.8;
const INTRO_BOX = 132;
// The settled lockup is the header brand scaled up, so it reads as the same mark.
const LOCK_SCALE = 2.75;
const LOCK_BOX = 29 * LOCK_SCALE;
const LOCK_GAP = 7 * LOCK_SCALE;
// Timeline (ms): held at GATHER_END until startup is ready (at most HOLD_MAX),
// complete at INTRO_END; the slow settle runs on to TIMELINE_END.
const GATHER_END = 260;
const INTRO_END = 2260;
const TIMELINE_END = 2900;
const HOLD_MAX = 700;
const EXIT_MS = 640;
const INK = '#090a0c';
const WORDMARK = '#F1F1F1';
const SEA_GLASS = [113, 185, 176];
const rgba = (c: number[], a: number) => `rgba(${c[0]}, ${c[1]}, ${c[2]}, ${Math.max(0, a)})`;
/**
* Facet `f` around mark centre `o`, `unit` px per grid unit: pushed `out` along its
* 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();
interface Iris {
inward: number;
theta: number;
grow: number;
}
function irisAt(time: number): Iris {
const p = phase(time, 140, 1180);
return { inward: INNER_APOTHEM * (1 - IrisOpen(p)), theta: ((-44 * (1 - IrisTwist(p))) * Math.PI) / 180, grow: mix(0.64, 1, Emphasized(p)) };
}
/** 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;
function facetPath(ctx: CanvasRenderingContext2D, facet: (typeof FACETS)[number], iris: Iris, unit: number, o: Point) {
const c = Math.cos(iris.theta);
const s = Math.sin(iris.theta);
const k = unit * iris.grow;
facet.points.forEach((p, i) => {
const x = p.x - facet.normal.x * iris.inward;
const y = p.y - facet.normal.y * iris.inward;
const px = o.x + (x * c - y * s) * k;
const py = o.y + (x * s + y * c) * k;
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
@ -126,7 +116,7 @@ function shardPath(ctx: CanvasRenderingContext2D, f: Facet, pos: Point, size: nu
function hexagon(ctx: CanvasRenderingContext2D, o: Point, radius: number) {
for (let i = 0; i < 6; i++) {
const a = rad(-90 + 60 * i);
const a = ((-90 + 60 * i) * Math.PI) / 180;
const x = o.x + Math.cos(a) * radius;
const y = o.y + Math.sin(a) * radius;
if (i === 0) ctx.moveTo(x, y);
@ -135,14 +125,41 @@ function hexagon(ctx: CanvasRenderingContext2D, o: Point, radius: number) {
ctx.closePath();
}
function draw(ctx: CanvasRenderingContext2D, w: number, h: number, time: number, q: number) {
const o = { x: w / 2, y: h / 2 };
interface Letters {
font: string;
chars: string[];
x: number[];
width: number;
cap: number;
}
function draw(ctx: CanvasRenderingContext2D, w: number, h: number, time: number, q: number, letters: Letters) {
const center = { 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;
const lockup = Emphasized(phase(time, 1250, 2000));
const lockWidth = LOCK_BOX + LOCK_GAP + letters.width;
const box = mix(INTRO_BOX, LOCK_BOX, lockup);
// A slow push-in keeps the settled frame alive.
const drift = 1 + 0.025 * InOut(phase(time, 1900, 2900));
let cx = mix(center.x, center.x - lockWidth / 2 + LOCK_BOX / 2, lockup);
let cy = center.y;
let zoom = 1;
let textAlpha = 1;
let textShift = 0;
let hole = 0;
if (q > 0) {
zoom = Math.exp(Math.log(52) * Flight(q));
const recenter = Standard(Math.min(1, q / 0.75));
cx = mix(cx, center.x, recenter);
cy = mix(cy, center.y, recenter);
textAlpha = 1 - Standard(phase(q, 0, 0.4));
textShift = -14 * Standard(phase(q, 0, 0.4));
hole = InOut(phase(q, 0.12, 0.5));
}
const unit = (box / 64) * drift * zoom;
const o = { x: cx, y: cy };
// 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;
@ -158,81 +175,159 @@ function draw(ctx: CanvasRenderingContext2D, w: number, h: number, time: number,
ctx.globalAlpha = 1;
}
const bloom = 0.09 * InOut(phase(time, 0, 260)) * (1 - Standard(phase(time, 420, 1100)));
if (bloom > 0.001) {
const iris = irisAt(time);
const lightUp = EmphasizedDecelerate(phase(time, 0, 620));
const light = lightUp * (1 - Standard(phase(time, 620, 1250)));
const ambient = 0.03 * InOut(phase(time, 300, 900)) * (1 - Standard(phase(time, 1500, 2300)));
// Light behind the blades: a soft bloom, a hot core, and rays leaking
// through the six gaps while the iris turns.
if (light > 0.001 || ambient > 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));
const bloom = 250;
let g = ctx.createRadialGradient(o.x, o.y, 0, o.x, o.y, bloom);
g.addColorStop(0, rgba(SEA_GLASS, 0.16 * light + ambient));
g.addColorStop(0.45, rgba(SEA_GLASS, 0.04 * light + ambient * 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.arc(o.x, o.y, bloom, 0, Math.PI * 2);
ctx.fill();
if (light > 0.001) {
const core = ((26 * unit) / 2.0625) * mix(0.6, 1, light);
g = ctx.createRadialGradient(o.x, o.y, 0, o.x, o.y, core);
g.addColorStop(0, `rgba(255, 250, 236, ${0.95 * light})`);
g.addColorStop(0.35, `rgba(238, 242, 221, ${0.55 * light})`);
g.addColorStop(1, 'rgba(238, 242, 221, 0)');
ctx.fillStyle = g;
ctx.beginPath();
ctx.arc(o.x, o.y, core, 0, Math.PI * 2);
ctx.fill();
const rays = light * Math.min(1, IrisOpen(phase(time, 140, 1180)) * 2.5);
for (let i = 0; i < 6; i++) {
const angle = ((-90 + 60 * i) * Math.PI) / 180 + iris.theta;
const length = mix(40, 250, lightUp) * (0.75 + 0.25 * Math.sin(i * 2.1 + 1));
const end = { x: o.x + Math.cos(angle) * length, y: o.y + Math.sin(angle) * length };
g = ctx.createLinearGradient(o.x, o.y, end.x, end.y);
g.addColorStop(0, `rgba(255, 248, 230, ${0.42 * rays})`);
g.addColorStop(0.25, `rgba(214, 236, 226, ${0.12 * rays})`);
g.addColorStop(1, 'rgba(214, 236, 226, 0)');
ctx.fillStyle = g;
ctx.beginPath();
ctx.moveTo(o.x, o.y);
ctx.lineTo(o.x + Math.cos(angle - 0.014) * length, o.y + Math.sin(angle - 0.014) * length);
ctx.lineTo(o.x + Math.cos(angle + 0.014) * length, o.y + Math.sin(angle + 0.014) * length);
ctx.closePath();
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));
// Facets. Short echoes of earlier frames act as motion blur while the
// blades turn; they disappear beneath the facets once the iris is still.
const facetAlpha = (i: number) => EmphasizedDecelerate(phase(time, 40 + i * 34, 380 + i * 34));
if (time < 1400) {
for (const [delay, alpha] of [
[84, 0.07],
[56, 0.12],
[28, 0.2],
]) {
const echo = irisAt(time - delay);
FACETS.forEach((f, i) => {
ctx.globalAlpha = alpha * facetAlpha(i);
ctx.fillStyle = f.color;
ctx.beginPath();
facetPath(ctx, f, echo, unit, o);
ctx.fill();
});
}
}
FACETS.forEach((f, i) => {
ctx.globalAlpha = facetAlpha(i);
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));
facetPath(ctx, f, iris, unit, o);
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) {
const sheen = phase(time, 980, 1560);
if (light > 0.01 || (sheen > 0 && sheen < 1)) {
ctx.save();
ctx.beginPath();
FACETS.forEach((f) => facetPath(ctx, f, o, unit));
FACETS.forEach((f) => facetPath(ctx, f, iris, unit, o));
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);
// Backlight tints the blades while the core is hot, so they read as glass.
if (light > 0.01) {
const radius = (36 * unit) / 2.0625;
const g = ctx.createRadialGradient(o.x, o.y, 0, o.x, o.y, radius);
g.addColorStop(0, `rgba(255, 252, 240, ${0.26 * light})`);
g.addColorStop(1, 'rgba(255, 252, 240, 0)');
ctx.fillStyle = g;
ctx.fillRect(o.x - radius, o.y - radius, radius * 2, radius * 2);
}
// One diagonal band of light crosses the settled mark.
if (sheen > 0 && sheen < 1) {
const reach = 34 * unit;
const a = (36 * Math.PI) / 180;
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();
}
// The wordmark slides out from behind the mark as it moves into the lockup.
if (time >= 1400 && textAlpha > 0) {
const scale = (box / LOCK_BOX) * drift;
const textLeft = cx - (box * drift) / 2 + (LOCK_BOX + LOCK_GAP) * scale;
const slide = EmphasizedDecelerate(phase(time, 1400, 2050));
const baseline = cy + (letters.cap / 2) * scale;
ctx.save();
ctx.beginPath();
const clipLeft = cx + 24.5 * unit + 2 * scale;
ctx.rect(clipLeft, 0, w - clipLeft, h);
ctx.clip();
ctx.font = letters.font;
ctx.fillStyle = WORDMARK;
ctx.textBaseline = 'alphabetic';
letters.chars.forEach((ch, i) => {
const start = 1460 + i * 45;
const reveal = Standard(phase(time, start, start + 320));
if (reveal <= 0) return;
ctx.save();
ctx.globalAlpha = reveal * textAlpha;
ctx.translate(textLeft + (letters.x[i] - (1 - slide) * letters.width * 0.42) * scale + textShift, baseline);
ctx.scale(scale, scale);
ctx.fillText(ch, 0, 0);
ctx.restore();
});
ctx.restore();
}
}
async function measureLetters(): Promise<Letters> {
const size = 19 * LOCK_SCALE;
const font = `700 ${size}px 'Inter Variable', 'Segoe UI', sans-serif`;
await document.fonts?.load(font).catch(() => {});
const ctx = document.createElement('canvas').getContext('2d')!;
ctx.font = font;
const tracking = 1.4 * LOCK_SCALE;
const chars = 'KALEIDO'.split('');
const x: number[] = [];
let at = 0;
for (const ch of chars) {
x.push(at);
at += ctx.measureText(ch).width + tracking;
}
return { font, chars, x, width: at - tracking, cap: size * 0.711 };
}
export function Splash({ ready, onDone }: { ready: boolean; onDone: () => void }) {
@ -254,6 +349,7 @@ export function Splash({ ready, onDone }: { ready: boolean; onDone: () => void }
const ctx = el.getContext('2d')!;
let raf = 0;
let stopped = false;
let letters: Letters | null = null;
const size = () => {
const dpr = window.devicePixelRatio || 1;
el.width = Math.round(window.innerWidth * dpr);
@ -263,35 +359,43 @@ export function Splash({ ready, onDone }: { ready: boolean; onDone: () => void }
size();
window.addEventListener('resize', size);
// Timeline time advances with the clock, except while held at GATHER_END.
let last = 0;
let time = 0;
let held = 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;
const dt = last ? Math.min(64, now - last) : 0;
last = now;
if (time < GATHER_END) time = Math.min(GATHER_END, time + dt);
else if (time === GATHER_END && !readyRef.current && held < HOLD_MAX) held += dt;
else time = Math.min(TIMELINE_END, time + dt);
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 (letters) draw(ctx, window.innerWidth, window.innerHeight, time, q, letters);
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);
// Draw the first (dark) frame at once; start the clock once the wordmark's font is ready.
ctx.fillStyle = INK;
ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
measureLetters().then((l) => {
letters = l;
if (!stopped) 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);
setTimeout(() => document.documentElement.classList.remove('splash-arrival'), 700);
};
}, [reduced]);

View file

@ -1,12 +1,22 @@
import { isNative } from '../platform/native';
import { WindowControls } from '../app/TopBar';
import { isNative, win } from '../platform/native';
import { Icon } from '../ui/Icon';
/** A draggable strip with window controls for full-screen states without the top bar. */
export function WindowDrag() {
if (!isNative) return null;
return (
<div className="window-drag" data-tauri-drag-region>
<WindowControls />
<div className="window-controls">
<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>
);
}

View file

@ -16,21 +16,26 @@ function shuffled<T>(list: T[], salt = 0): T[] {
return out;
}
/** Recently released, highly rated, recently added, start watching, recommended. */
const FEATURE_SOURCES: RegExp[] = [/recentlyreleased|recentlyaired/, /topunwatched|toprated/, /recentlyadded/, /startwatching/, /curated|genre|by\.actor|moreingenre/];
const FEATURE_SOURCES: [RegExp, string][] = [
[/recentlyreleased|recentlyaired/, 'Recently released'],
[/topunwatched|toprated/, 'Highly rated'],
[/recentlyadded/, 'Recently added'],
[/startwatching/, 'Start watching'],
[/curated|genre|by\.actor|moreingenre/, 'Recommended'],
];
/**
* Features interleave recently released, highly rated unwatched and
* Plex-recommended titles; they need artwork and skip in-progress titles.
*/
export function buildFeatures(hubs: Hub[], limit = 8, salt = 0): Feature[] {
const pools: Feature[][] = FEATURE_SOURCES.map((re) =>
const pools: Feature[][] = FEATURE_SOURCES.map(([re, eyebrow]) =>
shuffled(
hubs
.filter((h) => re.test(h.id))
.flatMap((h) => h.items)
.filter((i) => (i.type === 'movie' || i.type === 'show') && i.art && !i.viewOffset && i.summary)
.map((item) => ({ item })),
.map((item) => ({ item, eyebrow })),
salt,
),
);

View file

@ -5,7 +5,7 @@ import { useSections, useServerQuery } from '../../app/queries';
import * as api from '../../plex/api';
import { art } from '../../app/format';
import { useDownloads } from '../../downloads/store';
import { appInfo, fullscreenShortcut, isMac, isNative, openExternal, pickFolder, revealPath, shortcut, type AppInfo } from '../../platform/native';
import { appInfo, isNative, openExternal, pickFolder, revealPath, type AppInfo } from '../../platform/native';
import { checkForUpdate, installUpdate, useUpdater } from '../../app/updater';
import { Button, Segmented, Select, Switch } from '../../ui/primitives';
import { confirmDialog } from '../../ui/overlays';
@ -42,16 +42,14 @@ const skipOptions: { value: SkipMode; label: string }[] = [
{ value: 'off', label: 'Off' },
];
const OS_NAMES: Record<string, string> = { windows: 'Windows', macos: 'macOS', linux: 'Linux' };
const SHORTCUTS: [string, string][][] = [
[
[shortcut('K'), 'Search'],
[isMac ? '⌘[ / Mouse back' : 'Alt + ← / Mouse back', 'Go back'],
[isMac ? '⌘] / Mouse forward' : 'Alt + → / Mouse forward', 'Go forward'],
['Ctrl + K', 'Search'],
['Alt + ← / Mouse back', 'Go back'],
['Alt + → / Mouse forward', 'Go forward'],
['Esc', 'Go back or close a dialog'],
[fullscreenShortcut, 'Full screen'],
[shortcut(','), 'Settings'],
['F11', 'Full screen'],
['Ctrl + ,', 'Settings'],
['Right-click a title', 'Title actions'],
],
[
@ -65,7 +63,7 @@ const SHORTCUTS: [string, string][][] = [
['C', 'Next subtitle track'],
['U', 'Cycle upscaling'],
['B', 'Compare with enhancement off'],
['Shift + P / N', 'Previous / next episode'],
['Shift + N', 'Next episode'],
['0–9', 'Jump to 0–90%'],
['Esc or Backspace', 'Exit full screen, then keep playing in the corner'],
],
@ -184,7 +182,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.">
<Switch checked={s.hwdec} onChange={(v) => set('hwdec', v)} />
</Pref>
<Pref label="HDR passthrough" description={`Sends HDR video to HDR-capable displays${isMac ? '' : ' when Windows HDR is on'}. Applies after restarting Kaleido.`}>
<Pref label="HDR passthrough" description="Sends HDR video to HDR-capable displays when Windows HDR is on. Applies after restarting Kaleido.">
<Switch checked={s.hdrPassthrough} onChange={(v) => set('hdrPassthrough', v)} />
</Pref>
</SettingsSection>
@ -192,27 +190,14 @@ export function AppSettings({ tab }: { tab: string }) {
<Pref label="Skip intros">
<Select value={s.skipIntro} onChange={(v) => set('skipIntro', v)} options={skipOptions} />
</Pref>
<Pref label="Skip movie credits" description="Episodes open Up Next when their credits begin.">
<Pref label="Skip credits">
<Select value={s.skipCredits} onChange={(v) => set('skipCredits', v)} options={skipOptions} />
</Pref>
<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.">
<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 label="Play the next episode automatically">
<Switch checked={s.autoplayNext} onChange={(v) => set('autoplayNext', v)} />
</Pref>
<Pref label="Autoplay next episode">
<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 label="Countdown" description="Seconds before the next episode starts.">
<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` }))} />
</Pref>
<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` }))} />
@ -389,7 +374,7 @@ export function AppSettings({ tab }: { tab: string }) {
<div>
<h2>Kaleido</h2>
<p className="muted">
Version {info?.version ?? '—'} · {OS_NAMES[info?.platform ?? ''] ?? info?.platform}
Version {info?.version ?? '—'} · {info?.platform === 'windows' ? 'Windows' : info?.platform}
</p>
</div>
</div>

View file

@ -52,28 +52,6 @@ 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 }) {
const server = useServer();
const item = session.item;
@ -121,7 +99,7 @@ function NowPlaying({ session, onStop }: { session: admin.Session; onStop: () =>
function Dashboard() {
const server = useServer();
const sessions = useServerQuery(['sessions'], (s) => admin.sessions(s), { refetchInterval: 5000, staleTime: 0 });
const bw = useServerQuery(['bandwidth'], (s) => admin.bandwidth(s, 6), { refetchInterval: 1000, staleTime: 0 });
const bw = useServerQuery(['bandwidth'], (s) => admin.bandwidth(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 sections = useServerQuery(['sections'], (s) => api.sections(s));
@ -129,7 +107,10 @@ function Dashboard() {
const list = sessions.data ?? [];
const transcodes = list.filter((s) => s.decision?.video === 'transcode').length;
const { lan, wan } = perSecond(bw.data?.points ?? []);
const points = (bw.data?.points ?? []).slice(-40);
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 cpu = r[r.length - 1];
const totalBandwidth = list.reduce((a, s) => a + s.bandwidth, 0);
@ -169,7 +150,7 @@ function Dashboard() {
))}
</Card>
<div className="admin-2-col">
<Card title="Bandwidth" actions={<span className="note">Last 2 minutes · live</span>}>
<Card title="Bandwidth" actions={<span className="note">Last few minutes · live</span>}>
<AreaChart
series={[
{ values: wan, color: '#6797f5', label: 'Remote' },

View file

@ -248,14 +248,6 @@
display: flex;
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 {
@ -270,11 +262,10 @@ html.os-macos:not(.window-fullscreen) .topbar {
pointer-events: none;
}
/* The app beneath settles from a slight zoom as the camera flies through the
aperture (held for the first quarter of the exit, then decelerating).
The duration matches EXIT_MS in Splash.tsx. */
aperture (held for the first quarter of the exit, then decelerating). */
html.splash-arrival .app-shell,
html.splash-arrival .auth-screen {
animation: splash-arrival 540ms linear both;
animation: splash-arrival 640ms linear both;
}
@keyframes splash-arrival {
0% {
@ -516,12 +507,6 @@ html.splash-arrival .auth-screen {
.backdrop-layer.ready {
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 {
@ -535,42 +520,14 @@ html.splash-arrival .auth-screen {
-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 {
position: absolute;
inset: 0;
opacity: 0;
transition: opacity 420ms var(--ease);
}
.backdrop-wash.ready {
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 {
position: absolute;
@ -647,9 +604,11 @@ html.splash-arrival .auth-screen {
transform: none;
}
}
/* Scoped so the later `.title-art { margin: 0 }` can't cancel the gap above the facts. */
.hero-content .hero-title {
margin: 0 0 22px;
.hero-eyebrow {
margin-bottom: 16px;
}
.hero-title {
margin: 0 0 18px;
}
.hero-episode {
font-size: 14px;
@ -854,7 +813,6 @@ html.splash-arrival .auth-screen {
overflow-y: hidden;
scroll-snap-type: x proximity;
scroll-padding: 0 var(--gutter);
overflow-anchor: none;
padding: 4px var(--gutter) 10px;
scrollbar-width: none;
}
@ -1093,23 +1051,6 @@ html.splash-arrival .auth-screen {
.card.landscape .card-title {
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 {
font-size: 11.5px;
color: #8a9196;

View file

@ -86,7 +86,7 @@ html.player-mini.video-active .app-shell {
visibility: visible;
-webkit-mask-image: linear-gradient(#000 0 0), url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 160 90'%3E%3Crect width='160' height='90' rx='3.6'/%3E%3C/svg%3E");
-webkit-mask-size: 100% 100%, var(--mini-w) var(--mini-h);
-webkit-mask-position: 0 0, right var(--mini-x, var(--mini-gap)) bottom var(--mini-y, var(--mini-gap));
-webkit-mask-position: 0 0, right var(--mini-gap) bottom var(--mini-gap);
-webkit-mask-repeat: no-repeat;
-webkit-mask-composite: xor;
mask-composite: exclude;

View file

@ -69,9 +69,6 @@
transition: opacity 400ms var(--ease);
}
/* The window's own buttons, top right, fading with the rest of the chrome. */
html.os-macos:not(.window-fullscreen) .player-top {
padding-left: var(--traffic-lights);
}
.player-top .window-controls {
position: absolute;
top: 0;
@ -328,35 +325,17 @@ html.os-macos:not(.window-fullscreen) .player-top {
}
/* Controls */
/* Volume and time | playback, centred under the timeline | tracks and window. */
.player-controls {
display: grid;
grid-template-columns: 1fr auto 1fr;
display: flex;
align-items: center;
gap: 16px;
justify-content: space-between;
margin-top: 6px;
}
.player-controls-left,
.player-controls-center,
.player-controls-right {
display: flex;
align-items: center;
gap: 4px;
min-width: 0;
}
.player-controls-right {
justify-content: flex-end;
}
.player-controls-center {
gap: 10px;
}
.player-icon-spacer {
width: 44px;
height: 44px;
}
.player-icon:disabled {
opacity: 0.32;
pointer-events: none;
}
.player-icon {
width: 44px;
@ -382,12 +361,11 @@ html.os-macos:not(.window-fullscreen) .player-top {
color: var(--accent-strong);
}
.player-icon.big {
width: 54px;
height: 54px;
width: 48px;
height: 48px;
}
.player-time {
margin-left: 8px;
white-space: nowrap;
margin-left: 12px;
font-size: 13px;
font-variant-numeric: tabular-nums;
color: #f0f2f2;
@ -429,8 +407,6 @@ html.os-macos:not(.window-fullscreen) .player-top {
/* Panels */
.player-panel {
position: absolute;
/* Above the skip and post-play cards. */
z-index: 2;
right: clamp(24px, 3.5vw, 56px);
bottom: 84px;
min-width: 300px;
@ -570,13 +546,9 @@ html.os-macos:not(.window-fullscreen) .player-top {
font-size: 13px;
color: #d9dedf;
}
.panel-option:hover:not(:disabled) {
.panel-option:hover {
background: rgba(255, 255, 255, 0.09);
}
.panel-option:disabled {
opacity: 0.45;
cursor: default;
}
.panel-option.selected {
color: #fff;
font-weight: 620;
@ -659,10 +631,7 @@ html.os-macos:not(.window-fullscreen) .player-top {
min-width: 340px;
}
/* The skip button sits above the bottom chrome. */
.skip-button {
z-index: 1;
}
/* Skip & post-play */
.skip-button {
position: absolute;
right: clamp(24px, 3.5vw, 56px);
@ -690,272 +659,74 @@ html.os-macos:not(.window-fullscreen) .player-top {
background: #f3f5f4;
color: #111;
}
/* An automatic skip fills the button as it counts down. */
.skip-button.counting {
overflow: hidden;
}
.skip-button.counting::before {
content: '';
.post-play {
position: absolute;
inset: 0 auto 0 0;
width: var(--p, 0%);
background: rgba(255, 255, 255, 0.18);
transition: width 260ms linear;
}
.skip-button.counting:hover::before {
background: rgba(0, 0, 0, 0.1);
}
.skip-button > * {
position: relative;
}
/* —— Up Next ————————————————————————————————————————————————————————
The credits keep playing in the top-left frame: the native video is drawn
into its rectangle and the scene has a matching hole (PostPlay.tsx). Only
the rows scroll, so the frame never moves. */
.up-next {
right: clamp(24px, 3.5vw, 56px);
bottom: 150px;
display: flex;
flex-direction: column;
--up-top: 64px;
--up-video-w: clamp(320px, 34vw, 640px);
gap: 16px;
align-items: center;
width: min(520px, calc(100vw - 48px));
padding: 14px;
border-radius: 14px;
background: rgba(20, 22, 24, 0.88);
backdrop-filter: blur(20px);
box-shadow:
0 24px 70px rgba(0, 0, 0, 0.6),
inset 0 0 0 1px rgba(255, 255, 255, 0.12);
animation: rise-in 360ms var(--ease-out);
}
.up-next-scene {
position: absolute;
inset: 0;
overflow: hidden;
isolation: isolate;
background: var(--bg);
pointer-events: none;
}
.up-next.placed .up-next-scene {
-webkit-mask-image: linear-gradient(#000 0 0), url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 160 90'%3E%3Crect width='160' height='90' rx='2.4'/%3E%3C/svg%3E");
-webkit-mask-size: 100% 100%, var(--up-w) var(--up-h);
-webkit-mask-position: 0 0, var(--up-x) var(--up-y);
-webkit-mask-repeat: no-repeat;
-webkit-mask-composite: xor;
mask-composite: exclude;
}
.up-next-backdrop {
height: min(78vh, 860px);
bottom: auto;
}
.backdrop-tint.up-next-backdrop {
height: 100%;
}
/* The next episode's details sit over the artwork, so it stays dimmer here
than on a title page, with or without the colour wash. */
.up-next-backdrop .backdrop-scrim,
.up-next-backdrop.washed .backdrop-scrim {
background:
linear-gradient(90deg, rgba(9, 10, 12, 0.96) 0%, rgba(9, 10, 12, 0.9) 38%, rgba(9, 10, 12, 0.74) 62%, rgba(9, 10, 12, 0.55) 100%),
linear-gradient(0deg, var(--bg) 0%, rgba(9, 10, 12, 0.6) 22%, transparent 55%);
}
.up-next-top {
height: 60px;
z-index: 3;
}
.up-next-fullscreen {
margin-left: auto;
}
/* Beside the window's own buttons (Windows, outside full screen), it takes
their size and line so the four read as one group. */
.up-next-top:has(> .window-controls) .up-next-fullscreen {
align-self: flex-start;
width: 46px;
height: 34px;
margin-right: 110px;
border-radius: 0;
color: #e4e8e9;
}
.up-next-top:has(> .window-controls) .up-next-fullscreen svg {
width: 15px;
height: 15px;
}
.up-next-head {
.post-play-art {
position: relative;
z-index: 1;
flex: none;
display: flex;
align-items: flex-start;
gap: clamp(28px, 3vw, 48px);
padding: var(--up-top) var(--gutter) 30px;
animation: fade-in 320ms var(--ease);
}
.up-next-now {
flex: none;
width: var(--up-video-w);
}
.up-next-video {
display: block;
width: 100%;
width: 180px;
aspect-ratio: 16 / 9;
border-radius: 8px;
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.16);
transition: box-shadow var(--t-fast);
}
.up-next-video:hover,
.up-next-video:focus-visible {
outline: none;
box-shadow: 0 0 0 2px #fff;
}
.up-next-progress {
margin-top: 12px;
}
.up-next-progress-text {
display: flex;
justify-content: space-between;
gap: 12px;
font-size: 12px;
color: var(--muted);
}
.up-next-progress-text span {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.up-next-progress-text small {
flex: none;
font-size: inherit;
color: var(--dim);
font-variant-numeric: tabular-nums;
background: #000;
}
.up-next-video:hover + .up-next-progress .up-next-progress-text span {
color: #fff;
}
.up-next-progress-bar {
height: 3px;
margin-top: 8px;
border-radius: 3px;
background: rgba(255, 255, 255, 0.22);
overflow: hidden;
}
.up-next-progress-bar i {
display: block;
.post-play-art img {
width: 100%;
height: 100%;
background: var(--accent);
object-fit: cover;
}
.up-next-info {
flex: 1;
min-width: 0;
max-width: 680px;
padding-top: 6px;
text-shadow: 0 1px 12px rgba(0, 0, 0, 0.5);
}
.up-next-info .micro {
display: block;
margin-bottom: 12px;
}
.up-next-info .up-next-logo {
margin-bottom: 14px;
}
.up-next-info .title-text {
font-size: clamp(26px, 2.4vw, 36px);
margin-bottom: 12px;
}
.up-next-info h1 {
margin: 0 0 10px;
font-size: clamp(20px, 1.7vw, 26px);
line-height: 1.2;
letter-spacing: -0.025em;
font-weight: 680;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.up-next-summary {
margin: 14px 0 0;
color: #e3e7e9;
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6), 0 1px 14px rgba(0, 0, 0, 0.55);
font-size: 14px;
line-height: 1.62;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
/* The countdown: a lighter fill sweeps across the button, without numbers. */
.up-next-play {
position: relative;
overflow: hidden;
isolation: isolate;
margin-top: 22px;
text-shadow: none;
}
.up-next-play.counting,
.up-next-play.counting:hover:not(:disabled) {
background: #a3a8a9;
}
.up-next-play-fill {
.post-play-ring {
position: absolute;
inset: 0;
z-index: -1;
background: #f6f7f7;
transform: scaleX(0);
transform-origin: left;
will-change: transform;
margin: auto;
width: 46px;
height: 46px;
transform: rotate(-90deg);
}
.up-next-play:focus-visible {
outline: 2px solid #fff;
outline-offset: 3px;
.post-play-ring circle {
fill: rgba(0, 0, 0, 0.45);
stroke: #fff;
stroke-width: 3;
stroke-dasharray: 107;
animation: ring 8s linear forwards;
}
.up-next-rows {
position: relative;
z-index: 1;
flex: 1;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
padding-bottom: 12px;
animation: fade-in 420ms var(--ease);
}
.up-next-shelf {
margin-bottom: 22px;
}
/* Cards are sized from the space below the header, so the season and related
rows fill it (--up-row: a row's height besides its artwork). In a short,
wide window they keep a sensible size and the related row runs off the
bottom, as on Android TV. */
.up-next-rows {
container-type: size;
--up-row: 128px;
}
.up-next-shelf .shelf .card.landscape {
width: clamp(15vw, calc((50cqh - var(--up-row)) * 16 / 9), 26vw);
}
@media (max-width: 1333px) {
.up-next-shelf .shelf .card.landscape {
width: clamp(200px, calc((50cqh - var(--up-row)) * 16 / 9), 26vw);
@keyframes ring {
from {
stroke-dashoffset: 107;
}
to {
stroke-dashoffset: 0;
}
}
.up-next-shelf .card {
scroll-margin-left: 0;
.post-play-text {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
@media (max-height: 760px) {
.up-next-head {
padding-bottom: 20px;
}
.up-next-info .micro {
margin-bottom: 8px;
}
.up-next-info .up-next-logo {
height: 44px !important;
margin-bottom: 10px;
}
.up-next-info .up-next-logo img {
max-height: 44px !important;
}
.up-next-summary {
-webkit-line-clamp: 2;
margin-top: 10px;
}
.up-next-play {
margin-top: 16px;
}
.up-next-shelf {
margin-bottom: 14px;
}
.post-play-text b {
font-size: 14px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.up-next .card:focus-visible {
outline: none;
.post-play-text .actions {
margin-top: 6px;
}
.player-error {
position: absolute;
@ -987,11 +758,10 @@ html.os-macos:not(.window-fullscreen) .player-top {
--mini-h: calc(var(--mini-w) * 9 / 16);
--mini-gap: 24px;
}
/* --mini-x/-y: where it was dragged to, from the right and bottom (PlayerOverlay). */
.mini-player {
position: fixed;
right: var(--mini-x, var(--mini-gap));
bottom: var(--mini-y, var(--mini-gap));
right: var(--mini-gap);
bottom: var(--mini-gap);
z-index: 600;
width: var(--mini-w);
height: var(--mini-h);
@ -1004,9 +774,6 @@ html.os-macos:not(.window-fullscreen) .player-top {
.mini-player.loading {
background: #000;
}
.mini-player.dragging {
cursor: grabbing;
}
/* Opacity only: the video beneath can't follow a transform. */
@keyframes mini-in {
from {
@ -1030,8 +797,6 @@ html.os-macos:not(.window-fullscreen) .player-top {
.mini-player:hover .mini-top,
.mini-player:hover .mini-center,
.mini-player:hover .mini-caption,
.mini-player.dragging .mini-scrim,
.mini-player.dragging .mini-caption,
.mini-player.loading .mini-center,
.mini-player:focus-within .mini-top,
.mini-player:focus-within .mini-center {

View file

@ -430,30 +430,6 @@ button.chip:hover {
letter-spacing: -0.035em;
font-weight: 700;
}
.season-switch {
display: inline-flex;
align-items: center;
gap: 6px;
margin-left: -8px;
padding: 2px 6px 2px 8px;
border-radius: 8px;
font: inherit;
letter-spacing: inherit;
transition: background var(--t-fast);
}
.season-switch svg {
color: #aeb5b8;
transition:
color var(--t-fast),
transform var(--t-fast);
}
.season-switch:hover {
background: rgba(255, 255, 255, 0.08);
}
.season-switch:hover svg {
color: #fff;
transform: translateY(1px);
}
.synopsis-wrap {
max-width: 640px;
}
@ -604,29 +580,122 @@ button.chip:hover {
}
/* Episodes */
.episodes {
margin-bottom: 34px;
margin-bottom: 36px;
}
.episodes .shelf-head {
padding: 0;
.episodes-head {
display: flex;
align-items: center;
gap: 16px;
margin-bottom: 8px;
}
.episode-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(clamp(240px, 19vw, 320px), 1fr));
gap: 30px 16px;
.episodes-head h2 {
margin: 0;
font-size: 19px;
letter-spacing: -0.028em;
}
.episode-grid .card {
.episodes-sub {
color: var(--dim);
font-size: 12px;
}
.season-summary {
color: #aeb5b8;
font-size: 12.5px;
line-height: 1.6;
max-width: 760px;
margin: 4px 0 8px;
}
.episode-row {
scroll-margin: 96px 0 48px;
display: grid;
grid-template-columns: 34px 220px minmax(0, 1fr) 40px;
gap: 20px;
align-items: center;
padding: 16px 12px 16px 6px;
border-bottom: 1px solid var(--line-soft);
border-radius: 10px;
cursor: pointer;
transition: background var(--t-fast);
}
.episode-card-summary {
margin: 7px 0 0;
.episode-row:hover,
.episode-row:focus-visible {
background: rgba(255, 255, 255, 0.045);
}
.episode-row:focus-visible {
outline: 2px solid #f2f5f4;
outline-offset: 0;
}
.episode-index {
font-size: 22px;
font-weight: 650;
color: #8a9196;
text-align: center;
font-variant-numeric: tabular-nums;
}
.episode-pic {
position: relative;
aspect-ratio: 16 / 9;
border-radius: 6px;
overflow: hidden;
background: #1c2024;
}
.episode-pic .artwork {
position: absolute;
inset: 0;
}
.episode-play {
position: absolute;
left: 50%;
top: 50%;
width: 42px;
height: 42px;
margin: -21px 0 0 -21px;
border-radius: 50%;
display: grid;
place-items: center;
background: rgba(255, 255, 255, 0.92);
color: #121314;
opacity: 0;
transform: scale(0.9);
transition:
opacity var(--t),
transform var(--t) var(--ease-out);
}
.episode-row:hover .episode-play {
opacity: 1;
transform: none;
}
.episode-text h3 {
font-size: 14px;
margin: 0 0 4px;
font-weight: 640;
display: flex;
align-items: center;
gap: 8px;
}
.episode-watched {
color: #9fd6bb;
}
.episode-meta {
font-size: 11.5px;
color: #8a9196;
margin-bottom: 7px;
}
.episode-text p {
margin: 0;
font-size: 12px;
line-height: 1.55;
color: #a1a8ac;
color: #a8afb3;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.episode-more {
opacity: 0;
}
.episode-row:hover .episode-more {
opacity: 1;
}
/* —— Search ————————————————————————————————————————————————— */
.search-hero {
@ -1976,6 +2045,10 @@ button.chip:hover {
.download-intro {
grid-template-columns: minmax(0, 1fr);
}
.episode-row {
grid-template-columns: 26px 160px minmax(0, 1fr) 36px;
gap: 14px;
}
.history-row {
grid-template-columns: 36px minmax(0, 1fr) 120px 90px;
}

View file

@ -1,25 +1,21 @@
import { useEffect, useRef, useState, type CSSProperties } from 'react';
import { useEffect, useRef, useState } from 'react';
import type { Item } from '../plex/types';
import { useServer } from '../app/session';
import { useSettings } from '../app/settings';
import { art, washColors } from '../app/format';
import { art, washGradient } from '../app/format';
interface Layer {
key: number;
src: string;
blur: Item['ultraBlur'];
wash: string;
ready: boolean;
}
/** How long an outgoing layer lingers: its fade (with delay) plus a margin. */
const LEAVE_MS = 700;
/**
* Artwork-led page background. The image sits top-right and fades into the
* page toward its left and bottom edges; the UltraBlur colour wash tints the
* page beneath it and carries on down behind the rows. Artwork crossfades
* once the new image has decoded, and the wash's colours blend into the new
* title's at the same moment (registered custom properties, app.css).
* page beneath it and carries on down behind the rows. Changes crossfade; the
* outgoing layer stays until the new image has decoded.
*/
export function Backdrop({ item, className = '', width = 1600, height = 900, wash: forceWash }: { item: Item | null | undefined; className?: string; width?: number; height?: number; wash?: Item['ultraBlur'] }) {
const server = useServer();
@ -29,50 +25,39 @@ export function Backdrop({ item, className = '', width = 1600, height = 900, was
const path = item ? art.backdrop(item) : '';
const src = path ? server.image(path, width, height) : '';
const blur = forceWash ?? item?.ultraBlur ?? null;
const blurKey = blur ? `${blur.topLeft}${blur.topRight}${blur.bottomRight}${blur.bottomLeft}` : '';
const wash = colorWash && blur ? washGradient(blur) : '';
useEffect(() => {
if (!src && !blur) return;
if (!src && !wash) return;
setLayers((prev) => {
const last = prev[prev.length - 1];
// Same art, maybe new colours: the wash blends to them in place.
if (last && last.src === src) return prev.map((l) => (l === last ? { ...l, blur } : l));
// Keep only what is on screen (the newest layer that has shown) under the new one.
const shown = prev.filter((l) => l.ready).slice(-1);
return [...shown, { key: ++counter.current, src, blur, ready: !src }];
if (prev.length && prev[prev.length - 1].src === src) {
// Same art, maybe new wash.
return prev.map((l, i) => (i === prev.length - 1 ? { ...l, wash } : l));
}
return [...prev.slice(-1), { key: ++counter.current, src, wash, ready: !src }];
});
}, [src, blurKey]);
}, [src, wash]);
const onReady = (key: number) => setLayers((prev) => (prev.some((l) => l.key === key && !l.ready) ? prev.map((l) => (l.key === key ? { ...l, ready: true } : l)) : prev));
// Once the newest layer is in, the ones beneath fade out and then go.
const newest = layers[layers.length - 1];
useEffect(() => {
if (!newest?.ready || layers.length < 2) return;
const t = setTimeout(() => setLayers((p) => (p[p.length - 1]?.key === newest.key ? p.slice(-1) : p)), LEAVE_MS);
return () => clearTimeout(t);
}, [newest?.key, newest?.ready, layers.length]);
let top = -1;
layers.forEach((l, i) => l.ready && (top = i));
const colors = top >= 0 ? washColors(layers[top].blur) : null;
const washStyle = {
'--wash-tr': colors?.topRight ?? 'transparent',
'--wash-tl': colors?.topLeft ?? 'transparent',
'--wash-br': colors?.bottomRight ?? 'transparent',
'--wash-bl': colors?.bottomLeft ?? 'transparent',
} as CSSProperties;
const onReady = (key: number) =>
setLayers((prev) => {
const idx = prev.findIndex((l) => l.key === key);
if (idx < 0) return prev;
const next = prev.map((l) => (l.key === key ? { ...l, ready: true } : l));
// Drop older layers once the newest is visible (after its fade).
setTimeout(() => setLayers((p) => (p.length > 1 && p[p.length - 1].key === key ? p.slice(-1) : p)), 500);
return next;
});
return (
<>
{colorWash && (
<div className={`backdrop-tint ${className}`} aria-hidden="true">
<div className="backdrop-wash" style={washStyle} />
{layers.map((l) => l.wash && <div key={l.key} className={`backdrop-wash${l.ready ? ' ready' : ''}`} style={{ background: l.wash }} />)}
</div>
)}
<div className={`backdrop ${className}${colorWash ? ' washed' : ''}`} aria-hidden="true">
{layers.map((l, i) => (
<div key={l.key} className={`backdrop-layer${l.ready ? ' ready' : ''}${i < top ? ' leaving' : ''}`}>
{layers.map((l) => (
<div key={l.key} className={`backdrop-layer${l.ready ? ' ready' : ''}`}>
{l.src && <img className="backdrop-art" src={l.src} alt="" draggable={false} decoding="async" onLoad={() => onReady(l.key)} onError={() => onReady(l.key)} />}
</div>
))}

View file

@ -14,6 +14,7 @@ const ROTATE_MS = 8000;
export interface Feature {
item: Item;
eyebrow: string;
}
/**
@ -43,14 +44,14 @@ export function Hero({ features, variant = 'home' }: { features: Feature[]; vari
img.decode?.().catch(() => {});
}, [upcoming?.id]);
// Pause rotation when the hero is scrolled away; it picks up again on its return.
const [visible, setVisible] = useState(true);
useEffect(() => {
if (!rotate || reduced || count < 2 || hover || !visible) return;
if (!rotate || reduced || count < 2 || hover) return;
const t = setTimeout(() => go(index + 1), ROTATE_MS);
return () => clearTimeout(t);
}, [index, rotate, reduced, count, hover, visible]);
}, [index, rotate, reduced, count, hover]);
// Pause rotation when the hero is scrolled away.
const [visible, setVisible] = useState(true);
useEffect(() => {
const el = root.current;
if (!el) return;
@ -60,6 +61,7 @@ export function Hero({ features, variant = 'home' }: { features: Feature[]; vari
}, []);
const go = (i: number) => {
if (!visible && i !== index) return;
setIndex(((i % count) + count) % count);
setCopyKey((k) => k + 1);
};
@ -73,6 +75,7 @@ export function Hero({ features, variant = 'home' }: { features: Feature[]; vari
<section ref={root} className={`hero ${variant}`} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
<Backdrop item={item} className="hero-backdrop" />
<div className="hero-content" key={copyKey}>
<div className="micro hero-eyebrow">{feature.eyebrow}</div>
<TitleArt item={item} className="hero-title" maxWidth={variant === 'home' ? 420 : 380} maxHeight={variant === 'home' ? 128 : 108} />
{item.type === 'episode' && (
<div className="hero-episode">

View file

@ -13,7 +13,6 @@ const PATHS: Record<string, string> = {
arrowLeft: '<path d="M19 12H5m6-6-6 6 6 6"/>',
play: '<path d="M7 4.8v14.4a.8.8 0 0 0 1.2.7l11.6-7.2a.8.8 0 0 0 0-1.4L8.2 4.1a.8.8 0 0 0-1.2.7Z" fill="currentColor" stroke="none"/>',
pause: '<rect x="6" y="4.5" width="4" height="15" rx="1.2" fill="currentColor" stroke="none"/><rect x="14" y="4.5" width="4" height="15" rx="1.2" fill="currentColor" stroke="none"/>',
stop: '<rect x="5.5" y="5.5" width="13" height="13" rx="1.6" fill="currentColor" stroke="none"/>',
plus: '<path d="M12 5v14M5 12h14"/>',
minus: '<path d="M5 12h14"/>',
check: '<path d="m5 12.5 4.2 4.2L19 7"/>',

View file

@ -1,10 +1,9 @@
import { memo, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { memo, useEffect, useRef, useState, type ReactNode } from 'react';
import type { Item } from '../plex/types';
import { useServer, useSession } from '../app/session';
import { useServer } from '../app/session';
import { useSettings } from '../app/settings';
import { art, date, displayTitle, duration, episodeLabel, formatBadges, isWatched, progress, remaining, remainingEpisodes } from '../app/format';
import { art, displayTitle, duration, episodeLabel, formatBadges, isWatched, progress, remaining, remainingEpisodes } from '../app/format';
import { itemMenu, openItem, playWithVersion } from '../app/actions';
import { navigate } from '../app/router';
import { Artwork } from './primitives';
import { Icon } from './Icon';
import { openMenu } from './overlays';
@ -91,8 +90,7 @@ export function Facts({ item, withFormats = true, episode = true, children }: {
/** Original clear-logo artwork, falling back to the title in type. */
export function TitleArt({ item, logo, className = '', maxWidth = 420, maxHeight = 130, as: As = 'h1' }: { item: Item; logo?: string; className?: string; maxWidth?: number; maxHeight?: number; as?: 'h1' | 'h2' }) {
// The player shows this offline too, where there is no server to draw the logo from.
const server = useSession((s) => s.server);
const server = useServer();
const path = logo ?? item.logo;
const [failed, setFailed] = useState(false);
const [ready, setReady] = useState(false);
@ -101,7 +99,7 @@ export function TitleArt({ item, logo, className = '', maxWidth = 420, maxHeight
setReady(false);
}, [path]);
const title = item.type === 'episode' ? item.grandparentTitle : item.type === 'season' ? item.parentTitle || item.title : item.title;
if (!path || failed || !server)
if (!path || failed)
return (
<As className={`title-text ${className}`} style={{ maxWidth: maxWidth * 1.4 }}>
{title}
@ -142,14 +140,9 @@ function WatchBadge({ item }: { item: Item }) {
return null;
}
/**
* A watched title's leftover position (from an unfinished rewatch) only shows where it's
* what you're resuming: Continue Watching, or the season's up-next episode.
*/
function ProgressLine({ item, always = false }: { item: Item; always?: boolean }) {
const percent = useSettings((s) => s.watchedPercent);
function ProgressLine({ item }: { item: Item }) {
const p = progress(item);
if (!p || p > 0.995 || (!always && isWatched(item, percent))) return null;
if (!p || p > 0.995) return null;
return (
<span className="progress-line">
<i style={{ width: `${Math.max(3, p * 100)}%` }} />
@ -210,15 +203,12 @@ export const PosterCard = memo(function PosterCard({ item, caption = 'year', cla
const server = useServer();
const handlers = useCardHandlers(item);
const path = art.poster(item);
// On its show's page a season is just "Season 2"; anywhere else it needs the show's name.
const seasonAlone = item.type === 'season' && caption !== 'episodes' && !!item.parentTitle;
const title = item.type === 'season' && !seasonAlone ? item.title : displayTitle(item);
let meta: ReactNode = null;
if (caption === 'year') meta = item.type === 'episode' ? episodeLabel(item) : item.type === 'season' ? item.title : item.type === 'collection' ? (item.childCount ? `${item.childCount} titles` : 'Collection') : item.year || '';
if (caption === 'year') meta = item.type === 'episode' ? episodeLabel(item) : item.type === 'season' ? (item.leafCount ? `${item.leafCount} episodes` : '') : item.type === 'collection' ? (item.childCount ? `${item.childCount} titles` : 'Collection') : item.year || '';
if (caption === 'episodes') meta = item.leafCount ? `${item.leafCount} episodes` : '';
if (caption === 'role') meta = (item as any).roleName ?? item.year;
return (
<article className={`card poster ${className}`} role="button" tabIndex={0} aria-label={seasonAlone ? `${title}, ${item.title}` : title} {...handlers} {...previewHandlers(item)}>
<article className={`card poster ${className}`} role="button" tabIndex={0} aria-label={item.title} {...handlers} {...previewHandlers(item)}>
<div className="card-cover">
<Artwork src={server.image(path, 240, 360)} alt="" fallback={<span className="cover-fallback">{displayTitle(item)}</span>} />
<div className="card-hover" />
@ -228,8 +218,8 @@ export const PosterCard = memo(function PosterCard({ item, caption = 'year', cla
</div>
{caption !== 'none' && (
<div className="card-caption">
<div className="card-title" title={title}>
{title}
<div className="card-title" title={item.type === 'season' ? item.title : displayTitle(item)}>
{item.type === 'season' ? item.title : displayTitle(item)}
</div>
{meta ? <div className="card-meta">{meta}</div> : null}
</div>
@ -241,16 +231,14 @@ export const PosterCard = memo(function PosterCard({ item, caption = 'year', cla
export const LandscapeCard = memo(function LandscapeCard({ item, continueWatching, showTitle = true, episodeStyle = false }: { item: Item; continueWatching?: boolean; showTitle?: boolean; episodeStyle?: boolean }) {
const server = useServer();
const handlers = useCardHandlers(item, { continueWatching });
const percent = useSettings((s) => s.watchedPercent);
const inProgress = !!item.viewOffset && (continueWatching || !isWatched(item, percent));
const isEp = item.type === 'episode';
const path = isEp ? item.thumb || item.grandparentArt : art.landscape(item);
const title = episodeStyle && isEp ? `${item.index}. ${item.title}` : displayTitle(item);
const meta = isEp
? episodeStyle
? [duration(item.duration), inProgress ? remaining(item) : ''].filter(Boolean).join(' · ')
? [duration(item.duration), item.viewOffset ? remaining(item) : ''].filter(Boolean).join(' · ')
: `${episodeLabel(item)} ${item.title}`
: inProgress
: item.viewOffset
? remaining(item)
: [item.year, duration(item.duration)].filter(Boolean).join(' · ');
return (
@ -265,25 +253,12 @@ export const LandscapeCard = memo(function LandscapeCard({ item, continueWatchin
<div className="card-hover" />
<CardActions item={item} ctx={{ continueWatching }} />
{episodeStyle && <WatchBadge item={item} />}
<ProgressLine item={item} always={continueWatching} />
<ProgressLine item={item} />
</div>
{showTitle && (
<div className="card-caption">
<div className="card-title" title={title}>
{isEp && !episodeStyle && item.grandparentId ? (
<button
className="card-title-link"
tabIndex={-1}
onClick={(e) => {
e.stopPropagation();
navigate({ name: 'item', id: item.grandparentId, title: item.grandparentTitle });
}}
>
{title}
</button>
) : (
title
)}
{title}
</div>
<div className="card-meta">{meta}</div>
</div>
@ -292,34 +267,6 @@ export const LandscapeCard = memo(function LandscapeCard({ item, continueWatchin
);
});
/** An episode with its synopsis, for a season's episode grid. `upNext` shows its resume point even when watched. */
export const EpisodeCard = memo(function EpisodeCard({ item, upNext = false }: { item: Item; upNext?: boolean }) {
const server = useServer();
const handlers = useCardHandlers(item);
const percent = useSettings((s) => s.watchedPercent);
const inProgress = !!item.viewOffset && (upNext || !isWatched(item, percent));
const title = item.index ? `${item.index}. ${item.title}` : item.title;
const meta = [duration(item.duration), inProgress ? remaining(item) : date(item.originallyAvailableAt)].filter(Boolean).join(' · ');
return (
<article className="card landscape episode-card" role="button" tabIndex={0} aria-label={title} {...handlers}>
<div className="card-cover">
<Artwork src={server.image(item.thumb || item.grandparentArt, 400, 225)} alt="" fallback={<span className="cover-fallback">{title}</span>} />
<div className="card-hover" />
<CardActions item={item} />
<WatchBadge item={item} />
<ProgressLine item={item} always={upNext} />
</div>
<div className="card-caption">
<div className="card-title" title={title}>
{title}
</div>
<div className="card-meta">{meta}</div>
{item.summary && <p className="episode-card-summary">{item.summary}</p>}
</div>
</article>
);
});
export function PersonCard({ name, role, thumb, onClick }: { name: string; role?: string; thumb?: string; onClick?: () => void }) {
const server = useServer();
const initials = name
@ -342,22 +289,15 @@ export function PersonCard({ name, role, thumb, onClick }: { name: string; role?
export function Shelf({ title, subtitle, onViewAll, children, className = '', kind = 'poster' }: { title: ReactNode; subtitle?: ReactNode; onViewAll?: () => void; children: ReactNode; className?: string; kind?: 'poster' | 'landscape' | 'people' | 'wide' }) {
const row = useRef<HTMLDivElement>(null);
const atStart = useRef(true);
const [edges, setEdges] = useState({ start: true, end: false });
const update = () => {
const el = row.current;
if (!el) return;
const start = el.scrollLeft < 8;
const end = el.scrollLeft + el.clientWidth >= el.scrollWidth - 8;
atStart.current = start;
// Runs on every scroll event; re-render only when an edge changes.
setEdges((prev) => (prev.start === start && prev.end === end ? prev : { start, end }));
};
// A row the viewer hasn't scrolled stays at its start when items are added
// in front (Continue Watching), rather than holding on to the old first card.
useLayoutEffect(() => {
if (atStart.current && row.current) row.current.scrollLeft = 0;
}, [children]);
useEffect(() => {
update();
const el = row.current;

View file

@ -2,11 +2,14 @@
`latest.json` is the feed the in-app updater reads (see `plugins.updater.endpoints` in
`src-tauri/tauri.conf.json`). It lists one signed build per platform:
`windows-x86_64` and `darwin-aarch64`.
`windows-x86_64`, `darwin-aarch64`, `darwin-x86_64` and `linux-x86_64`.
Regenerate it once a release has every platform's build uploaded (see
`docs/development.md` → Releases); it reads the release's assets on Forgejo:
Regenerate it after building a release, pointing at the release's download folder:
```bash
node scripts/update-manifest.mjs 0.2.0
node scripts/update-manifest.mjs 0.2.0 https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.2.0
```
Platforms built elsewhere can be merged in by listing their bundle folders in
`KALEIDO_BUNDLES` (separated by `;`). Existing platform entries are kept, so each OS
can publish independently.

View file

@ -1,11 +1,11 @@
{
"version": "1.0.1",
"notes": "A quicker start, a Stop button, and recovery when the server drops out mid-video.\r\n\r\n- Kaleido starts faster: the opening animation is shorter, so you reach your library in about a second.\r\n- The player has a Stop button, next to the forward controls, which closes the player completely instead of moving it to the miniplayer.\r\n- 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.",
"pub_date": "2026-11-17T17:47:20.996Z",
"platforms": {
"windows-x86_64": {
"signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NFZMQVRPVll0SHZPQWJWUlIyQnZEME10bldKUnYxSkhHWEJSWWxOT3FoVHp6NlNsU0dwdlg1UmUweGlEdzNoQnduSnora0dZempZS2ZWdFZLa3BIRkFJPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzk0OTM3NjI5CWZpbGU6S2FsZWlkb18xLjAuMV94NjQtc2V0dXAuZXhlCXZlcnNpb246MS4wLjEKeUI5aUJ4d3hONmVlNlBBWDFxQkFkYTV4WXU0eHIzb1ZKaVZjaDhpODhpbXdvL2RWRlhTRTBwQXJGV3hJYlg2RERnMDBhSFBRWHZDekxCRTVNNCtIRFE9PQo=",
"url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v1.0.1/Kaleido_1.0.1_x64-setup.exe"
"signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVURlZleWFKRzhRNU10Wmg5dG9WZmYwUkVSUDMya0VucTJST282UG9ublBxVmsxMzROYmNabTRyeDZ6ZTZaQm1rM0RvcEFGS01ncWhRN3ZRMmRtSldTR0FHNkVWdXlHMFFzPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzNDE0NDYwCWZpbGU6S2FsZWlkb18wLjEuMC1iZXRhLjRfeDY0LXNldHVwLmV4ZQl2ZXJzaW9uOjAuMS4wLWJldGEuNApiLzdwNkI3NTVzaGl4SFZrSVdHRW9ac1BVNUFlR3lZRW5MUFlqbTdsRlZuRnlEN0libUM5aTBvR2l3cWJvV0UzbkQ1cGo3MVhlWllrTHBiSHJ0b2NDQT09Cg==",
"url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.4/Kaleido_0.1.0-beta.4_x64-setup.exe"
}
}
},
"version": "0.1.0-beta.4",
"notes": "A Quality upscaling tier, with checks that upscaling is really running.\n\n- 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.\n- 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.\n- 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.",
"pub_date": "2026-10-31T02:41:31.551Z"
}

View file

@ -6,7 +6,7 @@ folder, which is ignored by git and fetched by a script:
| OS | Folder | How to fetch |
| --- | --- | --- |
| Windows | `windows/libmpv-2.dll` | `scripts/fetch-libmpv.ps1` (shinchiro `mpv-dev-x86_64` build) |
| macOS | `macos/libmpv.2.dylib` and the libraries it links | `scripts/fetch-libmpv.sh` (Homebrew `mpv`, made self-contained) |
| macOS | `macos/libmpv.2.dylib` | `scripts/fetch-libmpv.sh` (Homebrew `mpv`) |
| Linux | system `libmpv.so.2` | Install your distribution's `libmpv2` package |
At runtime Kaleido looks in the app's resources, beside the executable, here, and

View file

@ -34,10 +34,5 @@ export default defineConfig({
plugins: [react(), devSession()],
clearScreen: false,
server: { port: 1420, strictPort: true, watch: { ignored: ['**/src-tauri/**'] } },
build: {
target: 'es2022',
chunkSizeWarningLimit: 1500,
// The miniplayer window has a page of its own (src/mini/).
rollupOptions: { input: { main: path.resolve(import.meta.dirname, 'index.html'), mini: path.resolve(import.meta.dirname, 'mini.html') } },
},
build: { target: 'es2022', chunkSizeWarningLimit: 1500 },
});