diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ef98c0..89d5b1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,86 @@ # 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. diff --git a/docs/development.md b/docs/development.md index 7f2db78..dbf8d76 100644 --- a/docs/development.md +++ b/docs/development.md @@ -47,6 +47,12 @@ 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 diff --git a/package-lock.json b/package-lock.json index 71aea19..a12cc89 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "kaleido-desktop", - "version": "0.1.0-beta.13", + "version": "1.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "kaleido-desktop", - "version": "0.1.0-beta.13", + "version": "1.0.1", "dependencies": { "@fontsource-variable/inter": "^5.3.0", "@tanstack/react-query": "^5.105.0", diff --git a/package.json b/package.json index 758ab7c..ffa1da4 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "kaleido-desktop", "private": true, - "version": "0.1.0-beta.13", + "version": "1.0.1", "type": "module", "scripts": { "dev": "vite", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index d21aa89..fd8584e 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2173,7 +2173,7 @@ dependencies = [ [[package]] name = "kaleido" -version = "0.1.0-beta.13" +version = "1.0.1" dependencies = [ "fs2", "futures-util", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 6205fe5..c879aaf 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kaleido" -version = "0.1.0-beta.13" +version = "1.0.1" description = "Kaleido — a Plex client for Windows" authors = ["Elijah"] edition = "2021" diff --git a/src-tauri/src/downloads.rs b/src-tauri/src/downloads.rs index 2d3490c..89c183c 100644 --- a/src-tauri/src/downloads.rs +++ b/src-tauri/src/downloads.rs @@ -5,8 +5,9 @@ //! server-relative source path; resuming after a restart asks the interface for //! a freshly signed URL. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -47,10 +48,19 @@ 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, + /// Closes once the task has exited and let go of the file. + done: watch::Receiver<()>, +} + pub struct Downloads { items: Mutex>, dir: Mutex>, - cancels: Mutex>>, + workers: Mutex>, + generation: AtomicU64, permits: Arc, client: reqwest::Client, } @@ -60,7 +70,8 @@ impl Default for Downloads { Downloads { items: Mutex::new(Vec::new()), dir: Mutex::new(None), - cancels: Mutex::new(HashMap::new()), + workers: Mutex::new(HashMap::new()), + generation: AtomicU64::new(0), permits: Arc::new(Semaphore::new(MAX_ACTIVE)), client: reqwest::Client::builder() .connect_timeout(Duration::from_secs(20)) @@ -168,8 +179,11 @@ pub async fn download_start(app: AppHandle, 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!(".{}.jpg", sanitize(name))); + let target = folder.join(format!(".{stem}.{}.jpg", sanitize(name))); if fetch_to(&state.client, url, &target).await.is_ok() { local.insert(name.clone(), Value::String(target.display().to_string())); } @@ -204,21 +218,48 @@ async fn fetch_to(client: &reqwest::Client, url: &str, target: &Path) -> Result< tokio::fs::write(target, bytes).await.map_err(|e| e.to_string()) } +/// 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(app: AppHandle, id: String, url: String) { + let state = app.state::(); + let generation = state.generation.fetch_add(1, Ordering::Relaxed); let (tx, rx) = watch::channel(false); - app.state::().cancels.lock().insert(id.clone(), tx); + let (done_tx, done_rx) = watch::channel(()); + let previous = state.workers.lock().insert(id.clone(), Worker { generation, cancel: tx, done: done_rx }); + let previous = previous.map(|w| { + let _ = w.cancel.send(true); + w.done + }); tauri::async_runtime::spawn(async move { + // 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::().permits.clone(); let _permit = tokio::select! { p = permits.acquire_owned() => p, - _ = cancelled(rx.clone()) => return, + _ = cancelled(rx.clone()) => { release(&app, &id, generation); return; } }; - let result = transfer(&app, &id, &url, rx).await; - app.state::().cancels.lock().remove(&id); + // 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; + } 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); }); @@ -236,6 +277,30 @@ fn spawn(app: AppHandle, id: String, url: String) { }); } +/// Drops the worker entry, unless a newer task has taken it over. +fn release(app: &AppHandle, id: &str, generation: u64) { + let state = app.state::(); + 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(app: &AppHandle, id: &str) -> bool { + let Some(path) = app.state::().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) { while !*rx.borrow() { if rx.changed().await.is_err() { @@ -248,10 +313,7 @@ async fn cancelled(mut rx: watch::Receiver) { async fn transfer(app: &AppHandle, id: &str, url: &str, rx: watch::Receiver) -> Result { let Some(item) = app.state::().items.lock().iter().find(|i| i.id == id).cloned() else { return Ok(false) }; let final_path = PathBuf::from(&item.file_path); - let part_path = final_path.with_extension(format!( - "{}.part", - final_path.extension().and_then(|e| e.to_str()).unwrap_or("bin") - )); + let part_path = part_path(&final_path); let existing = tokio::fs::metadata(&part_path).await.map(|m| m.len()).unwrap_or(0); let client = app.state::().client.clone(); @@ -259,7 +321,10 @@ async fn transfer(app: &AppHandle, id: &str, url: &str, rx: watch if existing > 0 { request = request.header("Range", format!("bytes={existing}-")); } - let response = request.send().await.map_err(|e| format!("Could not reach the server: {e}"))?; + let response = tokio::select! { + r = request.send() => r.map_err(|e| format!("Could not reach the server: {e}"))?, + _ = cancelled(rx.clone()) => return Ok(false), + }; let status = response.status(); if status.as_u16() == 401 || status.as_u16() == 403 { return Err("The server does not allow downloads for this account.".into()); @@ -336,10 +401,14 @@ async fn transfer(app: &AppHandle, id: &str, url: &str, rx: watch Ok(true) } -fn cancel(app: &AppHandle, id: &str) { - if let Some(tx) = app.state::().cancels.lock().remove(id) { - let _ = tx.send(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(app: &AppHandle, id: &str) -> Option> { + let state = app.state::(); + let workers = state.workers.lock(); + let worker = workers.get(id)?; + let _ = worker.cancel.send(true); + Some(worker.done.clone()) } #[tauri::command] @@ -356,7 +425,7 @@ pub fn download_pause(app: AppHandle, id: String) { #[tauri::command] pub fn download_resume(app: AppHandle, id: String, url: String) { - cancel(&app, &id); + // `spawn` takes over from a transfer still winding down. update(&app, &id, |i| { i.status = Status::Queued; i.error = None; @@ -366,7 +435,7 @@ pub fn download_resume(app: AppHandle, id: String, url: String) { #[tauri::command] pub async fn download_remove(app: AppHandle, id: String, delete_files: bool) -> Result<(), String> { - cancel(&app, &id); + let running = cancel(&app, &id); let removed = { let state = app.state::(); let mut items = state.items.lock(); @@ -375,14 +444,24 @@ pub async fn download_remove(app: AppHandle, id: String, delete_f }; if let (Some(item), true) = (removed, delete_files) { let path = PathBuf::from(&item.file_path); - // Give the cancelled transfer a moment to release its file handle. - tokio::time::sleep(Duration::from_millis(150)).await; + // 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; + } let _ = tokio::fs::remove_file(&path).await; - let part = path.with_extension(format!("{}.part", path.extension().and_then(|e| e.to_str()).unwrap_or("bin"))); - let _ = tokio::fs::remove_file(&part).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 = app + .state::() + .items + .lock() + .iter() + .filter_map(|i| i.meta.get("localAssets").and_then(Value::as_object)) + .flat_map(|a| a.values().filter_map(Value::as_str).map(str::to_owned)) + .collect(); if let Value::Object(assets) = &item.meta["localAssets"] { for v in assets.values() { - if let Some(p) = v.as_str() { + if let Some(p) = v.as_str().filter(|p| !in_use.contains(*p)) { let _ = tokio::fs::remove_file(p).await; } } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 9b74fde..e6ecb1d 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Kaleido", - "version": "0.1.0-beta.13", + "version": "1.0.1", "identifier": "tv.kaleido.desktop", "build": { "beforeDevCommand": "npm run dev", diff --git a/src/app/App.tsx b/src/app/App.tsx index 6623697..c0e8786 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -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, win } from '../platform/native'; +import { isMac, isNative, win } from '../platform/native'; import { usePlayer } from '../player/store'; import { PlayerOverlay } from '../player/PlayerOverlay'; import { DialogHost } from '../screens/dialogs/DialogHost'; @@ -111,7 +111,9 @@ function useGlobalShortcuts() { 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; - useRouter.getState().back(); + // Esc leaves full screen first (kept from the player when it went to the corner). + if (e.key === 'Escape' && isNative) win.isFullscreen().then((fs) => (fs ? win.setFullscreen(false) : useRouter.getState().back())); + else useRouter.getState().back(); } else if ((e.ctrlKey || e.metaKey) && e.key === ',') { e.preventDefault(); navigate({ name: 'settings', mode: 'app', tab: 'general' }); diff --git a/src/app/TopBar.tsx b/src/app/TopBar.tsx index 3c538fc..6007226 100644 --- a/src/app/TopBar.tsx +++ b/src/app/TopBar.tsx @@ -19,13 +19,21 @@ const NAV = [ /** 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; let off: (() => void) | undefined; - const sync = () => win.isMaximized().then(setMaximized); + let gone = false; + const sync = () => { + win.isMaximized().then((m) => !gone && setMaximized(m)); + win.isFullscreen().then((f) => !gone && setFullscreen(f)); + }; sync(); - win.onResized(sync).then((u) => (off = u)); - return () => off?.(); + win.onResized(sync).then((u) => (gone ? u() : (off = u))); + return () => { + gone = true; + off?.(); + }; }, []); if (!isNative || isMac) return null; return ( @@ -33,9 +41,15 @@ export function WindowControls() { - + {fullscreen ? ( + + ) : ( + + )} diff --git a/src/app/format.ts b/src/app/format.ts index 47d138a..e4a7ba9 100644 --- a/src/app/format.ts +++ b/src/app/format.ts @@ -36,10 +36,19 @@ 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.viewOffset > 0 && item.duration > 0) return item.viewCount > 0 && item.viewOffset / item.duration >= percent / 100; - return item.viewCount > 0; + 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; } export function remainingEpisodes(item: Item): number { @@ -174,17 +183,24 @@ export function plural(n: number, word: string, pluralWord = `${word}s`) { return `${n.toLocaleString()} ${n === 1 ? word : pluralWord}`; } -/** Hex UltraBlur colors → CSS gradient layers for the artwork colour wash. */ -export function washGradient(u: Item['ultraBlur'], strength = 1): string { - if (!u) return ''; +/** 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; 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(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%)`, + `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%)`, ].join(', '); } diff --git a/src/app/keyboardNav.ts b/src/app/keyboardNav.ts index 8a77535..4e01527 100644 --- a/src/app/keyboardNav.ts +++ b/src/app/keyboardNav.ts @@ -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, episode lists and people rows. + * the same across shelves, grids and people rows. */ -const TARGETS = '.card, .person-card:not(:disabled), .episode-row, .shelf-title-link'; +const TARGETS = '.card, .person-card:not(:disabled), .shelf-title-link'; function center(r: DOMRect) { return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; diff --git a/src/app/queries.ts b/src/app/queries.ts index 80e5bb9..e3aceb3 100644 --- a/src/app/queries.ts +++ b/src/app/queries.ts @@ -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 } from './session'; +import { useServer, useSession } from './session'; import { useSettings } from './settings'; export const queryClient = new QueryClient({ @@ -27,6 +27,13 @@ export const PROGRESS = { ...WATCH_STATE, staleTime: 15_000, refetchInterval: 60 // 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(); diff --git a/src/downloads/store.ts b/src/downloads/store.ts index 9820dc8..d56474e 100644 --- a/src/downloads/store.ts +++ b/src/downloads/store.ts @@ -52,12 +52,16 @@ 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. */ -function slim(raw: any) { +/** + * Trims metadata kept for offline display: no extras, related hubs or raw blobs, and + * only the version downloaded, so its streams describe the file that plays. + */ +function slim(raw: any, mediaIndex: number) { const { Extras, Related, OnDeck, ...rest } = raw ?? {}; void Extras; void Related; void OnDeck; + if (Array.isArray(rest.Media) && rest.Media[mediaIndex]) rest.Media = [rest.Media[mediaIndex]]; return rest; } @@ -102,9 +106,12 @@ export const useDownloads = create((set, get) => ({ try { await get().init(); const item = await api.metadata(server, input.id); - const media = item.media[0]; + // A download is one file. A version split across several (CD1, CD2) would be + // kept as its first part only, so prefer a version in one piece. + const media = item.media.find((m) => m.parts.length === 1) ?? item.media[0]; const part = media?.parts[0]; 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.'); @@ -129,7 +136,7 @@ export const useDownloads = create((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) } satisfies DownloadMeta, + meta: { serverId: server.machineId, serverName: server.name, ratingKey: item.id, partKey: part.key, raw: slim(item.raw, item.media.indexOf(media)) } satisfies DownloadMeta, assets, }, }); diff --git a/src/player/PlayerOverlay.tsx b/src/player/PlayerOverlay.tsx index 10d2760..5094fb2 100644 --- a/src/player/PlayerOverlay.tsx +++ b/src/player/PlayerOverlay.tsx @@ -14,6 +14,7 @@ import { separateMini } from './miniWindow'; import { PREPARING_NOTICE_MS, UPSCALING_ORDER, hasFailed, readDiagnostics, requestEnhancement, tierAvailable, toggleBypass, type Diagnostics } from './enhance'; import { toast } from '../ui/overlays'; import type { Item } from '../plex/types'; +import { PostPlay } from './PostPlay'; const HIDE_AFTER = 3000; @@ -505,8 +506,8 @@ 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); @@ -519,15 +520,17 @@ function SkipButton() { 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 mode = marker?.type === 'intro' ? skipIntro : skipCredits; - const auto = !!marker && mode === 'auto' && !(marker.type === 'credits' && nextUp); + 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); - seek(marker.end / 1000); + if (marker.type === 'credits' && item?.type === 'episode') usePlayer.getState().showPostPlay(); + else seek(marker.end / 1000); }; const cancel = () => { if (!pending) return; @@ -567,8 +570,7 @@ function SkipButton() { return () => window.removeEventListener('keydown', onKey, true); }, [counting]); - if (!marker || mode === 'off' || countdown !== null) return null; - if (marker.type === 'credits' && nextUp) return null; + if (!marker || (episodeCredits && !postPlayDismissed) || mode === 'off' || countdown !== null) return null; const what = marker.type === 'intro' ? 'intro' : 'credits'; const elapsed = counting ? Math.max(0, position - counting.from) : 0; return ( @@ -588,41 +590,6 @@ function SkipButton() { ); } -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 ( -
e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}> -
- - {countdown > 0 && ( - - - - )} -
-
- Next episode{countdown > 0 ? ` in ${countdown}` : ''} - - {episodeLabel(nextUp)} · {nextUp.title} - -
- - -
-
-
- ); -} - /** The title opens its show or movie page, with playback moving to the miniplayer. */ function openFromPlayer(id: string | undefined) { if (!id) return; @@ -791,7 +758,7 @@ function MiniPlayer() {
- {(loading || st.buffering) && !st.error ? ( + {(loading || st.buffering || st.reconnecting) && !st.error ? ( ) : st.error ? ( Playback stopped @@ -844,6 +811,9 @@ 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; @@ -941,7 +911,7 @@ export function PlayerOverlay() { }, [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 && !visible && st.firstFrame && !st.error; + const chromeHidden = st.open && !st.mini && !st.postPlay && !visible && st.firstFrame && !st.error; useEffect(() => { if (!chromeHidden) return; win.setButtonsVisible(false); @@ -951,6 +921,7 @@ export function PlayerOverlay() { 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 : ; + if (st.postPlay && !st.error) return ; const item = st.item; const loading = !st.firstFrame && !st.error; const art = item.type === 'episode' ? item.grandparentArt || item.art : item.art; @@ -994,10 +965,12 @@ export function PlayerOverlay() { {!st.fullscreen && }
- {(loading || st.buffering || st.seeking || preparing) && !st.error && ( + {(loading || st.buffering || st.seeking || preparing || st.reconnecting) && !st.error && (
- {preparing && ( + {st.reconnecting ? ( +

Lost connection to {server?.name ?? 'the server'}

+ ) : preparing && (

Preparing {UPSCALING[st.enhance.active].label} upscaling First time on this computer only @@ -1036,7 +1009,6 @@ export function PlayerOverlay() { )} - {!st.error && (

e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}> @@ -1053,6 +1025,8 @@ export function PlayerOverlay() {
+ {/* Balances Stop on the other side, so play/pause stays centred. */} +
+ + {!fullscreen && } +
+ +
+
+
+
+ + {upcoming || !contextReady ? 'Up next' : 'More to watch'} + + {item.grandparentId ? ( + + ) : ( + + )} + {upcoming ? ( + <> +

{upcoming.title}

+ + {upcoming.summary &&

{upcoming.summary}

} + + + ) : ( + contextReady &&

You’ve reached the end of this series.

+ )} +
+
+ + {server && } +
+ ); +} + +/** + * 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, frame: React.RefObject) { + 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 ( +
+
+ + {episodeLabel(item)} · {item.title} + + −{clock(Math.max(0, total - position))} +
+
+ +
+
+ ); +} + +/** + * 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 }) { + const counting = usePlayer((s) => s.countdown !== null && s.countdownTotal > 0); + const fill = useRef(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 ( + + ); +} + +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(null); + useLayoutEffect(() => { + const row = seasonRow.current?.querySelector('.shelf'); + const current = row?.querySelector('[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 ( +
+ {episodes.length > 0 && ( +
+ + {episodes.map((ep) => ( + choose(ep)} + /> + ))} + +
+ )} + {shows.length > 0 && ( + + {shows.map((show) => ( + void browse(show)} /> + ))} + + )} +
+ ); +} + +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 ( +
{ + if (e.key !== 'Enter' && e.key !== ' ') return; + e.preventDefault(); + onChoose(); + }} + > +
+ {title}} /> +
+ {episode && !current && ( +
+ +
+ )} + {progress > 0 && ( + + + + )} +
+
+
+ {title} +
+ {caption &&
{caption}
} +
+
+ ); +} diff --git a/src/player/miniWindow.ts b/src/player/miniWindow.ts index 2f1966c..eebe2b2 100644 --- a/src/player/miniWindow.ts +++ b/src/player/miniWindow.ts @@ -30,6 +30,7 @@ interface PlayerView { duration: number; firstFrame: boolean; buffering: boolean; + reconnecting: boolean; error: string; } @@ -50,7 +51,8 @@ function view(st: PlayerView): MiniState { position: st.position, duration: st.duration, loading: !st.firstFrame && !st.error, - buffering: st.buffering, + // Waiting for the server to come back shows as buffering. + buffering: st.buffering || st.reconnecting, error: !!st.error, }; } diff --git a/src/player/store.test.ts b/src/player/store.test.ts new file mode 100644 index 0000000..df87345 --- /dev/null +++ b/src/player/store.test.ts @@ -0,0 +1,280 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { MpvEvent } from './engine'; + +const harness = vi.hoisted(() => { + const memory = new Map(); + 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[]) => 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[]) => 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(); + }); +}); diff --git a/src/player/store.ts b/src/player/store.ts index ea32564..0606a41 100644 --- a/src/player/store.ts +++ b/src/player/store.ts @@ -2,12 +2,14 @@ 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 { channelLabel } from '../app/format'; import { invalidateLibrary } from '../app/queries'; -import { keepAwake, isNative, win } from '../platform/native'; +import { invoke, keepAwake, isNative, win } from '../platform/native'; import { mpv, type MpvEvent, type MpvTrack } from './engine'; import { toast } from '../ui/overlays'; import { stopThemeMusic } from './theme'; @@ -32,6 +34,10 @@ 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 { @@ -44,6 +50,8 @@ interface PlayerState { 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; @@ -66,7 +74,10 @@ interface PlayerState { 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. */ @@ -96,6 +107,8 @@ interface PlayerState { playNext(): Promise; playPrevious(): Promise; cancelCountdown(): void; + showPostPlay(): void; + dismissPostPlay(): void; toggleFullscreen(): Promise; previewAt(seconds: number): string; } @@ -107,13 +120,23 @@ let lastReport = 0; let sessionAnswered = false; let reportTimer: ReturnType | null = null; let countdownTimer: ReturnType | 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; -const server = () => useSession.getState().server; +/** + * 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; /** * mpv applies its volume on a cubic curve, so halfway on a linear slider was @@ -218,8 +241,34 @@ 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 { + if (state === 'paused' || state === 'stopped') saveLocalProgress(); const s = server(); const { item, position, delivery } = usePlayer.getState(); if (!s || !item || !session || item.type === 'clip') return Promise.resolve(false); @@ -266,9 +315,11 @@ function onTerminated(text: string) { function checkScrobble() { const { item, position, duration } = usePlayer.getState(); const s = server(); - if (!item || !s || scrobbled || !duration || item.type === 'clip') return; + if (!item || 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) @@ -291,30 +342,142 @@ async function findNeighbours(item: Item): Promise<{ prevUp: Item | null; nextUp } } +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.nextUp || st.countdown !== null || st.postPlayDismissed) return; + if (!st.open || !st.postPlay || st.error || !st.nextUp || st.postPlayDismissed || st.countdown !== null) return; const settings = useSettings.getState(); - if (!settings.autoplayNext) { - usePlayer.setState({ countdown: -1 }); - return; - } - usePlayer.setState({ countdown: settings.countdownSeconds }); - countdownTimer && clearInterval(countdownTimer); + 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); countdownTimer = setInterval(() => { - 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); + 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); } 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 { + 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. */ @@ -334,36 +497,7 @@ async function applyInitialTracks(tracks: MpvTrack[]) { if (!subs.length) subs = tracks.filter((t) => t.type === 'sub').map(mpvTrackLabel); } - // 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 ?? ''; - } - } + const { audioKey, subKey } = preferredTracks(audio, subs, prefs, st.audioKey, st.subKey); usePlayer.setState({ audioTracks: audio, subTracks: subs, audioKey, subKey }); if (direct) { const a = audio.find((t) => t.key === audioKey); @@ -467,7 +601,7 @@ function onEvent(e: MpvEvent) { } break; case 'eof-reached': - if (v === true) onEnded(); + if (v === true) onStreamEnd(); break; } break; @@ -488,11 +622,14 @@ function onEvent(e: MpvEvent) { // (Briefly: an unreachable server shouldn't hold up the error.) const failed = session; Promise.race([report('buffering'), new Promise((r) => setTimeout(() => r(false), 3000))]).then((terminated) => { - if (terminated || !usePlayer.getState().open || session !== failed) return; + 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') onEnded(); + } else if (e.reason === 'eof') onStreamEnd(); break; case 'log': noteMpvLog(e.level, e.prefix, e.text); @@ -501,6 +638,9 @@ 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() { @@ -509,14 +649,74 @@ 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' }); + st.play(st.item, { offsetMs: st.position * 1000 || startOffsetMs, mediaIndex: st.mediaIndex, quality: '1080', tracks: currentTracks(st) }); } function maybeCredits(pos: number) { const st = usePlayer.getState(); - 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(); + 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 | 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 { + 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; } function onEnded() { @@ -525,7 +725,11 @@ function onEnded() { usePlayer.setState({ ended: true }); report('stopped'); checkScrobble(); - if (st.nextUp) startCountdown(); + // 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(); + } } export const usePlayer = create((set, get) => ({ @@ -537,6 +741,7 @@ export const usePlayer = create((set, get) => ({ firstFrame: false, error: '', terminated: false, + reconnecting: false, position: 0, duration: 0, cacheTime: 0, @@ -557,7 +762,10 @@ export const usePlayer = create((set, get) => ({ ended: false, nextUp: null, prevUp: null, + episodeContextReady: false, countdown: null, + countdownTotal: 0, + postPlay: false, postPlayDismissed: false, fullscreen: false, mini: false, @@ -567,7 +775,8 @@ export const usePlayer = create((set, get) => ({ async play(input, opts = {}) { const token = ++loadToken; - const s = server(); + // Closing or starting something else while this one is still setting up wins. + const stale = () => token !== loadToken; const prefs = useSettings.getState(); stopThemeMusic(); stopCountdown(); @@ -576,13 +785,29 @@ export const usePlayer = create((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'); - if (previous.delivery?.session && s) stopTranscode(s, previous.delivery.session); + const ps = server(); + if (previous.delivery?.session && ps) stopTranscode(ps, 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 = await win.isFullscreen().catch(() => false); + wasFullscreenBeforePlay = fullscreenNow; } set({ open: true, @@ -590,6 +815,7 @@ export const usePlayer = create((set, get) => ({ firstFrame: false, error: '', terminated: false, + reconnecting: false, position: (opts.offsetMs ?? 0) / 1000, lastSeek: 0, duration: input.duration / 1000, @@ -599,16 +825,19 @@ export const usePlayer = create((set, get) => ({ ended: false, nextUp: null, prevUp: null, + episodeContextReady: false, countdown: null, + countdownTotal: 0, + postPlay: false, postPlayDismissed: false, chapters: [], audioTracks: [], subTracks: [], - audioKey: '', - subKey: '__init', + audioKey: opts.tracks?.audioKey ?? '', + subKey: opts.tracks?.subKey ?? '__init', video: null, - fullscreen: wasFullscreenBeforePlay, - mini: false, + fullscreen: fullscreenNow, + mini: opts.keepMini ? previous.open && previous.mini : false, videoGamma: '', enhance: { ...previous.enhance, bypass: false, preparing: false }, }); @@ -619,16 +848,16 @@ export const usePlayer = create((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 (token !== loadToken) return; + if (stale()) return; const mediaIndex = Math.min(opts.mediaIndex ?? 0, Math.max(0, item.media.length - 1)); - const media = item.media[mediaIndex]; + let 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); - session = crypto.randomUUID(); - sessionAnswered = false; - scrobbled = false; + 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; let delivery: Delivery; if (opts.localFile) { @@ -638,30 +867,52 @@ export const usePlayer = create((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 }), + url: transcodeUrl(s, item, { mediaIndex, quality, offsetMs, session: tsession, local, audioStreamID, subtitleStreamID: subtitleStreamID || undefined }), 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: streams.filter((x) => x.streamType === 2).map(audioTrackFromStream), - subTracks: streams.filter((x) => x.streamType === 3).map(subTrackFromStream), + 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); }); await mpv.init({ hwdec: prefs.hwdec, hdr: prefs.hdrPassthrough }); if (!unlisten) unlisten = await mpv.on(onEvent); - if (token !== loadToken) return; + if (stale()) return; // mpv keeps pause across files: a title paused and closed would start paused. await mpv.set('pause', false); await mpv.set('mute', false); @@ -669,16 +920,24 @@ export const usePlayer = create((set, get) => ({ 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); @@ -686,7 +945,6 @@ export const usePlayer = create((set, get) => ({ const st = get(); if (st.open && !st.ended) report(st.paused ? 'paused' : st.buffering ? 'buffering' : 'playing'); }, 10000); - findNeighbours(item).then((n) => token === loadToken && set(n)); } catch (e: any) { if (token !== loadToken) return; set({ error: e?.message ?? String(e), buffering: false }); @@ -697,11 +955,17 @@ export const usePlayer = create((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) { @@ -710,14 +974,25 @@ export const usePlayer = create((set, get) => ({ await mpv.command('stop').catch(() => {}); await mpv.show(false).catch(() => {}); } - set({ open: false, mini: false, item: null, delivery: null, error: '', terminated: false, countdown: null, nextUp: null, prevUp: null, firstFrame: false }); - const fs = await win.isFullscreen().catch(() => false); - if (fs && !wasFullscreenBeforePlay) win.setFullscreen(false); + 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); + } 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 }); @@ -729,10 +1004,7 @@ export const usePlayer = create((set, get) => ({ 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.countdown !== null) { - stopCountdown(); - set({ countdown: null }); - } + if (st.postPlay) st.dismissPostPlay(); mpv.command('seek', target.toFixed(3), 'absolute+exact').catch(() => {}); }, @@ -768,12 +1040,9 @@ export const usePlayer = create((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 }); - // Full screen was for the video; browsing goes back to the window. - if (st.fullscreen && !wasFullscreenBeforePlay) { - await win.setFullscreen(false).catch(() => {}); - set({ fullscreen: false }); - } if (separateMini) { // Once the page is opaque again (no video in it), the video moves into // the miniplayer's own window (miniWindow.ts). @@ -794,35 +1063,30 @@ export const usePlayer = create((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) { - await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality }); + // 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 } }); 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 }); - usePlayer.setState({ subKey: key }); + await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality, tracks: { ...currentTracks(st), 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 }); + await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: q, tracks: currentTracks(st) }); }, async selectVersion(index) { @@ -835,13 +1099,15 @@ export const usePlayer = create((set, get) => ({ const st = get(); stopCountdown(); if (!st.nextUp) return; - await st.play(st.nextUp, { resume: true, quality: st.quality }); + // 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: true, quality: st.quality }); + await st.play(st.prevUp, { resume: false, quality: st.quality }); }, cancelCountdown() { @@ -849,6 +1115,17 @@ export const usePlayer = create((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); @@ -885,6 +1162,31 @@ usePlayer.subscribe((st, prev) => { 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; +}); + /** Subtitle look changes apply to the playing video straight away. */ const SUBTITLE_PREFS = ['subtitleScale', 'subtitleColor', 'subtitleEdge', 'subtitleBox', 'subtitleBold', 'subtitlePosition'] as const; useSettings.subscribe((prefs, prev) => { diff --git a/src/plex/client.ts b/src/plex/client.ts index 3548c35..a64ce79 100644 --- a/src/plex/client.ts +++ b/src/plex/client.ts @@ -121,23 +121,41 @@ export async function plexRequest(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((_, 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 { - 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); + 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); + } } 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 { diff --git a/src/plex/playback.ts b/src/plex/playback.ts index 60408da..39464b1 100644 --- a/src/plex/playback.ts +++ b/src/plex/playback.ts @@ -39,6 +39,10 @@ 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), diff --git a/src/plex/plex.test.ts b/src/plex/plex.test.ts index 8be9e2e..fdd06ff 100644 --- a/src/plex/plex.test.ts +++ b/src/plex/plex.test.ts @@ -3,7 +3,7 @@ import { parseItem, parseScores } from './parse'; import { isLocalAddress } from './account'; import { partAt } from './playback'; import { headerSafe } from './client'; -import { duration, formatBadges, isWatched, remaining, washGradient } from '../app/format'; +import { duration, formatBadges, isWatched, remaining, resumable, washGradient } from '../app/format'; import { buildFeatures } from '../screens/discover'; import type { Hub } from './types'; @@ -65,10 +65,16 @@ describe('parsing', () => { }); describe('watched rules', () => { - 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); + it('keeps a title watched while it is being rewatched', () => { + expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 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', () => { diff --git a/src/screens/Item.tsx b/src/screens/Item.tsx index ebaf887..dba8e82 100644 --- a/src/screens/Item.tsx +++ b/src/screens/Item.tsx @@ -4,12 +4,12 @@ import type { Item } from '../plex/types'; import { PROGRESS, useChildren, useItem, useRelated, useServerQuery } from '../app/queries'; import { useServer } from '../app/session'; import { useSettings } from '../app/settings'; -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 { 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 { Backdrop } from '../ui/Backdrop'; -import { Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media'; -import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader, Select } from '../ui/primitives'; +import { EpisodeCard, Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media'; +import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader } from '../ui/primitives'; import { Icon } from '../ui/Icon'; import { openMenu } from '../ui/overlays'; import { useDownloads } from '../downloads/store'; @@ -255,11 +255,12 @@ function AboutPanel({ item }: { item: Item }) { // —— Movie —————————————————————————————————————————————————————————— function MovieDetail({ item }: { item: Item }) { - const resume = item.viewOffset > 0 && !isWatched(item); + const resume = resumable(item); return (
- + {/* The Resume button carries the time left; the facts give the runtime. */} +
- {p > 0 && !watched && ( - - - - )} -
-
-

- {ep.title} - {watched && } -

-
- {[duration(ep.duration), ep.originallyAvailableAt ? date(ep.originallyAvailableAt) : '', ep.viewOffset && !watched ? remaining(ep) : ''].filter(Boolean).join(' · ')} -
- {ep.summary &&

{ep.summary}

} -
- +
+ {episodes.map((ep) => ( + + ))}
); } -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; +function EpisodesSection({ episodes, subtitle, upNextId }: { episodes: Item[] | undefined; subtitle?: string; upNextId?: string }) { return (
-
-

Episodes

- {showPicker && seasons.length > 1 && ( - set('skipIntro', v)} options={skipOptions} /> - + set('countdownSeconds', v)} options={[5, 8, 10, 15, 20, 30].map((v) => ({ value: v, label: `${v} seconds` }))} /> + + set('seekStep', v)} options={[5, 10, 15, 30].map((v) => ({ value: v, label: `${v} seconds` }))} /> diff --git a/src/styles/app.css b/src/styles/app.css index a1d258e..ff3508c 100644 --- a/src/styles/app.css +++ b/src/styles/app.css @@ -270,10 +270,11 @@ 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). */ + aperture (held for the first quarter of the exit, then decelerating). + The duration matches EXIT_MS in Splash.tsx. */ html.splash-arrival .app-shell, html.splash-arrival .auth-screen { - animation: splash-arrival 640ms linear both; + animation: splash-arrival 540ms linear both; } @keyframes splash-arrival { 0% { @@ -515,6 +516,12 @@ 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 { @@ -528,14 +535,42 @@ 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: ''; + inherits: false; + initial-value: transparent; +} +@property --wash-tl { + syntax: ''; + inherits: false; + initial-value: transparent; +} +@property --wash-br { + syntax: ''; + inherits: false; + initial-value: transparent; +} +@property --wash-bl { + syntax: ''; + 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; @@ -819,6 +854,7 @@ 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; } @@ -1057,6 +1093,23 @@ 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; diff --git a/src/styles/player.css b/src/styles/player.css index 8233fec..d09a418 100644 --- a/src/styles/player.css +++ b/src/styles/player.css @@ -350,6 +350,10 @@ html.os-macos:not(.window-fullscreen) .player-top { .player-controls-center { gap: 10px; } +.player-icon-spacer { + width: 44px; + height: 44px; +} .player-icon:disabled { opacity: 0.32; pointer-events: none; @@ -655,9 +659,8 @@ html.os-macos:not(.window-fullscreen) .player-top { min-width: 340px; } -/* Skip & post-play: above the bottom chrome, whose title row spans the full width behind them. */ -.skip-button, -.post-play { +/* The skip button sits above the bottom chrome. */ +.skip-button { z-index: 1; } .skip-button { @@ -705,74 +708,254 @@ html.os-macos:not(.window-fullscreen) .player-top { .skip-button > * { position: relative; } -.post-play { - position: absolute; - right: clamp(24px, 3.5vw, 56px); - bottom: 150px; - display: flex; - 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); -} -.post-play-art { - position: relative; - width: 180px; - aspect-ratio: 16 / 9; - border-radius: 8px; - overflow: hidden; - flex: none; - background: #000; -} -.post-play-art img { - width: 100%; - height: 100%; - object-fit: cover; -} -.post-play-ring { - position: absolute; - inset: 0; - margin: auto; - width: 46px; - height: 46px; - transform: rotate(-90deg); -} -.post-play-ring circle { - fill: rgba(0, 0, 0, 0.45); - stroke: #fff; - stroke-width: 3; - stroke-dasharray: 107; - animation: ring 8s linear forwards; -} -@keyframes ring { - from { - stroke-dashoffset: 107; - } - to { - stroke-dashoffset: 0; - } -} -.post-play-text { +/* —— 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 { display: flex; flex-direction: column; - gap: 6px; - min-width: 0; + --up-top: 64px; + --up-video-w: clamp(320px, 34vw, 640px); } -.post-play-text b { - font-size: 14px; +.up-next-scene { + position: absolute; + inset: 0; overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; + isolation: isolate; + background: var(--bg); + pointer-events: none; } -.post-play-text .actions { - margin-top: 6px; +.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 { + 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%; + 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; +} +.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; + height: 100%; + background: var(--accent); +} +.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 { + position: absolute; + inset: 0; + z-index: -1; + background: #f6f7f7; + transform: scaleX(0); + transform-origin: left; + will-change: transform; +} +.up-next-play:focus-visible { + outline: 2px solid #fff; + outline-offset: 3px; +} +.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); + } +} +.up-next-shelf .card { + scroll-margin-left: 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; + } +} +.up-next .card:focus-visible { + outline: none; } .player-error { position: absolute; diff --git a/src/styles/screens.css b/src/styles/screens.css index 64b7acd..1f617ce 100644 --- a/src/styles/screens.css +++ b/src/styles/screens.css @@ -430,6 +430,30 @@ 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; } @@ -580,122 +604,29 @@ button.chip:hover { } /* Episodes */ .episodes { - margin-bottom: 36px; + margin-bottom: 34px; } -.episodes-head { - display: flex; - align-items: center; - gap: 16px; - margin-bottom: 8px; +.episodes .shelf-head { + padding: 0; } -.episodes-head h2 { - margin: 0; - font-size: 19px; - letter-spacing: -0.028em; +.episode-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(clamp(240px, 19vw, 320px), 1fr)); + gap: 30px 16px; } -.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 { +.episode-grid .card { 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-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; +.episode-card-summary { + margin: 7px 0 0; font-size: 12px; line-height: 1.55; - color: #a8afb3; + color: #a1a8ac; display: -webkit-box; - -webkit-line-clamp: 2; + -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; } -.episode-more { - opacity: 0; -} -.episode-row:hover .episode-more { - opacity: 1; -} /* —— Search ————————————————————————————————————————————————— */ .search-hero { @@ -2045,10 +1976,6 @@ 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; } diff --git a/src/ui/Backdrop.tsx b/src/ui/Backdrop.tsx index 15116b6..f3338a9 100644 --- a/src/ui/Backdrop.tsx +++ b/src/ui/Backdrop.tsx @@ -1,21 +1,25 @@ -import { useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState, type CSSProperties } from 'react'; import type { Item } from '../plex/types'; import { useServer } from '../app/session'; import { useSettings } from '../app/settings'; -import { art, washGradient } from '../app/format'; +import { art, washColors } from '../app/format'; interface Layer { key: number; src: string; - wash: string; + blur: Item['ultraBlur']; 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. Changes crossfade; the - * outgoing layer stays until the new image has decoded. + * 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). */ 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(); @@ -25,39 +29,50 @@ 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 wash = colorWash && blur ? washGradient(blur) : ''; + const blurKey = blur ? `${blur.topLeft}${blur.topRight}${blur.bottomRight}${blur.bottomLeft}` : ''; useEffect(() => { - if (!src && !wash) return; + if (!src && !blur) return; setLayers((prev) => { - 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 }]; + 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 }]; }); - }, [src, wash]); + }, [src, blurKey]); - 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; - }); + 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; return ( <> {colorWash && (