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/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/store.ts b/src/player/store.ts index ea32564..3b1439d 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,8 @@ 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 }; } interface PlayerState { @@ -113,7 +117,16 @@ 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 +231,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 +305,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) @@ -317,25 +358,12 @@ function stopCountdown() { countdownTimer = null; } -/** Applies Plex/user track preferences once mpv has loaded the file. */ -async function applyInitialTracks(tracks: MpvTrack[]) { - const st = usePlayer.getState(); - const prefs = useSettings.getState(); - const direct = st.delivery?.mode !== 'transcode'; - const byFF = (type: string, idx: number) => tracks.find((t) => t.type === type && t['ff-index'] === idx && !t.external); - - let audio = st.audioTracks; - let subs = st.subTracks; - if (direct) { - audio = audio.map((t) => ({ ...t, mpvId: t.stream ? (byFF('audio', t.stream.index)?.id ?? null) : t.mpvId })); - subs = subs.map((t) => ({ ...t, mpvId: t.stream && !t.external ? (byFF('sub', t.stream.index)?.id ?? null) : t.mpvId })); - // Files without Plex stream info (offline) use mpv's own list. - if (!audio.length) audio = tracks.filter((t) => t.type === 'audio').map(mpvTrackLabel); - 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; +/** + * 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 = @@ -345,8 +373,6 @@ async function applyInitialTracks(tracks: MpvTrack[]) { 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); @@ -364,6 +390,87 @@ async function applyInitialTracks(tracks: MpvTrack[]) { 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. */ +async function applyInitialTracks(tracks: MpvTrack[]) { + const st = usePlayer.getState(); + const prefs = useSettings.getState(); + const direct = st.delivery?.mode !== 'transcode'; + const byFF = (type: string, idx: number) => tracks.find((t) => t.type === type && t['ff-index'] === idx && !t.external); + + let audio = st.audioTracks; + let subs = st.subTracks; + if (direct) { + audio = audio.map((t) => ({ ...t, mpvId: t.stream ? (byFF('audio', t.stream.index)?.id ?? null) : t.mpvId })); + subs = subs.map((t) => ({ ...t, mpvId: t.stream && !t.external ? (byFF('sub', t.stream.index)?.id ?? null) : t.mpvId })); + // Files without Plex stream info (offline) use mpv's own list. + if (!audio.length) audio = tracks.filter((t) => t.type === 'audio').map(mpvTrackLabel); + if (!subs.length) subs = tracks.filter((t) => t.type === 'sub').map(mpvTrackLabel); + } + + 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); @@ -501,6 +608,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,7 +619,7 @@ 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) { @@ -567,7 +677,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 +687,25 @@ export const usePlayer = create((set, get) => ({ return; } const previous = get(); + // 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; if (!previous.open) { triedFallback = false; wasFullscreenBeforePlay = await win.isFullscreen().catch(() => false); + if (stale()) return; } set({ open: true, @@ -604,8 +727,8 @@ export const usePlayer = create((set, get) => ({ chapters: [], audioTracks: [], subTracks: [], - audioKey: '', - subKey: '__init', + audioKey: opts.tracks?.audioKey ?? '', + subKey: opts.tracks?.subKey ?? '__init', video: null, fullscreen: wasFullscreenBeforePlay, mini: false, @@ -619,16 +742,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 +761,43 @@ 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 ?? {}), }); 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 +805,21 @@ 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); + if (stale()) return; keepAwake(true); report('buffering'); reportTimer && clearInterval(reportTimer); @@ -702,6 +843,10 @@ export const usePlayer = create((set, get) => ({ 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) { @@ -794,35 +939,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) { @@ -885,6 +1025,24 @@ usePlayer.subscribe((st, prev) => { bridgeMiniWindow(usePlayer); +/** + * 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/screens/LibraryBrowser.tsx b/src/screens/LibraryBrowser.tsx index 70d9cae..6d7e9c7 100644 --- a/src/screens/LibraryBrowser.tsx +++ b/src/screens/LibraryBrowser.tsx @@ -236,6 +236,33 @@ function LibraryGrid({ section, type, sort, filters, title, sortTitle }: { secti loadPage(0); }, [loadPage]); + // Pages are copied out of the cache, so nothing re-renders when it is invalidated + // (watched state, edits, deletions, library changes): fetch the loaded ones again. + const loaded = useRef(pages); + loaded.current = pages; + useEffect(() => { + const prefix = JSON.stringify([server.machineId, 'libraryPage', section.id, params]); + const due = new Set(); + let timer: ReturnType | null = null; + const unsubscribe = queryClient.getQueryCache().subscribe((event) => { + if (event.type !== 'updated' || event.action.type !== 'invalidate') return; + const key = event.query.queryKey; + const p = key[4]; + if (typeof p !== 'number' || !loaded.current[p] || JSON.stringify(key.slice(0, 4)) !== prefix) return; + due.add(p); + // One pass after the whole invalidation, not one per page as it happens. + timer ??= setTimeout(() => { + timer = null; + for (const page of due) loadPage(page); + due.clear(); + }); + }); + return () => { + unsubscribe(); + if (timer) clearTimeout(timer); + }; + }, [loadPage]); + const gap = 16; const target = CARD_WIDTH[posterSize]; const cols = Math.max(2, Math.floor((width + gap) / (target + gap))); diff --git a/src/ui/Hero.tsx b/src/ui/Hero.tsx index cc85c9c..122163a 100644 --- a/src/ui/Hero.tsx +++ b/src/ui/Hero.tsx @@ -43,14 +43,14 @@ export function Hero({ features, variant = 'home' }: { features: Feature[]; vari img.decode?.().catch(() => {}); }, [upcoming?.id]); + // Pause rotation when the hero is scrolled away; it picks up again on its return. + const [visible, setVisible] = useState(true); useEffect(() => { - if (!rotate || reduced || count < 2 || hover) return; + if (!rotate || reduced || count < 2 || hover || !visible) return; const t = setTimeout(() => go(index + 1), ROTATE_MS); return () => clearTimeout(t); - }, [index, rotate, reduced, count, hover]); + }, [index, rotate, reduced, count, hover, visible]); - // Pause rotation when the hero is scrolled away. - const [visible, setVisible] = useState(true); useEffect(() => { const el = root.current; if (!el) return; @@ -60,7 +60,6 @@ export function Hero({ features, variant = 'home' }: { features: Feature[]; vari }, []); const go = (i: number) => { - if (!visible && i !== index) return; setIndex(((i % count) + count) % count); setCopyKey((k) => k + 1); }; diff --git a/src/ui/media.tsx b/src/ui/media.tsx index da07294..11b9136 100644 --- a/src/ui/media.tsx +++ b/src/ui/media.tsx @@ -1,6 +1,6 @@ import { memo, useEffect, useRef, useState, type ReactNode } from 'react'; import type { Item } from '../plex/types'; -import { useServer } from '../app/session'; +import { useServer, useSession } from '../app/session'; import { useSettings } from '../app/settings'; import { art, displayTitle, duration, episodeLabel, formatBadges, isWatched, progress, remaining, remainingEpisodes } from '../app/format'; import { itemMenu, openItem, playWithVersion } from '../app/actions'; @@ -90,7 +90,8 @@ export function Facts({ item, withFormats = true, episode = true, children }: { /** Original clear-logo artwork, falling back to the title in type. */ export function TitleArt({ item, logo, className = '', maxWidth = 420, maxHeight = 130, as: As = 'h1' }: { item: Item; logo?: string; className?: string; maxWidth?: number; maxHeight?: number; as?: 'h1' | 'h2' }) { - const server = useServer(); + // The player shows this offline too, where there is no server to draw the logo from. + const server = useSession((s) => s.server); const path = logo ?? item.logo; const [failed, setFailed] = useState(false); const [ready, setReady] = useState(false); @@ -99,7 +100,7 @@ export function TitleArt({ item, logo, className = '', maxWidth = 420, maxHeight setReady(false); }, [path]); const title = item.type === 'episode' ? item.grandparentTitle : item.type === 'season' ? item.parentTitle || item.title : item.title; - if (!path || failed) + if (!path || failed || !server) return ( {title}