Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 105 additions & 2 deletions tools/launcher/core/src/services/simaudio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@
//! length, payload. Out: 1 open (u32 rate, u32 channels), 2 data, 3 close; in: 4 microphone (f32 mono 48 kHz, replaces
//! the input streams' source while it arrives), 5 microphone off. A slow tap loses data, never slows a stream.
//! <state>/simaudio-out/<Linux pid> marks a process with an output stream open (jetsam keeps audio apps that play).
//! <state>/simaudio-streams.json maps active output stream IDs (matching simaudio-tap.sock) to their SO_PEERCRED
//! host_pid, rate, and channels without changing the 8-byte OPEN tap wire format.
//! env: X86SIM_AUDIO_VOLUME (0..1, 0.5), X86SIM_AUDIO_PLAYER (pw-cat | pacat)
use super::wait_timeout;
use serde::Serialize;
use std::collections::{BTreeMap, HashMap};
use std::io::{BufRead, BufReader, Read, Write};
use std::os::unix::fs::PermissionsExt;
Expand Down Expand Up @@ -243,6 +246,60 @@ impl Taps {
}
}

/// Active output stream attribution for a tap stream id (from kernel SO_PEERCRED).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub struct OutputStreamInfo {
pub host_pid: i32,
pub rate: u32,
pub channels: u32,
}

#[derive(Serialize)]
struct StreamsSnapshot<'a> {
schema: u32,
streams: &'a BTreeMap<String, OutputStreamInfo>,
}

struct StreamRegistry {
path: Option<PathBuf>,
streams: Mutex<BTreeMap<u32, OutputStreamInfo>>,
}

impl StreamRegistry {
fn new(path: Option<PathBuf>) -> Self {
let reg = Self { path, streams: Mutex::default() };
let empty = BTreeMap::new();
reg.flush_locked(&empty);
reg
}

fn insert(&self, sid: u32, info: OutputStreamInfo) {
let mut streams = self.streams.lock().unwrap();
streams.insert(sid, info);
self.flush_locked(&streams);
}

fn remove(&self, sid: u32) {
let mut streams = self.streams.lock().unwrap();
if streams.remove(&sid).is_some() {
self.flush_locked(&streams);
}
}

fn flush_locked(&self, streams: &BTreeMap<u32, OutputStreamInfo>) {
let Some(path) = self.path.as_ref() else { return };
let keyed: BTreeMap<String, OutputStreamInfo> = streams.iter().map(|(sid, info)| (sid.to_string(), *info)).collect();
let Ok(bytes) = serde_json::to_vec(&StreamsSnapshot { schema: 1, streams: &keyed }) else { return };
let tmp = path.with_extension("json.tmp");
if std::fs::write(&tmp, &bytes).is_ok() {
let _ = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600));
if std::fs::rename(&tmp, path).is_err() {
let _ = std::fs::remove_file(&tmp);
}
}
}
}

struct Service {
playback: bool,
mic: bool,
Expand All @@ -253,6 +310,7 @@ struct Service {
micfeed: Mutex<MicFeed>,
out_dir: Option<PathBuf>,
out_n: Mutex<HashMap<i32, i64>>,
streams: StreamRegistry,
}

/// a player that stopped while its stream still ran (once a connection): its exit status, if it ends within 1 s
Expand Down Expand Up @@ -345,7 +403,9 @@ impl Service {
if direction == 0 {
let pid = peer_pid(&conn);
self.out_mark(pid, 1);
self.streams.insert(n as u32, OutputStreamInfo { host_pid: pid, rate, channels: ch });
self.output(&conn, n, rate, ch);
self.streams.remove(n as u32);
self.out_mark(pid, -1);
} else {
self.input(&conn, n, rate, ch);
Expand Down Expand Up @@ -478,10 +538,12 @@ pub fn run(path: &Path) -> std::io::Result<()> {
let tap_path = abs_dir(path).join("simaudio-tap.sock");
let t = listen(&tap_path, 0o700)?;
// the marks, a previous boot's removed
let out = abs_dir(path).join("simaudio-out");
let state_dir = abs_dir(path);
let out = state_dir.join("simaudio-out");
let _ = std::fs::remove_dir_all(&out);
let out_dir = std::fs::create_dir_all(&out).is_ok().then_some(out);
let svc = Arc::new(Service { playback, mic, player, volume: volume.clone(), gain, taps: Taps::default(), micfeed: Mutex::default(), out_dir, out_n: Mutex::default() });
let streams = StreamRegistry::new(Some(state_dir.join("simaudio-streams.json")));
let svc = Arc::new(Service { playback, mic, player, volume: volume.clone(), gain, taps: Taps::default(), micfeed: Mutex::default(), out_dir, out_n: Mutex::default(), streams });
{
let svc = svc.clone();
std::thread::spawn(move || {
Expand Down Expand Up @@ -535,4 +597,45 @@ mod tests {
f.off();
assert!(!f.active());
}

#[test]
fn stream_registry_tracks_open_and_close_atomically() {
let path = std::env::temp_dir().join(format!("x86sim-simaudio-streams-{}.json", std::process::id()));
let tmp = path.with_extension("json.tmp");
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_file(&tmp);

let reg = StreamRegistry::new(Some(path.clone()));
let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(v["schema"], 1);
assert_eq!(v["streams"].as_object().unwrap().len(), 0);
assert!(!tmp.exists());
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);

reg.insert(1, OutputStreamInfo { host_pid: 4242, rate: 48000, channels: 2 });
reg.insert(2, OutputStreamInfo { host_pid: 5151, rate: 44100, channels: 1 });
let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(v["streams"]["1"]["host_pid"], 4242);
assert_eq!(v["streams"]["1"]["rate"], 48000);
assert_eq!(v["streams"]["1"]["channels"], 2);
assert_eq!(v["streams"]["2"]["host_pid"], 5151);

reg.remove(1);
let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert!(v["streams"].get("1").is_none());
assert_eq!(v["streams"]["2"]["host_pid"], 5151);

reg.remove(2);
let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(v["streams"].as_object().unwrap().len(), 0);
assert!(!tmp.exists());

let _ = std::fs::remove_file(&path);
}

#[test]
fn peer_pid_on_unix_socketpair() {
let (a, _b) = UnixStream::pair().unwrap();
assert_eq!(peer_pid(&a), std::process::id() as i32);
}
}
Loading