weirdnet-songnotes 0.9.0

SongNotes collaboration: the roles, permissions, links and consent requests for a SongNotes session, built on weirdnet-collab.
Documentation
//! Talkback policy (C6): who is talking, who the host muted, and where each voice is published.
//!
//! Talkback lives in the collab app: it captures the mic and plays the others. A person's voice is
//! one mono stream ([`stream_id`], stable for the person) published with the stream kind
//! [`TALKBACK_KIND`], so a recorder can tell it from music and ask for `mic.record` (with the
//! speaker's consent) instead of `stream.record`.
//!
//! The host keeps a [`TalkRoom`] per project: speakers announce their stream and whether their mic
//! is open; the host (or anyone with `mic.manage`) mutes one person or everyone; a kick takes the
//! person's voice out. Everyone reads the same [`TalkState`]. Every mic starts muted, on the
//! person's own switch, whatever the room says.

use crate::UserId;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use weirdnet_collab::ProjectId;

/// The stream parameter that names a stream's kind.
pub const KIND_PARAM: &str = "kind";
/// The stream kind (the `kind` parameter of the stream's metadata) that marks a talkback stream.
pub const TALKBACK_KIND: &str = "talkback";

/// The parameter pair to add to a talkback stream's parameters.
pub fn talkback_param() -> (String, String) {
    (KIND_PARAM.into(), TALKBACK_KIND.into())
}

/// Whether a stream with these parameters is talkback.
pub fn is_talkback(params: &[(String, String)]) -> bool {
    params.iter().any(|(k, v)| k == KIND_PARAM && v == TALKBACK_KIND)
}
/// A speaker's announcement lapses after this long without a refresh.
pub const SPEAKER_TTL_MS: i64 = crate::service::PRESENCE_TTL_MS;
/// The talkback sample rate: 48 kHz mono.
pub const SAMPLE_RATE: u32 = 48_000;

/// The talkback stream id of `user` in `project`: stable, so a route or a mute keeps pointing at it.
pub fn stream_id(project: &ProjectId, user: &UserId) -> String {
    let p: String = project.as_str().chars().filter(|c| c.is_ascii_alphanumeric()).take(12).collect();
    let u: String = user.as_str().chars().rev().filter(|c| c.is_ascii_alphanumeric()).take(12).collect::<Vec<_>>().into_iter().rev().collect();
    format!("talk-{p}-{u}")
}

/// One voice in the room.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Speaker {
    /// Who.
    pub user: UserId,
    /// The peer that publishes the voice (the speaker's collab app).
    pub peer: String,
    /// Where to dial it.
    pub addrs: Vec<String>,
    /// The stream id.
    pub stream: String,
    /// The speaker's mic is open (their own switch).
    pub live: bool,
    /// The host's clock at the last announcement.
    pub at_ms: i64,
}

/// What everyone in a project sees of the talkback room.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TalkState {
    /// The project.
    pub project: ProjectId,
    /// The host.
    pub host: UserId,
    /// Everyone but the host is muted.
    pub all_muted: bool,
    /// People muted by the host.
    pub muted: Vec<UserId>,
    /// Voices announced and fresh.
    pub speakers: Vec<Speaker>,
    /// The host's clock.
    pub at_ms: i64,
}

impl TalkState {
    /// Whether the room lets `user` send (their own switch still applies).
    pub fn may_send(&self, user: &UserId) -> bool {
        user == &self.host || (!self.all_muted && !self.muted.contains(user))
    }

    /// Whether the room forces `user`'s mic off.
    pub fn forced_mute(&self, user: &UserId) -> bool {
        !self.may_send(user)
    }

    /// The voices `me` should hear: everyone else who announced a stream and whom the room lets send.
    pub fn audible(&self, me: &UserId) -> Vec<&Speaker> {
        self.speakers.iter().filter(|s| &s.user != me && self.may_send(&s.user)).collect()
    }

    /// One speaker.
    pub fn speaker(&self, user: &UserId) -> Option<&Speaker> {
        self.speakers.iter().find(|s| &s.user == user)
    }
}

/// The host's talkback room for one project.
#[derive(Clone, Debug, Default)]
pub struct TalkRoom {
    all_muted: bool,
    muted: BTreeSet<UserId>,
    speakers: BTreeMap<UserId, Speaker>,
}

impl TalkRoom {
    /// An empty room.
    pub fn new() -> Self {
        TalkRoom::default()
    }

    /// `user` announces (or refreshes) their voice.
    pub fn announce(&mut self, user: &UserId, peer: &str, addrs: &[String], stream: &str, live: bool, now: i64) {
        self.speakers
            .insert(user.clone(), Speaker { user: user.clone(), peer: peer.into(), addrs: addrs.to_vec(), stream: stream.into(), live, at_ms: now });
    }

    /// `user` leaves talkback.
    pub fn leave(&mut self, user: &UserId) {
        self.speakers.remove(user);
    }

    /// Mute or unmute one person.
    pub fn mute(&mut self, user: &UserId, muted: bool) {
        if muted {
            self.muted.insert(user.clone());
        } else {
            self.muted.remove(user);
        }
    }

    /// Mute or unmute everyone but the host.
    pub fn mute_all(&mut self, muted: bool) {
        self.all_muted = muted;
        if !muted {
            self.muted.clear();
        }
    }

    /// A kick or a ban: the person's voice goes, and stays muted if they come back.
    pub fn kick(&mut self, user: &UserId) {
        self.speakers.remove(user);
        self.muted.insert(user.clone());
    }

    /// What everyone sees at `now` (stale voices dropped).
    pub fn state(&mut self, project: &ProjectId, host: &UserId, now: i64) -> TalkState {
        self.speakers.retain(|_, s| now - s.at_ms <= SPEAKER_TTL_MS);
        TalkState {
            project: project.clone(),
            host: host.clone(),
            all_muted: self.all_muted,
            muted: self.muted.iter().cloned().collect(),
            speakers: self.speakers.values().cloned().collect(),
            at_ms: now,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn u(_: u8) -> UserId {
        UserId::of_keypair(&crate::Keypair::generate_ed25519())
    }

    #[test]
    fn mutes_kicks_and_stale_voices() {
        let p = ProjectId::new("proj-1");
        let (host, a, b) = (u(1), u(2), u(3));
        let mut r = TalkRoom::new();
        r.announce(&a, "pa", &[], &stream_id(&p, &a), true, 0);
        r.announce(&b, "pb", &[], &stream_id(&p, &b), false, 0);
        r.announce(&host, "ph", &[], &stream_id(&p, &host), true, 0);
        let s = r.state(&p, &host, 10);
        assert_eq!(s.audible(&a).len(), 2, "a hears b and the host");
        assert!(s.may_send(&a) && s.may_send(&b));
        r.mute(&a, true);
        let s = r.state(&p, &host, 20);
        assert!(s.forced_mute(&a) && !s.forced_mute(&b));
        assert_eq!(s.audible(&b).iter().map(|s| &s.user).collect::<Vec<_>>(), vec![&host]);
        r.mute_all(true);
        let s = r.state(&p, &host, 30);
        assert!(s.forced_mute(&b) && !s.forced_mute(&host), "the host is never muted by the room");
        r.mute_all(false);
        assert!(r.state(&p, &host, 40).may_send(&a), "unmute all lifts single mutes too");
        r.kick(&b);
        let s = r.state(&p, &host, 50);
        assert!(s.speaker(&b).is_none() && s.forced_mute(&b), "kicked: gone and muted");
        let s = r.state(&p, &host, SPEAKER_TTL_MS + 1);
        assert!(s.speakers.is_empty(), "stale voices lapse");
    }

    #[test]
    fn stream_ids_are_stable_and_distinct() {
        let p = ProjectId::new("proj-1");
        let (a, b) = (u(2), u(3));
        assert_eq!(stream_id(&p, &a), stream_id(&p, &a));
        assert_ne!(stream_id(&p, &a), stream_id(&p, &b));
        assert!(is_talkback(&[("sample_rate".into(), "48000".into()), talkback_param()]) && !is_talkback(&[]));
        assert!(stream_id(&p, &a).starts_with("talk-proj1-"));
    }
}