| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | #![forbid(unsafe_code)] |
| 18 | |
| 19 | pub mod wire; |
| 20 | |
| 21 | use std::collections::{HashMap, VecDeque}; |
| 22 | use std::ffi::OsStr; |
| 23 | use std::io::{Read, Write}; |
| 24 | use std::os::unix::net::UnixStream; |
| 25 | use std::path::{Path, PathBuf}; |
| 26 | use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; |
| 27 | use std::sync::{Arc, Mutex, MutexGuard, mpsc}; |
| 28 | use std::thread::JoinHandle; |
| 29 | use std::time::Duration; |
| 30 | |
| 31 | use wire::{Reader, Tags, command}; |
| 32 | |
| 33 | |
| 34 | pub(crate) const APP_NAME: &str = "edith"; |
| 35 | |
| 36 | |
| 37 | const REPLY_TIMEOUT: Duration = Duration::from_secs(2); |
| 38 | |
| 39 | const LATENCY_MS: u64 = 100; |
| 40 | |
| 41 | const MINREQ_MS: u64 = 10; |
| 42 | |
| 43 | |
| 44 | const QUEUE_SECONDS: usize = 1; |
| 45 | |
| 46 | |
| 47 | const MAX_PAYLOAD: usize = 16 << 20; |
| 48 | |
| 49 | |
| 50 | const MAX_CAPTURE_SECONDS: usize = 2; |
| 51 | |
| 52 | const RECORD_FRAGMENT_MS: u64 = 10; |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | pub fn server_path() -> Option<PathBuf> { |
| 58 | server_path_from( |
| 59 | crate::envcfg::var("PULSE_SERVER").as_deref(), |
| 60 | crate::envcfg::var_os("XDG_RUNTIME_DIR").as_deref(), |
| 61 | ) |
| 62 | } |
| 63 | |
| 64 | fn server_path_from(server: Option<&str>, runtime_dir: Option<&OsStr>) -> Option<PathBuf> { |
| 65 | match server { |
| 66 | Some(server) => { |
| 67 | let first = server |
| 68 | .split(|c: char| c.is_whitespace() || c == ';') |
| 69 | .find(|entry| !entry.is_empty())?; |
| 70 | match first.strip_prefix("unix:") { |
| 71 | Some(path) => Some(PathBuf::from(path)), |
| 72 | None if first.starts_with('/') => Some(PathBuf::from(first)), |
| 73 | None => None, |
| 74 | } |
| 75 | } |
| 76 | None => Some(Path::new(runtime_dir?).join("pulse/native")), |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | fn cookie() -> Vec<u8> { |
| 84 | let path = crate::envcfg::var_os("PULSE_COOKIE").map(PathBuf::from).or_else(|| { |
| 85 | let config = crate::envcfg::var_os("XDG_CONFIG_HOME") |
| 86 | .map(PathBuf::from) |
| 87 | .or_else(|| crate::envcfg::var_os("HOME").map(|home| Path::new(&home).join(".config")))?; |
| 88 | Some(config.join("pulse/cookie")) |
| 89 | }); |
| 90 | path.and_then(|path| std::fs::read(path).ok()) |
| 91 | .filter(|bytes| !bytes.is_empty()) |
| 92 | .unwrap_or_else(|| vec![0; 256]) |
| 93 | } |
| 94 | |
| 95 | type Reply = Result<Vec<u8>, u32>; |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | struct Shared { |
| 101 | socket: Mutex<UnixStream>, |
| 102 | state: Mutex<State>, |
| 103 | |
| 104 | gain: AtomicU32, |
| 105 | |
| 106 | dead: AtomicBool, |
| 107 | } |
| 108 | |
| 109 | struct State { |
| 110 | |
| 111 | |
| 112 | |
| 113 | channel: u32, |
| 114 | channels: usize, |
| 115 | rate: u32, |
| 116 | |
| 117 | credits: u64, |
| 118 | |
| 119 | pending: VecDeque<f32>, |
| 120 | capacity: usize, |
| 121 | |
| 122 | |
| 123 | |
| 124 | primed: bool, |
| 125 | |
| 126 | waiters: HashMap<u32, mpsc::Sender<Reply>>, |
| 127 | next_tag: u32, |
| 128 | underruns: u64, |
| 129 | |
| 130 | last_underrun: i64, |
| 131 | |
| 132 | last_position: i64, |
| 133 | |
| 134 | |
| 135 | started: bool, |
| 136 | |
| 137 | |
| 138 | capturing: bool, |
| 139 | capture: VecDeque<f32>, |
| 140 | } |
| 141 | |
| 142 | |
| 143 | |
| 144 | fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> { |
| 145 | mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 146 | } |
| 147 | |
| 148 | |
| 149 | |
| 150 | fn take_packets(state: &mut State, gain: f32) -> Vec<u8> { |
| 151 | let stride = 4 * state.channels; |
| 152 | let by_credit = (state.credits as usize / stride) * state.channels; |
| 153 | let count = by_credit.min(state.pending.len()); |
| 154 | if count == 0 { |
| 155 | return Vec::new(); |
| 156 | } |
| 157 | let mut data = Vec::with_capacity(count * 4); |
| 158 | for sample in state.pending.drain(..count) { |
| 159 | let value = if gain == 1.0 { sample } else { sample * gain }; |
| 160 | data.extend_from_slice(&value.to_le_bytes()); |
| 161 | } |
| 162 | state.credits -= data.len() as u64; |
| 163 | let mut packet = wire::header(data.len() as u32, state.channel, 0, 0).to_vec(); |
| 164 | packet.extend_from_slice(&data); |
| 165 | packet |
| 166 | } |
| 167 | |
| 168 | |
| 169 | fn send(shared: &Shared, bytes: &[u8]) -> bool { |
| 170 | if bytes.is_empty() { |
| 171 | return true; |
| 172 | } |
| 173 | if shared.dead.load(Ordering::Acquire) { |
| 174 | return false; |
| 175 | } |
| 176 | let sent = lock(&shared.socket).write_all(bytes).is_ok(); |
| 177 | if !sent { |
| 178 | shared.dead.store(true, Ordering::Release); |
| 179 | } |
| 180 | sent |
| 181 | } |
| 182 | |
| 183 | fn read_loop(mut socket: UnixStream, shared: Arc<Shared>) { |
| 184 | let mut header = [0u8; wire::HEADER_LEN]; |
| 185 | loop { |
| 186 | if socket.read_exact(&mut header).is_err() { |
| 187 | break; |
| 188 | } |
| 189 | let (len, channel, _, _) = wire::parse_header(&header); |
| 190 | if len as usize > MAX_PAYLOAD { |
| 191 | break; |
| 192 | } |
| 193 | let mut payload = vec![0u8; len as usize]; |
| 194 | if socket.read_exact(&mut payload).is_err() { |
| 195 | break; |
| 196 | } |
| 197 | if channel == wire::CONTROL_CHANNEL { |
| 198 | dispatch(&shared, &payload); |
| 199 | } else { |
| 200 | capture(&shared, channel, &payload); |
| 201 | } |
| 202 | } |
| 203 | shared.dead.store(true, Ordering::Release); |
| 204 | |
| 205 | lock(&shared.state).waiters.clear(); |
| 206 | } |
| 207 | |
| 208 | |
| 209 | |
| 210 | |
| 211 | fn capture(shared: &Shared, channel: u32, payload: &[u8]) { |
| 212 | let mut state = lock(&shared.state); |
| 213 | if !state.capturing || channel != state.channel { |
| 214 | return; |
| 215 | } |
| 216 | let cap = state.rate as usize * state.channels * MAX_CAPTURE_SECONDS; |
| 217 | let (samples, _) = payload.as_chunks::<4>(); |
| 218 | state.capture.extend(samples.iter().map(|b| f32::from_le_bytes(*b))); |
| 219 | let excess = state.capture.len().saturating_sub(cap); |
| 220 | state.capture.drain(..excess); |
| 221 | } |
| 222 | |
| 223 | fn dispatch(shared: &Shared, payload: &[u8]) { |
| 224 | let mut reader = Reader::new(payload); |
| 225 | let (Some(cmd), Some(tag)) = (reader.u32(), reader.u32()) else { |
| 226 | return; |
| 227 | }; |
| 228 | match cmd { |
| 229 | command::REPLY => { |
| 230 | if let Some(waiter) = lock(&shared.state).waiters.remove(&tag) { |
| 231 | let _ = waiter.send(Ok(reader.rest().to_vec())); |
| 232 | } |
| 233 | } |
| 234 | command::ERROR => { |
| 235 | let code = reader.u32().unwrap_or(0); |
| 236 | if let Some(waiter) = lock(&shared.state).waiters.remove(&tag) { |
| 237 | let _ = waiter.send(Err(code)); |
| 238 | } |
| 239 | } |
| 240 | command::REQUEST => { |
| 241 | let (Some(channel), Some(len)) = (reader.u32(), reader.u32()) else { |
| 242 | return; |
| 243 | }; |
| 244 | let packet = { |
| 245 | let mut state = lock(&shared.state); |
| 246 | if channel != state.channel { |
| 247 | return; |
| 248 | } |
| 249 | state.credits += u64::from(len); |
| 250 | take_packets(&mut state, f32::from_bits(shared.gain.load(Ordering::Relaxed))) |
| 251 | }; |
| 252 | send(shared, &packet); |
| 253 | } |
| 254 | command::UNDERFLOW => { |
| 255 | let mut state = lock(&shared.state); |
| 256 | if state.primed { |
| 257 | state.underruns += 1; |
| 258 | state.last_underrun = state.last_position; |
| 259 | } |
| 260 | } |
| 261 | command::PLAYBACK_STREAM_KILLED | command::RECORD_STREAM_KILLED => shared.dead.store(true, Ordering::Release), |
| 262 | _ => {} |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | |
| 267 | |
| 268 | fn connect(path: &Path, rate: u32, channels: u32) -> Option<(Arc<Shared>, JoinHandle<()>)> { |
| 269 | if !(8_000..=768_000).contains(&rate) || !(1..=32).contains(&channels) { |
| 270 | return None; |
| 271 | } |
| 272 | let socket = UnixStream::connect(path).ok()?; |
| 273 | socket.set_write_timeout(Some(REPLY_TIMEOUT)).ok()?; |
| 274 | let reader = socket.try_clone().ok()?; |
| 275 | let shared = Arc::new(Shared { |
| 276 | socket: Mutex::new(socket), |
| 277 | state: Mutex::new(State { |
| 278 | channel: 0, |
| 279 | channels: channels as usize, |
| 280 | rate, |
| 281 | credits: 0, |
| 282 | pending: VecDeque::new(), |
| 283 | capacity: rate as usize * channels as usize * QUEUE_SECONDS, |
| 284 | primed: false, |
| 285 | waiters: HashMap::new(), |
| 286 | next_tag: 1, |
| 287 | underruns: 0, |
| 288 | last_underrun: -1, |
| 289 | last_position: -1, |
| 290 | started: false, |
| 291 | capturing: false, |
| 292 | capture: VecDeque::new(), |
| 293 | }), |
| 294 | gain: AtomicU32::new(1.0f32.to_bits()), |
| 295 | dead: AtomicBool::new(false), |
| 296 | }); |
| 297 | let thread = { |
| 298 | let shared = shared.clone(); |
| 299 | std::thread::spawn(move || read_loop(reader, shared)) |
| 300 | }; |
| 301 | Some((shared, thread)) |
| 302 | } |
| 303 | |
| 304 | |
| 305 | fn greet(shared: &Shared) -> bool { |
| 306 | let Some(_) = call(shared, command::AUTH, Tags::new().u32(wire::PROTOCOL_VERSION).arbitrary(&cookie())) else { |
| 307 | eprintln!("pulse: the server refused the connection"); |
| 308 | return false; |
| 309 | }; |
| 310 | call(shared, command::SET_CLIENT_NAME, Tags::new().proplist(&[("application.name", APP_NAME)])).is_some() |
| 311 | } |
| 312 | |
| 313 | |
| 314 | |
| 315 | fn call(shared: &Shared, cmd: u32, args: Tags) -> Option<Vec<u8>> { |
| 316 | let (tx, rx) = mpsc::channel(); |
| 317 | let tag = { |
| 318 | let mut state = lock(&shared.state); |
| 319 | let tag = state.next_tag; |
| 320 | state.next_tag = state.next_tag.wrapping_add(1); |
| 321 | state.waiters.insert(tag, tx); |
| 322 | tag |
| 323 | }; |
| 324 | if !send(shared, &wire::control(cmd, tag, args)) { |
| 325 | lock(&shared.state).waiters.remove(&tag); |
| 326 | return None; |
| 327 | } |
| 328 | match rx.recv_timeout(REPLY_TIMEOUT) { |
| 329 | Ok(Ok(payload)) => Some(payload), |
| 330 | Ok(Err(_)) | Err(_) => { |
| 331 | lock(&shared.state).waiters.remove(&tag); |
| 332 | None |
| 333 | } |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | |
| 338 | |
| 339 | pub struct Playback { |
| 340 | shared: Arc<Shared>, |
| 341 | reader: Option<JoinHandle<()>>, |
| 342 | } |
| 343 | |
| 344 | impl Playback { |
| 345 | |
| 346 | |
| 347 | |
| 348 | pub fn open(rate: u32, channels: u32) -> Option<Self> { |
| 349 | Self::open_at(&server_path()?, rate, channels) |
| 350 | } |
| 351 | |
| 352 | |
| 353 | pub fn open_at(path: &Path, rate: u32, channels: u32) -> Option<Self> { |
| 354 | let (shared, reader) = connect(path, rate, channels)?; |
| 355 | let mut playback = Self { |
| 356 | shared, |
| 357 | reader: Some(reader), |
| 358 | }; |
| 359 | playback.handshake(rate, channels).then_some(playback) |
| 360 | } |
| 361 | |
| 362 | fn handshake(&mut self, rate: u32, channels: u32) -> bool { |
| 363 | if !greet(&self.shared) { |
| 364 | return false; |
| 365 | } |
| 366 | let bytes_per_second = u64::from(rate) * u64::from(channels) * 4; |
| 367 | let tlength = (bytes_per_second * LATENCY_MS / 1000) as u32; |
| 368 | let minreq = (bytes_per_second * MINREQ_MS / 1000) as u32; |
| 369 | let args = wire::create_playback_stream_args(rate, channels as u8, tlength, minreq, wire::VOLUME_NORM); |
| 370 | let Some(reply) = self.request(command::CREATE_PLAYBACK_STREAM, args) else { |
| 371 | eprintln!("pulse: the server would not create a {rate} Hz, {channels}-channel stream"); |
| 372 | return false; |
| 373 | }; |
| 374 | |
| 375 | |
| 376 | let mut reader = Reader::new(&reply); |
| 377 | let (Some(channel), Some(_sink_input), Some(requested)) = (reader.u32(), reader.u32(), reader.u32()) else { |
| 378 | return false; |
| 379 | }; |
| 380 | let mut state = lock(&self.shared.state); |
| 381 | state.channel = channel; |
| 382 | state.credits = u64::from(requested); |
| 383 | true |
| 384 | } |
| 385 | |
| 386 | |
| 387 | |
| 388 | fn request(&self, cmd: u32, args: Tags) -> Option<Vec<u8>> { |
| 389 | call(&self.shared, cmd, args) |
| 390 | } |
| 391 | |
| 392 | |
| 393 | fn tell(&self, cmd: u32, args: Tags) -> bool { |
| 394 | send(&self.shared, &wire::control(cmd, 0, args)) |
| 395 | } |
| 396 | |
| 397 | fn channel(&self) -> u32 { |
| 398 | lock(&self.shared.state).channel |
| 399 | } |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | pub fn write(&mut self, samples: &[f32]) -> Option<usize> { |
| 406 | if self.shared.dead.load(Ordering::Acquire) { |
| 407 | return None; |
| 408 | } |
| 409 | let gain = f32::from_bits(self.shared.gain.load(Ordering::Relaxed)); |
| 410 | let (taken, packet) = { |
| 411 | let mut state = lock(&self.shared.state); |
| 412 | let frame = state.channels; |
| 413 | let room = state.capacity.saturating_sub(state.pending.len()); |
| 414 | let taken = samples.len().min(room) / frame * frame; |
| 415 | state.pending.extend(&samples[..taken]); |
| 416 | if taken > 0 { |
| 417 | state.primed = true; |
| 418 | } |
| 419 | (taken, take_packets(&mut state, gain)) |
| 420 | }; |
| 421 | send(&self.shared, &packet).then_some(taken) |
| 422 | } |
| 423 | |
| 424 | |
| 425 | |
| 426 | |
| 427 | pub fn position(&self) -> Option<i64> { |
| 428 | let args = Tags::new().u32(self.channel()).timeval(0, 0); |
| 429 | let reply = self.request(command::GET_PLAYBACK_LATENCY, args)?; |
| 430 | let mut reader = Reader::new(&reply); |
| 431 | let sink_usec = reader.u64()?; |
| 432 | let _source_usec = reader.u64()?; |
| 433 | let playing = reader.bool()?; |
| 434 | reader.timeval()?; |
| 435 | reader.timeval()?; |
| 436 | let _write_index = reader.i64()?; |
| 437 | let read_index = reader.i64()?; |
| 438 | let mut state = lock(&self.shared.state); |
| 439 | state.started |= playing; |
| 440 | if !state.started || read_index < 0 { |
| 441 | return None; |
| 442 | } |
| 443 | let stride = 4 * state.channels as i64; |
| 444 | let frames = read_index / stride; |
| 445 | let sink_frames = (sink_usec as i64).saturating_mul(i64::from(state.rate)) / 1_000_000; |
| 446 | let played = (frames - sink_frames).max(0); |
| 447 | state.last_position = played; |
| 448 | Some(played) |
| 449 | } |
| 450 | |
| 451 | |
| 452 | |
| 453 | pub fn stream_ended(&self) { |
| 454 | lock(&self.shared.state).primed = false; |
| 455 | } |
| 456 | |
| 457 | |
| 458 | |
| 459 | pub fn set_active(&self, active: bool) -> bool { |
| 460 | self.request(command::CORK_PLAYBACK_STREAM, Tags::new().u32(self.channel()).bool(!active)) |
| 461 | .is_some() |
| 462 | } |
| 463 | |
| 464 | |
| 465 | |
| 466 | |
| 467 | pub fn set_volume(&self, gain: f32) -> bool { |
| 468 | if !(0.0..=1.0).contains(&gain) { |
| 469 | return false; |
| 470 | } |
| 471 | self.shared.gain.store(gain.to_bits(), Ordering::Relaxed); |
| 472 | true |
| 473 | } |
| 474 | |
| 475 | |
| 476 | pub fn gain(&self) -> f32 { |
| 477 | f32::from_bits(self.shared.gain.load(Ordering::Relaxed)) |
| 478 | } |
| 479 | |
| 480 | |
| 481 | |
| 482 | pub fn flush(&self) -> bool { |
| 483 | { |
| 484 | let mut state = lock(&self.shared.state); |
| 485 | state.pending.clear(); |
| 486 | state.primed = false; |
| 487 | } |
| 488 | self.request(command::FLUSH_PLAYBACK_STREAM, Tags::new().u32(self.channel())).is_some() |
| 489 | } |
| 490 | |
| 491 | |
| 492 | pub fn underruns(&self) -> (u64, Option<i64>) { |
| 493 | let state = lock(&self.shared.state); |
| 494 | (state.underruns, (state.last_underrun >= 0).then_some(state.last_underrun)) |
| 495 | } |
| 496 | } |
| 497 | |
| 498 | impl Drop for Playback { |
| 499 | fn drop(&mut self) { |
| 500 | if !self.shared.dead.load(Ordering::Acquire) { |
| 501 | self.tell(command::DELETE_PLAYBACK_STREAM, Tags::new().u32(self.channel())); |
| 502 | } |
| 503 | let underruns = lock(&self.shared.state).underruns; |
| 504 | if underruns > 0 { |
| 505 | eprintln!("pulse: {underruns} underruns"); |
| 506 | } |
| 507 | let _ = lock(&self.shared.socket).shutdown(std::net::Shutdown::Both); |
| 508 | if let Some(reader) = self.reader.take() { |
| 509 | let _ = reader.join(); |
| 510 | } |
| 511 | } |
| 512 | } |
| 513 | |
| 514 | |
| 515 | |
| 516 | pub struct Recording { |
| 517 | shared: Arc<Shared>, |
| 518 | reader: Option<JoinHandle<()>>, |
| 519 | } |
| 520 | |
| 521 | impl Recording { |
| 522 | |
| 523 | |
| 524 | |
| 525 | pub fn open(rate: u32, channels: u32, source: Option<&str>) -> Option<Self> { |
| 526 | Self::open_at(&server_path()?, rate, channels, source) |
| 527 | } |
| 528 | |
| 529 | |
| 530 | pub fn open_at(path: &Path, rate: u32, channels: u32, source: Option<&str>) -> Option<Self> { |
| 531 | let (shared, reader) = connect(path, rate, channels)?; |
| 532 | let mut recording = Self { |
| 533 | shared, |
| 534 | reader: Some(reader), |
| 535 | }; |
| 536 | recording.handshake(rate, channels, source).then_some(recording) |
| 537 | } |
| 538 | |
| 539 | fn handshake(&mut self, rate: u32, channels: u32, source: Option<&str>) -> bool { |
| 540 | if !greet(&self.shared) { |
| 541 | return false; |
| 542 | } |
| 543 | let fragsize = (u64::from(rate) * u64::from(channels) * 4 * RECORD_FRAGMENT_MS / 1000) as u32; |
| 544 | let args = wire::create_record_stream_args(rate, channels as u8, source, fragsize); |
| 545 | let Some(reply) = call(&self.shared, command::CREATE_RECORD_STREAM, args) else { |
| 546 | eprintln!("pulse: the server would not record {rate} Hz, {channels} channels"); |
| 547 | return false; |
| 548 | }; |
| 549 | |
| 550 | let Some(channel) = Reader::new(&reply).u32() else { |
| 551 | return false; |
| 552 | }; |
| 553 | let mut state = lock(&self.shared.state); |
| 554 | state.channel = channel; |
| 555 | state.capturing = true; |
| 556 | true |
| 557 | } |
| 558 | |
| 559 | |
| 560 | |
| 561 | pub fn read(&self) -> Vec<f32> { |
| 562 | lock(&self.shared.state).capture.drain(..).collect() |
| 563 | } |
| 564 | |
| 565 | |
| 566 | pub fn alive(&self) -> bool { |
| 567 | !self.shared.dead.load(Ordering::Acquire) |
| 568 | } |
| 569 | |
| 570 | |
| 571 | |
| 572 | pub fn set_active(&self, active: bool) -> bool { |
| 573 | let channel = lock(&self.shared.state).channel; |
| 574 | call(&self.shared, command::CORK_RECORD_STREAM, Tags::new().u32(channel).bool(!active)).is_some() |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | impl Drop for Recording { |
| 579 | fn drop(&mut self) { |
| 580 | if !self.shared.dead.load(Ordering::Acquire) { |
| 581 | let channel = lock(&self.shared.state).channel; |
| 582 | send(&self.shared, &wire::control(command::DELETE_RECORD_STREAM, 0, Tags::new().u32(channel))); |
| 583 | } |
| 584 | let _ = lock(&self.shared.socket).shutdown(std::net::Shutdown::Both); |
| 585 | if let Some(reader) = self.reader.take() { |
| 586 | let _ = reader.join(); |
| 587 | } |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | |
| 592 | #[derive(Clone, Debug, PartialEq)] |
| 593 | pub struct Source { |
| 594 | |
| 595 | pub name: String, |
| 596 | pub description: String, |
| 597 | |
| 598 | pub monitor: bool, |
| 599 | } |
| 600 | |
| 601 | |
| 602 | |
| 603 | pub fn list_sources() -> Option<Vec<Source>> { |
| 604 | list_sources_at(&server_path()?) |
| 605 | } |
| 606 | |
| 607 | |
| 608 | pub fn list_sources_at(path: &Path) -> Option<Vec<Source>> { |
| 609 | let (shared, reader) = connect(path, 48_000, 2)?; |
| 610 | let sources = greet(&shared) |
| 611 | .then(|| call(&shared, command::GET_SOURCE_INFO_LIST, Tags::new())) |
| 612 | .flatten() |
| 613 | .and_then(|reply| parse_sources(&reply)); |
| 614 | let _ = lock(&shared.socket).shutdown(std::net::Shutdown::Both); |
| 615 | let _ = reader.join(); |
| 616 | sources |
| 617 | } |
| 618 | |
| 619 | |
| 620 | |
| 621 | fn parse_sources(reply: &[u8]) -> Option<Vec<Source>> { |
| 622 | let mut r = Reader::new(reply); |
| 623 | let mut sources = Vec::new(); |
| 624 | while !r.rest().is_empty() { |
| 625 | r.u32()?; |
| 626 | let name = r.string_or_null()?.unwrap_or_default(); |
| 627 | let description = r.string_or_null()?.unwrap_or_default(); |
| 628 | r.sample_spec()?; |
| 629 | r.channel_map()?; |
| 630 | r.u32()?; |
| 631 | r.cvolume()?; |
| 632 | r.bool()?; |
| 633 | let monitor_of = r.u32()?; |
| 634 | r.string_or_null()?; |
| 635 | r.u64()?; |
| 636 | r.string_or_null()?; |
| 637 | r.u32()?; |
| 638 | r.skip_proplist()?; |
| 639 | r.u64()?; |
| 640 | r.volume()?; |
| 641 | r.u32()?; |
| 642 | r.u32()?; |
| 643 | r.u32()?; |
| 644 | for _ in 0..r.u32()? { |
| 645 | r.string_or_null()?; |
| 646 | r.string_or_null()?; |
| 647 | r.u32()?; |
| 648 | r.u32()?; |
| 649 | r.string_or_null()?; |
| 650 | r.u32()?; |
| 651 | } |
| 652 | r.string_or_null()?; |
| 653 | for _ in 0..r.u8()? { |
| 654 | r.format_info()?; |
| 655 | } |
| 656 | sources.push(Source { |
| 657 | name, |
| 658 | description, |
| 659 | monitor: monitor_of != wire::DEFAULT, |
| 660 | }); |
| 661 | } |
| 662 | Some(sources) |
| 663 | } |
| 664 | |
| 665 | #[cfg(test)] |
| 666 | mod tests { |
| 667 | use super::*; |
| 668 | use std::os::unix::net::UnixListener; |
| 669 | use std::time::Instant; |
| 670 | |
| 671 | |
| 672 | struct Sent { |
| 673 | channel: u32, |
| 674 | |
| 675 | command: u32, |
| 676 | tag: u32, |
| 677 | args: Vec<u8>, |
| 678 | |
| 679 | data: Vec<u8>, |
| 680 | } |
| 681 | |
| 682 | |
| 683 | |
| 684 | struct Mock { |
| 685 | |
| 686 | |
| 687 | socket: Option<UnixStream>, |
| 688 | accepted: mpsc::Receiver<UnixStream>, |
| 689 | rx: mpsc::Receiver<Sent>, |
| 690 | dir: PathBuf, |
| 691 | } |
| 692 | |
| 693 | impl Mock { |
| 694 | fn bind(name: &str) -> (Self, PathBuf) { |
| 695 | let dir = std::env::temp_dir().join(format!("edith-pulse-{}-{name}", std::process::id())); |
| 696 | let _ = std::fs::remove_dir_all(&dir); |
| 697 | std::fs::create_dir_all(&dir).unwrap(); |
| 698 | let path = dir.join("native"); |
| 699 | let listener = UnixListener::bind(&path).unwrap(); |
| 700 | let (tx, rx) = mpsc::channel(); |
| 701 | let (accepted_tx, accepted_rx) = mpsc::channel(); |
| 702 | std::thread::spawn(move || { |
| 703 | let (socket, _) = listener.accept().unwrap(); |
| 704 | let reader = socket.try_clone().unwrap(); |
| 705 | accepted_tx.send(socket).unwrap(); |
| 706 | let mut reader = reader; |
| 707 | let mut header = [0u8; wire::HEADER_LEN]; |
| 708 | while reader.read_exact(&mut header).is_ok() { |
| 709 | let (len, channel, _, _) = wire::parse_header(&header); |
| 710 | let mut payload = vec![0u8; len as usize]; |
| 711 | if reader.read_exact(&mut payload).is_err() { |
| 712 | break; |
| 713 | } |
| 714 | let sent = if channel == wire::CONTROL_CHANNEL { |
| 715 | let mut r = Reader::new(&payload); |
| 716 | let command = r.u32().unwrap(); |
| 717 | let tag = r.u32().unwrap(); |
| 718 | Sent { channel, command, tag, args: r.rest().to_vec(), data: Vec::new() } |
| 719 | } else { |
| 720 | Sent { channel, command: u32::MAX, tag: 0, args: Vec::new(), data: payload } |
| 721 | }; |
| 722 | if tx.send(sent).is_err() { |
| 723 | break; |
| 724 | } |
| 725 | } |
| 726 | }); |
| 727 | ( |
| 728 | Self { |
| 729 | socket: None, |
| 730 | accepted: accepted_rx, |
| 731 | rx, |
| 732 | dir: dir.clone(), |
| 733 | }, |
| 734 | path, |
| 735 | ) |
| 736 | } |
| 737 | |
| 738 | fn expect(&self, command: u32) -> Sent { |
| 739 | let deadline = Instant::now() + Duration::from_secs(3); |
| 740 | loop { |
| 741 | let left = deadline.saturating_duration_since(Instant::now()); |
| 742 | let sent = self.rx.recv_timeout(left).expect("the client sent nothing in time"); |
| 743 | if sent.command == command { |
| 744 | return sent; |
| 745 | } |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | |
| 750 | fn memblock_within(&self, wait: Duration) -> Vec<u8> { |
| 751 | let deadline = Instant::now() + wait; |
| 752 | let mut data = Vec::new(); |
| 753 | loop { |
| 754 | let left = deadline.saturating_duration_since(Instant::now()); |
| 755 | match self.rx.recv_timeout(left) { |
| 756 | Ok(sent) if sent.channel != wire::CONTROL_CHANNEL => data.extend(sent.data), |
| 757 | Ok(_) => {} |
| 758 | Err(_) => return data, |
| 759 | } |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | fn send(&mut self, packet: &[u8]) { |
| 764 | if self.socket.is_none() { |
| 765 | self.socket = Some(self.accepted.recv().unwrap()); |
| 766 | } |
| 767 | self.socket.as_mut().unwrap().write_all(packet).unwrap(); |
| 768 | } |
| 769 | |
| 770 | |
| 771 | fn close(&mut self) { |
| 772 | if let Some(socket) = &self.socket { |
| 773 | let _ = socket.shutdown(std::net::Shutdown::Both); |
| 774 | } |
| 775 | } |
| 776 | |
| 777 | fn reply(&mut self, tag: u32, args: Tags) { |
| 778 | let packet = wire::control(command::REPLY, tag, args); |
| 779 | self.send(&packet); |
| 780 | } |
| 781 | |
| 782 | fn request_bytes(&mut self, channel: u32, len: u32) { |
| 783 | let packet = wire::control(command::REQUEST, u32::MAX, Tags::new().u32(channel).u32(len)); |
| 784 | self.send(&packet); |
| 785 | } |
| 786 | |
| 787 | fn underflow(&mut self, channel: u32) { |
| 788 | let packet = wire::control(command::UNDERFLOW, u32::MAX, Tags::new().u32(channel).i64(0)); |
| 789 | self.send(&packet); |
| 790 | } |
| 791 | |
| 792 | |
| 793 | |
| 794 | fn handshake(&mut self, requested: u32) -> Sent { |
| 795 | let auth = self.expect(command::AUTH); |
| 796 | let mut r = Reader::new(&auth.args); |
| 797 | assert_eq!(r.u32(), Some(wire::PROTOCOL_VERSION)); |
| 798 | assert_eq!(r.arbitrary().map(<[u8]>::len), Some(256), "the cookie is sent"); |
| 799 | self.reply(auth.tag, Tags::new().u32(wire::PROTOCOL_VERSION)); |
| 800 | let name = self.expect(command::SET_CLIENT_NAME); |
| 801 | self.reply(name.tag, Tags::new().u32(1)); |
| 802 | let create = self.expect(command::CREATE_PLAYBACK_STREAM); |
| 803 | self.reply( |
| 804 | create.tag, |
| 805 | Tags::new() |
| 806 | .u32(0) |
| 807 | .u32(7) |
| 808 | .u32(requested) |
| 809 | .u32(wire::DEFAULT) |
| 810 | .u32(38_400) |
| 811 | .u32(38_400) |
| 812 | .u32(1_920), |
| 813 | ); |
| 814 | create |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | impl Drop for Mock { |
| 819 | fn drop(&mut self) { |
| 820 | self.close(); |
| 821 | let _ = std::fs::remove_dir_all(&self.dir); |
| 822 | } |
| 823 | } |
| 824 | |
| 825 | |
| 826 | |
| 827 | |
| 828 | fn answered<T: Send + 'static>( |
| 829 | mock: &mut Mock, |
| 830 | playback: Playback, |
| 831 | cmd: u32, |
| 832 | call: impl FnOnce(&Playback) -> T + Send + 'static, |
| 833 | ) -> (T, Playback, Vec<u8>) { |
| 834 | let asking = std::thread::spawn(move || { |
| 835 | let out = call(&playback); |
| 836 | (out, playback) |
| 837 | }); |
| 838 | let sent = mock.expect(cmd); |
| 839 | mock.reply(sent.tag, Tags::new()); |
| 840 | let (out, playback) = asking.join().unwrap(); |
| 841 | (out, playback, sent.args) |
| 842 | } |
| 843 | |
| 844 | fn open(path: PathBuf) -> JoinHandle<Option<Playback>> { |
| 845 | std::thread::spawn(move || Playback::open_at(&path, 48_000, 2)) |
| 846 | } |
| 847 | |
| 848 | fn stereo_samples(frames: usize, value: f32) -> Vec<f32> { |
| 849 | vec![value; frames * 2] |
| 850 | } |
| 851 | |
| 852 | fn as_f32s(bytes: &[u8]) -> Vec<f32> { |
| 853 | bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect() |
| 854 | } |
| 855 | |
| 856 | #[test] |
| 857 | fn handshake_stream_credits_and_clock() { |
| 858 | let (mut mock, path) = Mock::bind("handshake"); |
| 859 | let handle = open(path); |
| 860 | let create = mock.handshake(4_096); |
| 861 | let mut playback = handle.join().unwrap().expect("the handshake completes"); |
| 862 | |
| 863 | assert_eq!(&create.args[..7], &[b'a', 5, 2, 0, 0, 0xbb, 0x80]); |
| 864 | assert_eq!(create.args[22], b'0'); |
| 865 | assert_eq!(playback.channel(), 0); |
| 866 | |
| 867 | |
| 868 | let samples: Vec<f32> = (0..4096).map(|i| i as f32).collect(); |
| 869 | assert_eq!(playback.write(&samples), Some(4096)); |
| 870 | let first = mock.memblock_within(Duration::from_millis(200)); |
| 871 | assert_eq!(as_f32s(&first), samples[..1024].to_vec()); |
| 872 | mock.request_bytes(0, 100_000); |
| 873 | let rest = mock.memblock_within(Duration::from_millis(200)); |
| 874 | assert_eq!(as_f32s(&rest), samples[1024..].to_vec()); |
| 875 | |
| 876 | |
| 877 | |
| 878 | let (position, playback) = ask_position(playback, &mut mock, 20_000, false, 0); |
| 879 | assert_eq!(position, None); |
| 880 | let (position, playback) = ask_position(playback, &mut mock, 20_000, true, 48_000 * 8); |
| 881 | assert_eq!(position, Some(48_000 - 960)); |
| 882 | |
| 883 | |
| 884 | mock.close(); |
| 885 | std::thread::sleep(Duration::from_millis(100)); |
| 886 | let mut playback = playback; |
| 887 | assert_eq!(playback.write(&stereo_samples(4, 0.0)), None); |
| 888 | } |
| 889 | |
| 890 | #[test] |
| 891 | fn pause_volume_flush_underflow_and_close() { |
| 892 | let (mut mock, path) = Mock::bind("controls"); |
| 893 | let handle = open(path); |
| 894 | mock.handshake(1 << 20); |
| 895 | let playback = handle.join().unwrap().unwrap(); |
| 896 | |
| 897 | |
| 898 | mock.underflow(0); |
| 899 | std::thread::sleep(Duration::from_millis(50)); |
| 900 | assert_eq!(playback.underruns(), (0, None)); |
| 901 | |
| 902 | let (ok, playback, args) = answered(&mut mock, playback, command::CORK_PLAYBACK_STREAM, |p| p.set_active(true)); |
| 903 | assert!(ok); |
| 904 | assert_eq!(args, Tags::new().u32(0).bool(false).into_bytes()); |
| 905 | let (ok, mut playback, args) = answered(&mut mock, playback, command::CORK_PLAYBACK_STREAM, |p| p.set_active(false)); |
| 906 | assert!(ok); |
| 907 | assert_eq!(args, Tags::new().u32(0).bool(true).into_bytes()); |
| 908 | |
| 909 | |
| 910 | assert!(playback.set_volume(0.5)); |
| 911 | assert!(!playback.set_volume(1.5)); |
| 912 | assert_eq!(playback.write(&stereo_samples(2, 1.0)), Some(4)); |
| 913 | assert_eq!(as_f32s(&mock.memblock_within(Duration::from_millis(100))), vec![0.5; 4]); |
| 914 | |
| 915 | |
| 916 | mock.underflow(0); |
| 917 | std::thread::sleep(Duration::from_millis(50)); |
| 918 | assert_eq!(playback.underruns().0, 1); |
| 919 | |
| 920 | |
| 921 | let (ok, playback, _) = answered(&mut mock, playback, command::FLUSH_PLAYBACK_STREAM, |p| p.flush()); |
| 922 | assert!(ok); |
| 923 | mock.request_bytes(0, 100_000); |
| 924 | assert!(mock.memblock_within(Duration::from_millis(100)).is_empty()); |
| 925 | |
| 926 | |
| 927 | drop(playback); |
| 928 | let delete = mock.expect(command::DELETE_PLAYBACK_STREAM); |
| 929 | assert_eq!(delete.args, Tags::new().u32(0).into_bytes()); |
| 930 | } |
| 931 | |
| 932 | #[test] |
| 933 | fn no_server_means_no_stream_and_the_path_follows_the_environment() { |
| 934 | let runtime = OsStr::new("/run/user/1000"); |
| 935 | assert_eq!( |
| 936 | server_path_from(None, Some(runtime)), |
| 937 | Some(PathBuf::from("/run/user/1000/pulse/native")) |
| 938 | ); |
| 939 | assert_eq!( |
| 940 | server_path_from(Some("unix:/tmp/x/native"), Some(runtime)), |
| 941 | Some(PathBuf::from("/tmp/x/native")) |
| 942 | ); |
| 943 | assert_eq!(server_path_from(Some("tcp:127.0.0.1:4713"), Some(runtime)), None); |
| 944 | let path = std::env::temp_dir().join(format!("edith-pulse-absent-{}", std::process::id())); |
| 945 | assert!(Playback::open_at(&path, 48_000, 2).is_none()); |
| 946 | } |
| 947 | |
| 948 | |
| 949 | |
| 950 | fn ask_position( |
| 951 | playback: Playback, |
| 952 | mock: &mut Mock, |
| 953 | sink_usec: u64, |
| 954 | playing: bool, |
| 955 | read_index: i64, |
| 956 | ) -> (Option<i64>, Playback) { |
| 957 | let asking = std::thread::spawn(move || { |
| 958 | let position = playback.position(); |
| 959 | (position, playback) |
| 960 | }); |
| 961 | let latency = mock.expect(command::GET_PLAYBACK_LATENCY); |
| 962 | mock.reply(latency.tag, latency_reply(sink_usec, playing, read_index)); |
| 963 | asking.join().unwrap() |
| 964 | } |
| 965 | |
| 966 | |
| 967 | |
| 968 | fn latency_reply(sink_usec: u64, playing: bool, read_index: i64) -> Tags { |
| 969 | Tags::new() |
| 970 | .usec(sink_usec) |
| 971 | .usec(0) |
| 972 | .bool(playing) |
| 973 | .timeval(0, 0) |
| 974 | .timeval(0, 0) |
| 975 | .i64(read_index) |
| 976 | .i64(read_index) |
| 977 | .u64(0) |
| 978 | .u64(0) |
| 979 | } |
| 980 | |
| 981 | } |