mnml-rs 0.2.20

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// 2026-08-22 — everything in this file except `Session::start`'s
// non-macOS Err-stub is macOS-only. On Linux + Windows CI those
// helpers become dead code and clippy `-D warnings` fails the run
// (broke `main` overnight on 32613577355). Silence dead_code on
// non-macOS builds file-wide rather than sprinkle 7 attrs.
#![cfg_attr(not(target_os = "macos"), allow(dead_code))]

//! Sending *this Mac's* audio to a Sonos, without AirPlay.
//!
//! macOS 26 has no programmatic way to pick an AirPlay target: the
//! Sound settings pane lists only CoreAudio devices, and Control
//! Center — the sole AirPlay picker — exposes an empty accessibility
//! tree, so it can be neither scripted nor inspected. A Sonos does
//! however play any HTTP audio stream on command, and mnml can be that
//! server:
//!
//! ```text
//!   system output ─▶ loopback device ─▶ ffmpeg (mp3) ─▶ mnml HTTP ─▶ Sonos
//! ```
//!
//! The loopback device is the one piece macOS won't provide: capturing
//! system output needs either a virtual audio driver (BlackHole) or
//! ScreenCaptureKit. BlackHole is a one-time install and needs no
//! Screen Recording grant, so it's the path taken here.
//!
//! Trade-off, stated plainly: the Sonos buffers a couple of seconds, so
//! this is right for music and wrong for anything you're watching.

use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream, UdpSocket};
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

/// Substring identifying the loopback output device. Matches
/// "BlackHole 2ch" and "BlackHole 16ch" alike.
pub const LOOPBACK_NAME: &str = "blackhole";

/// What to tell the user when the loopback driver is missing. Carried
/// here so the toast, the hover help and the manual can't drift.
pub const INSTALL_HINT: &str =
    "install the loopback driver first: brew install --cask blackhole-2ch";

/// mp3 bitrate for the stream. 256k is transparent enough for a
/// speaker and small enough to never trouble a LAN.
const BITRATE: &str = "256k";

/// A running stream: the HTTP server, its ffmpeg children, and the
/// output device to hand back when it stops.
pub struct Session {
    /// Port the local HTTP server is listening on.
    port: u16,
    /// This Mac's address on the interface that reaches the player.
    host_ip: String,
    /// Set on [`Session::stop`]; every thread watches it.
    shutdown: Arc<AtomicBool>,
    /// ffmpeg processes, one per connected client, killed on stop.
    children: Arc<Mutex<Vec<Child>>>,
    /// Output device to restore, so stopping the stream gives the user
    /// their speakers back without a trip to System Settings.
    previous_output: Option<u32>,
}

impl Session {
    /// The URI to hand the player. The `x-rincon-mp3radio://` scheme is
    /// what tells Sonos to treat it as a live stream rather than a file.
    pub fn sonos_uri(&self) -> String {
        format!(
            "x-rincon-mp3radio://{}:{}/mnml.mp3",
            self.host_ip, self.port
        )
    }

    /// False once [`Session::stop`] has run.
    pub fn is_alive(&self) -> bool {
        !self.shutdown.load(Ordering::Relaxed)
    }

    /// Stop streaming: close the server, kill the encoders, and put the
    /// system output back where it was.
    pub fn stop(self) {
        self.shutdown.store(true, Ordering::Relaxed);
        // Unblock the accept loop so the server thread can notice the
        // shutdown flag and exit.
        //
        // Must target `host_ip`, not 127.0.0.1: the listener binds to
        // the player-facing interface now, so nothing is listening on
        // loopback and a wake-up sent there would silently fail,
        // leaving the accept thread parked until some later connection
        // happened along. The peer check rejects this connection —
        // it's from the Mac, not the player — but `incoming()` returns
        // first and the loop reads the shutdown flag before looking at
        // the peer, which is all the wake-up needs to do.
        let _ = TcpStream::connect((self.host_ip.as_str(), self.port));
        if let Ok(mut children) = self.children.lock() {
            for mut child in children.drain(..) {
                let _ = child.kill();
                let _ = child.wait();
            }
        }
        #[cfg(target_os = "macos")]
        if let Some(id) = self.previous_output {
            let _ = super::coreaudio::set_default_output(id);
        }
    }

    /// Start capturing and serving. `player_host` is the Sonos, used
    /// only to work out which local interface it will reach us on.
    #[cfg(target_os = "macos")]
    pub fn start(_room: &str, player_host: &str) -> Result<Self, String> {
        let device = super::coreaudio::find_output(LOOPBACK_NAME)
            .ok_or_else(|| format!("no loopback audio device found — {INSTALL_HINT}"))?;
        let ffmpeg = ffmpeg_bin().ok_or("ffmpeg not found on PATH")?;
        let index = avfoundation_index(&ffmpeg, &device.name)?;
        let host_ip = local_ip_towards(player_host)
            .ok_or("could not work out this Mac's address on the network")?;
        // Bind to the interface facing the player, not 0.0.0.0. This
        // server streams a live encode of the Mac's ENTIRE system
        // output — whatever is playing, including the far end of a
        // call — and `pump` deliberately doesn't route on the request,
        // so before this every host that could reach the port got the
        // feed by asking. Narrowing the bind drops other interfaces
        // (VPNs, secondary NICs, container bridges); the peer check in
        // `serve` handles the rest of this subnet.
        let listener = TcpListener::bind((host_ip.as_str(), 0))
            .map_err(|e| format!("could not open a local stream port: {e}"))?;
        let port = listener
            .local_addr()
            .map_err(|e| format!("could not read the stream port: {e}"))?
            .port();

        // Switch the system output *after* everything else has
        // succeeded, so a failed start never leaves the Mac silent.
        let previous_output = super::coreaudio::default_output().map(|d| d.id);
        super::coreaudio::set_default_output(device.id)?;

        let shutdown = Arc::new(AtomicBool::new(false));
        let children: Arc<Mutex<Vec<Child>>> = Arc::new(Mutex::new(Vec::new()));
        // Only the player we handed the URL to may fetch it. mnml
        // sends `play_uri` to the group COORDINATOR (`control_host`),
        // and the coordinator is what fetches the stream and
        // redistributes to the rest of the group — so one allowed peer
        // is right even for grouped rooms.
        let allowed_peer = player_host.parse::<std::net::IpAddr>().ok();
        serve(
            listener,
            ffmpeg,
            index,
            shutdown.clone(),
            children.clone(),
            allowed_peer,
        );
        Ok(Session {
            port,
            host_ip,
            shutdown,
            children,
            previous_output,
        })
    }

    /// Non-macOS builds compile but decline: the capture half is
    /// CoreAudio-specific.
    #[cfg(not(target_os = "macos"))]
    pub fn start(_room: &str, _player_host: &str) -> Result<Self, String> {
        Err("streaming this Mac's audio to a Sonos is macOS-only today".to_string())
    }
}

/// Accept connections and stream mp3 to each, one encoder per client.
///
/// A fresh ffmpeg per connection is deliberate: Sonos reconnects when
/// it re-buffers, and a per-client encoder makes that a no-op instead
/// of a shared-pipe ownership problem.
fn serve(
    listener: TcpListener,
    ffmpeg: PathBuf,
    index: String,
    shutdown: Arc<AtomicBool>,
    children: Arc<Mutex<Vec<Child>>>,
    allowed_peer: Option<std::net::IpAddr>,
) {
    std::thread::spawn(move || {
        for conn in listener.incoming() {
            if shutdown.load(Ordering::Relaxed) {
                break;
            }
            let Ok(conn) = conn else { continue };
            if !peer_allowed(&conn, allowed_peer) {
                // Drop without a response. There is no auth to fail
                // and nothing useful to say — anything on this port
                // that isn't the player is either a scan or a mistake.
                continue;
            }
            let (ffmpeg, index) = (ffmpeg.clone(), index.clone());
            let (shutdown, children) = (shutdown.clone(), children.clone());
            std::thread::spawn(move || {
                pump(conn, &ffmpeg, &index, &shutdown, &children);
            });
        }
    });
}

/// True when `conn` comes from the player we handed the stream URL to.
///
/// Fails CLOSED on an unreadable peer address: this is a live feed of
/// the machine's audio, so "couldn't tell who this is" has to mean no.
/// `allowed_peer` is `None` only when the player host didn't parse as
/// an IP, which also denies — discovery always yields a literal.
fn peer_allowed(conn: &TcpStream, allowed_peer: Option<std::net::IpAddr>) -> bool {
    let (Some(allowed), Ok(peer)) = (allowed_peer, conn.peer_addr()) else {
        return false;
    };
    peer.ip() == allowed
}

/// Serve one client: read (and discard) its request, write stream
/// headers, then copy encoder output until either side gives up.
fn pump(
    mut conn: TcpStream,
    ffmpeg: &PathBuf,
    index: &str,
    shutdown: &Arc<AtomicBool>,
    children: &Arc<Mutex<Vec<Child>>>,
) {
    // Drain the request line/headers. Sonos sends a normal GET; we
    // don't route on it, but leaving it unread can wedge the socket.
    let mut scratch = [0u8; 1024];
    let _ = conn.read(&mut scratch);
    // HTTP/1.0 + no Content-Length is the classic shoutcast shape: an
    // endless body the client reads until close.
    let headers = "HTTP/1.0 200 OK\r\n\
Content-Type: audio/mpeg\r\n\
Cache-Control: no-cache, no-store\r\n\
icy-name: mnml — this Mac\r\n\
Connection: close\r\n\r\n";
    if conn.write_all(headers.as_bytes()).is_err() {
        return;
    }
    let Ok(mut child) = Command::new(ffmpeg)
        .args(encoder_args(index))
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .stdin(Stdio::null())
        .spawn()
    else {
        return;
    };
    let Some(mut out) = child.stdout.take() else {
        let _ = child.kill();
        return;
    };
    // Registered so `stop` can kill an encoder mid-copy; the id lets
    // this handler find its own child again when the client hangs up.
    let child_id = child.id();
    if let Ok(mut guard) = children.lock() {
        guard.push(child);
    }
    let mut buf = [0u8; 8192];
    while !shutdown.load(Ordering::Relaxed) {
        match out.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                if conn.write_all(&buf[..n]).is_err() {
                    break; // player hung up
                }
            }
            Err(_) => break,
        }
    }
    // The client is gone (or we're shutting down) — kill *this* encoder
    // rather than leaving an ffmpeg capturing audio into a dead socket.
    // Other clients' encoders stay running.
    if let Ok(mut guard) = children.lock()
        && let Some(pos) = guard.iter().position(|c| c.id() == child_id)
    {
        let mut child = guard.remove(pos);
        let _ = child.kill();
        let _ = child.wait();
    }
}

/// ffmpeg arguments: capture the loopback device, encode mp3, write to
/// stdout as fast as frames are produced.
fn encoder_args(index: &str) -> Vec<String> {
    vec![
        "-hide_banner".into(),
        "-loglevel".into(),
        "error".into(),
        "-f".into(),
        "avfoundation".into(),
        // Audio-only capture: the empty video slot before the colon.
        "-i".into(),
        format!(":{index}"),
        "-ac".into(),
        "2".into(),
        "-ar".into(),
        "44100".into(),
        "-c:a".into(),
        "libmp3lame".into(),
        "-b:a".into(),
        BITRATE.into(),
        // Flush every packet — buffering here would add to the delay
        // the Sonos already introduces.
        "-flush_packets".into(),
        "1".into(),
        "-f".into(),
        "mp3".into(),
        "pipe:1".into(),
    ]
}

/// Locate ffmpeg: `PATH` first, then the usual Homebrew prefixes (a
/// GUI-launched mnml can inherit a minimal `PATH`).
fn ffmpeg_bin() -> Option<PathBuf> {
    if let Some(paths) = std::env::var_os("PATH") {
        for dir in std::env::split_paths(&paths) {
            let candidate = dir.join("ffmpeg");
            if candidate.is_file() {
                return Some(candidate);
            }
        }
    }
    ["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg"]
        .iter()
        .map(PathBuf::from)
        .find(|p| p.is_file())
}

/// Find the avfoundation *input index* for `device_name`.
///
/// ffmpeg indexes capture devices in its own order, unrelated to
/// CoreAudio ids, and only prints the mapping — so this parses the
/// listing. `-list_devices` exits non-zero by design; the listing is on
/// stderr either way.
fn avfoundation_index(ffmpeg: &PathBuf, device_name: &str) -> Result<String, String> {
    let out = Command::new(ffmpeg)
        .args([
            "-hide_banner",
            "-f",
            "avfoundation",
            "-list_devices",
            "true",
            "-i",
            "",
        ])
        .output()
        .map_err(|e| format!("could not run ffmpeg: {e}"))?;
    let listing = String::from_utf8_lossy(&out.stderr);
    parse_avfoundation_index(&listing, device_name)
        .ok_or_else(|| format!("ffmpeg cannot see the '{device_name}' input device"))
}

/// Pull `[N] <name>` out of ffmpeg's device listing, restricted to the
/// audio section (video devices are indexed separately and can collide).
fn parse_avfoundation_index(listing: &str, device_name: &str) -> Option<String> {
    let needle = device_name.to_ascii_lowercase();
    let mut in_audio = false;
    for line in listing.lines() {
        let lower = line.to_ascii_lowercase();
        if lower.contains("audio devices:") {
            in_audio = true;
            continue;
        }
        if lower.contains("video devices:") {
            in_audio = false;
            continue;
        }
        if !in_audio {
            continue;
        }
        // `[AVFoundation indev @ 0x…] [1] BlackHole 2ch`
        let Some(open) = line.rfind('[') else {
            continue;
        };
        let Some(close) = line[open..].find(']').map(|i| i + open) else {
            continue;
        };
        let index = line[open + 1..close].trim();
        if !index.chars().all(|c| c.is_ascii_digit()) || index.is_empty() {
            continue;
        }
        if line[close + 1..]
            .trim()
            .to_ascii_lowercase()
            .contains(&needle)
        {
            return Some(index.to_string());
        }
    }
    None
}

/// This Mac's IP on the interface that routes to `host`.
///
/// No packets are sent — connecting a UDP socket only picks a route,
/// which is exactly the question being asked.
fn local_ip_towards(host: &str) -> Option<String> {
    let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
    socket.connect((host, super::soap::PORT)).ok()?;
    Some(socket.local_addr().ok()?.ip().to_string())
}

/// Minimal DIDL-Lite so the Sonos app shows a sensible title for the
/// stream instead of a bare URL.
pub fn didl(room: &str) -> String {
    let title = super::soap::escape(&format!("mnml — this Mac → {room}"));
    format!(
        "<DIDL-Lite xmlns:dc=\"http://purl.org/dc/elements/1.1/\" \
xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\" \
xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\">\
<item id=\"-1\" parentID=\"-1\" restricted=\"true\">\
<dc:title>{title}</dc:title>\
<upnp:class>object.item.audioItem.audioBroadcast</upnp:class>\
</item></DIDL-Lite>"
    )
}

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

    /// Verbatim shape of ffmpeg's listing on macOS.
    const LISTING: &str = "\
[AVFoundation indev @ 0x14f704080] AVFoundation video devices:
[AVFoundation indev @ 0x14f704080] [0] FaceTime HD Camera
[AVFoundation indev @ 0x14f704080] [1] Capture screen 0
[AVFoundation indev @ 0x14f704080] AVFoundation audio devices:
[AVFoundation indev @ 0x14f704080] [0] MacBook Pro Microphone
[AVFoundation indev @ 0x14f704080] [1] BlackHole 2ch
";

    #[test]
    fn finds_the_loopback_input_index() {
        assert_eq!(
            parse_avfoundation_index(LISTING, "BlackHole 2ch").as_deref(),
            Some("1")
        );
    }

    #[test]
    fn ignores_the_video_section_when_indexes_collide() {
        // "[1] Capture screen 0" is video index 1; a name-only match
        // that ignored sections could return it.
        assert_eq!(
            parse_avfoundation_index(LISTING, "MacBook Pro Microphone").as_deref(),
            Some("0")
        );
        assert!(parse_avfoundation_index(LISTING, "FaceTime HD Camera").is_none());
    }

    #[test]
    fn missing_device_is_none_not_a_guess() {
        assert!(parse_avfoundation_index(LISTING, "Loopback Audio").is_none());
        assert!(parse_avfoundation_index("", "BlackHole 2ch").is_none());
    }

    #[test]
    fn encoder_args_capture_audio_only_and_stream_to_stdout() {
        let args = encoder_args("1");
        assert!(args.contains(&":1".to_string()), "audio-only input spec");
        assert!(args.contains(&"pipe:1".to_string()));
        assert_eq!(args.last().unwrap(), "pipe:1");
        assert!(args.windows(2).any(|w| w[0] == "-f" && w[1] == "mp3"));
    }

    #[test]
    fn didl_escapes_the_room_name() {
        let d = didl("Kids' <Room>");
        assert!(d.contains("Kids&apos; &lt;Room&gt;"));
        assert!(d.contains("audioBroadcast"));
    }

    #[test]
    fn install_hint_names_the_actual_formula() {
        assert!(INSTALL_HINT.contains("blackhole-2ch"));
    }

    /// Connect to a throwaway listener and hand the accepted socket to
    /// `peer_allowed`. Uses a real TCP pair so the check is exercised
    /// against an actual `peer_addr()`, not a stub.
    fn check_with_real_socket(allowed: Option<std::net::IpAddr>) -> bool {
        let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
        let addr = listener.local_addr().unwrap();
        let client = std::thread::spawn(move || TcpStream::connect(addr).unwrap());
        let (server_side, _) = listener.accept().unwrap();
        let _c = client.join().unwrap();
        peer_allowed(&server_side, allowed)
    }

    #[test]
    fn the_expected_player_is_allowed() {
        // Loopback connection, loopback allowed.
        assert!(check_with_real_socket(Some("127.0.0.1".parse().unwrap())));
    }

    #[test]
    fn any_other_lan_host_is_refused() {
        // The finding: this server streams the Mac's entire system
        // audio and `pump` never routes on the request, so before the
        // peer check ANY host that reached the port got the feed.
        assert!(!check_with_real_socket(Some(
            "192.168.1.131".parse().unwrap()
        )));
    }

    #[test]
    fn an_unparseable_player_host_fails_closed() {
        // No allow-list ⇒ deny. For a live audio feed, "can't tell who
        // this is" has to mean no.
        assert!(!check_with_real_socket(None));
    }
}