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
//! Rust bindings to [`libxm`], a small XM player library.
//!
//! Start from [`Context`] struct documentation.
//!
//! [`libxm`]: https://github.com/Artefact2/libxm
//! [`Context`]: Context
//!
//! ## Feature flags:
//! - `defensive`: enables defensively checking the XM for errors/inconsistencies.
//! - `linear_interpolation`: enables linear interpolation (slightly increase CPU usage).
//! - `ramping`: enables ramping (smooth volume/panning transitions, slightly increase CPU usage).
//! - `strings`: enables module, instruments and sample names storing in context.

use std::{ffi::CStr, mem::MaybeUninit};

pub mod ffi;
use ffi::*;

/// Module context.
///
/// Can contain only one module and provides functions for manipulating it.
pub struct Context(InnerContext);

unsafe impl Send for Context {}
unsafe impl Sync for Context {}

impl Context {
    /// Create a context.
    ///
    /// The `module` parameter sets a contents of the module.
    /// The `rate` parameter specifies a sample rate (in Hz) with which samples will be generated.
    ///
    /// # Example
    /// ```no_run
    /// use exmod::Context;
    ///
    /// let context = Context::new(include_bytes!("module.xm"), 44100).unwrap();
    /// ```
    pub fn new(module: &[u8], rate: u32) -> Result<Self, ContextError> {
        let mut pointer = MaybeUninit::uninit();
        unsafe {
            match xm_create_context_safe(
                pointer.as_mut_ptr(),
                module.as_ptr() as _,
                module.len(),
                rate,
            ) {
                0 => Ok(Self::from_ptr(pointer.assume_init())),
                #[cfg(feature = "defensive")]
                1 => Err(ContextError::ModuleNotSane),
                2 => Err(ContextError::MemoryAllocFailed),
                unknown => Err(ContextError::Unknown(unknown)),
            }
        }
    }

    /// Returns a raw pointer to the inner context.
    pub fn as_ptr(&mut self) -> InnerContext {
        self.0
    }

    /// Creates a context directly from the raw pointer of another context.
    ///
    /// # Safety
    /// Pointer must be previously allocated via [`new`] function or it's equivalent - [`xm_create_context_safe`].
    ///
    /// [`new`]: Self::new
    /// [`xm_create_context_safe`]: xm_create_context_safe
    pub unsafe fn from_ptr(pointer: InnerContext) -> Self {
        Self(pointer)
    }

    /// Play the module and put a generated sample in the `output` slice.
    ///
    /// Requires mutability because generating samples moves a playback cursor within context.
    ///
    /// Create silence if the end of the module or the specified [`loop count`] is reached.
    ///
    /// [`loop count`]: Self::loop_count
    ///
    /// See `examples` crate folder for comprehensive example.
    pub fn generate_sample(&mut self, output: &mut [f32]) {
        unsafe { xm_generate_samples(self.0, output.as_mut_ptr(), output.len() / 2) }
    }

    /// Get the current number of playback loops of the module.
    ///
    /// The number will increase with each loop. When the maximum number of loops is reached,
    /// calls to [`generate_sample`] will only generate silence. You can set number of
    /// loops with [`set_max_loop_count`].
    ///
    /// [`generate_sample`]: Self::generate_sample
    /// [`set_max_loop_count`]: Self::set_max_loop_count
    pub fn loop_count(&self) -> u8 {
        unsafe { xm_get_loop_count(self.0) }
    }

    /// Set the max number of playback loops of the module.
    /// See also [`loop_count`].
    ///
    /// [`loop_count`]: Self::loop_count
    pub fn set_max_loop_count(&mut self, count: u8) {
        unsafe { xm_set_max_loop_count(self.0, count) }
    }

    /// Get the number of module channels.
    pub fn number_of_channels(&self) -> u16 {
        unsafe { xm_get_number_of_channels(self.0) }
    }

    /// Get the module length.
    pub fn module_length(&self) -> u16 {
        unsafe { xm_get_module_length(self.0) }
    }

    /// Get the number of module patterns.
    pub fn number_of_patterns(&self) -> u16 {
        unsafe { xm_get_number_of_patterns(self.0) }
    }

    /// Get the number of module rows.
    pub fn number_of_rows(&self, pattern: u16) -> Result<u16, OutOfBoundsError> {
        if pattern > self.number_of_patterns() {
            Err(OutOfBoundsError::Patterns)
        } else {
            unsafe { Ok(xm_get_number_of_rows(self.0, pattern)) }
        }
    }

    /// Get the number of module instruments.
    pub fn number_of_instruments(&self) -> u16 {
        unsafe { xm_get_number_of_instruments(self.0) }
    }

    /// Get the number of module samples.
    pub fn number_of_samples(&self, instrument: u16) -> Result<u16, OutOfBoundsError> {
        if instrument > self.number_of_instruments() {
            Err(OutOfBoundsError::Instruments)
        } else {
            unsafe { Ok(xm_get_number_of_samples(self.0, instrument)) }
        }
    }

    /// Get the panning of specific channel.
    pub fn panning_of_channel(&self, channel: u16) -> Result<f32, OutOfBoundsError> {
        if channel > self.number_of_channels() {
            Err(OutOfBoundsError::Channels)
        } else {
            unsafe { Ok(xm_get_panning_of_channel(self.0, channel)) }
        }
    }

    /// Get the volume of specific channel.
    pub fn volume_of_channel(&self, channel: u16) -> Result<f32, OutOfBoundsError> {
        if channel > self.number_of_channels() {
            Err(OutOfBoundsError::Channels)
        } else {
            unsafe { Ok(xm_get_volume_of_channel(self.0, channel)) }
        }
    }

    /// Get the frequency of specific channel.
    pub fn frequency_of_channel(&self, channel: u16) -> Result<f32, OutOfBoundsError> {
        if channel > self.number_of_channels() {
            Err(OutOfBoundsError::Channels)
        } else {
            unsafe { Ok(xm_get_frequency_of_channel(self.0, channel)) }
        }
    }

    /// Check if the channel is active.
    pub fn is_channel_active(&self, channel: u16) -> Result<bool, OutOfBoundsError> {
        if channel > self.number_of_channels() {
            Err(OutOfBoundsError::Channels)
        } else {
            unsafe { Ok(xm_is_channel_active(self.0, channel)) }
        }
    }

    /// Get the latest trigger of specific instrument.
    pub fn latest_trigger_of_instrument(&self, instrument: u16) -> Result<u64, OutOfBoundsError> {
        if instrument > self.number_of_instruments() {
            Err(OutOfBoundsError::Instruments)
        } else {
            unsafe { Ok(xm_get_latest_trigger_of_instrument(self.0, instrument)) }
        }
    }

    /// Get the latest trigger of specific sample.
    pub fn latest_trigger_of_sample(
        &self,
        instrument: u16,
        sample: u16,
    ) -> Result<u64, OutOfBoundsError> {
        if let Ok(samples) = self.number_of_samples(instrument) {
            if sample > samples {
                Err(OutOfBoundsError::Samples)
            } else {
                unsafe { Ok(xm_get_latest_trigger_of_sample(self.0, instrument, sample)) }
            }
        } else {
            Err(OutOfBoundsError::Instruments)
        }
    }

    /// Get the latest trigger of specific channel.
    pub fn latest_trigger_of_channel(&self, channel: u16) -> Result<u64, OutOfBoundsError> {
        if channel > self.number_of_channels() {
            Err(OutOfBoundsError::Channels)
        } else {
            unsafe { Ok(xm_get_latest_trigger_of_channel(self.0, channel)) }
        }
    }

    /// Get the module playing speed.
    pub fn playing_speed(&self) -> Speed {
        let (mut bpm, mut tempo) = (MaybeUninit::uninit(), MaybeUninit::uninit());
        unsafe {
            xm_get_playing_speed(self.0, bpm.as_mut_ptr(), tempo.as_mut_ptr());
            Speed {
                bpm: bpm.assume_init(),
                tempo: tempo.assume_init(),
            }
        }
    }

    /// Get the current playback position.
    pub fn position(&self) -> Position {
        let mut pattern_index = MaybeUninit::uninit();
        let mut pattern = MaybeUninit::uninit();
        let mut row = MaybeUninit::uninit();
        let mut generated_samples = MaybeUninit::uninit();
        unsafe {
            xm_get_position(
                self.0,
                pattern_index.as_mut_ptr(),
                pattern.as_mut_ptr(),
                row.as_mut_ptr(),
                generated_samples.as_mut_ptr(),
            );
            Position {
                pattern_index: pattern_index.assume_init(),
                pattern: pattern.assume_init(),
                row: row.assume_init(),
                generated_samples: generated_samples.assume_init(),
            }
        }
    }

    /// Mute the specific channel.
    pub fn mute_channel(&mut self, channel: u16, mute: bool) -> Result<bool, OutOfBoundsError> {
        if channel > self.number_of_channels() {
            Err(OutOfBoundsError::Channels)
        } else {
            unsafe { Ok(xm_mute_channel(self.0, channel, mute)) }
        }
    }

    /// Mute the specific instrument.
    pub fn mute_instrument(
        &mut self,
        instrument: u16,
        mute: bool,
    ) -> Result<bool, OutOfBoundsError> {
        if instrument > self.number_of_instruments() {
            Err(OutOfBoundsError::Instruments)
        } else {
            unsafe { Ok(xm_mute_instrument(self.0, instrument, mute)) }
        }
    }

    /// Seek the playback cursor to the specified position.
    ///
    /// # Safety
    /// Seek feature is broken by design and usually leads to access violation error, use at your own risk.
    pub unsafe fn seek(&mut self, pattern_index: u8, row: u8, tick: u16) {
        xm_seek(self.0, pattern_index, row, tick)
    }
}

#[cfg(feature = "strings")]
impl Context {
    /// Get the module name.
    ///
    /// # Safety
    /// The library relies that the module name will be encoded in UTF-8. If not, UB or invalid string is possible.
    pub unsafe fn module_name(&self) -> String {
        CStr::from_ptr(xm_get_module_name(self.0))
            .to_string_lossy()
            .trim_end_matches(' ')
            .into()
    }

    /// Get the the name of the tracker in which the module was created.
    ///
    /// # Safety
    /// The library relies that the tracker name will be encoded in UTF-8. If not, UB or invalid string is possible.
    pub unsafe fn tracker_name(&self) -> String {
        CStr::from_ptr(xm_get_tracker_name(self.0))
            .to_string_lossy()
            .trim_end_matches(' ')
            .into()
    }
}

impl Drop for Context {
    fn drop(&mut self) {
        unsafe { xm_free_context(self.0) }
    }
}

/// Module playback speed.
#[derive(Debug)]
pub struct Speed {
    pub bpm: u16,
    pub tempo: u16,
}

/// Module playback position.
#[derive(Debug)]
pub struct Position {
    pub pattern_index: u8,
    pub pattern: u8,
    pub row: u8,
    pub generated_samples: u64,
}

/// Context creation error.
#[derive(Debug)]
pub enum ContextError {
    #[cfg(feature = "defensive")]
    /// Module sanity error.
    ModuleNotSane,
    /// Error of memory allocation for module.
    MemoryAllocFailed,
    Unknown(i32),
}

/// Error of out of bounds.
#[derive(Debug)]
pub enum OutOfBoundsError {
    Patterns,
    Instruments,
    Channels,
    Samples,
}