mlua-pulse 0.1.0

Lua-friendly music composition and audio export bindings built on tunes and mlua
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
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
515
516
517
518
519
520
521
522
523
//! Error and result types shared by the Rust API and Lua bindings.

use std::path::PathBuf;

/// Result type used by mlua-pulse internals.
pub type PulseResult<T> = Result<T, PulseError>;

/// Domain errors surfaced by mlua-pulse before they are mapped to Lua errors.
#[derive(Debug, thiserror::Error)]
pub enum PulseError {
    /// A note name could not be parsed into an equal-tempered frequency.
    #[error("invalid note name: {value}")]
    InvalidNoteName {
        /// The rejected note name.
        value: String,
    },
    /// A scale or mode name is not in the supported theory catalog.
    #[error("invalid mode: {value}")]
    InvalidMode {
        /// The rejected mode name.
        value: String,
    },
    /// A chord kind name is not in the supported theory catalog.
    #[error("invalid chord kind: {value}")]
    InvalidChordKind {
        /// The rejected chord kind.
        value: String,
    },
    /// A song tempo is zero, negative, or not finite.
    #[error("invalid tempo: {bpm}")]
    InvalidTempo {
        /// The rejected tempo in beats per minute.
        bpm: f32,
    },
    /// A note or sequence duration is zero, negative, or not finite.
    #[error("invalid duration: {duration}")]
    InvalidDuration {
        /// The rejected duration in beats.
        duration: f32,
    },
    /// A sequence has a different number of events and durations.
    #[error("duration count mismatch: {notes} notes and {durations} durations")]
    DurationCountMismatch {
        /// Number of note or chord events.
        notes: usize,
        /// Number of duration entries.
        durations: usize,
    },
    /// A chord event contains no voices or too many voices for export.
    #[error("invalid chord voice count: {count}")]
    InvalidChordVoiceCount {
        /// Number of voices found in the chord event.
        count: usize,
    },
    /// A sequence option such as volume, pan, velocity, or start offset is invalid.
    #[error("invalid sequence option {option}: {value}")]
    InvalidSequenceOption {
        /// Option name.
        option: String,
        /// Rejected value rendered for diagnostics.
        value: String,
    },
    /// A Lua-facing instrument alias could not be resolved.
    #[error("invalid instrument: {value}")]
    InvalidInstrument {
        /// The rejected instrument alias.
        value: String,
    },
    /// A Lua-facing drum alias could not be resolved.
    #[error("invalid drum type: {value}")]
    InvalidDrumType {
        /// The rejected drum alias.
        value: String,
    },
    /// A named rhythm pattern is not registered.
    #[error("invalid rhythm pattern: {value}")]
    InvalidRhythmPattern {
        /// The rejected rhythm pattern name.
        value: String,
    },
    /// A MIDI note number is outside the `0..=127` range.
    #[error("invalid midi note: {note}")]
    InvalidMidiNote {
        /// The rejected MIDI note number.
        note: i64,
    },
    /// A frequency is zero, negative, or not finite.
    #[error("invalid frequency: {frequency}")]
    InvalidFrequency {
        /// The rejected frequency in Hertz.
        frequency: f32,
    },
    /// A drum grid was created with zero steps.
    #[error("invalid drum grid steps: {steps}")]
    InvalidDrumGridSteps {
        /// The rejected step count.
        steps: usize,
    },
    /// A drum grid step duration is zero, negative, or not finite.
    #[error("invalid step duration: {duration}")]
    InvalidStepDuration {
        /// The rejected step duration in beats.
        duration: f32,
    },
    /// A drum-grid mix or timing option is invalid.
    #[error("invalid drum option {option}: {value}")]
    InvalidDrumOption {
        /// Option name.
        option: String,
        /// Rejected value rendered for diagnostics.
        value: String,
    },
    /// A phrase repeat count is zero.
    #[error("invalid repeat times: {repeat_times}")]
    InvalidRepeatTimes {
        /// The rejected repeat count.
        repeat_times: usize,
    },
    /// `tunes` failed to import a MIDI file.
    #[error("midi import failed: {message}")]
    MidiImportFailed {
        /// Error message returned by the MIDI importer.
        message: String,
    },
    /// `tunes` failed to export a MIDI file.
    #[error("midi export failed: {message}")]
    MidiExportFailed {
        /// Error message returned by the MIDI exporter.
        message: String,
    },
    /// An export path could not be represented as UTF-8 for `tunes` APIs.
    #[error("invalid export path: {}", path.display())]
    InvalidExportPath {
        /// The rejected filesystem path.
        path: PathBuf,
    },
    /// The output extension is not one of the supported export formats.
    #[error("unsupported export format: {format}")]
    UnsupportedExportFormat {
        /// The rejected extension, or `missing` when no extension was present.
        format: String,
    },
    /// A WAV/FLAC sample rate is zero.
    #[error("invalid export sample_rate: {sample_rate}")]
    InvalidExportSampleRate {
        /// The rejected sample rate.
        sample_rate: u32,
    },
    /// A final loudness-normalization option is outside the supported range.
    #[error("invalid export normalize option {option}: {value}")]
    InvalidExportNormalizeOption {
        /// Option name.
        option: String,
        /// Rejected value rendered for diagnostics.
        value: String,
    },
    /// A requested FLAC bit depth is unsupported by the direct encoder path.
    #[error("invalid export flac_bits_per_sample: {bits_per_sample}")]
    InvalidExportFlacBitsPerSample {
        /// The rejected bit depth.
        bits_per_sample: u32,
    },
    /// A MIDI export loudness option is invalid.
    #[error("invalid export midi option {option}: {value}")]
    InvalidExportMidiOption {
        /// Option name.
        option: String,
        /// Rejected value rendered for diagnostics.
        value: String,
    },
    /// A WAV/FLAC export failed after validation.
    #[error("export failed: {message}")]
    ExportFailed {
        /// Error message returned by the audio engine or encoder.
        message: String,
    },
    /// GPU export was requested without enabling the crate's `gpu` feature.
    #[error("gpu feature is not enabled")]
    GpuFeatureNotEnabled,
    /// The real-time playback engine reported an error.
    #[error("playback failed: {message}")]
    PlaybackFailed {
        /// Error message returned by the playback engine.
        message: String,
    },
    /// A playback rate is zero, negative, or not finite.
    #[error("invalid playback rate: {rate}")]
    InvalidPlaybackRate {
        /// The rejected playback rate.
        rate: f32,
    },
    /// A playback volume is outside `0..=1`.
    #[error("invalid playback volume: {volume}")]
    InvalidPlaybackVolume {
        /// The rejected playback volume.
        volume: f32,
    },
    /// A playback pan value is outside `-1..=1`.
    #[error("invalid playback pan: {pan}")]
    InvalidPlaybackPan {
        /// The rejected stereo pan value.
        pan: f32,
    },
    /// An algorithm generator name is not registered.
    #[error("invalid generator: {name}")]
    InvalidGenerator {
        /// The rejected generator name.
        name: String,
    },
    /// A required generator option was not supplied.
    #[error("missing generator option: {name}")]
    MissingGeneratorOption {
        /// Missing option name.
        name: String,
    },
    /// A generator option has the wrong type or range.
    #[error("invalid generator option {name}: {value}")]
    InvalidGeneratorOption {
        /// Option name.
        name: String,
        /// Rejected value rendered for diagnostics.
        value: String,
    },
    /// A generated value shape cannot be converted to Lua.
    #[error("unsupported generator output: {output}")]
    UnsupportedGeneratorOutput {
        /// Output shape label.
        output: String,
    },
    /// An effect name is not registered.
    #[error("invalid effect: {name}")]
    InvalidEffect {
        /// The rejected effect name.
        name: String,
    },
    /// An effect preset is not supported for the selected effect.
    #[error("invalid effect preset {effect}: {preset}")]
    InvalidEffectPreset {
        /// Effect name.
        effect: String,
        /// Rejected preset name.
        preset: String,
    },
    /// An effect option has the wrong type, range, or name.
    #[error("invalid effect option {effect}.{option}: {value}")]
    InvalidEffectOption {
        /// Effect name.
        effect: String,
        /// Option name.
        option: String,
        /// Rejected value rendered for diagnostics.
        value: String,
    },
    /// An effect was placed on a scope where `tunes` cannot apply it.
    #[error("invalid effect scope {effect}: {scope}")]
    InvalidEffectScope {
        /// Effect name.
        effect: String,
        /// Rejected scope name.
        scope: String,
    },
    /// A synthesis algorithm name is not registered.
    #[error("invalid synth: {name}")]
    InvalidSynth {
        /// The rejected synth name.
        name: String,
    },
    /// A synth preset is not supported for the selected algorithm.
    #[error("invalid synth preset {synth}: {preset}")]
    InvalidSynthPreset {
        /// Synth name.
        synth: String,
        /// Rejected preset name.
        preset: String,
    },
    /// A synth option has the wrong type, range, or name.
    #[error("invalid synth option {synth}.{option}: {value}")]
    InvalidSynthOption {
        /// Synth name.
        synth: String,
        /// Option name.
        option: String,
        /// Rejected value rendered for diagnostics.
        value: String,
    },
    /// A sample file could not be loaded or transformed.
    #[error("sample load failed: {message}")]
    SampleLoadFailed {
        /// Error message returned by the sample loader or transformer.
        message: String,
    },
    /// A sample clip option has the wrong range or shape.
    #[error("invalid sample option {option}: {value}")]
    InvalidSampleOption {
        /// Option name.
        option: String,
        /// Rejected value rendered for diagnostics.
        value: String,
    },
    /// A MIDI clip option has the wrong range or shape.
    #[error("invalid midi clip option {option}: {value}")]
    InvalidMidiClipOption {
        /// Option name.
        option: String,
        /// Rejected value rendered for diagnostics.
        value: String,
    },
}

impl From<PulseError> for mlua::Error {
    fn from(value: PulseError) -> Self {
        mlua::Error::external(value)
    }
}

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

    #[test]
    fn error_messages_start_lowercase_and_include_value() {
        let error = PulseError::InvalidMode {
            value: "superlocrian".to_string(),
        };

        assert_eq!(error.to_string(), "invalid mode: superlocrian");
    }

    #[test]
    fn pulse_error_converts_to_lua_external_error() {
        let lua_error: mlua::Error = PulseError::InvalidTempo { bpm: 0.0 }.into();

        let rendered = lua_error.to_string();
        assert!(rendered.contains("invalid tempo: 0"));
    }

    #[test]
    fn capability_expansion_errors_render_lowercase_values() {
        assert_eq!(
            PulseError::InvalidDrumType {
                value: "kick_707".to_string()
            }
            .to_string(),
            "invalid drum type: kick_707"
        );
        assert_eq!(
            PulseError::InvalidRhythmPattern {
                value: "vaporwave_backbeat".to_string()
            }
            .to_string(),
            "invalid rhythm pattern: vaporwave_backbeat"
        );
        assert_eq!(
            PulseError::InvalidMidiNote { note: 200 }.to_string(),
            "invalid midi note: 200"
        );
        assert_eq!(
            PulseError::InvalidDrumGridSteps { steps: 0 }.to_string(),
            "invalid drum grid steps: 0"
        );
        assert_eq!(
            PulseError::InvalidStepDuration { duration: 0.0 }.to_string(),
            "invalid step duration: 0"
        );
        assert_eq!(
            PulseError::InvalidRepeatTimes { repeat_times: 0 }.to_string(),
            "invalid repeat times: 0"
        );
        assert_eq!(
            PulseError::UnsupportedExportFormat {
                format: "ogg".to_string()
            }
            .to_string(),
            "unsupported export format: ogg"
        );
        assert_eq!(
            PulseError::GpuFeatureNotEnabled.to_string(),
            "gpu feature is not enabled"
        );
        assert_eq!(
            PulseError::InvalidExportNormalizeOption {
                option: "target_db".to_string(),
                value: "3".to_string()
            }
            .to_string(),
            "invalid export normalize option target_db: 3"
        );
        assert_eq!(
            PulseError::InvalidExportFlacBitsPerSample {
                bits_per_sample: 12
            }
            .to_string(),
            "invalid export flac_bits_per_sample: 12"
        );
        assert_eq!(
            PulseError::InvalidExportMidiOption {
                option: "midi_velocity_gain".to_string(),
                value: "0".to_string()
            }
            .to_string(),
            "invalid export midi option midi_velocity_gain: 0"
        );
        assert_eq!(
            PulseError::PlaybackFailed {
                message: "device unavailable".to_string()
            }
            .to_string(),
            "playback failed: device unavailable"
        );
        assert_eq!(
            PulseError::InvalidPlaybackRate { rate: 0.0 }.to_string(),
            "invalid playback rate: 0"
        );
        assert_eq!(
            PulseError::InvalidPlaybackVolume { volume: 1.5 }.to_string(),
            "invalid playback volume: 1.5"
        );
        assert_eq!(
            PulseError::InvalidPlaybackPan { pan: 2.0 }.to_string(),
            "invalid playback pan: 2"
        );
        assert_eq!(
            PulseError::InvalidGenerator {
                name: "vaporwave_sequence".to_string()
            }
            .to_string(),
            "invalid generator: vaporwave_sequence"
        );
        assert_eq!(
            PulseError::MissingGeneratorOption {
                name: "length".to_string()
            }
            .to_string(),
            "missing generator option: length"
        );
        assert_eq!(
            PulseError::InvalidGeneratorOption {
                name: "length".to_string(),
                value: "0".to_string()
            }
            .to_string(),
            "invalid generator option length: 0"
        );
        assert_eq!(
            PulseError::UnsupportedGeneratorOutput {
                output: "tuple3".to_string()
            }
            .to_string(),
            "unsupported generator output: tuple3"
        );
        assert_eq!(
            PulseError::InvalidEffect {
                name: "shimmer".to_string()
            }
            .to_string(),
            "invalid effect: shimmer"
        );
        assert_eq!(
            PulseError::InvalidEffectPreset {
                effect: "delay".to_string(),
                preset: "cathedral".to_string()
            }
            .to_string(),
            "invalid effect preset delay: cathedral"
        );
        assert_eq!(
            PulseError::InvalidEffectOption {
                effect: "delay".to_string(),
                option: "feedback".to_string(),
                value: "1.2".to_string()
            }
            .to_string(),
            "invalid effect option delay.feedback: 1.2"
        );
        assert_eq!(
            PulseError::InvalidEffectScope {
                effect: "filter".to_string(),
                scope: "master".to_string()
            }
            .to_string(),
            "invalid effect scope filter: master"
        );
        assert_eq!(
            PulseError::InvalidSynth {
                name: "subtractive".to_string()
            }
            .to_string(),
            "invalid synth: subtractive"
        );
        assert_eq!(
            PulseError::InvalidSynthPreset {
                synth: "fm".to_string(),
                preset: "glass".to_string()
            }
            .to_string(),
            "invalid synth preset fm: glass"
        );
        assert_eq!(
            PulseError::InvalidSynthOption {
                synth: "additive".to_string(),
                option: "harmonics".to_string(),
                value: "empty".to_string()
            }
            .to_string(),
            "invalid synth option additive.harmonics: empty"
        );
        assert_eq!(
            PulseError::SampleLoadFailed {
                message: "missing.wav".to_string()
            }
            .to_string(),
            "sample load failed: missing.wav"
        );
        assert_eq!(
            PulseError::InvalidSampleOption {
                option: "rate".to_string(),
                value: "0".to_string()
            }
            .to_string(),
            "invalid sample option rate: 0"
        );
    }
}