// Which browser tab does a playback stream belong to? // // Chrome opens its audio streams per tab but gives them all the same // properties, and its extension API knows which tabs are audible but not // which stream they use. TabTracker links the two by time: a tab becomes // audible just after its stream starts running. Whatever stays ambiguous is // left unnamed; a wrong name is worse than none. ///| /// A tab reported by the browser extension. #derive(Eq, Debug) pub(all) struct BrowserTab { id : Int32 title : String audible : Bool } ///| /// A tab a stream was matched to, as the mixer shows it. `key` is unique /// across browsers; streams with the same key share one row. #derive(Eq, Debug) pub(all) struct TabName { key : String title : String } ///| /// A tab turns audible at most this long after its stream starts. pub const TAB_WINDOW_MS : Int64 = 1500L ///| /// ... and, since the two reports take different paths, at most this long /// before we see the stream. pub const TAB_SLOP_MS : Int64 = 400L ///| /// Streams older than this may be matched by elimination. pub const TAB_SETTLE_MS : Int64 = 3000L ///| struct TrackedStream { since : Int64 /// False when it was already running when tracking began. seen_start : Bool mut tab : Int32? /// Matched by elimination, not by time. mut weak : Bool /// Elimination was contradicted: do not try it again. mut doubt : Bool } ///| struct TrackedTab { mut title : String mut audible : Bool mut since : Int64 mut seen_start : Bool } ///| pub struct TabTracker { streams : Map[String, TrackedStream] // by object.serial tabs : Map[Int32, TrackedTab] mut got_tabs : Bool } ///| pub fn TabTracker::new() -> TabTracker { { streams: Map([]), tabs: Map([]), got_tabs: false, } } ///| /// The set of running streams. `initial` for the first, already running set. /// A stream that stops loses its tab: Chrome reuses idle streams. pub fn TabTracker::set_streams( self : TabTracker, serials : Array[String], now : Int64, initial~ : Bool = false, ) -> Unit { for s in self.streams.keys().to_array() { if !serials.contains(s) { self.streams.remove(s) } } for s in serials { if !self.streams.contains(s) { self.streams.set(s, { since: now, seen_start: !initial, tab: None, weak: false, doubt: false, }) } } } ///| /// All tabs that are or have been audible and are still open. pub fn TabTracker::set_tabs( self : TabTracker, tabs : Array[BrowserTab], now : Int64, ) -> Unit { let initial = !self.got_tabs self.got_tabs = true for id in self.tabs.keys().to_array() { if !tabs.any(fn(t) { t.id == id }) { self.tabs.remove(id) for _, s in self.streams { if s.tab == Some(id) { s.tab = None } } } } for t in tabs { match self.tabs.get(t.id) { Some(old) => { old.title = t.title if t.audible && !old.audible { old.since = now old.seen_start = true } old.audible = t.audible } None => self.tabs.set(t.id, { title: t.title, audible: t.audible, since: now, seen_start: !initial, }) } } } ///| fn TabTracker::has_stream(self : TabTracker, tab : Int32) -> Bool { for _, s in self.streams { if s.tab == Some(tab) { return true } } false } ///| fn in_window(s : TrackedStream, t : TrackedTab) -> Bool { let d = t.since - s.since s.seen_start && t.seen_start && d >= -TAB_SLOP_MS && d <= TAB_WINDOW_MS } ///| /// Match what can be matched at `now`. `eliminate` must be false when tabs /// of the same browser may be missing (another profile has its own list). pub fn TabTracker::settle( self : TabTracker, now : Int64, eliminate~ : Bool = true, ) -> Unit { if !self.got_tabs { return } if !eliminate { for _, s in self.streams { if s.weak { s.tab = None s.weak = false } } } let audible : Array[Int32] = [] let free_tabs : Array[Int32] = [] for id, t in self.tabs { if t.audible { audible.push(id) if !self.has_stream(id) { free_tabs.push(id) } } } // By time: the stream's only candidate is this tab. Several streams may // start with one tab (media plus Web Audio), never the reverse. let found : Array[(TrackedStream, Int32)] = [] for _, s in self.streams { if s.tab is None && now - s.since >= TAB_WINDOW_MS { let near = audible.filter(fn(id) { match self.tabs.get(id) { Some(t) => in_window(s, t) None => false } }) // A tab that already has a stream comes second. let free = near.filter(fn(id) { free_tabs.contains(id) }) let cands = if free.length() > 0 { free } else { near } if cands is [id] { found.push((s, id)) } } } for f in found { f.0.tab = Some(f.1) f.0.weak = false } // A tab has been audible for a while with no stream left for it: one of // the eliminated matches must be wrong, so drop them all. let left = free_tabs.filter(fn(id) { !self.has_stream(id) }) let free_streams : Array[TrackedStream] = [] let mut pending = false for _, s in self.streams { if s.tab is None { free_streams.push(s) if now - s.since < TAB_SETTLE_MS { pending = true } } } let overdue = left.any(fn(id) { match self.tabs.get(id) { Some(t) => now - t.since >= TAB_SETTLE_MS None => false } }) if overdue && free_streams.length() == 0 { for _, s in self.streams { if s.weak { s.tab = None s.weak = false s.doubt = true } } return } if !eliminate || pending { return } let settled = left.all(fn(id) { match self.tabs.get(id) { Some(t) => now - t.since >= TAB_SETTLE_MS None => false } }) if !settled { return } let target = if audible is [only] { // A single tab makes sound: every stream left is its own. Some(only) } else if left is [only] && free_streams.length() == 1 { Some(only) } else { None } match target { Some(id) => for s in free_streams { if !s.doubt { s.tab = Some(id) s.weak = true } } None => () } } ///| /// Matched streams: (object.serial, tab id, tab title). pub fn TabTracker::matches(self : TabTracker) -> Array[(String, Int32, String)] { let out = [] for serial, s in self.streams { match s.tab { Some(id) => match self.tabs.get(id) { Some(t) => out.push((serial, id, t.title)) None => () } None => () } } out } ///| /// Parse a message from the extension: /// `{"tabs":[{"id":1,"title":"...","audible":true}]}`. None if malformed. pub fn parse_tabs(text : String) -> Array[BrowserTab]? { let json = @json.parse(text) catch { _ => return None } guard json is Object({ "tabs": Array(items), .. }) else { return None } let out = [] for item in items { guard item is Object( { "id": Number(id, ..), "title": String(title), "audible": True | False as audible, .. } ) else { return None } out.push({ id: id.to_int(), title, audible: audible is True, }) } Some(out) } ///| /// What one tab host publishes: its browser's pid and its matches. #derive(Eq, Debug) pub(all) struct TabFile { browser : Int32 streams : Array[(String, Int32, String)] // serial, tab id, title } ///| pub fn TabFile::to_text(self : TabFile) -> String { let streams : Array[Json] = self.streams.map(fn(s) { let o : Json = { "serial": Json::string(s.0), "tab": Json::number(s.1.to_double()), "title": Json::string(s.2), } o }) let o : Json = { "browser": Json::number(self.browser.to_double()), "streams": Json::array(streams), } o.stringify() } ///| pub fn TabFile::parse(text : String) -> TabFile? { let json = @json.parse(text) catch { _ => return None } guard json is Object({ "browser": Number(pid, ..), "streams": Array(items), .. }) else { return None } let streams = [] for item in items { guard item is Object( { "serial": String(serial), "tab": Number(tab, ..), "title": String(title), .. } ) else { return None } streams.push((serial, tab.to_int(), title)) } Some({ browser: pid.to_int(), streams, }) } ///| /// Names for the mixer from every host's file. A stream that two hosts /// claim (two profiles of one browser) is ambiguous and stays unnamed. pub fn merge_tab_files(files : Array[TabFile]) -> Map[String, TabName] { let out : Map[String, TabName] = Map([]) let clash : Map[String, Bool] = Map([]) for f in files { for s in f.streams { if out.contains(s.0) { clash.set(s.0, true) } out.set(s.0, { key: "\{f.browser}:\{s.1}", title: s.2, }) } } for s, _ in clash { out.remove(s) } out } ///| /// Parse "pid\ttitle" lines. pub fn parse_media_titles(text : String) -> Map[Int32, String] { let out : Map[Int32, String] = Map([]) for line in text.split("\n") { match line.find("\t") { Some(i) => { let pid = @string.parse_int(line[:i]) catch { _ => continue } out.set(pid, line[i + 1:].to_owned()) } None => () } } out }