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
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::slice;
use crate::structures::{EmuType, EmuHandle, GmeError, GmeVoidResult, GmeHandleResult};
use std::fs::File;
use std::io::Read;
use std::path::Path;

pub(crate) fn delete(handle: &EmuHandle) {
    unsafe { gme_delete(handle.to_raw()); }
}

/// Determine likely `EmuType` based on first four bytes of file.
pub fn identify_header(buffer: &[u8]) -> EmuType {
    unsafe {
        EmuType::from_extension(&CStr::from_ptr(gme_identify_header(buffer.as_ptr())).to_str()
            .unwrap().to_string())
    }
}

/// Load music file from memory into emulator. Makes a copy of data passed.
pub fn load_data(handle: &EmuHandle, data: &[u8]) -> GmeVoidResult {
    unsafe {
        let mut emu_ptr: *const MusicEmu = std::ptr::null_mut();
        process_result(gme_load_data(handle.to_raw(), data.as_ptr(), data.len()))
    }
}

/// Load music file into emulator
pub fn load_file(handle: &EmuHandle, path: impl AsRef<Path>) -> GmeVoidResult {
    let buffer = get_file_data(path);
    load_data(handle, &buffer)
}

/// Creates an `EmuHandle` with the specified `EmuType`
pub fn new_emu(emu_type: EmuType, sample_rate: u32) -> EmuHandle {
    unsafe {
        let cstring = CString::new(emu_type.to_extension()).unwrap();
        let gme_type = gme_identify_extension(cstring.as_ptr());
        let music_emu = gme_new_emu(gme_type, sample_rate as i32);
        EmuHandle::new(music_emu)
    }
}


/// Creates a new `EmuHandle` and loads it with `data`. Makes a copy of the data.
pub fn open_data(data: &[u8], sample_rate: u32) -> GmeHandleResult {
    let emu_type = identify_header(data);
    let handle = new_emu(emu_type, sample_rate);
    let error = load_data(&handle, data);
    if error.is_ok() { Ok(handle) } else { Err(error.err().unwrap()) }
}

/// Creates a new `EmuHandle` and loads it with the file at the specified path
pub fn open_file(path: impl AsRef<Path>, sample_rate: u32) -> GmeHandleResult {
    let buffer = get_file_data(path);
    open_data(&buffer, sample_rate)
}

/// Generate `count` 16-bit signed samples into `buffer`. Output is in stereo.
pub fn play(handle: &EmuHandle, count: usize, buffer: &mut [i16]) -> GmeVoidResult {
    unsafe { process_result(gme_play(handle.to_raw(), count as i32, buffer.as_mut_ptr())) }
}

/// Start a track, where 0 is the first track
pub fn start_track(handle: &EmuHandle, index: u32) -> GmeVoidResult {
    unsafe { process_result(gme_start_track(handle.to_raw(), index as i32)) }
}

/// Number of milliseconds played since beginning of track
pub fn tell(handle: &EmuHandle) -> u32 {
    unsafe {gme_tell(handle.to_raw()) as u32}
}

/// Number of tracks available
pub fn track_count(handle: &EmuHandle) -> usize {
    unsafe { gme_track_count(handle.to_raw()) as usize }
}

/// True if track ended
pub fn track_ended(handle: &EmuHandle) -> bool {
    unsafe { gme_track_ended(handle.to_raw()) }
}

/// Returns all of the supported `EmuTypes`. This is based on the features the crate is compiled
/// with.
pub fn type_list() -> Vec<EmuType> {
    let mut types = Vec::new();
    unsafe {
        let mut p = gme_type_list();
        while *p != std::ptr::null() {
            let gme_type = p.clone().read();
            let extension = CStr::from_ptr((*gme_type).extension).to_str().unwrap();
            types.push(EmuType::from_extension(extension));
            p = p.offset(1);
        }
    }
    types
}

fn process_result(result: *const c_char) -> GmeVoidResult {
    if result.is_null() {
        Ok(())
    } else {
        unsafe { Err(GmeError::new(CStr::from_ptr(result).to_str().unwrap().to_string())) }
    }
}

pub(crate) fn get_file_data(path: impl AsRef<Path>) -> Vec<u8> {
    let mut file = File::open(path).unwrap();
    let mut buffer = Vec::new();
    file.read_to_end(&mut buffer).unwrap();
    buffer
}

#[repr(C)]
#[derive(Clone)]
pub struct MusicEmu { _private: isize }

// gme_type_t_ is struct
// gme_type_t holds pointer to other
#[repr(C)]
pub struct gme_type_t_struct {
    /// name of system this music file type is generally for
    pub system: *const c_char,
    /// non-zero for formats with a fixed number of tracks
    track_count: i32,
    /// Create new emulator for this type (useful in C++ only)
    new_emu: *const isize,
    /// Create new info reader for this type
    new_info: *const isize,

    pub extension: *const c_char,
    /// internal
    flags: i32,
}

//#[derive(Debug, Copy, Clone)]
type gme_type_t = *const gme_type_t_struct;

extern {
    /// Finish using emulator and free memory
    fn gme_delete(emu: *const MusicEmu);

    /// Determine likely game music type based on first four bytes of file. Returns string
    /// containing proper file suffix (i.e. "NSF", "SPC", etc.) or "" if file header is not
    /// recognized.
    fn gme_identify_header(header: *const u8) -> *const c_char;

    /// Get corresponding music type for file path or extension passed in.
    fn gme_identify_extension(extension: *const c_char) -> *const gme_type_t;

    /// Load music file from memory into emulator. Makes a copy of data passed.
    fn gme_load_data(emu: *const MusicEmu, data: *const u8, size: usize) -> *const c_char;

    /// Generate `count` 16-bit signed samples into `buffer`. Output is in stereo.
    fn gme_play(emu: *const MusicEmu, count: i32, out: *mut i16) -> *const c_char;

    /// Create new emulator and set sample rate.
    fn gme_new_emu(gme_type: *const gme_type_t, sample_rate: i32) -> *const MusicEmu;

    /// Start a track, where 0 is the first track
    fn gme_start_track(emu: *const MusicEmu, index: i32) -> *const c_char;

    /// Number of milliseconds played since beginning of track
    fn gme_tell(emu: *const MusicEmu) -> i32;

    /// Number of tracks available
    fn gme_track_count(emu: *const MusicEmu) -> i32;

    /// True if a track has reached its end
    fn gme_track_ended(emu: *const MusicEmu) -> bool;

    /// Pointer to array of all music types, with NULL entry at end.
    fn gme_type_list() -> *const gme_type_t;
}

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

    #[test]
    fn test_get_types() {
        let types = type_list();
        assert!(types.len() > 1);
    }

    #[test]
    fn test_open_data() {
        let mut file = File::open("test.nsf").unwrap();
        let mut buffer = Vec::new();
        file.read_to_end(&mut buffer).unwrap();

        let handle = open_data(&buffer, 44100).ok().unwrap();
        assert_eq!(track_count(&handle), 1);
        start_track(&handle, 0);
    }

    #[test]
    fn test_open_file() {
        let handle = open_file("test.nsf", 44100).ok().unwrap();
        assert_eq!(track_count(&handle), 1);
        start_track(&handle, 0);
    }
}