maolan 0.2.0

Rust DAW application for recording, editing, routing, automation, export, and plugin hosting
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
#[path = "../audio_defaults.rs"]
mod audio_defaults;

use maolan_engine::{
    client::Client,
    message::{Action, Message as EngineMessage},
};
use std::{
    path::PathBuf,
    time::{Duration, Instant},
};
use tokio::sync::mpsc::Receiver;

#[derive(Debug, Clone)]
struct TestOptions {
    plugin_path: PathBuf,
    device: String,
    input_device: Option<String>,
    duration_secs: u64,
    sample_rate_hz: i32,
    period_frames: usize,
    nperiods: usize,
    track_name: String,
    param_id: Option<u32>,
    param_value: Option<f64>,
    verbose: bool,
}

impl Default for TestOptions {
    fn default() -> Self {
        Self {
            plugin_path: PathBuf::new(),
            device: "/dev/dsp6".to_string(),
            input_device: Some("/dev/dsp6".to_string()),
            duration_secs: 5,
            sample_rate_hz: audio_defaults::SAMPLE_RATE_HZ,
            period_frames: audio_defaults::PERIOD_FRAMES,
            nperiods: audio_defaults::NPERIODS,
            track_name: "test".to_string(),
            param_id: None,
            param_value: None,
            verbose: false,
        }
    }
}

fn print_verbose(verbose: bool, msg: &str) {
    if verbose {
        println!("[maolan-test] {msg}");
    }
}

fn parse_options(args: impl IntoIterator<Item = String>) -> Result<TestOptions, String> {
    let mut options = TestOptions::default();
    let mut args = args.into_iter();
    let _ = args.next();
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "--plugin-path" => {
                options.plugin_path = PathBuf::from(
                    args.next()
                        .ok_or_else(|| "--plugin-path requires a value".to_string())?,
                );
            }
            "--device" => {
                options.device = args
                    .next()
                    .ok_or_else(|| "--device requires a value".to_string())?;
            }
            "--input-device" => {
                options.input_device = Some(
                    args.next()
                        .ok_or_else(|| "--input-device requires a value".to_string())?,
                );
            }
            "--duration-secs" => {
                let value = args
                    .next()
                    .ok_or_else(|| "--duration-secs requires a value".to_string())?;
                options.duration_secs = value
                    .parse()
                    .map_err(|_| format!("Invalid --duration-secs value: {value}"))?;
            }
            "--sample-rate" => {
                let value = args
                    .next()
                    .ok_or_else(|| "--sample-rate requires a value".to_string())?;
                options.sample_rate_hz = value
                    .parse()
                    .map_err(|_| format!("Invalid --sample-rate value: {value}"))?;
            }
            "--period-frames" => {
                let value = args
                    .next()
                    .ok_or_else(|| "--period-frames requires a value".to_string())?;
                options.period_frames = value
                    .parse()
                    .map_err(|_| format!("Invalid --period-frames value: {value}"))?;
            }
            "--nperiods" => {
                let value = args
                    .next()
                    .ok_or_else(|| "--nperiods requires a value".to_string())?;
                options.nperiods = value
                    .parse()
                    .map_err(|_| format!("Invalid --nperiods value: {value}"))?;
            }
            "--track-name" => {
                options.track_name = args
                    .next()
                    .ok_or_else(|| "--track-name requires a value".to_string())?;
            }
            "--param-id" => {
                let value = args
                    .next()
                    .ok_or_else(|| "--param-id requires a value".to_string())?;
                options.param_id = Some(
                    value
                        .parse()
                        .map_err(|_| format!("Invalid --param-id value: {value}"))?,
                );
            }
            "--param-value" => {
                let value = args
                    .next()
                    .ok_or_else(|| "--param-value requires a value".to_string())?;
                options.param_value = Some(
                    value
                        .parse()
                        .map_err(|_| format!("Invalid --param-value value: {value}"))?,
                );
            }
            "--verbose" | "-v" => {
                options.verbose = true;
            }
            "--help" | "-h" => {
                return Err(help_text());
            }
            other => {
                if other.starts_with('-') {
                    return Err(format!("Unknown argument: {other}\n\n{}", help_text()));
                }
                if !options.plugin_path.as_os_str().is_empty() {
                    return Err(format!(
                        "Only one plugin path may be provided.\n\n{}",
                        help_text()
                    ));
                }
                options.plugin_path = PathBuf::from(other);
            }
        }
    }
    if options.plugin_path.as_os_str().is_empty() {
        return Err(format!("--plugin-path is required.\n\n{}", help_text()));
    }
    Ok(options)
}

fn help_text() -> String {
    "Usage: maolan-test --plugin-path <PATH> [options]

Options:
  --plugin-path <PATH>     Path to CLAP plugin binary (required)
  --device <PATH>          Output OSS device (default: /dev/dsp6)
  --input-device <PATH>    Input OSS device (default: /dev/dsp6)
  --duration-secs <N>      How many seconds to run playback (default: 5)
  --sample-rate <HZ>       Sample rate (default: 48000)
  --period-frames <N>      Period size (default: 1024)
  --nperiods <N>           Number of periods (default: 1)
  --track-name <NAME>      Track name (default: test)
  --param-id <ID>          Parameter ID to set after load
  --param-value <VALUE>    Parameter value to set (requires --param-id)
  --verbose, -v            Print detailed progress
  --help, -h               Show this help"
        .to_string()
}

#[derive(Debug, Default)]
struct TestState {
    hw_ready: bool,
    hw_channels: usize,
    hw_rate: usize,
    clap_instance_count: usize,
    workers_ready: usize,
    workers_total: usize,
    playing: bool,
    diagnostics_received: bool,
    plugin_load_error: Option<String>,
}

async fn wait_for_condition<F>(
    rx: &mut Receiver<EngineMessage>,
    timeout: Duration,
    mut condition: F,
) -> Result<bool, String>
where
    F: FnMut(&EngineMessage) -> bool,
{
    let start = Instant::now();
    loop {
        if start.elapsed() > timeout {
            return Ok(false);
        }
        match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
            Ok(Some(msg)) => {
                if condition(&msg) {
                    return Ok(true);
                }
            }
            Ok(None) => return Err("Engine channel closed".to_string()),
            Err(_) => continue,
        }
    }
}

fn update_state_from_message(state: &mut TestState, msg: &EngineMessage) {
    if let EngineMessage::Response(Ok(Action::HWInfo { channels, rate, .. })) = msg {
        state.hw_ready = true;
        state.hw_channels = *channels;
        state.hw_rate = *rate;
    }
    if let EngineMessage::Response(Ok(Action::Play)) = msg {
        state.playing = true;
    }
    if let EngineMessage::Response(Ok(Action::Stop)) = msg {
        state.playing = false;
    }
    if let EngineMessage::Response(Ok(Action::SessionDiagnosticsReport {
        clap_instance_count,
        workers_ready,
        workers_total,
        playing,
        ..
    })) = msg
    {
        state.clap_instance_count = *clap_instance_count;
        state.workers_ready = *workers_ready;
        state.workers_total = *workers_total;
        state.playing = *playing;
        state.diagnostics_received = true;
    }
    if let EngineMessage::Response(Err(err)) = msg {
        state.plugin_load_error = Some(err.clone());
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let options = match parse_options(std::env::args()) {
        Ok(options) => options,
        Err(message) if message.starts_with("Usage: ") => {
            println!("{message}");
            return Ok(());
        }
        Err(message) => {
            eprintln!("{message}");
            std::process::exit(1);
        }
    };

    print_verbose(options.verbose, "Starting maolan engine...");
    let client = Client::default();
    let mut rx = client.subscribe().await;

    let mut state = TestState::default();

    // 1. Open audio device
    print_verbose(
        options.verbose,
        &format!("Opening audio device '{}'...", options.device),
    );
    client
        .send(EngineMessage::Request(Action::OpenAudioDevice {
            device: options.device.clone(),
            input_device: options.input_device.clone(),
            sample_rate_hz: options.sample_rate_hz,
            bits: audio_defaults::BIT_DEPTH as i32,
            exclusive: false,
            period_frames: options.period_frames,
            realtime_frames: audio_defaults::REALTIME_FRAMES.min(options.period_frames),
            low_watermark_frames: audio_defaults::LOW_WATERMARK_FRAMES.min(options.period_frames),
            nperiods: options.nperiods,
            sync_mode: audio_defaults::SYNC_MODE,
            hybrid_enabled: audio_defaults::HYBRID_BUFFER_ENABLED,
        }))
        .await?;

    let hw_ok = wait_for_condition(&mut rx, Duration::from_secs(10), |msg| {
        update_state_from_message(&mut state, msg);
        state.hw_ready
    })
    .await?;

    if !hw_ok {
        eprintln!("ERROR: Audio device did not become ready within 10 seconds");
        let _ = client.send(EngineMessage::Request(Action::Quit)).await;
        std::process::exit(1);
    }

    print_verbose(
        options.verbose,
        &format!(
            "Audio ready: {} channels @ {} Hz",
            state.hw_channels, state.hw_rate
        ),
    );

    // 2. Create track
    print_verbose(
        options.verbose,
        &format!("Creating track '{}'...", options.track_name),
    );
    client
        .send(EngineMessage::Request(Action::AddTrack {
            name: options.track_name.clone(),
            audio_ins: 2,
            audio_outs: 2,
            midi_ins: 1,
            midi_outs: 1,
        }))
        .await?;

    tokio::time::sleep(Duration::from_millis(100)).await;

    // 3. Load CLAP plugin
    let plugin_path = options.plugin_path.to_string_lossy().to_string();
    print_verbose(
        options.verbose,
        &format!("Loading CLAP plugin '{}'...", plugin_path),
    );
    client
        .send(EngineMessage::Request(Action::TrackLoadClapPlugin {
            track_name: options.track_name.clone(),
            plugin_path: plugin_path.clone(),
            instance_id: Some(0),
        }))
        .await?;

    // Wait for plugin to load by polling diagnostics
    tokio::time::sleep(Duration::from_millis(500)).await;
    client
        .send(EngineMessage::Request(Action::RequestSessionDiagnostics))
        .await?;

    let plugin_loaded = wait_for_condition(&mut rx, Duration::from_secs(30), |msg| {
        update_state_from_message(&mut state, msg);
        state.diagnostics_received && state.clap_instance_count > 0
    })
    .await?;

    if !plugin_loaded {
        if let Some(ref err) = state.plugin_load_error {
            eprintln!("ERROR: Plugin load failed: {err}");
        } else {
            eprintln!("ERROR: Plugin did not load within 30 seconds (clap_instance_count = 0)");
        }
        let _ = client.send(EngineMessage::Request(Action::Quit)).await;
        std::process::exit(1);
    }

    print_verbose(
        options.verbose,
        &format!(
            "Plugin loaded. Workers: {}/{} ready",
            state.workers_ready, state.workers_total
        ),
    );

    // 4. Optionally set parameter
    if let (Some(param_id), Some(param_value)) = (options.param_id, options.param_value) {
        print_verbose(
            options.verbose,
            &format!("Setting parameter {param_id} = {param_value}..."),
        );
        client
            .send(EngineMessage::Request(Action::TrackSetClapParameter {
                track_name: options.track_name.clone(),
                instance_id: 0,
                param_id,
                value: param_value,
            }))
            .await?;
        tokio::time::sleep(Duration::from_millis(100)).await;
    }

    // 5. Start playback
    print_verbose(options.verbose, "Starting playback...");
    client
        .send(EngineMessage::Request(Action::SetClipPlaybackEnabled(true)))
        .await?;
    client.send(EngineMessage::Request(Action::Play)).await?;

    let play_ok = wait_for_condition(&mut rx, Duration::from_secs(5), |msg| {
        update_state_from_message(&mut state, msg);
        state.playing
    })
    .await?;

    if !play_ok {
        eprintln!("ERROR: Playback did not start within 5 seconds");
        let _ = client.send(EngineMessage::Request(Action::Quit)).await;
        std::process::exit(1);
    }

    // 6. Run for specified duration
    print_verbose(
        options.verbose,
        &format!("Running for {} seconds...", options.duration_secs),
    );
    tokio::time::sleep(Duration::from_secs(options.duration_secs)).await;

    // 7. Stop playback
    print_verbose(options.verbose, "Stopping playback...");
    client.send(EngineMessage::Request(Action::Stop)).await?;

    let stop_ok = wait_for_condition(&mut rx, Duration::from_secs(5), |msg| {
        update_state_from_message(&mut state, msg);
        !state.playing
    })
    .await?;

    if !stop_ok {
        eprintln!("WARNING: Playback did not stop within 5 seconds");
    }

    // 8. Final diagnostics check
    state.diagnostics_received = false;
    client
        .send(EngineMessage::Request(Action::RequestSessionDiagnostics))
        .await?;

    let final_ok = wait_for_condition(&mut rx, Duration::from_secs(10), |msg| {
        update_state_from_message(&mut state, msg);
        state.diagnostics_received
    })
    .await?;

    if !final_ok {
        eprintln!("ERROR: Did not receive final diagnostics");
        let _ = client.send(EngineMessage::Request(Action::Quit)).await;
        std::process::exit(1);
    }

    // 9. Evaluate results
    let success = state.clap_instance_count > 0
        && state.workers_ready == state.workers_total
        && state.workers_total > 0;

    println!("Test Results:");
    println!("  CLAP instances:    {}", state.clap_instance_count);
    println!(
        "  Workers ready:     {}/{}",
        state.workers_ready, state.workers_total
    );
    println!(
        "  Audio channels:    {} @ {} Hz",
        state.hw_channels, state.hw_rate
    );
    println!("  Duration:          {}s", options.duration_secs);
    println!("  Plugin path:       {}", plugin_path);

    if success {
        println!("  Result:            PASS");
    } else {
        println!("  Result:            FAIL");
        if state.clap_instance_count == 0 {
            println!("  Reason:            No CLAP instances found (plugin may have crashed)");
        }
        if state.workers_ready != state.workers_total {
            println!(
                "  Reason:            Only {}/{} workers ready",
                state.workers_ready, state.workers_total
            );
        }
    }

    // 10. Cleanup
    print_verbose(options.verbose, "Unloading plugin and shutting down...");
    let _ = client
        .send(EngineMessage::Request(
            Action::TrackUnloadClapPluginInstance {
                track_name: options.track_name.clone(),
                instance_id: 0,
            },
        ))
        .await;
    tokio::time::sleep(Duration::from_millis(200)).await;
    let _ = client.send(EngineMessage::Request(Action::Quit)).await;
    tokio::time::sleep(Duration::from_millis(500)).await;

    if success {
        std::process::exit(0);
    } else {
        std::process::exit(1);
    }
}