diff --git a/README.md b/README.md index 158438f8..4b3ee151 100644 --- a/README.md +++ b/README.md @@ -1197,15 +1197,16 @@ bar, as a key's does, and on the phone. Settings, Remote, pairs one: name it, **Pair a phone**, and scan the QR code with the phone's camera, or **Copy link** to send it. A remote joins the [guests' room](#guests), so it needs the room, its key, and the join page set -there first; its page is `remote.html` beside the join page, and the link +there first; its page is `remote.html` beside the join page, so a join page +in a directory ends with `/` (`https://example.com/join/`), and the link lasts as long as a guest's (`--guest-expiry`). The pane lists each phone paired, whether it is connected, and its link, with **Show link** while that link still works, **New link**, and **Remove**. Treat the link like a password: anyone holding it can drive the show until you remove it. - A remote presses only what is safe to press by mistake from a pocket: a - scene's pad, TAKE, AUTO, and a sound's mute. Going live, ending the - stream, the panic key, recording, and replay stay on the studio. + scene's pad, TAKE, AUTO, and the mute of a source with sound. Going live, + ending the stream, the panic key, recording, and replay stay on the studio. - A remote's token, signed by the room key like a guest's, may publish only its presses, at `.press//` in the room, and read only the desk the studio publishes it at `.remote//`, which carries @@ -1218,10 +1219,13 @@ password: anyone holding it can drive the show until you remove it. before the studio restarted or rejoined the room is not done again, since it was most likely done before: the page asks you to check it first. - **Remove** stops reading its presses at once, and stops renewing its token, - so it is disconnected within `--guest-expiry`; **New link** pairs it again + so it is disconnected within `--guest-expiry`, and no press of it is done + once Remove says it is removed; **New link** pairs it again under a new generation, which a link from before cannot reach. Pairings and removals outlast a restart, kept beside the room key as - `room.remotes.toml` for `room.jwk`. + `room.remotes.toml` for `room.jwk`. While the studio moves to another room, + or rejoins this one with new settings, pairing, removing, and inviting + guests are refused until it has joined, so the next room misses none. ## Scene file diff --git a/rs/moq-studio/src/controls.rs b/rs/moq-studio/src/controls.rs index a29087e6..ce5b11d3 100644 --- a/rs/moq-studio/src/controls.rs +++ b/rs/moq-studio/src/controls.rs @@ -186,7 +186,7 @@ impl Action { let sounds = state .sources .iter() - .filter(|(_, feed)| feed.strip().is_some()) + .filter(|(name, _)| sounds(state, name)) .map(|(name, _)| Self::Mute(name.to_string())); let mut listed: Vec = FIXED.iter().map(|fixed| fixed.action.clone()).collect(); listed.extend(scenes.chain(sounds)); @@ -485,6 +485,7 @@ impl Controls { Action::Mute(name) if !collection.sources.contains_key(name) => { Some(format!("there is no source `{name}`")) } + Action::Mute(name) if !sounds(state, name) => Some(format!("`{name}` has no sound")), Action::Marker => self.markers.refused(), // Whichever is picked, any replay source plays it. Action::Replay => replay_source(collection, None).err().map(|err| err.to_string()), @@ -682,6 +683,11 @@ impl Controls { if let Some(path) = room.1.path() { self.engine.remember_room(&path); } + // The room left changes nothing kept beside its key once the next + // reads it, which would otherwise bring back a remote removed meanwhile. + if let Some(left) = self.engine.room() { + left.leave(); + } let joining = crate::guests::Joining::connect(&room.1, room.0.as_ref(), &stream.client(), stream.quic().clone()); // Weak, so the remotes never keep the controls, and the engine, alive. @@ -891,6 +897,7 @@ fn replay_source(collection: &moq_scene::Collection, picked: Option<&str>) -> an pub fn mute(state: &mut State, name: &str) -> anyhow::Result { let collection = state.collection(); anyhow::ensure!(collection.sources.contains_key(name), "there is no source `{name}`"); + anyhow::ensure!(sounds(state, name), "`{name}` has no sound"); let mut audio = collection.audio.get(name).cloned().unwrap_or_default(); audio.muted = !audio.muted; let (verb, done) = match audio.muted { @@ -903,6 +910,11 @@ pub fn mute(state: &mut State, name: &str) -> anyhow::Result { Ok(format!("{done} `{name}`")) } +/// Whether the source called `name` has sound, and so a mute. +fn sounds(state: &State, name: &str) -> bool { + state.sources.get(name).is_some_and(|feed| feed.strip().is_some()) +} + /// Take the scene called `name` on program, under `state` locked by the /// caller, following any rename the window has yet to move its key through. pub fn take(state: &mut State, name: &str) -> anyhow::Result { diff --git a/rs/moq-studio/src/engine.rs b/rs/moq-studio/src/engine.rs index b15fc583..d17a3638 100644 --- a/rs/moq-studio/src/engine.rs +++ b/rs/moq-studio/src/engine.rs @@ -4309,6 +4309,8 @@ mod tests { height: 640, }); collection.scenes.extend([moq_scene::Scene::new("Guest"), portrait]); + let host = moq_scene::Source::Broadcast { path: "host".into() }; + collection.sources.insert("host".into(), host); let gpu = Gpu::new(wgpu::Backends::all()).await.expect("a GPU"); let (autosave, _) = Autosave::open(dir.path().join("show.toml")).unwrap(); let engine = start(gpu, Vec::new(), dir.path(), autosave, loaded) @@ -4441,7 +4443,11 @@ mod tests { refused(Action::Replay).as_deref(), Some("no replay source; add one in Sources") ); - assert_eq!(refused(Action::Mute("red".into())), None); + assert_eq!(refused(Action::Mute("host".into())), None); + assert_eq!( + refused(Action::Mute("red".into())).as_deref(), + Some("`red` has no sound") + ); assert!(refused(Action::Mute("nobody".into())).is_some()); assert!(Action::listed(&state).contains(&Action::Scene("Portrait".into()))); } @@ -4482,17 +4488,26 @@ mod tests { } // A sound's key or palette row flips its mute, an edit undo takes back. - let mute = crate::controls::Action::Mute("red".into()); - assert_eq!(controls.fire(&mute).unwrap(), "muted `red`"); - assert!(engine.state.lock().unwrap().collection().audio["red"].muted); - assert_eq!(controls.fire(&mute).unwrap(), "unmuted `red`"); - assert!(!engine.state.lock().unwrap().collection().audio["red"].muted); + let mute = crate::controls::Action::Mute("host".into()); + assert_eq!(controls.fire(&mute).unwrap(), "muted `host`"); + assert!(engine.state.lock().unwrap().collection().audio["host"].muted); + assert_eq!(controls.fire(&mute).unwrap(), "unmuted `host`"); + assert!(!engine.state.lock().unwrap().collection().audio["host"].muted); assert_eq!( engine.state.lock().unwrap().undo().unwrap().as_deref(), - Some("Unmute `red`") + Some("Unmute `host`") ); - assert!(engine.state.lock().unwrap().collection().audio["red"].muted); + assert!(engine.state.lock().unwrap().collection().audio["host"].muted); assert!(controls.fire(&crate::controls::Action::Mute("nobody".into())).is_err()); + // A source with no sound has no mute, from a key or a phone. + let silent = crate::controls::Action::Mute("red".into()); + let err = controls.fire(&silent).unwrap_err(); + assert_eq!(format!("{err:#}"), "`red` has no sound"); + assert!(!engine.state.lock().unwrap().collection().audio.contains_key("red")); + { + use crate::guests::remote::Board; + assert_eq!(controls.clone().press(&silent), Err("`red` has no sound".into())); + } let stopping = engine.clone(); tokio::task::spawn_blocking(move || stopping.stop()).await.unwrap(); } diff --git a/rs/moq-studio/src/guests.rs b/rs/moq-studio/src/guests.rs index 478f70e3..09cff55e 100644 --- a/rs/moq-studio/src/guests.rs +++ b/rs/moq-studio/src/guests.rs @@ -29,6 +29,7 @@ pub mod remote; use std::collections::{BTreeMap, BTreeSet}; use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; @@ -65,6 +66,9 @@ pub const MAX_GUESTS: usize = 4; /// reach the guest and the relay before the token it replaces expires. const MIN_EXPIRY: Duration = Duration::from_secs(60); +/// Why a room the studio is leaving refuses a change to what is kept beside its key. +const LEFT: &str = "the studio is leaving this room; try again once it has joined the next"; + /// The two broadcasts a guest publishes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Kind { @@ -116,7 +120,8 @@ pub struct Config { /// The join page a guest opens, `js/join` hosted anywhere. Its link carries /// the room's relay URL, the guest's name, and its token in the fragment. - /// Defaults to `https://join.studio.moq.dev/`. + /// A remote's page is beside it, so a directory ends with `/`. Defaults to + /// `https://join.studio.moq.dev/`. #[usage(long)] pub join_page: Option, @@ -216,6 +221,8 @@ pub struct Room { participants: Mutex>, /// Where removals are kept, or `None` to keep them in memory alone. removals: Option, + /// Whether the studio is leaving the room, which changes its guests no more. + left: AtomicBool, /// Bumped when who is renewed changes, which wakes the renewals and the /// return feeds. changed: tokio::sync::watch::Sender<()>, @@ -324,6 +331,7 @@ impl Room { expiry, participants: Mutex::default(), removals: None, + left: AtomicBool::new(false), changed: Default::default(), session: Default::default(), origin: Default::default(), @@ -360,6 +368,16 @@ impl Room { Ok(self) } + /// Refuse every change to what is kept beside the key from now on, once + /// any under way is kept, as the studio leaves the room: the room it + /// joins next reads the files after this, so it misses none, such as a + /// remote's removal, which it would otherwise undo. + pub fn leave(&self) { + self.left.store(true, Ordering::SeqCst); + drop(self.participants.lock().unwrap()); + self.remotes.leave(); + } + /// Apply `change` to `identity` once the file holds it, so a failed write /// leaves both as they were. fn change( @@ -368,6 +386,8 @@ impl Room { identity: &str, change: impl FnOnce(&mut Participant), ) -> anyhow::Result<()> { + // The caller holds `participants`, which `leave` waits on. + anyhow::ensure!(!self.left.load(Ordering::SeqCst), LEFT); let participant = participants.entry(identity.to_string()).or_default(); let before = participant.clone(); change(participant); @@ -419,6 +439,8 @@ impl Room { // studio would never see this guest join. anyhow::ensure!(!name.starts_with('.'), "a guest's name cannot start with `.`"); let mut participants = self.participants.lock().unwrap(); + // A link the room joined next would never renew. + anyhow::ensure!(!self.left.load(Ordering::SeqCst), LEFT); let removed = participants.get(name).is_some_and(|participant| participant.removed); let appeared = participants.get(name).is_some_and(|participant| participant.appeared); let generation = participants.get(name).map_or(0, |participant| participant.generation); diff --git a/rs/moq-studio/src/guests/remote.rs b/rs/moq-studio/src/guests/remote.rs index f3d80705..7115ae99 100644 --- a/rs/moq-studio/src/guests/remote.rs +++ b/rs/moq-studio/src/guests/remote.rs @@ -21,7 +21,8 @@ use std::collections::BTreeMap; use std::path::PathBuf; -use std::sync::{Arc, Mutex, Weak}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, RwLock, RwLockReadGuard, Weak}; use std::task::{Poll, ready}; use std::time::Duration; @@ -77,9 +78,11 @@ pub struct Remote { /// The remotes the room key paired, kept beside it. #[derive(Default)] pub(super) struct Remotes { - paired: Mutex>, + paired: RwLock>, /// Where they are kept, or `None` to keep them in memory alone. file: Option, + /// Whether the studio is leaving the room, which changes them no more. + left: AtomicBool, /// Bumped when which remotes are read changes. changed: tokio::sync::watch::Sender<()>, } @@ -110,8 +113,9 @@ impl Remotes { (name, remote) }); Ok(Self { - paired: Mutex::new(paired.collect()), + paired: RwLock::new(paired.collect()), file: Some(path), + left: AtomicBool::new(false), changed: Default::default(), }) } @@ -135,7 +139,8 @@ impl Remotes { /// Apply `change` to the remote called `name` once the file holds it, so /// a failed write leaves both as they were. fn change(&self, name: &str, change: impl FnOnce(&mut Remote)) -> anyhow::Result { - let mut paired = self.paired.lock().unwrap(); + let mut paired = self.paired.write().unwrap(); + anyhow::ensure!(!self.left.load(Ordering::SeqCst), super::LEFT); let before = paired.get(name).cloned(); let remote = paired.entry(name.to_string()).or_default(); change(remote); @@ -154,17 +159,32 @@ impl Remotes { /// The remotes whose presses are read, and in which generation. fn read(&self) -> Vec<(String, u64)> { - let paired = self.paired.lock().unwrap(); + let paired = self.paired.read().unwrap(); let read = paired.iter().filter(|(_, remote)| !remote.removed); read.map(|(name, remote)| (name.clone(), remote.generation)).collect() } + /// A hold on the remotes while the one called `name` in `generation` is + /// read, or `None` once it is not: a removal waits for the hold, so what + /// is done under it never follows one. + fn reading(&self, name: &str, generation: u64) -> Option>> { + let paired = self.paired.read().unwrap(); + let remote = paired.get(name)?; + (!remote.removed && remote.generation == generation).then_some(paired) + } + /// Note whether the page of the remote called `name` is connected. fn connect(&self, name: &str, connected: bool) { - if let Some(remote) = self.paired.lock().unwrap().get_mut(name) { + if let Some(remote) = self.paired.write().unwrap().get_mut(name) { remote.connected = connected; } } + + /// Refuse every change from now on, once any under way is kept. + pub(super) fn leave(&self) { + self.left.store(true, Ordering::SeqCst); + drop(self.paired.write().unwrap()); + } } impl Room { @@ -180,8 +200,16 @@ impl Room { "a remote's name is one path segment, without `/` or `\\`" ); anyhow::ensure!(!name.starts_with('.'), "a remote's name cannot start with `.`"); + // `Url::join` reads a last segment as a file, so a directory without its + // `/` would put the remote's page beside the directory, not in it. + let last = self.page.path_segments().and_then(Iterator::last).unwrap_or_default(); + anyhow::ensure!( + last.is_empty() || last.contains('.'), + "the join page {} ends in a directory without its `/`, so no remote's page is beside it; end it with `/`", + self.page + ); let page = self.page.join(PAGE).context("the join page has no page beside it")?; - let before = self.remotes.paired.lock().unwrap().get(name).cloned(); + let before = self.remotes.paired.read().unwrap().get(name).cloned(); let generation = before .as_ref() .map_or(0, |remote| remote.generation + u64::from(remote.removed)); @@ -208,7 +236,7 @@ impl Room { /// Every phone paired as a remote, by name. pub fn remotes(&self) -> BTreeMap { - self.remotes.paired.lock().unwrap().clone() + self.remotes.paired.read().unwrap().clone() } /// A token for the remote called `name` in `generation`, and when it @@ -507,16 +535,21 @@ impl Paired { } }; self.room.remotes.connect(&self.name, true); - tokio::select! { + let changed = tokio::select! { result = self.drive(broadcast, &mut done) => { if let Err(err) = result { tracing::debug!(remote = self.name, error = format!("{err:#}"), "stopped reading a remote"); } - next = following.available().await; + None } - changed = following.available() => next = changed, - } + changed = following.available() => Some(changed), + }; + // Not connected while waiting for the page's next broadcast. self.room.remotes.connect(&self.name, false); + next = match changed { + Some(changed) => changed, + None => following.available().await, + }; } } @@ -573,7 +606,10 @@ impl Paired { } => { pressed = true; match press { - Ok(Some(press)) => *done = Some(self.handle(press, &mut listening, done.as_ref())), + Ok(Some(press)) => { + let _reading = self.reading()?; + *done = Some(self.handle(press, &mut listening, done.as_ref())); + } Ok(None) => return Ok(()), Err(moq_json::Error::Net(err)) => return Err(err.into()), // Refused whole, as one the page cannot be told about. @@ -603,8 +639,18 @@ impl Paired { Ok(()) } + /// Hold the remote paired while a press is done or a token renewed, so + /// neither follows its removal. + fn reading(&self) -> anyhow::Result>> { + self.room + .remotes + .reading(&self.name, self.generation) + .context("the remote was removed") + } + /// Publish the remote a fresh token. fn renew(&self, published: &mut Published) -> anyhow::Result<()> { + let _reading = self.reading()?; let (token, _) = self.room.sign_remote(&self.name, self.generation)?; let at = moq_net::Timestamp::unscaled(published.next); published.tokens.write_frame(at, token)?; @@ -737,6 +783,8 @@ impl Presses { #[cfg(test)] mod tests { + use std::sync::Mutex; + use super::super::tests::{EXPIRY, Relay, fragment, key}; use super::*; use url::Url; @@ -912,6 +960,22 @@ mod tests { assert!(room.pair(name).is_err(), "{name:?}"); } assert_eq!(room.remotes().len(), 1, "a refused name is paired"); + + // The remote's page is beside the join page, which a directory without + // its `/` cannot say where. + let connect = Url::parse("https://relay.example/show").unwrap(); + let at = |page: &str| { + let page = Url::parse(page).unwrap(); + let room = Room::new(&connect, "guests", key.clone(), page, EXPIRY).unwrap(); + room.pair("phone").map(|invite| invite.link.path().to_string()) + }; + assert_eq!( + at("https://studio.example/join/index.html").unwrap(), + "/join/remote.html" + ); + assert_eq!(at("https://studio.example/").unwrap(), "/remote.html"); + let err = at("https://studio.example/join").unwrap_err(); + assert!(format!("{err:#}").contains("end it with `/`"), "{err:#}"); } /// Who is paired, removed, and in which generation outlasts a restart, @@ -944,6 +1008,28 @@ mod tests { room.pair("tablet").unwrap(); assert_eq!(start().remotes()["tablet"].generation, 1); + // The studio leaving the room for the next, which reads the file only + // once the room left can change it no more: a removal there would be + // missed, and an unexpired link would press again. + room.leave(); + let next = start(); + let err = room.unpair("phone").unwrap_err(); + assert_eq!(format!("{err:#}"), super::super::LEFT); + assert!(!room.remotes()["phone"].removed); + assert!(room.pair("laptop").is_err(), "a pairing the next room would miss"); + assert!( + room.stop_renewing("alice").is_err(), + "a guest's removal the next room would miss" + ); + assert!( + room.invite("bob").is_err(), + "a guest's link the next room would not renew" + ); + next.unpair("phone").unwrap(); + assert!(start().remotes()["phone"].removed); + next.pair("phone").unwrap(); + let room = next; + // A removal the file cannot hold is not made. std::fs::remove_file(&file).unwrap(); std::fs::create_dir(&file).unwrap(); @@ -1025,15 +1111,34 @@ mod tests { assert_eq!(refused.said, "Go live is not for a remote"); assert_eq!(fake.pressed().len(), 2); + let mute = Action::Mute("Desk mic".into()); + page.press(press(14, Some(mute.clone()))); + clock.advance(FRAME); + let muted = done(&mut desks, 14).await; + assert!(muted.ok, "{muted:?}"); + assert_eq!(fake.pressed().len(), 3); + // The page back on a new connection: the press read first is the - // last it made, which is not done again. + // last it made, which is not done again, and the desk still says how + // it went. drop(page); while desks.latest().await.unwrap().is_some() {} + let built = fake.built(); let mut page = Page::open(&heard, "phone", 0); - page.press(press(13, Some(Action::GoLive))); + page.press(press(14, Some(mute))); let mut desks = read_desks(publish.consume(), "phone", 0).await; clock.advance(FRAME); - assert_eq!(done(&mut desks, 13).await, refused, "the last press, again"); + // Read once the desk is built again after the one the page connected to. + for _ in 0..100 { + if fake.built() >= built + 2 { + break; + } + tokio::task::yield_now().await; + } + assert_eq!(fake.built(), built + 2, "the press is read"); + let replayed = desks.latest().await.unwrap().unwrap().value.done; + assert_eq!(replayed, Some(muted), "the last press, again"); + assert_eq!(fake.pressed().len(), 3, "done again"); // A page whose press the studio may have done before it restarted, // which is told to check it, not done again. @@ -1054,15 +1159,18 @@ mod tests { }; assert!(!again.ok); assert_eq!(again.said, RESTARTED); - assert_eq!(fake.pressed().len(), 2, "done again"); + assert_eq!(fake.pressed().len(), 3, "done again"); - // Removed: the desk ends, and nothing more is read. - room.unpair("phone").unwrap(); - while desks.latest().await.is_ok_and(|desk| desk.is_some()) {} + // Removed while a press waits to be read: it is never done, and the + // desk ends. page.press(press(2, Some(scene))); clock.advance(FRAME); - tokio::task::yield_now().await; - assert_eq!(fake.pressed().len(), 2, "a removed remote drives"); + room.unpair("phone").unwrap(); + while desks.latest().await.is_ok_and(|desk| desk.is_some()) {} + for _ in 0..20 { + tokio::task::yield_now().await; + } + assert_eq!(fake.pressed().len(), 3, "a removed remote drives"); assert!(!room.remotes()["phone"].connected); } @@ -1128,6 +1236,13 @@ mod tests { clock.advance(Duration::from_secs(1)); assert!(done(&mut desks, 2).await.ok); assert_eq!(fake.pressed(), [scene.clone(), scene]); + + // The page stops pressing while its broadcast stays announced: its desk + // ends, and it is no longer connected. + let _finished = page.track.clone().finish().unwrap(); + clock.advance(Duration::from_secs(1)); + while desks.latest().await.unwrap().is_some() {} + assert!(!room.remotes()["phone"].connected, "connected after its presses end"); } /// A page that opens the link reaches the relay with its token, presses diff --git a/rs/moq-studio/src/shots.rs b/rs/moq-studio/src/shots.rs index aca81e9f..866d097f 100644 --- a/rs/moq-studio/src/shots.rs +++ b/rs/moq-studio/src/shots.rs @@ -1152,6 +1152,7 @@ fn settings_change_the_show_and_move_the_guests() { harness.get_by_label("Pair a phone").click(); harness.run_steps(2); assert!(harness.query_by_label("Copy link").is_some(), "the phone's link shows"); + let left = engine.room().unwrap(); harness.get_by_label("Guests").click(); harness.run_steps(2); fill(&mut harness, 0, "other"); @@ -1172,6 +1173,8 @@ fn settings_change_the_show_and_move_the_guests() { fill(&mut harness, 1, "other.jwk"); harness.get_by_label("Save").click(); joined(&mut harness, "other"); + // The room left changes nothing the next could have missed. + assert!(left.unpair("phone").is_err(), "the room left removes a remote"); let saved = std::fs::read_to_string("show.stream.toml").unwrap(); assert!(saved.contains("room = \"other\""), "{saved}"); // ...until the room is another, which its link cannot join.