nooise 2.5.5

Ambient music generator for the terminal
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
//! Binary entry point: CLI parsing for `run`/`version`/`update`/`render`/`auto`
//! and a bare song code, then handoff to the matching `fluid` entry.

use clap::{Args, Parser, Subcommand};
use std::error::Error;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::process::Command;
use update_check::check_for_update;

mod audio;
mod fluid;
mod fx;
mod midi;
mod synth;
mod update_check;

fn main() -> Result<(), Box<dyn Error>> {
    let cli = Cli::parse();
    if cli.midi_config() != midi::MidiConfig::default()
        && matches!(
            cli.command,
            Some(CliCommand::Update | CliCommand::MidiPorts | CliCommand::Render(_))
        )
    {
        return Err("MIDI port flags only apply to live playback".into());
    }
    let midi = cli.midi_config();
    let bars = cli.bars.unwrap_or(fluid::DEFAULT_AUTO_BARS);
    match cli.command {
        None => match cli.song.as_deref() {
            None => fluid::run(cli.osc, midi),
            Some(song) => play_song(song, bars, cli.osc, midi),
        },
        Some(CliCommand::Update) => update_nooise(),
        Some(CliCommand::MidiPorts) => midi::list_ports(),
        Some(CliCommand::Render(args)) => render(args),
        Some(CliCommand::Auto) => fluid::run_auto(bars, cli.osc, midi),
    }
}

#[derive(Debug, Parser)]
#[command(
    version,
    about,
    after_help = "Play a song: nooise <SONG>, where a song is a built-in number \
                  (nooise 9), several of them (nooise 9,10,11), or a shared code \
                  (nooise n1_...)."
)]
struct Cli {
    #[command(subcommand)]
    command: Option<CliCommand>,
    /// A song to play: a built-in number (9), several of them (9,10,11), or a
    /// shared `n1_` code.
    song: Option<String>,
    /// Bars each song holds before morphing into the next. Defaults to 64.
    #[arg(long, global = true)]
    bars: Option<u32>,
    /// Mirror live telemetry (beat, chord, kick hits) as OSC over UDP for an
    /// external visualizer. Bare `--osc` targets 127.0.0.1:9000, foorm's
    /// default listen address; give ADDR to send elsewhere.
    #[arg(
        long,
        global = true,
        value_name = "ADDR",
        num_args = 0..=1,
        default_missing_value = fluid::DEFAULT_OSC_TARGET,
        require_equals = true
    )]
    osc: Option<SocketAddr>,
    /// Use one exact-name MIDI port for input and output, both on channel 1.
    #[arg(long, global = true, value_name = "PORT")]
    midi: Option<String>,
    /// Receive MIDI notes from an exactly named input port.
    #[arg(long, global = true, value_name = "PORT")]
    midi_in: Option<String>,
    /// Send MIDI notes and clock to an exactly named output port.
    #[arg(long, global = true, value_name = "PORT")]
    midi_out: Option<String>,
    /// Input MIDI channel (1-16, default 1).
    #[arg(long, global = true, default_value_t = 1, value_parser = clap::value_parser!(u8).range(1..=16))]
    midi_in_channel: u8,
    /// Output MIDI channel (1-16, default 1).
    #[arg(long, global = true, default_value_t = 1, value_parser = clap::value_parser!(u8).range(1..=16))]
    midi_out_channel: u8,
}

impl Cli {
    fn midi_config(&self) -> midi::MidiConfig<'_> {
        midi::MidiConfig {
            input: self
                .midi_in
                .as_deref()
                .or(self.midi.as_deref())
                .map(|name| midi::MidiEndpoint {
                    name,
                    channel: self.midi_in_channel,
                }),
            output: self
                .midi_out
                .as_deref()
                .or(self.midi.as_deref())
                .map(|name| midi::MidiEndpoint {
                    name,
                    channel: self.midi_out_channel,
                }),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Subcommand)]
enum CliCommand {
    #[command(about = "Update nooise from crates.io", visible_alias = "upgrade")]
    Update,
    #[command(about = "List available MIDI input and output port names")]
    MidiPorts,
    #[command(about = "Render the default mix to a wav file")]
    Render(RenderArgs),
    #[command(about = "Morph through every built-in song, forever")]
    Auto,
}

#[derive(Debug, Clone, PartialEq, Args)]
struct RenderArgs {
    #[arg(long, default_value_t = 20.0)]
    seconds: f32,
    #[arg(long, default_value = "nooise.wav")]
    out: PathBuf,
    #[arg(long)]
    seed: Option<u64>,
}

fn render(args: RenderArgs) -> Result<(), Box<dyn Error>> {
    if args.seconds <= 0.0 {
        return Err("--seconds must be positive".into());
    }
    fluid::render_wav(args.seconds, &args.out, args.seed)
}

/// A song is named either by a shared `n1_` code or by its number in the
/// built-in set — the same thing reached two ways, so they share one argument
/// rather than one being a flag and the other a positional. Several numbers
/// morph through in the order given and loop.
fn play_song(
    song: &str,
    bars: u32,
    osc: Option<SocketAddr>,
    midi: midi::MidiConfig<'_>,
) -> Result<(), Box<dyn Error>> {
    if song.starts_with(fluid::CODE_PREFIX) {
        let state = fluid::decode_song_code(song).map_err(|error| error.to_string())?;
        return fluid::run_with_song_state(state, osc, midi);
    }
    let numbers = song
        .split(',')
        .map(|part| {
            part.trim()
                .parse::<usize>()
                .map_err(|_| format!("{part:?} is neither a song number nor an n1_ code").into())
        })
        .collect::<Result<Vec<usize>, Box<dyn Error>>>()?;
    fluid::run_songs(&numbers, bars, osc, midi)
}

fn update_nooise() -> Result<(), Box<dyn Error>> {
    println!("Checking crates.io for nooise updates...");
    let Some(latest) = check_for_update()? else {
        println!("nooise is up to date (v{})", env!("CARGO_PKG_VERSION"));
        return Ok(());
    };

    let latest_version = latest.semver().to_string();
    println!("Updating nooise to {latest}...");
    let status = Command::new("cargo")
        .args(cargo_install_args(&latest_version))
        .status()
        .map_err(|e| format!("failed to run cargo install nooise: {e}"))?;

    if status.success() {
        Ok(())
    } else {
        Err(format!("cargo install nooise failed with {status}").into())
    }
}

fn cargo_install_args(version: &str) -> [&str; 6] {
    [
        "install",
        "nooise",
        "--locked",
        "--version",
        version,
        "--force",
    ]
}

#[cfg(test)]
mod tests {
    use super::{Cli, CliCommand, RenderArgs, cargo_install_args, render};
    use clap::{CommandFactory, Parser, error::ErrorKind};
    use std::path::PathBuf;

    fn parse(items: &[&str]) -> Result<Cli, clap::Error> {
        let args = std::iter::once("nooise").chain(items.iter().copied());
        Cli::try_parse_from(args)
    }

    #[test]
    fn no_args_runs_app() {
        let cli = parse(&[]).unwrap();
        assert_eq!(cli.command, None);
        assert_eq!(cli.osc, None);
        assert_eq!(cli.midi_out, None);
    }

    #[test]
    fn midi_output_name_is_global_and_channel_is_implicitly_one() {
        for args in [
            &["--midi-out", "Take 5", "9"][..],
            &["9", "--midi-out", "Take 5"],
            &["auto", "--midi-out", "Take 5"],
        ] {
            assert_eq!(parse(args).unwrap().midi_out.as_deref(), Some("Take 5"));
        }
        assert_eq!(
            parse(&["midi-ports"]).unwrap().command,
            Some(CliCommand::MidiPorts)
        );
    }

    #[test]
    fn midi_flag_selects_both_directions_with_independent_overrides() {
        let cli = parse(&["--midi", "Take 5"]).unwrap();
        let config = cli.midi_config();
        assert_eq!(config.input.unwrap().name, "Take 5");
        assert_eq!(config.output.unwrap().name, "Take 5");
        assert_eq!(config.input.unwrap().channel, 1);
        assert_eq!(config.output.unwrap().channel, 1);

        let cli = parse(&[
            "auto",
            "--midi",
            "Take 5",
            "--midi-in",
            "Keyboard",
            "--midi-in-channel",
            "2",
            "--midi-out-channel",
            "5",
        ])
        .unwrap();
        let config = cli.midi_config();
        assert_eq!(config.input.unwrap().name, "Keyboard");
        assert_eq!(config.input.unwrap().channel, 2);
        assert_eq!(config.output.unwrap().name, "Take 5");
        assert_eq!(config.output.unwrap().channel, 5);
        assert!(parse(&["--midi-in-channel", "17"]).is_err());
    }

    /// `--osc` is a global: it reads the same before a song, after it, and on
    /// `auto`. Bare `--osc` means foorm's default port; `--osc=ADDR` sends
    /// elsewhere; a value that is not a socket address is refused. The value
    /// needs `=` so a bare `--osc` never eats a following song argument.
    #[test]
    fn osc_target_defaults_to_foorm_and_accepts_an_address() {
        let default = "127.0.0.1:9000".parse().ok();
        for args in [
            &["--osc"][..],
            &["9", "--osc"],
            &["--osc", "9"],
            &["auto", "--osc"],
        ] {
            let cli = parse(args).unwrap();
            assert_eq!(cli.osc, default, "{args:?}");
        }
        assert_eq!(parse(&["--osc", "9"]).unwrap().song.as_deref(), Some("9"));
        assert_eq!(
            parse(&["--osc=10.0.0.5:7000", "9"]).unwrap().osc,
            "10.0.0.5:7000".parse().ok()
        );
        assert_eq!(
            parse(&["--osc=localhost"]).unwrap_err().kind(),
            ErrorKind::ValueValidation
        );
    }

    /// A song is one argument whether it is named by code or by number, and
    /// it is a plain positional, so flags read the same on either side of it.
    #[test]
    fn a_song_is_one_positional_named_by_code_or_by_number() {
        for (args, song, bars) in [
            (vec!["n1_abc"], "n1_abc", None),
            (vec!["9"], "9", None),
            (vec!["9,10,11"], "9,10,11", None),
            (vec!["9", "--bars", "4"], "9", Some(4)),
            (vec!["--bars", "4", "9"], "9", Some(4)),
        ] {
            let cli = parse(&args).unwrap();
            assert_eq!(cli.song.as_deref(), Some(song), "{args:?}");
            assert_eq!(cli.bars, bars, "{args:?}");
            assert_eq!(cli.command, None, "{args:?}");
        }
    }

    /// A subcommand name still wins over the song positional.
    #[test]
    fn subcommands_are_not_mistaken_for_songs() {
        assert!(matches!(
            parse(&["render"]).unwrap().command,
            Some(CliCommand::Render(_))
        ));
        assert_eq!(parse(&["auto"]).unwrap().command, Some(CliCommand::Auto));
        assert_eq!(parse(&["render"]).unwrap().song, None);
    }

    #[test]
    fn version_flags_are_available() {
        assert_eq!(
            parse(&["-V"]).unwrap_err().kind(),
            ErrorKind::DisplayVersion
        );
        assert_eq!(
            parse(&["--version"]).unwrap_err().kind(),
            ErrorKind::DisplayVersion
        );
    }

    #[test]
    fn update_and_upgrade_run_updater() {
        assert_eq!(
            parse(&["update"]).unwrap().command,
            Some(CliCommand::Update)
        );
        assert_eq!(
            parse(&["upgrade"]).unwrap().command,
            Some(CliCommand::Update)
        );
    }

    #[test]
    fn updater_installs_exact_latest_version() {
        assert_eq!(
            cargo_install_args("1.2.3"),
            [
                "install",
                "nooise",
                "--locked",
                "--version",
                "1.2.3",
                "--force"
            ]
        );
    }

    #[test]
    fn unknown_arg_errors() {
        assert!(parse(&["--experiment"]).is_err());
    }

    #[test]
    fn render_defaults_and_flags_parse() {
        assert_eq!(
            parse(&["render"]).unwrap().command,
            Some(CliCommand::Render(RenderArgs {
                seconds: 20.0,
                out: PathBuf::from("nooise.wav"),
                seed: None,
            }))
        );
        assert_eq!(
            parse(&[
                "render",
                "--seconds",
                "3.5",
                "--out",
                "/tmp/x.wav",
                "--seed",
                "42"
            ])
            .unwrap()
            .command,
            Some(CliCommand::Render(RenderArgs {
                seconds: 3.5,
                out: PathBuf::from("/tmp/x.wav"),
                seed: Some(42),
            }))
        );
    }

    /// `auto` used to take bars positionally. It takes none now, so an old
    /// `nooise auto 4` fails loudly instead of quietly meaning song four.
    #[test]
    fn auto_takes_bars_only_as_a_flag() {
        assert_eq!(parse(&["auto"]).unwrap().bars, None);
        assert_eq!(parse(&["auto", "--bars", "32"]).unwrap().bars, Some(32));
        assert!(parse(&["auto", "4"]).is_err());
    }

    #[test]
    fn render_rejects_bad_input() {
        assert!(parse(&["render", "--seconds"]).is_err());
        assert!(parse(&["render", "--seconds", "abc"]).is_err());
        assert!(parse(&["render", "--loud"]).is_err());
        assert!(parse(&["update", "extra"]).is_err());
    }

    #[test]
    fn render_rejects_non_positive_seconds() {
        let err = render(RenderArgs {
            seconds: 0.0,
            out: PathBuf::from("/tmp/nooise-zero.wav"),
            seed: None,
        })
        .unwrap_err()
        .to_string();
        assert!(err.contains("--seconds must be positive"));
    }

    #[test]
    fn help_mentions_version_update_and_render() {
        let help = Cli::command().render_help().to_string();
        assert!(help.contains("--version"));
        assert!(help.contains("update"));
        assert!(help.contains("upgrade"));
        assert!(help.contains("render"));
        // The footer teaches the one grammar the CLI has: a song is a number,
        // a list of them, or a code.
        assert!(help.contains("nooise 9"));
        assert!(help.contains("nooise 9,10,11"));
        assert!(help.contains("nooise n1_..."));
    }
}