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
//! Lightweight playback preview wrappers around `tunes::engine::AudioEngine`.

use crate::composition::PulseSong;
use crate::error::{PulseError, PulseResult};
use crate::files::PulseImportedMidi;
use std::rc::Rc;
use tunes::engine::{AudioEngine, SoundId};
use tunes::track::Mixer;

#[derive(Clone)]
/// Shared playback engine used by Lua playback handles.
pub struct PulsePlaybackEngine {
    engine: Rc<AudioEngine>,
}

#[derive(Clone)]
/// Handle for a real-time or looping sound started by `PulsePlaybackEngine`.
pub struct PulsePlaybackHandle {
    engine: Rc<AudioEngine>,
    sound_id: SoundId,
}

impl std::fmt::Debug for PulsePlaybackHandle {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PulsePlaybackHandle")
            .field("sound_id", &self.sound_id)
            .finish_non_exhaustive()
    }
}

/// A value that can be converted into a `tunes` mixer for playback.
pub enum PulsePlayable<'a> {
    /// A song built with the mlua-pulse composition DSL.
    Song(&'a PulseSong),
    /// A MIDI file imported through `PulseImportedMidi`.
    ImportedMidi(&'a PulseImportedMidi),
}

fn playback_error(error: impl std::fmt::Display) -> PulseError {
    PulseError::PlaybackFailed {
        message: error.to_string(),
    }
}

/// Converts a playback target into a fresh `tunes` mixer.
///
/// # Errors
///
/// Returns an error when the source song cannot be converted to a mixer.
pub fn mixer_from_playable(playable: PulsePlayable<'_>) -> PulseResult<Mixer> {
    match playable {
        PulsePlayable::Song(song) => song.to_mixer(),
        PulsePlayable::ImportedMidi(imported) => Ok(imported.cloned_mixer()),
    }
}

/// Validates a playback-rate multiplier.
///
/// # Errors
///
/// Returns an error when `rate` is zero, negative, or not finite.
pub fn validate_playback_rate(rate: f32) -> PulseResult<f32> {
    if !rate.is_finite() || rate <= 0.0 {
        return Err(PulseError::InvalidPlaybackRate { rate });
    }
    Ok(rate)
}

/// Validates a real-time playback volume.
///
/// # Errors
///
/// Returns an error when `volume` is outside `0..=1`.
pub fn validate_playback_volume(volume: f32) -> PulseResult<f32> {
    if !volume.is_finite() || !(0.0..=1.0).contains(&volume) {
        return Err(PulseError::InvalidPlaybackVolume { volume });
    }
    Ok(volume)
}

/// Validates a real-time playback pan value.
///
/// # Errors
///
/// Returns an error when `pan` is outside `-1..=1`.
pub fn validate_playback_pan(pan: f32) -> PulseResult<f32> {
    if !pan.is_finite() || !(-1.0..=1.0).contains(&pan) {
        return Err(PulseError::InvalidPlaybackPan { pan });
    }
    Ok(pan)
}

impl PulsePlaybackEngine {
    /// Creates a playback engine using `tunes::engine::AudioEngine::new`.
    ///
    /// # Errors
    ///
    /// Returns a playback error when the audio engine cannot initialize.
    pub fn new() -> PulseResult<Self> {
        let engine = AudioEngine::new().map_err(playback_error)?;
        Ok(Self {
            engine: Rc::new(engine),
        })
    }

    /// Plays a target immediately and waits for `tunes` to schedule playback.
    ///
    /// # Errors
    ///
    /// Returns an error when mixer creation or playback scheduling fails.
    pub fn play(&self, playable: PulsePlayable<'_>) -> PulseResult<()> {
        let mixer = mixer_from_playable(playable)?;
        self.engine.play_mixer(&mixer).map_err(playback_error)
    }

    /// Starts real-time playback and returns a handle for later control.
    ///
    /// # Errors
    ///
    /// Returns an error when mixer creation or playback scheduling fails.
    pub fn play_realtime(&self, playable: PulsePlayable<'_>) -> PulseResult<PulsePlaybackHandle> {
        let mixer = mixer_from_playable(playable)?;
        let sound_id = self
            .engine
            .play_mixer_realtime(&mixer)
            .map_err(playback_error)?;
        Ok(PulsePlaybackHandle::from_parts(
            Rc::clone(&self.engine),
            sound_id,
        ))
    }

    /// Starts looping playback and returns a handle for later control.
    ///
    /// # Errors
    ///
    /// Returns an error when mixer creation or playback scheduling fails.
    pub fn play_looping(&self, playable: PulsePlayable<'_>) -> PulseResult<PulsePlaybackHandle> {
        let mixer = mixer_from_playable(playable)?;
        let sound_id = self.engine.play_looping(&mixer).map_err(playback_error)?;
        Ok(PulsePlaybackHandle::from_parts(
            Rc::clone(&self.engine),
            sound_id,
        ))
    }

    /// Plays a target with a playback-rate multiplier.
    ///
    /// # Errors
    ///
    /// Returns an error when `rate` is invalid or playback fails.
    pub fn play_at_rate(&self, playable: PulsePlayable<'_>, rate: f32) -> PulseResult<()> {
        let rate = validate_playback_rate(rate)?;
        let mixer = mixer_from_playable(playable)?;
        self.engine
            .play_mixer_at_rate(&mixer, rate)
            .map_err(playback_error)
    }

    /// Starts real-time playback with a playback-rate multiplier.
    ///
    /// # Errors
    ///
    /// Returns an error when `rate` is invalid or playback fails.
    pub fn play_realtime_at_rate(
        &self,
        playable: PulsePlayable<'_>,
        rate: f32,
    ) -> PulseResult<PulsePlaybackHandle> {
        let rate = validate_playback_rate(rate)?;
        let mixer = mixer_from_playable(playable)?;
        let sound_id = self
            .engine
            .play_mixer_realtime_at_rate(&mixer, rate)
            .map_err(playback_error)?;
        Ok(PulsePlaybackHandle::from_parts(
            Rc::clone(&self.engine),
            sound_id,
        ))
    }
}

impl PulsePlaybackHandle {
    /// Creates a handle from an engine reference and `tunes` sound identifier.
    #[must_use]
    pub fn from_parts(engine: Rc<AudioEngine>, sound_id: SoundId) -> Self {
        Self { engine, sound_id }
    }

    /// Returns the underlying `tunes` sound identifier.
    #[must_use]
    pub fn sound_id(&self) -> SoundId {
        self.sound_id
    }

    /// Stops playback and returns a cloned handle for Lua chainability.
    ///
    /// # Errors
    ///
    /// Returns an error when the engine rejects the stop request.
    pub fn stop(&self) -> PulseResult<Self> {
        self.engine.stop(self.sound_id).map_err(playback_error)?;
        Ok(self.clone())
    }

    /// Sets playback volume and returns a cloned handle for Lua chainability.
    ///
    /// # Errors
    ///
    /// Returns an error when `volume` is invalid or the engine rejects the request.
    pub fn volume(&self, volume: f32) -> PulseResult<Self> {
        let volume = validate_playback_volume(volume)?;
        self.engine
            .set_volume(self.sound_id, volume)
            .map_err(playback_error)?;
        Ok(self.clone())
    }

    /// Sets playback stereo pan and returns a cloned handle for Lua chainability.
    ///
    /// # Errors
    ///
    /// Returns an error when `pan` is invalid or the engine rejects the request.
    pub fn pan(&self, pan: f32) -> PulseResult<Self> {
        let pan = validate_playback_pan(pan)?;
        self.engine
            .set_pan(self.sound_id, pan)
            .map_err(playback_error)?;
        Ok(self.clone())
    }

    /// Sets playback rate and returns a cloned handle for Lua chainability.
    ///
    /// # Errors
    ///
    /// Returns an error when `rate` is invalid or the engine rejects the request.
    pub fn rate(&self, rate: f32) -> PulseResult<Self> {
        let rate = validate_playback_rate(rate)?;
        self.engine
            .set_playback_rate(self.sound_id, rate)
            .map_err(playback_error)?;
        Ok(self.clone())
    }

    /// Pauses playback and returns a cloned handle for Lua chainability.
    ///
    /// # Errors
    ///
    /// Returns an error when the engine rejects the pause request.
    pub fn pause(&self) -> PulseResult<Self> {
        self.engine.pause(self.sound_id).map_err(playback_error)?;
        Ok(self.clone())
    }

    /// Resumes playback and returns a cloned handle for Lua chainability.
    ///
    /// # Errors
    ///
    /// Returns an error when the engine rejects the resume request.
    pub fn resume(&self) -> PulseResult<Self> {
        self.engine.resume(self.sound_id).map_err(playback_error)?;
        Ok(self.clone())
    }
}

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

    #[test]
    fn playback_rate_rejects_zero_negative_and_non_finite_values() {
        assert_eq!(
            validate_playback_rate(0.0)
                .expect_err("zero rate should fail")
                .to_string(),
            "invalid playback rate: 0"
        );
        assert_eq!(
            validate_playback_rate(-1.0)
                .expect_err("negative rate should fail")
                .to_string(),
            "invalid playback rate: -1"
        );
        assert_eq!(
            validate_playback_rate(f32::NAN)
                .expect_err("NaN rate should fail")
                .to_string(),
            "invalid playback rate: NaN"
        );
        assert_eq!(validate_playback_rate(1.25).unwrap(), 1.25);
    }

    #[test]
    fn playback_volume_accepts_unit_range_only() {
        assert_eq!(validate_playback_volume(0.0).unwrap(), 0.0);
        assert_eq!(validate_playback_volume(1.0).unwrap(), 1.0);
        assert_eq!(
            validate_playback_volume(1.5)
                .expect_err("too-loud volume should fail")
                .to_string(),
            "invalid playback volume: 1.5"
        );
        assert_eq!(
            validate_playback_volume(f32::INFINITY)
                .expect_err("infinite volume should fail")
                .to_string(),
            "invalid playback volume: inf"
        );
    }

    #[test]
    fn playback_pan_accepts_stereo_range_only() {
        assert_eq!(validate_playback_pan(-1.0).unwrap(), -1.0);
        assert_eq!(validate_playback_pan(1.0).unwrap(), 1.0);
        assert_eq!(
            validate_playback_pan(2.0)
                .expect_err("pan outside stereo range should fail")
                .to_string(),
            "invalid playback pan: 2"
        );
        assert_eq!(
            validate_playback_pan(f32::NEG_INFINITY)
                .expect_err("non-finite pan should fail")
                .to_string(),
            "invalid playback pan: -inf"
        );
    }

    #[test]
    fn playback_handle_exposes_sound_id() {
        let engine = Rc::new(AudioEngine::new().expect("audio engine should initialize"));
        let handle = PulsePlaybackHandle::from_parts(engine, 42);

        assert_eq!(handle.sound_id(), 42);
    }

    #[test]
    fn playable_song_builds_a_mixer_without_playing_audio() {
        let song = PulseSong::new();

        let mixer = mixer_from_playable(PulsePlayable::Song(&song));

        assert!(mixer.is_ok());
    }

    #[test]
    fn playable_imported_midi_clones_its_mixer_without_playing_audio() {
        let imported = PulseImportedMidi::new(Mixer::new(Tempo::new(120.0)));

        let mixer = mixer_from_playable(PulsePlayable::ImportedMidi(&imported));

        assert!(mixer.is_ok());
    }

    #[test]
    fn playable_song_preserves_master_effects_in_mixer() {
        let effect =
            crate::effects::effect_from_options("eq", crate::effects::EffectOptions::Default)
                .expect("default eq should parse");
        let song = PulseSong::new().with_master_effect(effect);

        let mixer = mixer_from_playable(PulsePlayable::Song(&song))
            .expect("song with master effect should build mixer");

        assert!(mixer.master.eq.is_some());
    }

    #[test]
    fn playback_engine_can_be_constructed_without_playing_audio() {
        let engine = PulsePlaybackEngine::new();

        assert!(engine.is_ok());
    }

    #[test]
    fn handle_control_methods_validate_arguments_before_forwarding() {
        let engine = Rc::new(AudioEngine::new().expect("audio engine should initialize"));
        let handle = PulsePlaybackHandle::from_parts(engine, 99);

        assert_eq!(
            handle
                .volume(1.5)
                .expect_err("invalid volume should fail before engine call")
                .to_string(),
            "invalid playback volume: 1.5"
        );
        assert_eq!(
            handle
                .pan(2.0)
                .expect_err("invalid pan should fail before engine call")
                .to_string(),
            "invalid playback pan: 2"
        );
        assert_eq!(
            handle
                .rate(0.0)
                .expect_err("invalid rate should fail before engine call")
                .to_string(),
            "invalid playback rate: 0"
        );
    }

    #[test]
    fn engine_rate_methods_validate_arguments_before_playing() {
        let engine = PulsePlaybackEngine::new().expect("playback engine should initialize");
        let song = PulseSong::new();

        assert_eq!(
            engine
                .play_at_rate(PulsePlayable::Song(&song), 0.0)
                .expect_err("invalid rate should fail before playback")
                .to_string(),
            "invalid playback rate: 0"
        );
        assert_eq!(
            engine
                .play_realtime_at_rate(PulsePlayable::Song(&song), f32::INFINITY)
                .expect_err("invalid rate should fail before playback")
                .to_string(),
            "invalid playback rate: inf"
        );
    }

    #[test]
    fn playback_handle_invalid_controls_are_chainable_lua_methods() {
        let lua = mlua::Lua::new();
        let engine = Rc::new(AudioEngine::new().expect("audio engine should initialize"));
        let handle = PulsePlaybackHandle::from_parts(engine, 7);

        lua.globals().set("handle", handle).unwrap();
        lua.load(
            r#"
            assert(type(handle.stop) == "function")
            assert(type(handle.volume) == "function")
            assert(type(handle.pan) == "function")
            assert(type(handle.rate) == "function")
            assert(type(handle.pause) == "function")
            assert(type(handle.resume) == "function")

            local ok_volume = pcall(function()
              handle:volume(1.5)
            end)
            assert(ok_volume == false)

            local ok_pan = pcall(function()
              handle:pan(2)
            end)
            assert(ok_pan == false)

            local ok_rate = pcall(function()
              handle:rate(0)
            end)
            assert(ok_rate == false)
            "#,
        )
        .exec()
        .expect("handle methods should be visible and validate before engine calls");
    }
}