//! `shell.player`'s films and series' episodes (6 Nov 2026): the same `now`//! as a song's, dealt, sourced and written by the core; the platform's//! instrument (Apple's player) only plays it and reports where it stands.//!//! **Dealing.** A `film` plays alone, a series its episode in progress (else the first not//! watched, else its first); a `film_episode` plays with the episodes after//! it in its series' order. With the cinema row's `autoplay_next` off an//! episode of a series plays alone. The next episode is the queue's.//!//! **Where it starts** (`resume_at_s`): the saved place (`position_seconds`,//! `position`), unless that is in the first [`RESUME_FROM_S`] or the last//! [`END_WITHIN_S`] of what it lasts, when it is the start; `at_s` on the//! play says it (`0`, Play from the start).//!//! **What it plays from.** A film kept here names its whole file's key (`file`) or its//! stream's bundle (`bundle`, the platform's bookmark); otherwise `stream`//! is the address the object signs, minted by the core and signed again on//! `op: refresh_link` (once a minute at most: a link refused again that soon//! is refused for good, in the player's words).//!//! **The listen.** The instrument reports `listened { table, id, at_s,//! seconds, duration_s?, ended? }` every `save_every_s` while it plays//! ([`FILM_SAVE_EVERY_S`]), at a pause and as it leaves. A film's place, `watching`, its series' `position_at`, and one watch row per//! play (seconds forward, scrubbing aside), `finished` and the film or//! episode Marked watched at [`film_player::FINISHED_SHARE`].use std::sync::Arc;use std::time::Instant;use serde_json::{json, Map, Value};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{iso_of_ms, now_iso};usesuper::{bad, Began, Held, Kind, Listened};usecrate::methods::MethodError;usecrate::phone::film_player::{self, caption_of, changed, episodes_of, marked, resume_episode, row, series_of, written, FILM_TABLE};usecrate::phone::songs::{made, text_of, Row};usecrate::shell::client::ClientController;pubconst FILM_EPISODE_TABLE: &str = film_player::EPISODE_TABLE;/// A saved place this near the start is no place: it starts at the start.pubconst RESUME_FROM_S: f64 = 5.0;/// A saved place this near the end is the end: it starts at the start.pubconst END_WITHIN_S: f64 = 15.0;/// The skip buttons' jump, back and forward.pubconst SKIP_S: f64 = 15.0;/// How often it reports where a film or a series' episode stands while it/// plays (film-progress-flood, 17 Nov 2026). Each report writes the film's/// resume point and its watch row, and a film is hours long: at fifteen/// seconds a viewing was hundreds of writes of one row. A pause, a stop and/// the end report at once whatever this is, so only a crash mid-film loses/// up to this much of the place.pubconst FILM_SAVE_EVERY_S: f64 = 60.0;/// The count before the next episode of a series plays itself.pubconst NEXT_COUNT_S: f64 = 10.0;/// The soonest a film's link is signed again.pubconst RELINK_AFTER_MS: i64 = 60_000;/// The face settings row the film player keeps (`face_settings.json`).pubconst CINEMA_ROW: &str = "cinema";/// Where a play starts: the saved place inside the window, else the start.pubfn resume_at(position: f64, duration: f64) -> f64 {if !position.is_finite() || position < RESUME_FROM_S {return0.0; }if duration > 0.0 && position >= duration - END_WITHIN_S {return0.0; } position}/// How often a film or a series' episode reports where it stands while it plays.pubfn save_every(_kind: Kind) -> f64 { FILM_SAVE_EVERY_S}/// The share of its length past which a film or a series' episode is watched.pubfn played_share(_kind: Kind) -> f64 { film_player::FINISHED_SHARE}// ── dealing ─────────────────────────────────────────────────────────────────/// What a play of a film or a series' episode deals: what plays,/// first the one asked; empty with the person's words when nothing can.pub(super) structKindDeal {pub(super) items: Vec<Held>,pub(super) refusal: Option<String>,}pub(super) fn deal(client: &ClientController, table: &str, id: &str, at_s: Option<f64>, hidden: bool) -> Result<KindDeal, MethodError> {// A hidden title plays while Hidden is open on this copy: the core's own unlock (`cinemas.unlock`, asked by the// shell only after the phone's lock passed; this account's, two minutes, shut by `cinemas.lock` when the app// leaves the screen and by sign-out), with or without the shell's `hidden: true`. Shut, `hidden: true` is// refused `locked`, and without it a hidden title is not found (`records.get` refuses it).let open = !hidden && crate::phone::cinemas_home::inside_hidden(client, false).is_ok();if hidden || open {crate::phone::cinemas_home::inside_hidden(client, true)?;crate::phone::records::call(client, "records.get.unfiltered", &json!({"table": table, "id": id}))?; } else {crate::phone::records::call(client, "records.get", &json!({"table": table, "id": id}))?; }let autoplay = Cinema::read(client)?.autoplay_next;let (table, id) = (table.to_string(), id.to_string());let read = client .read_rows("shell.player", &mut |ctx| {let dealt = match table.as_str() { FILM_TABLE => film_deal(ctx, &id, autoplay)?, _ => series_episode_deal(ctx, &id, autoplay)?, };Ok(dealt) }) .map_err(|why| MethodError::new("unreadable", why))?;ifletSome(said) = read.get("refusal").and_then(Value::as_str) {returnOk(KindDeal { items: vec![], refusal: Some(said.to_string()) }); }// Discreet or not is worked out at each answer from the categories as they stand (`shell_player::veil`).letmut items: Vec<Held> = read["items"].as_array().into_iter().flatten().map(held_of).collect();iflet (Some(at), Some(first)) = (at_s.filter(|at| at.is_finite() && *at >= 0.0), items.first_mut()) { first.resume_at_s = at; }Ok(KindDeal { items, refusal: None })}/// A line of the cards set, filled.pub(super) fn card_line(name: &str, fills: &[(&str, &str)]) -> Result<String, MethodError> { cotton_core::rules::shell_lines::LineSet::shipped("cards") .and_then(|lines| lines.say(name, fills)) .ok_or_else(|| MethodError::new("unreadable", format!("the cards set says no line {name}")))}/// What a hidden title is called wherever the phone shows what plays (HIDE FROM SCREEN): the app's name alone.pub(super) fn discreet_title() -> String { film_line("stream.hidden_now_playing", &[]).unwrap_or_else(|_| "Cinemas".to_string())}/// A line of the cinemas set (a film's own words), filled: named here so the/// line-keys check reads the set at each call, not this file's cards set.fn film_line(name: &str, fills: &[(&str, &str)]) -> Result<String, MethodError> { cotton_core::rules::shell_lines::LineSet::shipped("cinemas") .and_then(|lines| lines.say(name, fills)) .ok_or_else(|| MethodError::new("unreadable", format!("the cinemas set says no line {name}")))}fn refused(name: &str, fills: &[(&str, &str)]) -> Result<Value, String> {let said = film_player::line(name, fills).map_err(|failure| failure.message)?;Ok(json!({ "refusal": said }))}fn film_deal(ctx: &Ctx<'_>, id: &str, autoplay: bool) -> Result<Value, String> {let film = row(ctx, FILM_TABLE, "id, title, kind, file, poster, minutes, position, needs_mac", id)?;let title = text_of(&film, "title");if text_of(&film, "kind") == "series" {let episodes = episodes_of(ctx, id)?;letSome(first) = resume_episode(&episodes) else { return refused("player.nothing_to_play", &[("name", &title)]) };return series_items(&episodes, &first.id.clone(), id, &title, autoplay); }let file = text_of(&film, "file");if file.is_empty() {let converting = film.get("needs_mac").and_then(Value::as_i64) == Some(1) || film.get("needs_mac") == Some(&Value::Bool(true));return refused(if converting { "player.converting" } else { "player.nothing_to_play" }, &[("name", &title)]); }let duration = film.get("minutes").and_then(Value::as_f64).filter(|minutes| *minutes > 0.0).map_or(0.0, |minutes| minutes * 60.0);let position = film.get("position").and_then(Value::as_f64).unwrap_or(0.0);Ok(json!({ "items": [{"kind": "film", "table": FILM_TABLE, "id": id, "file": file, "title": title, "cover": text_of(&film, "poster"),"duration": duration, "resume_at_s": resume_at(position, duration), }] }))}fn series_episode_deal(ctx: &Ctx<'_>, id: &str, autoplay: bool) -> Result<Value, String> {let held = row(ctx, FILM_EPISODE_TABLE, "id, series, season", id)?;let series = series_of(ctx, &held)?;let title = text_of(&row(ctx, FILM_TABLE, "title", &series)?, "title");let episodes = episodes_of(ctx, &series)?; series_items(&episodes, id, &series, &title, autoplay)}/// A series' episode, and with autoplay the ones after it that have a file.fn series_items(episodes: &[film_player::Episode], from: &str, series: &str, title: &str, autoplay: bool) -> Result<Value, String> {let at = episodes.iter().position(|episode| episode.id == from).ok_or("the episode is in no season of its series")?;let asked = &episodes[at];if asked.file.is_empty() {let caption = caption_of(asked)?;let name = if asked.title.is_empty() { caption } else { asked.title.clone() };// One still on the Mac says so, as a film does, not that there is nothing (his library on build 19).return refused(if asked.converting { "player.converting" } else { "player.nothing_to_play" }, &[("name", &name)]); }let following = if autoplay { &episodes[at + 1..] } else { &[][..] };letmut items = Vec::new();for episode in std::iter::once(asked).chain(following.iter().filter(|episode| !episode.file.is_empty())) {let duration = episode.minutes.map_or(0.0, |minutes| minutes * 60.0); items.push(json!({"kind": "film", "table": FILM_EPISODE_TABLE, "id": episode.id, "file": episode.file, "title": title,"caption": caption_of(episode)?, "series": series, "cover": episode.still, "duration": duration,"resume_at_s": resume_at(episode.position.unwrap_or(0.0), duration), })); }Ok(json!({ "items": items }))}fn held_of(item: &Value) -> Held {let text = |key: &str| item.get(key).and_then(Value::as_str).map(str::trim).filter(|said| !said.is_empty()).map(str::to_string);Held { kind: Kind::Film, table: text("table").unwrap_or_default(), id: text("id").unwrap_or_default(), file: text("file").unwrap_or_default(), title: text("title").unwrap_or_default(), artist: text("artist").unwrap_or_default(), cover: text("cover"), caption: text("caption"), series: text("series"), played: text("played"), duration_s: item.get("duration").and_then(Value::as_f64).unwrap_or(0.0), resume_at_s: item.get("resume_at_s").and_then(Value::as_f64).unwrap_or(0.0), ..Held::default() }}// ── what it plays from ──────────────────────────────────────────────────────/// A film's signed address, as the core minted it for the film playing.#[derive(Debug, Clone)]pub(super) structLink {pub(super) id: String,pub(super) url: String,pub(super) expires_at: String,pub(super) minted_ms: i64,}/// Whether `held` plays from a link the core must sign: a film this phone/// does not keep.pub(super) fn needs_link(client: &ClientController, held: &Held) -> Result<bool, MethodError> {if held.kind != Kind::Film {returnOk(false); }Ok(crate::phone::films::here(client, &held.file)?.state.as_deref() != Some(crate::phone::films::KEPT))}/// The object's signed address for `held`'s file; `Err` holds the words.pub(super) fn mint(client: &ClientController, held: &Held, now_ms: i64, words: &Map<String, Value>) -> Result<Link, String> {let said = |key: &str| words.get(key).and_then(Value::as_str).unwrap_or_default().to_string();letSome(door) = client.object_door() else { returnErr(said("offline")) };// A WHOLE FILM IS SEALED (R6): the object's signed address would hand the// player bytes it cannot read, so the phone's own door opens it as it// plays, a range at a time, from where the object keeps it.ifcrate::phone::films::whole(&held.file) {return sealed_link(client, &door, held, now_ms).map_err(|refusal| {let no_key = refusal.message.starts_with(cotton_client::seal::SEAL_KEY_MISSING);if refusal.status == 0 && !no_key { said("offline") } else { said("refused") } }); }// A FILM THE MAC LAID AS AN HLS FOLDER IS SEALED FILE BY FILE (R6): its// master, playlists, segments and subtitles each open under their own// key, so the same door answers the folder. A master the object still// holds in the clear (laid before R6, not yet re-sealed) is not this// door's: it plays from the object's signed address as it did.ifcrate::phone::films::streams(&held.file) {match sealed_folder_link(client, &door, held, now_ms) {Ok(Some(link)) => returnOk(link),Ok(None) => {}Err(refusal) => {let no_key = refusal.message.starts_with(cotton_client::seal::SEAL_KEY_MISSING);returnErr(if refusal.status == 0 && !no_key { said("offline") } else { said("refused") }); } } }matchcrate::phone::films::stream(&door, &json!({ "key": held.file })) {Ok(grant) => Ok(Link { id: held.id.clone(), url: grant["url"].as_str().unwrap_or_default().to_string(), expires_at: grant["expires_at"].as_str().unwrap_or_default().to_string(), minted_ms: now_ms, }),Err(refusal) if refusal.code == "offline" => Err(said("offline")),Err(_) => Err(said("refused")), }}/// The phone's own player door for `held`'s sealed whole film (R6,/// `cotton_client::media::loopback`): checked once that it opens, then offered/// at 127.0.0.1 under a path of its own; each request the player makes opens/// the parts it asks for from where the object keeps them.fn sealed_link(client: &ClientController, door: &crate::phone::personal_object::ObjectDoor, held: &Held, now_ms: i64) -> Result<Link, cotton_client::transport::ServerRefusal> {use cotton_client::media::loopback::{Loopback, PlainSource};let transport = transport_for(client, door, &held.file); transport.open_remote(&held.file)?;let ext = held.file.rsplit('.').next().unwrap_or("mp4").to_ascii_lowercase();let content_type = if ext == "mov" { "video/quicktime" } else { "video/mp4" };let door = Loopback::shared().map_err(|why| cotton_client::transport::ServerRefusal::new(why, 500))?;let key = held.file.clone();let url = door.offer(&format!("film.{ext}"), content_type, Arc::new(move || { transport.open_remote(&key).map(|reader| Box::new(reader) asBox<dynPlainSource>).map_err(|refusal| refusal.message) }));let expires_at = iso_of_ms(now_ms + cotton_client::media::loopback::OFFER_LIFE.as_millis() as i64);Ok(Link { id: held.id.clone(), url, expires_at, minted_ms: now_ms })}/// The phone's own player door for `held`'s sealed HLS folder (R6): the/// master is checked once that it opens, then the folder is offered at/// 127.0.0.1 under a path of its own; each file the player asks for by the/// playlists' relative names is opened from where the object keeps it, under/// that file's own key. `None` when the object holds the master in the clear.fn sealed_folder_link(client: &ClientController, door: &crate::phone::personal_object::ObjectDoor, held: &Held, now_ms: i64) -> Result<Option<Link>, cotton_client::transport::ServerRefusal> {use cotton_client::media::loopback::{hls_type, Loopback, PlainSource};letSome((folder, index)) = held.file.rsplit_once('/') else { returnOk(None) };let database = held.file.split('/').next().unwrap_or_default();// A phone holding no data key opens no sealed folder: a master the object holds in the clear still plays from its// signed address, and one it holds sealed is refused by the player as unreadable, never opened.use cotton_client::seal::DataKeyStoreas _;if !matches!(client.data_keys().data_key(database), Ok(Some(_))) {returnOk(None); }let transport = transport_for(client, door, &held.file);match transport.open_remote(&held.file) {Ok(master) => look_ahead(&transport, folder, master, true),// Held, and not sealed: a film laid before R6.Err(refusal) if refusal.status == 422 && refusal.code.as_deref() == Some("seal_does_not_open") && refusal.message.contains("is not sealed") => returnOk(None),Err(refusal) => returnErr(refusal), }let loopback = Loopback::shared().map_err(|why| cotton_client::transport::ServerRefusal::new(why, 500))?;let folder = folder.to_string();let url = loopback.offer_folder(index, Arc::new(move |inner| {let key = format!("{folder}/{inner}"); transport.open_remote(&key).map(|reader| (hls_type(inner).to_string(), Box::new(reader) asBox<dynPlainSource>)).map_err(|refusal| refusal.message) }));let expires_at = iso_of_ms(now_ms + cotton_client::media::loopback::OFFER_LIFE.as_millis() as i64);Ok(Some(Link { id: held.id.clone(), url, expires_at, minted_ms: now_ms }))}/// The phones' doors to films' files at the object (PLAYER START, 26 Nov 2026; RELAY 2): for each phone (its/// player's key), the film playing and at most one prepared, each by its film, its credential and its door's/// exchange. A film prepared as its page opens, then played, stopped and played again reads the windows it already/// read (its master, its playlists, its index) from the phone, not again from the object.typeKept = ((String, String, String, usize), Arc<cotton_client::media::ObjectMediaTransport>);static KEPT: std::sync::Mutex<Vec<Kept>> = std::sync::Mutex::new(Vec::new());/// Each phone's film prepared last, by its film key: kept beside the one playing until another is prepared or it/// is let go.static PREPARED: std::sync::Mutex<std::collections::BTreeMap<String, String>> = std::sync::Mutex::new(std::collections::BTreeMap::new());/// The film playing and one prepared (RELAY 2: about 8 MiB each at most, cotton_client's `WINDOWS_KEPT`).const FILMS_KEPT: usize = 2;/// A film's key for its door: a whole film's own file, a folder's files all through its master's folder.fn film_of(file: &str) -> String {ifcrate::phone::films::whole(file) { file.to_string() } else { file.rsplit_once('/').map(|(folder, _)| folder.to_string()).unwrap_or_else(|| file.to_string()) }}fn door_of(door: &crate::phone::personal_object::ObjectDoor) -> (String, usize) { (door.credential.clone(), Arc::as_ptr(&door.exchange) as *const () as usize)}fn transport_for(client: &ClientController, door: &crate::phone::personal_object::ObjectDoor, file: &str) -> Arc<cotton_client::media::ObjectMediaTransport> {let phone = super::queue_key(client);let (credential, exchange) = door_of(door);let which = (phone.clone(), film_of(file), credential, exchange);letmut kept = KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);ifletSome(at) = kept.iter().position(|(k, _)| *k == which) {let found = kept.remove(at);let transport = Arc::clone(&found.1); kept.push(found);return transport; }let database = file.split('/').next().unwrap_or_default();let files = crate::phone::personal_object::person_files_of(client, database);let transport = Arc::new(cotton_client::media::ObjectMediaTransport::new(door.address.clone(), Arc::clone(&door.exchange), door.credential.clone()).sealing(files)); kept.push((which, Arc::clone(&transport)));while kept.iter().filter(|((p, ..), _)| *p == phone).count() > FILMS_KEPT {let oldest = kept.iter().position(|((p, ..), _)| *p == phone).expect("one of this phone's"); kept.remove(oldest).1.release(); } transport}/// RELAY 2: let go of this phone's films' windows but the one playing (`playing`, its file) and the one prepared,/// and of every door that is not this phone's now (signed out, or signed in afresh: the old credential's windows/// go). With `all`, every one goes (`shell.player { op: "release" }`: the app gone to the background, the player/// closed).pub(super) fn settle(client: &ClientController, playing: Option<&str>, all: bool) {let phone = super::queue_key(client);let now = client.object_door().map(|door| door_of(&door));letmut prepared = PREPARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);if all { prepared.remove(&phone); }let keep: Vec<String> = if all { Vec::new() } else { playing.map(film_of).into_iter().chain(prepared.get(&phone).cloned()).collect() };letmut kept = KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner); kept.retain(|((p, film, credential, exchange), transport)| {if *p != phone {returntrue; }let stays = keep.contains(film) && now.as_ref().is_some_and(|(c, e)| c == credential && e == exchange);if !stays { transport.release(); } stays });}/// This phone's films' doors kept now, each with the windows it holds (a test's look at RELAY 2's bound).#[cfg(test)]pub(super) fn kept_now(client: &ClientController) -> Vec<(String, usize)> {let phone = super::queue_key(client); KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().filter(|((p, ..), _)| *p == phone).map(|((_, film, ..), t)| (film.clone(), t.windows_held())).collect()}/// `shell.player { op: "prepare", table, id, network }` (PLAYER START, 26 Nov 2026; RELAY 2): the shell asks it as a/// film's or an episode's page opens, and for the next episode, so the first window Play needs is here before the/// tap: a whole film's head and first window, or an HLS folder's master, its first variant playlist and its init/// (never a segment). Nothing is offered and nothing is said. It asks nothing for a film kept on this phone, one/// with no sealed door, offline, or on mobile data when this phone's films keep to Wi-Fi (`network` is the shell's/// word, `wifi` or `cellular`; unsaid is taken as mobile data). A prepare lets the one before it go, unless it is/// playing; `unprepare` lets it go. Answers whether it went to fetch.pub(super) fn prepare(client: &ClientController, table: &str, id: &str, network: Option<&str>, playing: Option<&str>, hidden: bool) -> Result<bool, MethodError> {letSome(held) = deal(client, table, id, None, hidden)?.items.into_iter().next() else { returnOk(false) };if !needs_link(client, &held)? {returnOk(false); }if network != Some("wifi") && crate::phone::films::call_keeping(client)?["cellular"] != Value::Bool(true) {returnOk(false); }letSome(door) = client.object_door() else { returnOk(false) };let whole = crate::phone::films::whole(&held.file);if !whole && !crate::phone::films::streams(&held.file) {returnOk(false); }let database = held.file.split('/').next().unwrap_or_default();use cotton_client::seal::DataKeyStoreas _;if !matches!(client.data_keys().data_key(database), Ok(Some(_))) {returnOk(false); } PREPARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(super::queue_key(client), film_of(&held.file)); settle(client, playing, false);let transport = transport_for(client, &door, &held.file);let file = held.file.clone(); std::thread::spawn(move || {letOk(opened) = transport.open_remote(&file) else { return };if !whole {ifletSome((folder, _)) = file.rsplit_once('/') { look_ahead(&transport, folder, opened, false); } } });Ok(true)}/// `shell.player { op: "unprepare" }` (RELAY 2): the page left: the film prepared lets its windows go, unless it is/// the one playing.pub(super) fn unprepare(client: &ClientController, playing: Option<&str>) { PREPARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&super::queue_key(client)); settle(client, playing, false);}/// PLAYER START (26 Nov 2026): the files a player asks for next, after the master (its first variant playlist, then/// that playlist's init segment, and at Play its first segment: `segments`), fetched on a thread of their own while/// Play answers, so the player's own asks find them held, or in flight, rather than each its own round trip in turn/// (about 0.7 s apiece on dev). Each is opened, its first window alone. What cannot be read is left for the player's/// own ask, which says why.fn look_ahead(transport: &Arc<cotton_client::media::ObjectMediaTransport>, folder: &str, master: impl std::io::Read + Send + 'static, segments: bool) {let (transport, folder) = (Arc::clone(transport), folder.to_string()); std::thread::spawn(move || {let read = |mut reader: Box<dyn std::io::Read>| -> Option<String> {letmut text = String::new(); std::io::Read::read_to_string(&mut std::io::Read::take(&mut reader, 256 * 1024), &mut text).ok()?;Some(text) };letSome(master) = read(Box::new(master)) else { return };letSome(variant) = first_uri(&master) else { return };let variant_key = format!("{folder}/{variant}");letOk(playlist) = transport.open_remote(&variant_key) else { return };letSome(playlist) = read(Box::new(playlist)) else { return };let at = variant.rsplit_once('/').map(|(dir, _)| format!("{folder}/{dir}")).unwrap_or_else(|| folder.clone());let map = playlist.lines().find_map(|line| line.strip_prefix("#EXT-X-MAP:")).and_then(|attrs| attrs.split("URI=\"").nth(1)).and_then(|rest| rest.split('"').next()).map(str::to_string);for inner in map.into_iter().chain(first_uri(&playlist).filter(|_| segments)) {let transport = Arc::clone(&transport);let key = format!("{at}/{inner}"); std::thread::spawn(move || {let _ = transport.open_remote(&key); }); } });}/// The first line of a playlist naming a file (not a tag), relative to it.fn first_uri(playlist: &str) -> Option<String> { playlist.lines().map(str::trim).find(|line| !line.is_empty() && !line.starts_with('#') && !line.contains("://")).map(str::to_string)}/// What the instrument opens `held` from: `file`, `bundle` or `stream`.pub(super) fn source(client: &ClientController, held: &Held, link: Option<&Link>) -> Result<Map<String, Value>, MethodError> {letmut said = Map::new();match held.kind {Kind::Film => {let here = crate::phone::films::here(client, &held.file)?;let kept = here.state.as_deref() == Some(crate::phone::films::KEPT);match (kept, here.bookmark) { (true, Some(bookmark)) ifcrate::phone::films::streams(&held.file) => { said.insert("bundle".into(), json!(bookmark)); } (true, _) ifcrate::phone::films::whole(&held.file) => { said.insert("file".into(), json!(held.file)); } _ => {ifletSome(link) = link.filter(|link| link.id == held.id) { said.insert("stream".into(), json!(link.url)); said.insert("stream_expires_at".into(), json!(link.expires_at)); } } } }Kind::Song => {} }Ok(said)}// ── handed to a receiver ────────────────────────────────────────────────────/// The HLS a film's master names: fragmented MP4 (the film importer lays/// every rendition so); a receiver is told, since it assumes transport/// stream otherwise.pubconst HLS_SEGMENTS: &str = "fmp4";/// What a receiver is handed for `held`: the address the object signs (the/// film's folder, for its hours, no bearer), its type, and its poster when/// that lies in the same folder (signed by the same address); with the link/// it minted, or reused when the one held is under [`RELINK_AFTER_MS`] old./// A whole file a receiver cannot play (a MOV) is refused in the film's/// words, and so is a film with no network to sign it.pub(super) fn cast(client: &ClientController, held: &Held, link: Option<&Link>, now_ms: i64, words: &Map<String, Value>) -> Result<(Value, Link), String> {let title = if held.discreet { discreet_title() } else { held.title.clone() };letSome(content_type) = cast_type(&held.file) else {returnErr(film_line("player.cast_refused", &[("title", &title)]).unwrap_or_else(|unsaid| unsaid.message)); };let link = match link.filter(|link| link.id == held.id && now_ms - link.minted_ms < RELINK_AFTER_MS) {Some(link) => link.clone(),None => mint(client, held, now_ms, words)?, };letmut said = json!({ "url": link.url, "content_type": content_type, "title": title, "expires_at": link.expires_at });ifcrate::phone::films::streams(&held.file) { said["hls_segments"] = json!(HLS_SEGMENTS); }// A hidden title on a TV: the app's name, no caption, no poster.if held.discreet { said["discreet"] = json!(true);returnOk((said, link)); }ifletSome(caption) = &held.caption { said["caption"] = json!(caption); }ifletSome(poster) = held.cover.as_deref().and_then(|cover| beside(&link.url, &held.file, cover)) { said["poster"] = json!(poster); }Ok((said, link))}// ── a film on a TV (cinemas-airplay, 18 Nov 2026) ───────────────────────────/// What a `route` says of the player's route: it went to a TV (`external`),/// came back to the phone (`phone`), the time to see the film playing there/// is up (`check`), or the film failed on the TV (`failed`).pubconst ROUTES: [&str; 4] = ["external", "phone", "check", "failed"];/// How long a film handed to a TV is given to be seen playing there before/// it plays through the phone instead (airplay-refused, 18 Nov 2026). A/// receiver asks for the index, its variant and its first segments and starts/// within two to five seconds on a home network; eight leaves room for a/// slow one while the person waits on a dark screen no longer than that.pubconst ADVANCE_WITHIN_S: f64 = 8.0;/// How often a film seen playing on a TV is checked again.pubconst CHECK_EVERY_S: f64 = 10.0;/// How long a film playing on a TV may stand still, the phone saying it/// plays, before it plays through the phone instead. A receiver keeps a/// buffer ahead and in its steady state asks for a segment about every/// segment's length (6 s, as the film importer cuts them), reading it out over seconds:/// thirty is five segments of silence, past any buffer's breathing, and/// three checks.pubconst STALL_WITHIN_S: f64 = 30.0;/// The most the phone's time is taken to move between two checks: it moves/// with the film, never further than the time between them (a seek is not/// the film playing).const MOVED_AT_MOST_BEYOND_S: f64 = 2.0;/// The Wi-Fi door open for the film playing on a TV/// (`cotton_client::media::lan`): dropped, it is shut.#[derive(Debug)]pub(super) structLan {pub(super) id: String,pub(super) door: cotton_client::media::lan::LanDoor,}/// The watch on a film handed to a TV (airplay-refused): fetched is not/// playing; the film must be seen to advance there.#[derive(Debug, Clone)]pub(super) structWatch {pub(super) id: String,/// The window to see it advance runs from here (the route to the TV, or/// the person pressing play again). began: Instant,/// Where the phone said the film stood at the last route asked. last: Option<(Instant, f64)>,/// When it was last seen advancing; None until it first is. moved_at: Option<Instant>,}implWatch {pub(super) fn new(id: &str, now: Instant, at_s: Option<f64>) -> Watch {Watch { id: id.to_string(), began: now, last: at_s.map(|at| (now, at)), moved_at: None } }}/// What the phone and the door say at a check.#[derive(Debug, Clone, Copy)]pub(super) structSeen {/// Where Apple's player says the film stands; None when the shell said nothing.pub(super) at_s: Option<f64>,/// The person paused it (Apple's player at rest, not waiting to play).pub(super) paused: bool,/// For a film offered at the Wi-Fi door, when the receiver last took/// bytes of the film itself (`LanDoor::media_taken_at`): `Some(None)`/// while it never has; None for a film with no door (kept, or the/// object's address), which only the phone's time can show.pub(super) taken_at: Option<Option<Instant>>,}/// A check's verdict.#[derive(Debug, Clone, Copy, PartialEq)]pub(super) enumVerdict {/// Seen playing on the TV: checked again after `CHECK_EVERY_S`.Plays,/// Not yet judged: checked again after these seconds.Watching(f64),/// Never seen playing within `ADVANCE_WITHIN_S`, or stood still for/// `STALL_WITHIN_S`: it plays through the phone.Stalled,}/// Judge the film on the TV at `now` from what was `seen`.////// - Paused, nothing is judged: the window to see it advance starts again./// - Not yet seen advancing: the phone's time must move as the film does/// and, at the Wi-Fi door, the receiver must have taken the film itself,/// not just its index. Both seen, it plays; the window up first, stalled./// - Seen advancing: the phone's time standing still, or the receiver taking/// nothing of the film, for `STALL_WITHIN_S` while the phone says it plays,/// stalled.pub(super) fn judge(watch: &mutWatch, seen: &Seen, now: Instant) -> Verdict {let since = |then: Instant| now.saturating_duration_since(then).as_secs_f64();let moved = match (seen.at_s, watch.last) { (None, _) => true, (Some(at), Some((then, was))) => {let (moved, between) = (at - was, since(then)); moved > 0.0 && moved >= (between * 0.5).min(1.0) && moved <= between + MOVED_AT_MOST_BEYOND_S } (Some(_), None) => false, };ifletSome(at) = seen.at_s { watch.last = Some((now, at)); }if seen.paused { watch.began = now;if watch.moved_at.is_some() { watch.moved_at = Some(now); }returnVerdict::Watching(CHECK_EVERY_S); }letSome(moved_at) = watch.moved_at else {let taken = seen.taken_at.is_none_or(|taken| taken.is_some());if moved && taken { watch.moved_at = Some(now);returnVerdict::Plays; }let left = ADVANCE_WITHIN_S - since(watch.began);// A check a little early is the shell's timer, not time to spare.returnif left <= 0.5 { Verdict::Stalled } else { Verdict::Watching(left) }; };let moved_at = if moved { now } else { moved_at }; watch.moved_at = Some(moved_at);// Quiet counts from the last pause at most: a receiver whose buffer is full takes nothing for a while after.let quiet = match seen.taken_at {None => false,Some(taken) => since(taken.map_or(watch.began, |taken| taken.max(watch.began))) >= STALL_WITHIN_S, };if quiet || since(moved_at) >= STALL_WITHIN_S {Verdict::Stalled } else {Verdict::Plays }}/// What the player does for `held` on the route `to` (`route`): `receiver`,/// the TV plays it (from `stream` when the address changes for it, checked/// after `check_after_s`), or `phone`, the phone plays it and its picture goes/// to the TV (`said` once). A sealed film plays from the phone's own door at/// 127.0.0.1, which no TV reaches: on a TV it is offered again on the phone's/// Wi-Fi address (`wifi`) alone, at a door of its own, for as long as it plays/// there. A film the object signs an address for, or one this phone keeps, is/// the receiver's to play as it is. Every film on a TV is watched (`judge`,/// from where the phone says it stands, `at_s`, and whether it is `paused`):/// a film not seen playing there, or standing still, stays on the TV and is/// only logged. With no Wi-Fi address, a door that will not open, or a/// failure the player reports on the TV, it plays through the phone.#[allow(clippy::too_many_arguments)]pub(super) fn route(to: &str, held: &Held, link: Option<&Link>, lan: &mutOption<Lan>, watch: &mutOption<Watch>, at_s: Option<f64>, paused: bool, wifi: Option<std::net::IpAddr>, now: Instant) -> Result<Value, MethodError> {let through_phone = |lan: &mutOption<Lan>, watch: &mutOption<Watch>| -> Result<Value, MethodError> { *lan = None; *watch = None;let title = if held.discreet { discreet_title() } else { held.title.clone() };Ok(json!({ "to": "phone", "said": film_line("player.through_phone", &[("title", &title)])? })) };let open = lan.as_ref().filter(|open| open.id == held.id);let stream = open.map(|open| open.door.url().to_string());let receiver = |check_after_s: f64| match &stream {Some(url) => json!({ "to": "receiver", "stream": url, "check_after_s": check_after_s }),None => json!({ "to": "receiver", "check_after_s": check_after_s }), };match to {"phone" => { *lan = None; *watch = None;Ok(json!({ "to": "phone" })) }"failed" => through_phone(lan, watch),"check" => {let taken_at = open.map(|open| open.door.media_taken_at());letSome(watching) = watch.as_mut().filter(|watching| watching.id == held.id) else {// No watch held (the core began again): it is watched from now. *watch = Some(Watch::new(&held.id, now, at_s));returnOk(receiver(ADVANCE_WITHIN_S)); };match judge(watching, &Seen { at_s, paused, taken_at }, now) {Verdict::Plays => Ok(receiver(CHECK_EVERY_S)),Verdict::Watching(after) => Ok(receiver(after)),// The person chose the TV: a film not seen playing there stays there (owner, 18 Nov 2026).// A receiver with a full buffer takes nothing for longer than any window, and pulling a// playing film back to the phone is worse than a TV that waits. Only a failure the// player reports (`failed`), no Wi-Fi address or a door that will not open leave the TV.Verdict::Stalled => { eprintln!("[shell.player] {} is not seen playing on the TV (asked: {:?}): it stays on the TV", held.id, open.map(|open| open.door.asked()));Ok(receiver(CHECK_EVERY_S)) } } } _ => {if watch.as_ref().is_none_or(|watching| watching.id != held.id) { *watch = Some(Watch::new(&held.id, now, at_s)); }if stream.is_some() {returnOk(receiver(ADVANCE_WITHIN_S)); }letSome(own) = link.filter(|link| link.id == held.id && link.url.starts_with("http://127.0.0.1:")) else {returnOk(receiver(ADVANCE_WITHIN_S)); };letSome(ip) = wifi else { return through_phone(lan, watch) };let lent = cotton_client::media::loopback::Loopback::shared().and_then(|door| door.lend(&own.url, ip));match lent {Ok(door) => {let url = door.url().to_string(); *lan = Some(Lan { id: held.id.clone(), door });Ok(json!({ "to": "receiver", "stream": url, "check_after_s": ADVANCE_WITHIN_S })) }Err(why) => { eprintln!("[shell.player] the Wi-Fi door did not open ({why}): the film plays through the phone"); through_phone(lan, watch) } } } }}/// The type a receiver plays `file` as: an HLS master; None for anything/// else. A whole film is sealed on the person's devices (R6) and a TV holds/// no key to open it, so it plays only on the phone.pubfn cast_type(file: &str) -> Option<&'static str> {crate::phone::films::streams(file).then_some("application/x-mpegURL")}/// `other`'s address beside `file`'s signed `url`, when both lie in one film/// folder (the token signs the folder): the url's last `file` swapped.fn beside(url: &str, file: &str, other: &str) -> Option<String> {let folder = |key: &str| key.rsplit_once('/').map(|(folder, _)| folder.to_string());let (file_folder, other_folder) = (folder(file)?, folder(other)?);if file_folder != other_folder || other.contains("..") {returnNone; }let encoded = |key: &str| key.split('/').map(|part| percent(part)).collect::<Vec<_>>().join("/");let base = url.strip_suffix(&encoded(file))?;Some(format!("{base}{}", encoded(other)))}/// A key's part as the Worker writes it into a signed address (`encodeURIComponent`).fn percent(part: &str) -> String { part.bytes() .map(|byte| match byte { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')' => (byte as char).to_string(), _ => format!("%{byte:02X}"), }) .collect()}// ── the settings ────────────────────────────────────────────────────────────/// The cinema row's settings: the subtitles and the audio a film plays with,/// and whether a series' next episode plays itself.#[derive(Debug, Clone, PartialEq)]pub(crate) structCinema {pub(crate) subtitles_on: bool,pub(crate) subtitle_language: Option<String>,pub(crate) audio_language: Option<String>,pub(crate) autoplay_next: bool,}implCinema {pub(crate) fn read(client: &ClientController) -> Result<Cinema, MethodError> {letmut table = None; client .read_rows("shell.player", &mut |ctx| {let listed = cotton_tools::definitions::table_definitions(ctx).map_err(|failure| failure.to_string())?; table = crate::phone::catalogue::FaceChoiceTable::of(&listed.definitions).map(|choices| choices.table);Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?;let row = match &table {Some(id) => matchcrate::phone::records::call(client, "records.get", &json!({"table": id, "id": CINEMA_ROW})) {Ok(read) => read["data"].as_object().cloned().unwrap_or_default(),Err(error) ifcrate::phone::copy_standing::absent(&error.code) => Map::new(),Err(error) => returnErr(error), },None => Map::new(), };Ok(Cinema::of(&row)) }pub(super) fn of(row: &Map<String, Value>) -> Cinema {let on = |key: &str| match row.get(key) {Some(Value::Bool(on)) => *on,Some(Value::Number(on)) => on.as_i64() != Some(0), _ => true, };let language = |key: &str| row.get(key).and_then(Value::as_str).map(str::trim).filter(|said| !said.is_empty()).map(str::to_string);Cinema { subtitles_on: on("subtitles_on"), subtitle_language: language("subtitle_language"), audio_language: language("audio_language"), autoplay_next: on("autoplay_next") } }/// The tracks a film plays with: subtitles on or off, in their language/// (none named is the phone's), the audio in its (none is the film's own).pub(super) fn tracks(&self) -> Value { json!({ "subtitles": self.subtitles_on, "subtitle_language": self.subtitle_language, "audio_language": self.audio_language }) }}// ── a film's own subtitles: the track chosen and the timing ─────────────────/// One step of the subtitle timing control: a tenth of a second.pub(super) const TIMING_STEP_MS: i64 = 100;/// The furthest the timing goes either way: past half a minute the track is/// another cut's, not a late one.pub(super) const TIMING_LIMIT_MS: i64 = 30_000;/// What one film plays its subtitles with, over the cinema's settings: the/// track the owner last chose in its player (`subtitle_choice`: a/// rendition's `{language, name}`, or `off`) and its timing/// (`subtitle_offset`, milliseconds, negative earlier). Both are the film/// row's, so they follow the film to every device.#[derive(Debug, Clone, PartialEq, Default)]pub(super) structFilmSubtitles {pub(super) choice: Value,pub(super) offset_ms: i64,}implFilmSubtitles {pub(super) fn of(row: &Row) -> FilmSubtitles {let choice = match row.get("subtitle_choice") {Some(Value::String(said)) if said == "off" => json!("off"),Some(Value::String(said)) => match serde_json::from_str::<Value>(said) {Ok(Value::Object(chosen)) if chosen.get("language").is_some_and(Value::is_string) => Value::Object(chosen), _ => Value::Null, }, _ => Value::Null, };let offset_ms = row.get("subtitle_offset").and_then(Value::as_f64).map_or(0, |ms| ms.round() as i64).clamp(-TIMING_LIMIT_MS, TIMING_LIMIT_MS);FilmSubtitles { choice, offset_ms } }pub(super) fn read(client: &ClientController, held: &Held) -> Result<FilmSubtitles, MethodError> {letmut read = FilmSubtitles::default(); client .read_rows("shell.player", &mut |ctx| { read = FilmSubtitles::of(&row(ctx, &held.table, "id, subtitle_choice, subtitle_offset", &held.id)?);Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?;Ok(read) }/// The timing after one press: `step` -1 earlier, 1 later, 0 back in time.pub(super) fn stepped(&self, step: i64) -> i64 {match step {0 => 0, step => (self.offset_ms + step.signum() * TIMING_STEP_MS).clamp(-TIMING_LIMIT_MS, TIMING_LIMIT_MS), } }/// The control's words, the core's (the kit's lines): its title, its/// three buttons, and where the timing stands now.pub(super) fn words(&self) -> Result<Value, MethodError> {let seconds = format!("{:.1}", self.offset_ms.abs() as f64 / 1000.0);let said = matchself.offset_ms {0 => film_player::line("player.subtitles_in_time", &[])?, ms if ms < 0 => film_player::line("player.subtitles_earlier_by", &[("seconds", &seconds)])?, _ => film_player::line("player.subtitles_later_by", &[("seconds", &seconds)])?, };Ok(json!({"title": film_player::line("player.subtitle_timing", &[])?,"earlier": film_player::line("player.subtitles_earlier", &[])?,"later": film_player::line("player.subtitles_later", &[])?,"reset": film_player::line("player.subtitles_reset", &[])?,"said": said, })) }}/// The tracks a film plays with: the cinema's settings, the film's own choice/// and timing over them, and the timing control's words.////// Subtitles in a language the cinema does not name are in the phone's/// (`phone`, the platform's first preferred language), by its primary tag, so/// both phones play the same track: the rule is here, never in a shell.pub(super) fn tracks(client: &ClientController, held: &Held, phone: Option<&str>) -> Result<Value, MethodError> {letmut tracks = Cinema::read(client)?.tracks();if tracks["subtitle_language"].is_null() {let primary = phone.and_then(|tag| tag.trim().split(['-', '_']).next()).map(str::to_ascii_lowercase).filter(|tag| !tag.is_empty());ifletSome(language) = primary { tracks["subtitle_language"] = json!(language); } }let own = FilmSubtitles::read(client, held)?; tracks["choice"] = own.choice.clone(); tracks["offset_ms"] = json!(own.offset_ms); tracks["timing"] = own.words()?;Ok(tracks)}/// The film playing's subtitle choice (`{language, name}` or `off`) written on its row.pub(super) fn choose_subtitles(client: &ClientController, held: &Held, choice: &Value) -> Result<(), MethodError> {let stored = match choice {Value::String(off) if off == "off" => json!("off"),Value::Object(chosen) => {let language = chosen.get("language").and_then(Value::as_str).map(str::trim).filter(|l| !l.is_empty()).ok_or_else(|| bad("a subtitle choice names its language"))?;let name = chosen.get("name").and_then(Value::as_str).unwrap_or_default(); json!(json!({ "language": language, "name": name }).to_string()) } _ => returnErr(bad("a subtitle choice is a track's { language, name }, or off")), }; write_own(client, held, "subtitle_choice", stored)}/// The film playing's timing moved one step (`step` -1 earlier, 1 later, 0 back in time); answers the timing now.pub(super) fn step_timing(client: &ClientController, held: &Held, step: i64) -> Result<i64, MethodError> {let now = FilmSubtitles::read(client, held)?.stepped(step); write_own(client, held, "subtitle_offset", json!(now))?;Ok(now)}fn write_own(client: &ClientController, held: &Held, column: &str, value: Value) -> Result<(), MethodError> {if held.kind != Kind::Film {returnErr(bad("only a film's subtitles are chosen and timed")); }let (table, id) = (held.table.clone(), held.id.clone()); written(client, "shell.player", &mut |ctx| {letmut patch = Map::new(); patch.insert(column.to_string(), value.clone()); changed(ctx, &table, &id, patch)?;Ok(Value::Null) })?;Ok(())}// ── the picture a film wears, picked from the film ──────────────────────────/// The columns a film's or an episode's picture lives in: the picture worn,/// the one a picked frame replaced, and where in the film the frame was taken/// (set only while a picked frame is worn).structWorn { column: &'static str, before: &'static str, from: &'static str, use_frame: &'static str, is_now: &'static str,}implWorn {fn of(table: &str) -> Worn {if table == FILM_EPISODE_TABLE {Worn { column: "still", before: "still_before", from: "still_from", use_frame: "player.use_frame_still", is_now: "player.frame_is_still" } } else {Worn { column: "poster", before: "poster_before", from: "poster_from", use_frame: "player.use_frame_poster", is_now: "player.frame_is_poster" } } }fn columns(&self) -> String { format!("id, {}, {}, {}", self.column, self.before, self.from) }/// Whether this database's table holds the columns a pick is remembered/// in. A database whose server copy has not taken them yet drops them from/// a write without a word: the frame would be worn and the original lost,/// so there a frame is neither offered nor taken.fn remembered_in(&self, ctx: &Ctx<'_>, table: &str) -> Result<bool, String> {let listed = cotton_tools::definitions::table_definitions(ctx).map_err(|failure| failure.to_string())?;Ok(listed.definitions.iter().find(|definition| definition.id == table).is_some_and(|definition| { [self.before, self.from].iter().all(|key| definition.columns.iter().any(|column| column.key == *key)) })) }}/// The film playing's "more" choices, in their order. `needs: subtitles` is/// offered only by a player whose film carries subtitle tracks, which only/// the player can see; `failed` is what the player says when it could not/// take the frame. A frame is offered only where the original can be kept.pub(super) fn more(client: &ClientController, held: &Held) -> Result<Value, MethodError> {let worn = Worn::of(&held.table);let (mut picked, mut remembers) = (false, false); client .read_rows("shell.player", &mut |ctx| { remembers = worn.remembered_in(ctx, &held.table)?; picked = remembers && row(ctx, &held.table, &worn.columns(), &held.id)?.get(worn.from).is_some_and(|from| !from.is_null());Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?;letmut choices = vec![json!({ "id": "subtitle_timing", "label": film_player::line("player.subtitle_timing", &[])?, "needs": "subtitles" })];if remembers { choices.push(json!({ "id": "use_frame", "label": film_player::line(worn.use_frame, &[])?, "failed": film_player::line("player.frame_failed", &[])? })); }if picked { choices.push(json!({ "id": "original_picture", "label": film_player::line("player.original_picture", &[])? })); }Ok(json!({ "title": film_player::line("player.more", &[])?, "choices": choices }))}/// The frame at `path`, taken `at_s` into the film playing, kept sealed and/// worn. The picture it replaces is remembered once: a second frame picked/// leaves the original to go back to. Answers the media key and the words.pub(super) fn use_frame(client: &ClientController, held: &Held, path: &std::path::Path, at_s: f64) -> Result<(String, String), MethodError> {let worn = Worn::of(&held.table);let layout = client.layout().clone();letmut kept = String::new(); written(client, "shell.player", &mut |ctx| {if !worn.remembered_in(ctx, &held.table)? {returnErr("this database cannot remember the picture a frame replaces yet".to_string()); }let stands = row(ctx, &held.table, &worn.columns(), &held.id)?;let workspace_id = ctx.workspace_id.to_string();let now = now_iso(ctx); kept = crate::phone::media::keep_picture(ctx, &layout, &workspace_id, path, &now, "a film's frame")?;letmut patch = Map::new(); patch.insert(worn.column.to_string(), json!(kept)); patch.insert(worn.from.to_string(), json!(at_s));if stands.get(worn.from).is_none_or(Value::is_null) { patch.insert(worn.before.to_string(), stands.get(worn.column).cloned().unwrap_or(Value::Null)); } changed(ctx, &held.table, &held.id, patch)?;Ok(Value::Null) })?;Ok((kept, film_player::line(worn.is_now, &[])?))}/// The picture a picked frame replaced, worn again. Answers it (none when the/// film wore nothing before) and the words.pub(super) fn original_picture(client: &ClientController, held: &Held) -> Result<(Option<String>, String), MethodError> {let worn = Worn::of(&held.table);letmut back = None; written(client, "shell.player", &mut |ctx| {let stands = row(ctx, &held.table, &worn.columns(), &held.id)?;if stands.get(worn.from).is_none_or(Value::is_null) {returnErr("this film wears no picked frame".to_string()); }let before = stands.get(worn.before).cloned().unwrap_or(Value::Null); back = before.as_str().map(str::to_string);letmut patch = Map::new(); patch.insert(worn.column.to_string(), before); patch.insert(worn.before.to_string(), Value::Null); patch.insert(worn.from.to_string(), Value::Null); changed(ctx, &held.table, &held.id, patch)?;Ok(Value::Null) })?;Ok((back, film_player::line("player.original_is_back", &[])?))}// ── the listen ──────────────────────────────────────────────────────────────/// What a report wrote that the play keeps: its watch row, and whether it/// was played or watched already.#[derive(Debug, Clone, Default, PartialEq)]pub(super) structWrote {pub(super) watch: Option<String>,pub(super) done: bool,}/// One report of a film or a series' episode written: its place, its state, its/// watch row.pub(super) fn write(client: &ClientController, report: &Listened, began: Option<&Began>) -> Result<Wrote, MethodError> {let at = report.at_s.ok_or_else(|| bad("a film's report says at_s, where it stands"))?; write_film(client, report, at, began)}fn write_film(client: &ClientController, report: &Listened, at: f64, began: Option<&Began>) -> Result<Wrote, MethodError> {let table = if report.table == FILM_TABLE { FILM_TABLE } else { FILM_EPISODE_TABLE };let zone = film_player::zone(client)?;let device = report.device.clone().unwrap_or_else(|| "phone".to_string());letmut wrote = Wrote { watch: began.and_then(|began| began.watch.clone()), done: began.is_some_and(|began| began.done) }; written(client, "shell.player", &mut |ctx| {let columns = if table == FILM_EPISODE_TABLE { "id, status, minutes, position, series, season" } else { "id, status, minutes, position" };let held = row(ctx, table, columns, &report.id)?;let duration = report.duration_s.filter(|duration| *duration > 0.0).or_else(|| held.get("minutes").and_then(Value::as_f64).map(|minutes| minutes * 60.0)).unwrap_or(0.0);let series = if table == FILM_EPISODE_TABLE { Some(series_of(ctx, &held)?) } else { None };// One watch row per play, from its first report.let watch = match wrote.watch.clone() {Some(watch) => watch,None => {letmut data = Map::new(); data.insert("film".into(), json!(series.clone().unwrap_or_else(|| report.id.clone())));if series.is_some() { data.insert("episode".into(), json!(report.id)); }let started = began.map_or_else(|| iso_of_ms(cotton_tools::mcp::handlers::common::now_ms(ctx) - (report.seconds * 1000.0) as i64), |began| began.at.clone()); data.insert("started_at".into(), json!(started)); data.insert("seconds".into(), json!(0)); data.insert("finished".into(), json!(false)); data.insert("device".into(), json!(device)); made(ctx, film_player::WATCH_TABLE, data)? } }; wrote.watch = Some(watch.clone());let finished = report.ended.as_deref() == Some("finished") || (duration > 0.0 && at >= film_player::FINISHED_SHARE * duration);letmut patch = Map::new(); patch.insert("seconds".into(), json!(report.seconds.round() as i64));if finished { patch.insert("finished".into(), json!(true)); } changed(ctx, film_player::WATCH_TABLE, &watch, patch)?;if wrote.done {returnOk(Value::Null); }if finished { marked(ctx, table, &report.id, true, &zone)?; wrote.done = true;returnOk(Value::Null); } progress(ctx, table, &report.id, at.round(), &held, series.as_deref())?;Ok(Value::Null) })?;Ok(wrote)}/// The resume point on the record: `position` and `position_at`, `watching`;/// an episode's series takes `position_at` too, so it stands in Continue/// watching.////// A report at the place the record already holds (a pause just after a/// report, a second report of a stall) writes nothing: `position_at` alone/// moving is no change of place, and every write of a film row is a post/// and a change on the object (film-progress-flood, 17 Nov 2026).fn progress(ctx: &mutCtx<'_>, table: &str, id: &str, position: f64, held: &Row, series: Option<&str>) -> Result<(), String> {if held.get("position").and_then(Value::as_f64) == Some(position) {returnOk(()); }let now = now_iso(ctx);letmut patch = Map::new(); patch.insert("position".into(), json!(position)); patch.insert("position_at".into(), json!(now));let status = text_of(held, "status");match table { FILM_TABLE if status != "watched" && status != "watching" => { patch.insert("status".into(), json!("watching")); } FILM_EPISODE_TABLE if status.is_empty() => { patch.insert("status".into(), json!("watching")); } _ => {} } changed(ctx, table, id, patch)?;ifletSome(series) = series {let film = row(ctx, FILM_TABLE, "status", series)?;letmut patch = Map::new(); patch.insert("position_at".into(), json!(now));if text_of(&film, "status") != "watched" && text_of(&film, "status") != "watching" { patch.insert("status".into(), json!("watching")); } changed(ctx, FILM_TABLE, series, patch)?; }Ok(())}#[cfg(test)]#[path = "shell_player_kinds_tests.rs"]mod tests;