mtrack 0.12.0

A multitrack audio and MIDI player for live performances.
Documentation
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
// Copyright (C) 2026 Michael Wilson <mike@mdwn.dev>
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation, version 3.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>.
//
use std::{error::Error, str::FromStr, time::Duration};

use duration_string::DurationString;
use serde::{Deserialize, Serialize};

use crate::audio::SampleFormat;

const DEFAULT_AUDIO_PLAYBACK_DELAY: Duration = Duration::ZERO;
const DEFAULT_BUFFER_SIZE: usize = 1024;
const DEFAULT_BUFFER_THREADS: usize = 2;

/// Which resampling algorithm to use when source and output sample rates differ.
#[derive(Deserialize, Serialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ResamplerType {
    /// High-quality sinc interpolation (lower latency, higher CPU). This is the default.
    #[default]
    Sinc,
    /// FFT-based resampling (considerably faster for fixed-ratio resampling).
    Fft,
}

/// How to choose the CPAL stream buffer size (period size). Affects latency vs underrun tolerance.
#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(untagged)]
pub enum StreamBufferSize {
    /// Use the backend's default (may be high latency on some systems).
    #[serde(rename = "default")]
    Default,
    /// Use the device's minimum supported period size (lowest latency, most jitter-sensitive).
    #[serde(rename = "min")]
    Min,
    /// Use a fixed size in frames (same as buffer_size when not set).
    Fixed(usize),
}

/// A YAML representation of the audio configuration.
#[derive(Deserialize, Serialize, Clone)]
pub struct Audio {
    /// The audio device.
    device: String,

    /// Controls how long to wait before playback of an audio file starts.
    playback_delay: Option<String>,

    /// Target sample rate in Hz (default: 44100)
    sample_rate: Option<u32>,

    /// Target sample format (default: "int")
    sample_format: Option<String>,

    /// Target bits per sample (default: 32)
    bits_per_sample: Option<u16>,

    /// Buffer size for decoded audio samples (default: 1024 samples per channel)
    buffer_size: Option<usize>,

    /// CPAL stream buffer: "default" (backend default), "min" (lowest latency), or a number (frames).
    /// When unset, uses buffer_size. Lower values = lower latency but more sensitive to callback jitter.
    stream_buffer_size: Option<StreamBufferSize>,

    /// Number of worker threads for buffered song sources.
    /// Defaults to a small fixed value; must be >= 1.
    buffer_threads: Option<usize>,

    /// Resampling algorithm: "sinc" (default, high quality) or "fft" (faster on low-power hardware).
    resampler: Option<ResamplerType>,
}

impl Audio {
    /// New will create a new Audio configuration.
    pub fn new(device: &str) -> Audio {
        Audio {
            device: device.to_string(),
            playback_delay: None,
            sample_rate: None,
            sample_format: None,
            bits_per_sample: None,
            buffer_size: None,
            stream_buffer_size: None,
            buffer_threads: None,
            resampler: None,
        }
    }

    /// Returns the device from the configuration.
    pub fn device(&self) -> &str {
        &self.device
    }

    /// Returns the playback delay from the configuration.
    pub fn playback_delay(&self) -> Result<Duration, Box<dyn Error>> {
        super::parse_playback_delay(&self.playback_delay, DEFAULT_AUDIO_PLAYBACK_DELAY)
    }

    /// Returns the target sample rate (default: 44100)
    pub fn sample_rate(&self) -> u32 {
        self.sample_rate.unwrap_or(44100)
    }

    /// Returns the target sample format (default: Float)
    pub fn sample_format(&self) -> Result<SampleFormat, Box<dyn Error>> {
        match self.sample_format.as_deref() {
            Some(format) => SampleFormat::from_str(format),
            None => Ok(SampleFormat::Int),
        }
    }

    /// Returns the target bits per sample (default: 32)
    pub fn bits_per_sample(&self) -> u16 {
        self.bits_per_sample.unwrap_or(32)
    }

    /// Returns the buffer size for decoded audio samples (default: 1024 samples per channel)
    pub fn buffer_size(&self) -> usize {
        self.buffer_size.unwrap_or(DEFAULT_BUFFER_SIZE)
    }

    /// Returns the number of worker threads used for buffered song sources.
    pub fn buffer_threads(&self) -> usize {
        self.buffer_threads.unwrap_or(DEFAULT_BUFFER_THREADS).max(1)
    }

    /// Returns the stream buffer size choice for CPAL (default/min/fixed).
    /// When None, the stream uses buffer_size() as a fixed frame count.
    pub fn stream_buffer_size(&self) -> Option<StreamBufferSize> {
        self.stream_buffer_size.clone()
    }

    /// Returns the resampling algorithm to use (default: Sinc).
    pub fn resampler(&self) -> ResamplerType {
        self.resampler.unwrap_or_default()
    }

    /// Sets the target sample rate.
    #[allow(dead_code)]
    pub fn with_sample_rate(mut self, sample_rate: u32) -> Self {
        self.sample_rate = Some(sample_rate);
        self
    }

    /// Sets the buffer size for decoded audio samples.
    #[allow(dead_code)]
    pub fn with_buffer_size(mut self, buffer_size: usize) -> Self {
        self.buffer_size = Some(buffer_size);
        self
    }

    /// Sets the target sample format ("float" or "int").
    #[allow(dead_code)]
    pub fn with_sample_format(mut self, format: &str) -> Self {
        self.sample_format = Some(format.to_string());
        self
    }

    /// Sets the target bits per sample.
    #[allow(dead_code)]
    pub fn with_bits_per_sample(mut self, bits: u16) -> Self {
        self.bits_per_sample = Some(bits);
        self
    }

    /// Sets the CPAL stream buffer size.
    #[allow(dead_code)]
    pub fn with_stream_buffer_size(mut self, sbs: StreamBufferSize) -> Self {
        self.stream_buffer_size = Some(sbs);
        self
    }

    /// Sets the resampling algorithm.
    #[allow(dead_code)]
    pub fn with_resampler(mut self, resampler: ResamplerType) -> Self {
        self.resampler = Some(resampler);
        self
    }

    /// Validates the audio configuration for semantic issues.
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        if self.device.trim().is_empty() {
            errors.push("audio device must not be empty".to_string());
        }
        if let Some(rate) = self.sample_rate {
            if rate == 0 {
                errors.push("audio sample_rate must be greater than 0".to_string());
            }
        }
        if let Some(bits) = self.bits_per_sample {
            if bits == 0 {
                errors.push("audio bits_per_sample must be greater than 0".to_string());
            }
        }
        if let Some(ref fmt) = self.sample_format {
            if SampleFormat::from_str(fmt).is_err() {
                errors.push(format!(
                    "audio sample_format '{}' is invalid (expected 'int' or 'float')",
                    fmt
                ));
            }
        }
        if let Some(ref delay) = self.playback_delay {
            if DurationString::from_string(delay.clone()).is_err() {
                errors.push(format!(
                    "audio playback_delay '{}' is not a valid duration",
                    delay
                ));
            }
        }
        if let Some(size) = self.buffer_size {
            if size == 0 {
                errors.push("audio buffer_size must be greater than 0".to_string());
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

#[cfg(test)]
mod test {
    use std::time::Duration;

    use super::*;

    #[test]
    fn defaults() {
        let audio = Audio::new("test-device");
        assert_eq!(audio.device(), "test-device");
        assert_eq!(audio.sample_rate(), 44100);
        assert_eq!(audio.bits_per_sample(), 32);
        assert_eq!(audio.sample_format().unwrap(), SampleFormat::Int);
        assert_eq!(audio.buffer_size(), DEFAULT_BUFFER_SIZE);
        assert_eq!(audio.buffer_threads(), DEFAULT_BUFFER_THREADS);
        assert_eq!(audio.playback_delay().unwrap(), Duration::ZERO);
        assert!(audio.stream_buffer_size().is_none());
        assert_eq!(audio.resampler(), ResamplerType::Sinc);
    }

    #[test]
    fn builder_sample_rate() {
        let audio = Audio::new("dev").with_sample_rate(48000);
        assert_eq!(audio.sample_rate(), 48000);
    }

    #[test]
    fn builder_buffer_size() {
        let audio = Audio::new("dev").with_buffer_size(2048);
        assert_eq!(audio.buffer_size(), 2048);
    }

    #[test]
    fn builder_bits_per_sample() {
        let audio = Audio::new("dev").with_bits_per_sample(16);
        assert_eq!(audio.bits_per_sample(), 16);
    }

    #[test]
    fn builder_sample_format_float() {
        let audio = Audio::new("dev").with_sample_format("float");
        assert_eq!(audio.sample_format().unwrap(), SampleFormat::Float);
    }

    #[test]
    fn builder_sample_format_int() {
        let audio = Audio::new("dev").with_sample_format("int");
        assert_eq!(audio.sample_format().unwrap(), SampleFormat::Int);
    }

    #[test]
    fn sample_format_invalid() {
        let audio = Audio::new("dev").with_sample_format("wav");
        assert!(audio.sample_format().is_err());
    }

    #[test]
    fn playback_delay_valid() {
        let audio = Audio {
            playback_delay: Some("500ms".to_string()),
            ..Audio::new("dev")
        };
        assert_eq!(audio.playback_delay().unwrap(), Duration::from_millis(500));
    }

    #[test]
    fn playback_delay_invalid() {
        let audio = Audio {
            playback_delay: Some("not-a-duration".to_string()),
            ..Audio::new("dev")
        };
        assert!(audio.playback_delay().is_err());
    }

    #[test]
    fn buffer_threads_clamped_to_one() {
        let audio = Audio {
            buffer_threads: Some(0),
            ..Audio::new("dev")
        };
        assert_eq!(audio.buffer_threads(), 1);
    }

    #[test]
    fn buffer_threads_custom() {
        let audio = Audio {
            buffer_threads: Some(4),
            ..Audio::new("dev")
        };
        assert_eq!(audio.buffer_threads(), 4);
    }

    #[test]
    fn builder_resampler_fft() {
        let audio = Audio::new("dev").with_resampler(ResamplerType::Fft);
        assert_eq!(audio.resampler(), ResamplerType::Fft);
    }

    #[test]
    fn builder_stream_buffer_size() {
        let audio = Audio::new("dev").with_stream_buffer_size(StreamBufferSize::Min);
        assert!(matches!(
            audio.stream_buffer_size(),
            Some(StreamBufferSize::Min)
        ));
    }

    #[test]
    fn builder_chaining() {
        let audio = Audio::new("dev")
            .with_sample_rate(96000)
            .with_buffer_size(512)
            .with_bits_per_sample(24)
            .with_sample_format("float")
            .with_resampler(ResamplerType::Fft);

        assert_eq!(audio.sample_rate(), 96000);
        assert_eq!(audio.buffer_size(), 512);
        assert_eq!(audio.bits_per_sample(), 24);
        assert_eq!(audio.sample_format().unwrap(), SampleFormat::Float);
        assert_eq!(audio.resampler(), ResamplerType::Fft);
    }

    fn from_yaml(yaml: &str) -> Audio {
        config::Config::builder()
            .add_source(config::File::from_str(yaml, config::FileFormat::Yaml))
            .build()
            .expect("build config")
            .try_deserialize::<Audio>()
            .expect("deserialize")
    }

    #[test]
    fn serde_defaults_from_minimal_yaml() {
        let audio = from_yaml("device: minimal-device\n");

        assert_eq!(audio.device(), "minimal-device");
        assert_eq!(audio.sample_rate(), 44100);
        assert_eq!(audio.bits_per_sample(), 32);
        assert_eq!(audio.buffer_size(), DEFAULT_BUFFER_SIZE);
        assert_eq!(audio.resampler(), ResamplerType::Sinc);
    }

    #[test]
    fn serde_full_yaml() {
        let audio = from_yaml(
            r#"
            device: my-device
            sample_rate: 48000
            buffer_size: 512
            bits_per_sample: 24
            sample_format: float
            resampler: fft
            buffer_threads: 4
            playback_delay: 100ms
            "#,
        );

        assert_eq!(audio.device(), "my-device");
        assert_eq!(audio.sample_rate(), 48000);
        assert_eq!(audio.buffer_size(), 512);
        assert_eq!(audio.bits_per_sample(), 24);
        assert_eq!(audio.sample_format().unwrap(), SampleFormat::Float);
        assert_eq!(audio.resampler(), ResamplerType::Fft);
        assert_eq!(audio.buffer_threads(), 4);
        assert_eq!(audio.playback_delay().unwrap(), Duration::from_millis(100));
    }

    #[test]
    fn serde_resampler_variants() {
        let audio = from_yaml("device: dev\nresampler: sinc\n");
        assert_eq!(audio.resampler(), ResamplerType::Sinc);

        let audio = from_yaml("device: dev\nresampler: fft\n");
        assert_eq!(audio.resampler(), ResamplerType::Fft);
    }
}