Skip to main content

audio/
audio.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Plays beeps through the default audio device, and prints how the stream
16//! is doing once a second.
17//!
18//! ```text
19//! cargo run -p nadir-platform --example audio -- [options]
20//! ```
21//!
22//! Options:
23//!
24//! - `--seconds N`: stop after N seconds; 10 by default.
25//! - `--volume V`: how loud the beeps are, from 0 to 1; 0.2 by default.
26//! - `--latency MS`: the device's buffer, in milliseconds; 30 by default.
27//!
28//! Each second, a beep of 440 Hz on the left, then one of 660 Hz on the
29//! right.
30//!
31//! On Linux, `NADIR_ALSA_DEVICE` names the ALSA device to play on in place
32//! of `default`, such as `plughw:CARD=Device` (`aplay -L` lists them). A
33//! sound server, which `default` usually is, moves the stream to another
34//! device when one is unplugged, and the stream never sees it. To see the
35//! stream lose a device, aim it at a USB device itself, while the server
36//! leaves the device alone, unplug it while the beeps play, and plug it in
37//! again: the log says that the stream stopped, with ALSA's reason, then
38//! that it is open again, and the beeps go on in time.
39
40use std::error::Error;
41use std::f64::consts::TAU;
42use std::io::{self, Write};
43use std::process::ExitCode;
44use std::sync::Arc;
45use std::sync::atomic::{AtomicU64, Ordering};
46use std::thread;
47use std::time::{Duration, Instant};
48
49use nadir_core::cli::Args;
50use nadir_platform::{AudioOutputConfig, AudioRender, open_audio};
51
52/// How long a beep lasts, and how long its ends take to ramp, in seconds.
53const BEEP: f64 = 0.25;
54const RAMP: f64 = 0.005;
55
56fn main() -> ExitCode {
57    match run(Args::from_env(), &mut io::stdout()) {
58        Ok(()) => ExitCode::SUCCESS,
59        Err(error) => {
60            // If standard error is closed too, there is nobody left to tell.
61            let _ = writeln!(io::stderr(), "audio: {error}");
62            ExitCode::FAILURE
63        }
64    }
65}
66
67fn run(mut args: Args, out: &mut dyn Write) -> Result<(), Box<dyn Error>> {
68    let seconds: f64 = args.parsed("--seconds")?.unwrap_or(10.0);
69    let volume: f32 = args.parsed("--volume")?.unwrap_or(0.2);
70    let latency_ms: u32 = args.parsed("--latency")?.unwrap_or(30);
71    if let Some(extra) = args.finish()?.first() {
72        return Err(format!("unexpected argument `{extra}`").into());
73    }
74    if !(0.0..=1.0).contains(&volume) {
75        return Err(format!("the volume {volume} is not from 0 to 1").into());
76    }
77    let length = Duration::try_from_secs_f64(seconds)?;
78
79    let periods = Arc::new(AtomicU64::new(0));
80    let underruns = Arc::new(AtomicU64::new(0));
81    let beeps = Beeps {
82        frame: 0,
83        volume,
84        periods: Arc::clone(&periods),
85        underruns: Arc::clone(&underruns),
86    };
87    let config = AudioOutputConfig {
88        latency_ms,
89        ..AudioOutputConfig::default()
90    };
91    let stream = open_audio(&config, Box::new(beeps))?;
92    writeln!(
93        out,
94        "audio: {} Hz, {} channels; beeps of 440 Hz on the left, then 660 Hz on the right",
95        config.sample_rate, config.channels,
96    )?;
97
98    let start = Instant::now();
99    let mut second = 1;
100    while start.elapsed() < length {
101        let next = start + Duration::from_secs(second);
102        thread::sleep(next.saturating_duration_since(Instant::now()).min(length));
103        let device = match stream.latency() {
104            Some(latency) => format!("{:.1} ms of latency", latency.as_secs_f64() * 1000.0),
105            None => "no device".to_string(),
106        };
107        writeln!(
108            out,
109            "{:6.1} s: {} periods, {} underruns, {device}",
110            start.elapsed().as_secs_f64(),
111            periods.load(Ordering::Relaxed),
112            underruns.load(Ordering::Relaxed),
113        )?;
114        second += 1;
115    }
116    // The stream stops as it drops, here.
117    Ok(())
118}
119
120/// A beep on the left in the first quarter of each second, and one on the
121/// right in the third.
122struct Beeps {
123    frame: u64,
124    volume: f32,
125    periods: Arc<AtomicU64>,
126    underruns: Arc<AtomicU64>,
127}
128
129impl AudioRender for Beeps {
130    fn render(&mut self, out: &mut [f32], channels: u16, sample_rate: u32) {
131        let channels = usize::from(channels);
132        let rate = f64::from(sample_rate);
133        for frame in out.chunks_exact_mut(channels) {
134            let time = (self.frame % u64::from(sample_rate)) as f64 / rate;
135            let (left, right) = if time < BEEP {
136                (beep(time, 440.0), 0.0)
137            } else if (0.5..0.5 + BEEP).contains(&time) {
138                (0.0, beep(time - 0.5, 660.0))
139            } else {
140                (0.0, 0.0)
141            };
142            frame.fill(0.0);
143            frame[0] = left * self.volume;
144            if let Some(second) = frame.get_mut(1) {
145                *second = right * self.volume;
146            }
147            self.frame += 1;
148        }
149        self.periods.fetch_add(1, Ordering::Relaxed);
150    }
151
152    fn underrun(&mut self) {
153        self.underruns.fetch_add(1, Ordering::Relaxed);
154    }
155}
156
157/// A sine of `frequency` at `time` seconds into a beep, ramped in and out.
158fn beep(time: f64, frequency: f64) -> f32 {
159    let ramp = (time / RAMP).min((BEEP - time) / RAMP).clamp(0.0, 1.0);
160    ((TAU * frequency * time).sin() * ramp) as f32
161}