From dfefe1c3fa92abdec713a40c1424bee05f504fad Mon Sep 17 00:00:00 2001 From: "Jakob L. Kreuze" Date: Thu, 31 May 2018 16:05:00 -0400 Subject: Initial commit. --- .gitignore | 4 + Cargo.toml | 14 +++ LICENSE | 165 +++++++++++++++++++++++++++++++++ README.md | 29 ++++++ build.rs | 7 ++ examples/player/.gitignore | 2 + examples/player/Cargo.toml | 8 ++ examples/player/src/main.rs | 66 +++++++++++++ src/lib.rs | 220 ++++++++++++++++++++++++++++++++++++++++++++ 9 files changed, 515 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 build.rs create mode 100644 examples/player/.gitignore create mode 100644 examples/player/Cargo.toml create mode 100644 examples/player/src/main.rs create mode 100644 src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a821aa9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ + +/target +**/*.rs.bk +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..72750e1 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,14 @@ +[workspace] +members = [ + "examples/player", +] + +[package] +name = "wildmidi" +version = "0.1.0" +authors = ["Jakob L. Kreuze "] +links = "WildMidi" +build = "build.rs" + +[dependencies] +simple-error = "0.1" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/README.md b/README.md new file mode 100644 index 0000000..726a6e2 --- /dev/null +++ b/README.md @@ -0,0 +1,29 @@ +This is a light Rust wrapper around the WildMIDI software synthesizer library. + + +# Examples + +Included in this repository is a binary project exposing a very basic MIDI +player - essentially a clone of wildmidi(1) that is missing a majority of the +features. + +``` +$ cd examples/player/ +$ cargo run /tmp/D_E1A1.MID +``` + + +# Tests + +The WildMIDI C library maintains some global state, so tests should **not** be +run in parallel. Running tests consecutively can be achieved by invoking +cargo-test as: + +``` +cargo test -- --test-threads=1 +``` + + +# TODO + +- [ ] Valid MIDI blob for use in testing 'load' and the methods of 'Midi'. diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..18b479c --- /dev/null +++ b/build.rs @@ -0,0 +1,7 @@ +fn link_wildmidi() { + println!("cargo:rustc-flags=-l WildMidi"); +} + +fn main() { + link_wildmidi(); +} diff --git a/examples/player/.gitignore b/examples/player/.gitignore new file mode 100644 index 0000000..53eaa21 --- /dev/null +++ b/examples/player/.gitignore @@ -0,0 +1,2 @@ +/target +**/*.rs.bk diff --git a/examples/player/Cargo.toml b/examples/player/Cargo.toml new file mode 100644 index 0000000..98b68b3 --- /dev/null +++ b/examples/player/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "wildmidi-player" +version = "0.1.0" +authors = ["Jakob L. Kreuze "] + +[dependencies] +ao_rs = "0.1.5" +wildmidi = { path = "../../", version = "0.1" } diff --git a/examples/player/src/main.rs b/examples/player/src/main.rs new file mode 100644 index 0000000..c52a06c --- /dev/null +++ b/examples/player/src/main.rs @@ -0,0 +1,66 @@ +// Copyright (C) 2018 Jakob L. Kreuze, All Rights Reserved. +// +// This file is part of wildmidi. +// +// wildmidi is free software: you can redistribute it and/or modify it under the +// terms of the GNU Lesser General Public License as published by the Free +// Software Foundation, either version 3 of the License, or (at your option) any +// later version. +// +// wildmidi 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 Lesser General Public License for more +// details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with wildmidi. If not, see . + +extern crate ao_rs as ao; +extern crate wildmidi; + +use std::env::args; +use std::mem::transmute; +use std::path::Path; +use std::process::exit; + +use ao::{Ao, Device, Driver, Format}; +use wildmidi::Player; + +fn main() { + let args: Vec = args().collect(); + + if args.len() != 2 { + println!("usage: {} [MIDI]", args[0]); + exit(1); + } + + let path = &args[1]; + + if !Path::new(&path).exists() { + println!("{} does not exist.", path); + exit(1); + } + + let player = Player::new(44100).unwrap(); + let mut midi = player.load_file(&path).unwrap(); + + let _ao = Ao::new(); + let driver = Driver::new().unwrap(); + let format = Format::new(); + let device = Device::new(&driver, &format, None).unwrap(); + + loop { + // It would simply be too slow to do a safe conversion every time we + // buffer the PCM output. + let vec = midi.play(4096); + let pcm = unsafe { + transmute::<&[u8], &[i8]>(&vec[..]) + }; + + if pcm.len() <= 0 { + break; + } + + device.play(&pcm[..] as &[i8]); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..436bcbe --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,220 @@ +// Copyright (C) 2018 Jakob L. Kreuze, All Rights Reserved. +// +// This file is part of wildmidi. +// +// wildmidi is free software: you can redistribute it and/or modify it under the +// terms of the GNU Lesser General Public License as published by the Free +// Software Foundation, either version 3 of the License, or (at your option) any +// later version. +// +// wildmidi 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 Lesser General Public License for more +// details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with wildmidi. If not, see . + +#[macro_use] +extern crate simple_error; + +use std::error::Error; +use std::ffi::CString; +use std::os::raw::{c_char, c_uchar, c_ushort, c_int, c_ulong, c_void}; +use std::path::Path; + +extern "C" { + // "Methods" of the Midi player. + fn WildMidi_Init(cfg: *const c_char, rate: c_ushort, flags: c_ushort) -> c_int; + fn WildMidi_Open(path: *const c_char) -> *const c_void; + fn WildMidi_OpenBuffer(data: *const c_uchar, size: c_ulong) -> *const c_void; + // fn WildMidi_SetOption(); + fn WildMidi_MasterVolume(volume: c_uchar) -> c_int; + fn WildMidi_Shutdown(); + + // "Methods" of the individual Midi handles. + fn WildMidi_Close(ptr: *const c_void) -> c_int; + fn WildMidi_FastSeek(ptr: *const c_void, pos: c_ushort) -> c_int; + fn WildMidi_GetOutput(ptr: *const c_void, buf: *mut c_uchar, len: c_ulong) -> c_int; +} + +/// Loader for the Midi format. +pub struct Player; + +impl Player { + fn locate_cfg() -> Option<&'static str> { + let paths = vec![ + "/etc/wildmidi/wildmidi.cfg", + "/etc/wildmidi.cfg" + ]; + + for path in paths.iter() { + if Path::new(path).exists() { + return Some(path); + } + } + + None + } + + /// Create a new Player with the given sample rate, using the default + /// configuration file. + /// + /// # Errors + /// + /// Will fail if 'rate' is not on the interval [11025,65535], or if neither + /// of the default configuration files exist ('/etc/wildmidi/wildmidi.cfg', + /// '/etc/wildmidi.cfg'). + pub fn new(rate: u16) -> Result> { + let cfg = match Player::locate_cfg() { + Some(cfg) => cfg, + None => bail!("No valid configuration file found"), + }; + + Player::with_cfg(cfg, rate) + } + + /// Create a new Player with the given config path and sample rate. + /// + /// # Errors + /// + /// Will fail if 'rate' is not on the interval [11025,65535]. + pub fn with_cfg(cfg: &str, rate: u16) -> Result> { + let cfg = CString::new(cfg)?; + + unsafe { + // WildMidi_Shutdown(); + if WildMidi_Init(cfg.as_ptr(), rate, 0) != 0 { + bail!("Couldn't initialize WildMidi."); + } + } + + Ok(Player { }) + } + + // TODO: Document this. + pub fn volume(&mut self, volume: u8) -> Result<(), Box> { + unsafe { + if WildMidi_MasterVolume(volume) != 0 { + bail!("Couldn't set volume."); + } + } + + Ok(()) + } + + /// Loads a Midi file from memory. + /// + /// # Errors + /// + /// Will fail if an internal error occurs in WildMidi (such as a parse + /// error). + pub fn load(&self, data: &[u8]) -> Result> { + unsafe { + let len = data.len() as c_ulong; + let ptr = WildMidi_OpenBuffer(data.as_ptr(), len); + + if !ptr.is_null() { + return Ok(Midi::new(ptr)); + } + } + + bail!("Failed to open Midi file.") + } + + /// Loads a Midi file from disk. + /// + /// # Errors + /// + /// Will fail if the file does not exist, or if an internal error occurs in + /// WildMidi (such as a parse error). + pub fn load_file(&self, path: &str) -> Result> { + if !Path::new(path).exists() { + bail!("File does not exist"); + } + + let path = CString::new(path)?; + + unsafe { + let ptr = WildMidi_Open(path.as_ptr()); + + if !ptr.is_null() { + return Ok(Midi::new(ptr)); + } + } + + bail!("Failed to open Midi file.") + } +} + +impl Drop for Player { + fn drop(&mut self) { + unsafe { + WildMidi_Shutdown(); + } + } +} + +/// An actual Midi file, capable of producing a PCM output. +pub struct Midi { + ptr: *const c_void, +} + +impl Midi { + fn new(ptr: *const c_void) -> Midi { + Midi { ptr } + } + + /// Returns a Vec containing 'len' bytes of PCM data. + pub fn play(&mut self, len: usize) -> Vec { + let mut vec = vec![0;len]; + + unsafe { + let buf = vec.as_mut_ptr(); + let handle = self.ptr; + let read = WildMidi_GetOutput(handle, buf, len as c_ulong) as usize; + + if read < len { + vec.resize(read, 0); + } + } + + vec + } + + // TODO: Document this. + pub fn seek(&mut self, pos: u32) { + unsafe { + // FIXME: Doesn't check return value. + WildMidi_FastSeek(self.ptr, pos as c_ushort); + } + } +} + +impl Drop for Midi { + fn drop(&mut self) { + unsafe { + // There isn't much of a point in handling errors here. + WildMidi_Close(self.ptr); + } + } +} + +#[cfg(test)] +mod player_tests { + use ::*; + + #[test] + fn create() { + if let Err(e) = Player::new(44100) { + panic!("{}", e); + } + } + + #[test] + fn invalid_rate() { + if let Ok(_) = Player::new(0) { + panic!("Allowed player to be created with invalid rate."); + } + } +} -- cgit v1.3