diff --git a/Cargo.toml b/Cargo.toml index 31d80ed..43aa2dc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,4 +31,7 @@ path = "src/examples/record/main.rs" [[bin]] name = "simple_player" -path = "src/examples/simple_player/main.rs" \ No newline at end of file +path = "src/examples/simple_player/main.rs" + +[dependencies] +libc = "*" \ No newline at end of file diff --git a/src/audio_controller.rs b/src/audio_controller.rs index 39ca2ba..dc22a40 100644 --- a/src/audio_controller.rs +++ b/src/audio_controller.rs @@ -183,7 +183,7 @@ pub trait AudioController { * * `position` - A three dimensional vector of f32 containing the * position of the listener [x, y, z]. */ - fn set_position(&mut self, position: [f32, ..3]) -> (); + fn set_position(&mut self, position: [f32; 3]) -> (); /** * Get the position of the Audio Source in three dimensional space. @@ -192,7 +192,7 @@ pub trait AudioController { * A three dimensional vector of f32 containing the position of the * listener [x, y, z]. */ - fn get_position(&self) -> [f32, ..3]; + fn get_position(&self) -> [f32; 3]; /** * Set the direction of the Audio Source. @@ -204,7 +204,7 @@ pub trait AudioController { * # Argument * `direction` - The new direction of the Audio Source. */ - fn set_direction(&mut self, direction: [f32, ..3]) -> (); + fn set_direction(&mut self, direction: [f32; 3]) -> (); /** * Get the direction of the Audio Source. @@ -212,7 +212,7 @@ pub trait AudioController { * # Return * The current direction of the Audio Source. */ - fn get_direction(&self) -> [f32, ..3]; + fn get_direction(&self) -> [f32; 3]; /** * Set the maximum distance of the Audio Source. diff --git a/src/audio_tags.rs b/src/audio_tags.rs index 48902dd..9c8885a 100644 --- a/src/audio_tags.rs +++ b/src/audio_tags.rs @@ -40,7 +40,7 @@ use sndfile::StringSoundType::{ * * If the tags doesn't exist in the sound file, the string is "". */ -#[deriving(Clone, Show, PartialEq)] +#[derive(Clone, Debug, PartialEq)] pub struct Tags { /// The title of the sound as a String pub title: String, diff --git a/src/ears.rs b/src/ears.rs index 426078b..f233044 100644 --- a/src/ears.rs +++ b/src/ears.rs @@ -90,13 +90,18 @@ use ears::Music; */ #![crate_name = "ears"] -#![desc = "Easy Api in Rust for Sounds"] -#![license = "MIT"] +//#![desc = "Easy Api in Rust for Sounds"] +//#![license = "MIT"] #![crate_type = "dylib"] #![crate_type = "rlib"] #![allow(dead_code, unused_attributes)] -#![feature(macro_rules)] -#![feature(unsafe_destructor)] +//#![feature(macro_rules)] +//#![feature(unsafe_destructor)] + +#![allow(unused_imports)] +//#![allow(raw_pointer_derive)] +#![allow(unused_must_use)] +//#![allow(improper_ctypes)] extern crate libc; diff --git a/src/examples/many_sounds/main.rs b/src/examples/many_sounds/main.rs index a25c4b4..8bb7a78 100644 --- a/src/examples/many_sounds/main.rs +++ b/src/examples/many_sounds/main.rs @@ -23,9 +23,8 @@ extern crate ears; -use std::io::timer::sleep; -use std::time::Duration; -use std::task; +use std::thread::sleep_ms; +use std::thread; use ears::{Sound, AudioController}; @@ -33,19 +32,19 @@ fn main() -> () { // call ears_init() function to ensure that the ears context is not destroyed by a task. ears::init(); - let mut i = 0u; + let mut i = 0; while i < 20 { - task::spawn(proc() { + thread::spawn(|| { let mut snd2 = Sound::new("../res/shot.wav").expect("Error on Sound loading."); snd2.play(); while snd2.is_playing() {} }); i += 1; - sleep(Duration::milliseconds(150i64)); + sleep_ms(150); } // Wait until the last sound is played, the main task own the ears context, // so we should kepp it alive - sleep(Duration::milliseconds(900i64)); + sleep_ms(900); } \ No newline at end of file diff --git a/src/examples/record/main.rs b/src/examples/record/main.rs index f05db62..6641b81 100644 --- a/src/examples/record/main.rs +++ b/src/examples/record/main.rs @@ -23,8 +23,7 @@ extern crate ears; -use std::time::Duration; -use std::io::timer::sleep; +use std::thread::sleep_ms; fn main() -> () { // call ears_init() function to ensure that the ears context is not destroyed by a task. @@ -36,7 +35,7 @@ fn main() -> () { // Create a new Recorder using the RecordContext let mut recorder = ears::Recorder::new(ctxt); recorder.start(); - sleep(Duration::milliseconds(5000i64)); + sleep_ms(5000); recorder.stop(); match recorder.save_to_file("hello") { true => println!("Save okay !"), diff --git a/src/examples/simple_player/main.rs b/src/examples/simple_player/main.rs index 5e7f8e6..5b9dc23 100644 --- a/src/examples/simple_player/main.rs +++ b/src/examples/simple_player/main.rs @@ -24,7 +24,8 @@ extern crate ears; use std::io::stdin; -use std::io::stdio::flush; +use std::io::stdout; +use std::io::Write; use ears::{Music, AudioController}; use ears::State::{Playing, Stopped, Paused}; @@ -35,13 +36,20 @@ fn main() { let mut stdin = stdin(); print!("Insert the path to an audio file : "); - flush(); + stdout().flush().ok(); - let mut line = stdin.read_line().unwrap(); - unsafe { line.as_mut_vec().pop(); } + let mut line = String::new(); + stdin.read_line(&mut line).ok(); + loop { + match &line[line.len()-1..] { + "\n" => { line.pop(); () }, + "\r" => { line.pop(); () }, + _ => { break; }, + } + } // Try to create the music - let mut music = match Music::new(line.as_slice()) { + let mut music = match Music::new(&line[..]) { Some(music) => music, None => panic!("Cannot load the music.") }; @@ -52,12 +60,14 @@ fn main() { loop { // Make your choice println!("Commands :\n\tPlay : l\n\tPause : p\n\tStop : s\n\tExit : x\n"); - match stdin.read_line().unwrap().as_slice() { - "l\n" => music.play(), - "p\n" => music.pause(), - "s\n" => music.stop(), - "x\n" => { music.stop(); break; }, - _ => println!("Unknwon command.") + let mut cmd = String::new(); + stdin.read_line(&mut cmd).ok(); + match &cmd[..1] { + "l" => music.play(), + "p" => music.pause(), + "s" => music.stop(), + "x" => { music.stop(); break; }, + _ => println!("Unknwon command.") } match music.get_state() { Playing => println!("State : Playing"), diff --git a/src/init.rs b/src/init.rs index 1619df5..282cec3 100644 --- a/src/init.rs +++ b/src/init.rs @@ -79,6 +79,7 @@ mod test { use init; use init_in; + use std::thread; #[test] fn test_init_ears_OK() -> () { @@ -101,8 +102,8 @@ mod test { #[test] fn test_init_in_in_another_task_OK() -> () { init(); - spawn(proc() { + thread::spawn(move || { assert_eq!(init_in(), None) - }) + }); } } diff --git a/src/internal.rs b/src/internal.rs index 6ef881b..117375a 100644 --- a/src/internal.rs +++ b/src/internal.rs @@ -19,27 +19,28 @@ // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -//! Internal class to handle OpenAl context and device. +//! internal class to handle OpenAl context and device. //! //! Work as a Singleton, check_al_context must be called before each OpenAl object //! to be sure that the context is created. -#![macro_escape] -#![allow(raw_pointer_deriving)] +#![macro_use] +#![allow(raw_pointer_derive)] +use std::ffi::CString; use std::cell::RefCell; use std::ptr; use openal::ffi; use record_context; use record_context::RecordContext; -thread_local!(static AL_CONTEXT: RefCell> = RefCell::new(box OpenAlData::default())) +thread_local!(static AL_CONTEXT: RefCell> = RefCell::new(Box::new(OpenAlData::default()))); -#[deriving(Clone)] +#[derive(Clone)] pub struct OpenAlData { - pub al_context: *mut ffi::ALCcontext, - pub al_device: *mut ffi::ALCdevice, - pub al_capt_device: *mut ffi::ALCdevice + pub al_context: ffi::ALCcontextPtr, + pub al_device: ffi::ALCdevicePtr, + pub al_capt_device: ffi::ALCdevicePtr } impl OpenAlData { @@ -48,41 +49,41 @@ impl OpenAlData { /// Private method. fn new() -> Result { let device = unsafe { ffi::alcOpenDevice(ptr::null_mut()) }; - if device.is_null() { - return Err("Internal error: cannot open the default device.".to_string()); + if device == 0 { + return Err("internal error: cannot open the default device.".to_string()); } let context = unsafe { ffi::alcCreateContext(device, ptr::null_mut()) }; - if context.is_null() { - return Err("Internal error: cannot create the OpenAL context.".to_string()); + if context == 0 { + return Err("internal error: cannot create the OpenAL context.".to_string()); } if unsafe { ffi::alcMakeContextCurrent(context) } == ffi::ALC_FALSE { - return Err("Internal error: cannot make the OpenAL context current.".to_string()); + return Err("internal error: cannot make the OpenAL context current.".to_string()); } Ok( OpenAlData { al_context: context, al_device: device, - al_capt_device: ptr::null_mut() + al_capt_device: 0 } ) } fn default() -> OpenAlData { OpenAlData { - al_context: ptr::null_mut(), - al_device: ptr::null_mut(), - al_capt_device: ptr::null_mut() + al_context: 0, + al_device: 0, + al_capt_device: 0 } } fn is_default(&self) -> bool { - if self.al_context.is_null() && - self.al_device.is_null() && - self.al_capt_device.is_null() { - false - } else { + if self.al_context == 0 && + self.al_device == 0 && + self.al_capt_device == 0 { true + } else { + false } } @@ -96,7 +97,7 @@ impl OpenAlData { /// A result containing nothing if the OpenAlData struct exist, /// otherwise an error message. pub fn check_al_context() -> Result<(), String> { - if unsafe { ffi::alcGetCurrentContext().is_not_null() } { + if unsafe { ffi::alcGetCurrentContext() != 0 } { return Ok(()) } AL_CONTEXT.with(|f| { @@ -104,7 +105,7 @@ impl OpenAlData { if is_def { match OpenAlData::new() { Ok(al_data) => { - *f.borrow_mut() = box al_data; Ok(()) + *f.borrow_mut() = Box::new(al_data); Ok(()) }, Err(err) => Err(err) } @@ -120,11 +121,12 @@ impl OpenAlData { let is_def = f.borrow_mut().is_default(); if !is_def { let mut new_context = f.borrow_mut(); - if new_context.al_capt_device.is_not_null() { + if !new_context.al_capt_device == 0 { Ok(record_context::new(new_context.al_capt_device)) - } else { - if "ALC_EXT_CAPTURE".with_c_str(|c_str| unsafe { - ffi::alcIsExtensionPresent(new_context.al_device, c_str) }) == ffi::ALC_FALSE { + } else { + let c_str = CString::new("ALC_EXT_CAPTURE").unwrap(); + if unsafe { + ffi::alcIsExtensionPresent(new_context.al_device, c_str.as_ptr()) } == ffi::ALC_FALSE { return Err("Error: no input device available on your system.".to_string()) } else { new_context.al_capt_device = unsafe { @@ -132,8 +134,8 @@ impl OpenAlData { 44100, ffi::AL_FORMAT_MONO16, 44100) }; - if new_context.al_capt_device.is_null() { - return Err("Internal error: cannot open the default capture device.".to_string()) + if new_context.al_capt_device == 0 { + return Err("internal error: cannot open the default capture device.".to_string()) } else { let cap_device = new_context.al_capt_device; return Ok(record_context::new(cap_device)) @@ -159,7 +161,7 @@ impl OpenAlData { /// A result containing nothing if the OpenAlData struct exist, /// otherwise an error message. pub fn check_al_input_context() -> Result { - if unsafe { ffi::alcGetCurrentContext().is_not_null() } { + if unsafe { !ffi::alcGetCurrentContext() == 0 } { OpenAlData::is_input_context_init() } else { match OpenAlData::check_al_context() { @@ -174,7 +176,7 @@ impl Drop for OpenAlData { fn drop(&mut self) { unsafe { ffi::alcDestroyContext(self.al_context); - if self.al_capt_device.is_not_null() { + if !self.al_capt_device == 0 { ffi::alcCaptureCloseDevice(self.al_capt_device); } ffi::alcCloseDevice(self.al_device); @@ -189,4 +191,4 @@ macro_rules! check_openal_context( Err(err) => { println!("{}", err); return $def_ret; } } ); -) +); diff --git a/src/listener.rs b/src/listener.rs index 72e3aef..db2508a 100644 --- a/src/listener.rs +++ b/src/listener.rs @@ -86,7 +86,7 @@ pub fn get_volume() -> f32 { * # use ears::listener; * listener::set_position([45, 90, 35]); */ -pub fn set_position(position: [f32, ..3]) -> () { +pub fn set_position(position: [f32; 3]) -> () { check_openal_context!(()); al::alListenerfv(ffi::AL_POSITION, &position[0]); } @@ -105,10 +105,10 @@ pub fn set_position(position: [f32, ..3]) -> () { * println!("Listener position: {}", &pos); * ``` */ -pub fn get_position() -> [f32, ..3] { - check_openal_context!([0., ..3]); +pub fn get_position() -> [f32; 3] { + check_openal_context!([0.; 3]); - let mut position: [f32, ..3] = [0., ..3]; + let mut position: [f32; 3] = [0.; 3]; al::alGetListenerfv(ffi::AL_POSITION, &mut position[0]); position } @@ -128,9 +128,9 @@ pub fn get_position() -> [f32, ..3] { * listener::set_orientation([0.3f32, -0.4f32, 0.9f32], [0.7f32, 0.3f32, 0.8f32]); * ``` */ -pub fn set_orientation(orientation_at: [f32, ..3], orientation_up : [f32, ..3]) { +pub fn set_orientation(orientation_at: [f32; 3], orientation_up : [f32; 3]) { check_openal_context!(()); - let orientation: [f32, ..6] = [orientation_at[0], orientation_at[1], + let orientation: [f32; 6] = [orientation_at[0], orientation_at[1], orientation_at[2], orientation_up[0], orientation_up[1], orientation_up[2]]; al::alListenerfv(ffi::AL_ORIENTATION, &orientation[0]); @@ -150,9 +150,9 @@ pub fn set_orientation(orientation_at: [f32, ..3], orientation_up : [f32, ..3]) * println!("Up orientation: {}", &up); * ``` */ -pub fn get_orientation() -> ([f32, ..3], [f32, ..3]) { - check_openal_context!(([0., ..3], [0., ..3])); - let mut orientation: [f32, ..6] = [0., ..6]; +pub fn get_orientation() -> ([f32; 3], [f32; 3]) { + check_openal_context!(([0.; 3], [0.; 3])); + let mut orientation: [f32; 6] = [0.; 6]; al::alGetListenerfv(ffi::AL_ORIENTATION, &mut orientation[0]); ([orientation[0], orientation[1], orientation[2]], [orientation[3], orientation[4], orientation[5]]) @@ -175,18 +175,15 @@ mod test { pub fn listener_set_position() -> () { set_position([50f32, 150f32, 234f32]); let res = get_position(); - assert_eq!([res[0], res[1], res[2]][], [50f32, 150f32, 234f32][]) + assert_eq!((res[0], res[1], res[2]), (50f32, 150f32, 234f32)) } #[test] pub fn listener_set_orientation() -> () { set_orientation([50., 150., 234.], [277., 125., 71.]); - match get_orientation() { - ([x1, y1, z1], [x2, y2, z2]) => { - assert_eq!([x1, y1, z1][], [50f32, 150f32, 234f32][]); - assert_eq!([x2, y2, z2][], [277f32, 125f32, 71f32][]) - } - } + let (s1, s2) = get_orientation() ; + assert_eq!(s1, [50f32, 150f32, 234f32]); + assert_eq!(s2, [277f32, 125f32, 71f32]) } } diff --git a/src/music.rs b/src/music.rs index e82335a..abb8809 100644 --- a/src/music.rs +++ b/src/music.rs @@ -21,12 +21,13 @@ //! Play Music easily. -use std::io::timer::sleep; +use std::thread::sleep_ms; use std::mem; -use std::task; -use std::time::Duration; +use std::thread; +//use std::time::Duration; use libc::c_void; use std::vec::Vec; +use std::sync::mpsc::{channel, Sender, Receiver}; use internal::OpenAlData; use openal::{ffi, al}; @@ -65,7 +66,7 @@ pub struct Music { /// The internal OpenAL source identifier al_source: u32, /// The internal OpenAL buffers - al_buffers: [u32, ..2], + al_buffers: [u32; 2], /// The file open with libmscfile file: Option>, /// Information of the file @@ -93,14 +94,14 @@ impl Music { check_openal_context!(None); // Retrieve File and Music datas let file = match SndFile::new(path, Read) { - Ok(file) => box file, + Ok(file) => Box::new(file), Err(err) => { println!("{}", err); return None; } }; let infos = file.get_sndinfo(); // create the source and the buffers let mut source_id = 0; - let mut buffer_ids = [0, ..2]; + let mut buffer_ids = [0; 2]; // create the source al::alGenSources(1, &mut source_id); // create the buffers @@ -110,7 +111,7 @@ impl Music { let format = match al::get_channels_format(infos.channels) { Some(fmt) => fmt, None => { - println!("Internal error : unrecognized format."); + println!("internal error : unrecognized format."); return None; } }; @@ -143,11 +144,11 @@ impl Music { let al_buffers = self.al_buffers; // create buff - let mut samples = Vec::from_elem(sample_t_r as uint, 0i16); + let mut samples = vec![0i16; sample_t_r as usize];// as u32, 0i16); // full buff1 let mut len = mem::size_of::() * - self.file.as_mut().unwrap().read_i16(samples.as_mut_slice(), sample_t_r as i64) as uint; + self.file.as_mut().unwrap().read_i16(&mut samples[..], sample_t_r as i64) as usize; al::alBufferData(al_buffers[0], sample_format, samples.as_ptr() as *mut c_void, @@ -157,7 +158,7 @@ impl Music { // full buff2 samples.clear(); len = mem::size_of::() * - self.file.as_mut().unwrap().read_i16(samples.as_mut_slice(), sample_t_r as i64) as uint; + self.file.as_mut().unwrap().read_i16(&mut samples[..], sample_t_r as i64) as usize; al::alBufferData(al_buffers[1], sample_format, samples.as_ptr() as *mut c_void, @@ -170,22 +171,21 @@ impl Music { // Launche the Music al::alSourcePlay(al_source); - task::spawn(proc() { + thread::spawn(move|| { match OpenAlData::check_al_context() { Ok(_) => {}, Err(err) => { println!("{}", err);} }; - - let mut file: Box = port.recv(); - let mut samples = Vec::from_elem(sample_t_r as uint, 0i16); + let mut file : SndFile = port.recv().ok().unwrap(); + let mut samples = vec![0i16; sample_t_r as usize]; let mut status = ffi::AL_PLAYING; let mut i = 0; let mut buf = 0; - let mut read; + let mut read ; while status != ffi::AL_STOPPED { // wait a bit - sleep(Duration::milliseconds(50i64)); + sleep_ms(/*Duration::milliseconds(*/50/*)*/); if status == ffi::AL_PLAYING { al::alGetSourcei(al_source, ffi::AL_BUFFERS_PROCESSED, @@ -193,7 +193,7 @@ impl Music { if i != 0 { samples.clear(); al::alSourceUnqueueBuffers(al_source, 1, &mut buf); - read = file.read_i16(samples.as_mut_slice(), sample_t_r as i64) * + read = file.read_i16(&mut samples[..], sample_t_r as i64) * mem::size_of::() as i64; al::alBufferData(buf, sample_format, @@ -209,7 +209,7 @@ impl Music { al::alSourcei(al_source, ffi::AL_BUFFER, 0); }); let file = self.file.as_ref().unwrap().clone(); - chan.send(file); + chan.send(*file); } } @@ -239,7 +239,7 @@ impl AudioController for Music { if self.is_playing() { al::alSourceStop(self.al_source); // wait a bit for openal terminate - sleep(Duration::milliseconds(50i64)); + sleep_ms( 50); } self.file.as_mut().unwrap().seek(0, SeekSet); self.process_music(); @@ -263,7 +263,7 @@ impl AudioController for Music { check_openal_context!(()); al::alSourceStop(self.al_source); - sleep(Duration::milliseconds(50i64)); + sleep_ms(50); } /** @@ -513,7 +513,7 @@ impl AudioController for Music { * * `position` - A three dimensional vector of f32 containing the position * of the listener [x, y, z]. */ - fn set_position(&mut self, position: [f32, ..3]) -> () { + fn set_position(&mut self, position: [f32; 3]) -> () { check_openal_context!(()); al::alSourcefv(self.al_source, ffi::AL_POSITION, &position[0]); @@ -526,10 +526,10 @@ impl AudioController for Music { * A three dimensional vector of f32 containing the position of the * listener [x, y, z]. */ - fn get_position(&self) -> [f32, ..3] { - check_openal_context!([0., ..3]); + fn get_position(&self) -> [f32; 3] { + check_openal_context!([0.; 3]); - let mut position : [f32, ..3] = [0., ..3]; + let mut position : [f32; 3] = [0.; 3]; al::alGetSourcefv(self.al_source, ffi::AL_POSITION, &mut position[0]); position } @@ -544,7 +544,7 @@ impl AudioController for Music { * # Argument * `direction` - The new direction of the Music. */ - fn set_direction(&mut self, direction: [f32, ..3]) -> () { + fn set_direction(&mut self, direction: [f32; 3]) -> () { check_openal_context!(()); al::alSourcefv(self.al_source, ffi::AL_DIRECTION, &direction[0]); @@ -556,10 +556,10 @@ impl AudioController for Music { * # Return * The current direction of the Music. */ - fn get_direction(&self) -> [f32, ..3] { - check_openal_context!([0., ..3]); + fn get_direction(&self) -> [f32; 3] { + check_openal_context!([0.; 3]); - let mut direction : [f32, ..3] = [0., ..3]; + let mut direction : [f32; 3] = [0.; 3]; al::alGetSourcefv(self.al_source, ffi::AL_DIRECTION, &mut direction[0]); direction } @@ -827,7 +827,7 @@ mod test { msc.set_position([50., 150., 250.]); let res = msc.get_position(); - assert_eq!([res[0], res[1], res[2]][], [50f32, 150f32, 250f32][]); + assert_eq!([res[0], res[1], res[2]], [50f32, 150f32, 250f32]); } #[test] @@ -836,7 +836,7 @@ mod test { msc.set_direction([50., 150., 250.]); let res = msc.get_direction(); - assert_eq!([res[0], res[1], res[2]][], [50f32, 150f32, 250f32][]); + assert_eq!([res[0], res[1], res[2]], [50f32, 150f32, 250f32]); } #[test] diff --git a/src/openal.rs b/src/openal.rs index 14c7338..29ef8d6 100644 --- a/src/openal.rs +++ b/src/openal.rs @@ -25,16 +25,18 @@ */ #![allow(dead_code, non_snake_case)] - -#[link(name = "openal")] +#[link(name = "libsndfile-1")] +#[link(name = "openal32")] extern {} pub mod ffi { - use libc::{c_char, c_void}; + use libc::{c_char, c_void, intptr_t }; /// OpenAL types pub type ALCboolean = c_char; + pub type ALCdevicePtr = intptr_t; + pub type ALCcontextPtr = intptr_t; pub const ALC_TRUE: ALCboolean = 1; pub const ALC_FALSE: ALCboolean = 0; @@ -86,14 +88,14 @@ pub mod ffi { extern "C" { /// Context functions - pub fn alcCreateContext(device: *mut ALCdevice, attrlist: *mut i32) -> *mut ALCcontext; - pub fn alcMakeContextCurrent(context: *mut ALCcontext) -> ALCboolean; - pub fn alcDestroyContext(context: *mut ALCcontext); - pub fn alcGetCurrentContext() -> *mut ALCcontext; + pub fn alcCreateContext(device: ALCdevicePtr, attrlist: *mut i32) -> ALCcontextPtr; + pub fn alcMakeContextCurrent(context: ALCcontextPtr) -> ALCboolean; + pub fn alcDestroyContext(context: ALCcontextPtr); + pub fn alcGetCurrentContext() -> ALCcontextPtr; /// Device functions - pub fn alcOpenDevice(devicename: *mut c_char) -> *mut ALCdevice; - pub fn alcCloseDevice(device: *mut ALCdevice) -> ALCboolean; + pub fn alcOpenDevice(devicename: *mut c_char) -> ALCdevicePtr; + pub fn alcCloseDevice(device: ALCdevicePtr) -> ALCboolean; /// Listener functions pub fn alListenerf(param: i32, value: f32) -> (); @@ -119,15 +121,15 @@ pub mod ffi { pub fn alSourceUnqueueBuffers(source: u32, nb: i32, buffers: *mut u32) -> (); /// Sound capture functions - pub fn alcCaptureCloseDevice(device: *mut ALCdevice) -> ALCboolean; - pub fn alcCaptureOpenDevice(device: *mut c_char, sample_rate: i32, format: i32, buffer_size: i32) -> *mut ALCdevice; - pub fn alcCaptureStart(devide: *mut ALCdevice); - pub fn alcCaptureStop(devide: *mut ALCdevice); - pub fn alcGetIntegerv(devide: *mut ALCdevice, param: i32, size: i32, values: *mut i32); - pub fn alcCaptureSamples(devide: *mut ALCdevice, buffer: *mut c_void,sample: i32); + pub fn alcCaptureCloseDevice(device: ALCdevicePtr) -> ALCboolean; + pub fn alcCaptureOpenDevice(device: *mut c_char, sample_rate: i32, format: i32, buffer_size: i32) -> ALCdevicePtr; + pub fn alcCaptureStart(devide: ALCdevicePtr); + pub fn alcCaptureStop(devide: ALCdevicePtr); + pub fn alcGetIntegerv(devide: ALCdevicePtr, param: i32, size: i32, values: *mut i32); + pub fn alcCaptureSamples(devide: ALCdevicePtr, buffer: *mut c_void,sample: i32); /// extension check - pub fn alcIsExtensionPresent(device: *mut ALCdevice, extension: *const c_char) -> ALCboolean; + pub fn alcIsExtensionPresent(device: ALCdevicePtr, extension: *const c_char) -> ALCboolean; /// Buffers functions pub fn alGenBuffers(n: i32, buffers: *mut u32) -> (); diff --git a/src/record_context.rs b/src/record_context.rs index 2b486bc..4ea78de 100644 --- a/src/record_context.rs +++ b/src/record_context.rs @@ -19,22 +19,22 @@ // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -#![allow(raw_pointer_deriving)] +#![allow(raw_pointer_derive)] use openal::ffi; /// The context needed to initialize a new Recorder -#[deriving(Clone, PartialEq, Show, Copy)] +#[derive(Clone, PartialEq, Debug, Copy)] pub struct RecordContext { - capt_device: *mut ffi::ALCdevice + capt_device: ffi::ALCdevicePtr } -pub fn new(capt_device: *mut ffi::ALCdevice) -> RecordContext { +pub fn new(capt_device: ffi::ALCdevicePtr) -> RecordContext { RecordContext { capt_device: capt_device } } -pub fn get(ctxt: RecordContext) -> *mut ffi::ALCdevice { +pub fn get(ctxt: RecordContext) -> ffi::ALCdevicePtr { ctxt.capt_device } diff --git a/src/recorder.rs b/src/recorder.rs index 7f2b04a..9068880 100644 --- a/src/recorder.rs +++ b/src/recorder.rs @@ -21,8 +21,9 @@ //! Record audio -use std::{task, mem}; +use std::{thread, mem}; use std::vec::Vec; +use std::sync::mpsc::{channel, Sender, Receiver}; use record_context::RecordContext; use record_context; @@ -30,6 +31,7 @@ use openal::ffi; use sndfile::{SndInfo, SndFile}; use sndfile::OpenMode::Write; use sndfile::FormatType::{FormatWav, FormatPcm16}; +use std::intrinsics::transmute; /** * Record audio @@ -89,7 +91,7 @@ impl Recorder { self.stop_sender = Some(stop_sender); self.data_receiver = Some(data_receiver); - task::spawn(proc() { + thread::spawn(move || { let mut terminate = false; let ctxt = record_context::get(r_c); unsafe { ffi::alcCaptureStart(ctxt); } @@ -105,11 +107,10 @@ impl Recorder { }; if available_samples != 0 { - let tmp_buf = - Vec::from_elem(available_samples as uint, 0i16); + let tmp_buf = vec![0i16; available_samples as usize]; unsafe { ffi::alcCaptureSamples(ctxt, - mem::transmute(&tmp_buf.as_slice()[0]), + transmute(&tmp_buf[0]), available_samples); } samples.extend(tmp_buf.into_iter()); @@ -120,7 +121,7 @@ impl Recorder { unsafe { ffi::alcCaptureStop(ctxt); } terminate = true; }, - _ => {} + _ => {} } } data_sender.send(samples); @@ -133,7 +134,7 @@ impl Recorder { s_c.send(true); match self.data_receiver { Some(ref d_p) => { - self.samples = d_p.recv(); + self.samples = d_p.recv().ok().unwrap(); true }, None => false @@ -147,21 +148,23 @@ impl Recorder { if self.samples.len() == 0 { false } else { - let infos = box SndInfo { + let infos = Box::new(SndInfo { frames : self.samples.len() as i64, samplerate : 44100, channels : 1, format : (FormatPcm16 | FormatWav) as i32, sections : 0, seekable : 0 - }; + }); - let mut file_ext = String::from_str(filename); + + let mut file_ext = String::new(); + file_ext.push_str(filename); file_ext.push_str(".wav"); - match SndFile::new_with_info(file_ext.as_slice(), Write, infos) { + match SndFile::new_with_info(file_ext.as_ref(), Write, infos) { Ok(mut f) => { let len = self.samples.len() as i64; - f.write_i16(self.samples.as_mut_slice(), len); + f.write_i16(&mut self.samples[..], len); f.close(); true }, diff --git a/src/sndfile.rs b/src/sndfile.rs index 435312b..8088391 100644 --- a/src/sndfile.rs +++ b/src/sndfile.rs @@ -32,8 +32,15 @@ #![allow(dead_code)] +//use std::str::from_utf8; +use std::str::*; use std::ptr; -use std::c_str::CString; +use std::ffi::CString; +use std::ffi::CStr; +use std::ops::BitOr; +use std::ops::BitOr::*; +use std::i32::*; +use std::intrinsics::transmute; #[doc(hidden)] #[cfg(any(target_os="macos", target_os="linux", target_os="win32"))] @@ -49,7 +56,7 @@ mod ffi; /// The SndInfo structure is for passing data between the calling /// function and the library when opening a file for reading or writing. #[repr(C)] -#[deriving(Clone)] +#[derive(Clone)] pub struct SndInfo { pub frames : i64, pub samplerate : i32, @@ -64,37 +71,37 @@ pub struct SndInfo { /// * Read - Read only mode /// * Write - Write only mode /// * ReadWrite - Read and Write mode -#[deriving(Copy)] +#[derive(Copy, Clone)] pub enum OpenMode { - Read = ffi::SFM_READ as int, - Write = ffi::SFM_WRITE as int, - ReadWrite = ffi::SFM_RDWR as int + Read = ffi::SFM_READ as isize, + Write = ffi::SFM_WRITE as isize, + ReadWrite = ffi::SFM_RDWR as isize } /// Type of strings available for method get_string() -#[deriving(Copy)] +#[derive(Copy, Clone)] pub enum StringSoundType { - Title = ffi::SF_STR_TITLE as int, - Copyright = ffi::SF_STR_COPYRIGHT as int, - Software = ffi::SF_STR_SOFTWARE as int, - Artist = ffi::SF_STR_ARTIST as int, - Comment = ffi::SF_STR_COMMENT as int, - Date = ffi::SF_STR_DATE as int, - Album = ffi::SF_STR_ALBUM as int, - License = ffi::SF_STR_LICENSE as int, - TrackNumber = ffi::SF_STR_TRACKNUMBER as int, - Genre = ffi::SF_STR_GENRE as int + Title = ffi::SF_STR_TITLE as isize, + Copyright = ffi::SF_STR_COPYRIGHT as isize, + Software = ffi::SF_STR_SOFTWARE as isize, + Artist = ffi::SF_STR_ARTIST as isize, + Comment = ffi::SF_STR_COMMENT as isize, + Date = ffi::SF_STR_DATE as isize, + Album = ffi::SF_STR_ALBUM as isize, + License = ffi::SF_STR_LICENSE as isize, + TrackNumber = ffi::SF_STR_TRACKNUMBER as isize, + Genre = ffi::SF_STR_GENRE as isize } /// Types of error who can be return by API functions #[repr(C)] -#[deriving(Copy)] +#[derive(Copy, Clone)] pub enum Error { - NoError = ffi::SF_ERR_NO_ERROR as int, - UnrecognizedFormat = ffi::SF_ERR_UNRECOGNISED_FORMAT as int, - SystemError = ffi::SF_ERR_SYSTEM as int, - MalformedFile = ffi::SF_ERR_MALFORMED_FILE as int, - UnsupportedEncoding = ffi::SF_ERR_UNSUPPORTED_ENCODING as int, + NoError = ffi::SF_ERR_NO_ERROR as isize, + UnrecognizedFormat = ffi::SF_ERR_UNRECOGNISED_FORMAT as isize, + SystemError = ffi::SF_ERR_SYSTEM as isize, + MalformedFile = ffi::SF_ERR_MALFORMED_FILE as isize, + UnsupportedEncoding = ffi::SF_ERR_UNSUPPORTED_ENCODING as isize, } @@ -103,11 +110,11 @@ pub enum Error { /// * SeekSet - The offset is set to the start of the audio data plus offset (multichannel) frames. /// * SeekCur - The offset is set to its current location plus offset (multichannel) frames. /// * SeekEnd - The offset is set to the end of the data plus offset (multichannel) frames. -#[deriving(Copy)] +#[derive(Copy, Clone)] pub enum SeekMode { - SeekSet = ffi::SEEK_SET as int, - SeekCur = ffi::SEEK_CUR as int, - SeekEnd = ffi::SEEK_END as int + SeekSet = ffi::SEEK_SET as isize, + SeekCur = ffi::SEEK_CUR as isize, + SeekEnd = ffi::SEEK_END as isize } /// Enum who contains the list of the supported audio format @@ -165,73 +172,75 @@ pub enum SeekMode { /// * EndianBig - Force big endian-ness /// * EndianCpu - Force CPU endian-ness #[repr(C)] -#[deriving(Show, Clone, PartialOrd, PartialEq, Copy)] +#[derive(Debug, Clone, PartialOrd, PartialEq, Copy)] pub enum FormatType { - FormatWav = ffi::SF_FORMAT_WAV as int, - FormatAiff = ffi::SF_FORMAT_AIFF as int, - FormatAu = ffi::SF_FORMAT_AU as int, - FormatRaw = ffi::SF_FORMAT_RAW as int, - FormatPaf = ffi::SF_FORMAT_PAF as int, - FormatSvx = ffi::SF_FORMAT_SVX as int, - FormatNist = ffi::SF_FORMAT_NIST as int, - FormatVoc = ffi::SF_FORMAT_VOC as int, - FormatIrcam = ffi::SF_FORMAT_IRCAM as int, - FormatW64 = ffi::SF_FORMAT_W64 as int, - FormatMat4 = ffi::SF_FORMAT_MAT4 as int, - FormatMat5 = ffi::SF_FORMAT_MAT5 as int, - FormatPvf = ffi::SF_FORMAT_PVF as int, - FormatXi = ffi::SF_FORMAT_XI as int, - FormatHtk = ffi::SF_FORMAT_HTK as int, - FormatSds = ffi::SF_FORMAT_SDS as int, - FormatAvr = ffi::SF_FORMAT_AVR as int, - FormatWavex = ffi::SF_FORMAT_WAVEX as int, - FormatSd2 = ffi::SF_FORMAT_SD2 as int, - FormatFlac = ffi::SF_FORMAT_FLAC as int, - FormatCaf = ffi::SF_FORMAT_CAF as int, - FormatWve = ffi::SF_FORMAT_WVE as int, - FormatOgg = ffi::SF_FORMAT_OGG as int, - FormatMpc2k = ffi::SF_FORMAT_MPC2K as int, - FormatRf64 = ffi::SF_FORMAT_RF64 as int, - FormatPcmS8 = ffi::SF_FORMAT_PCM_S8 as int, - FormatPcm16 = ffi::SF_FORMAT_PCM_16 as int, - FormatPcm24 = ffi::SF_FORMAT_PCM_24 as int, - FormatPcm32 = ffi::SF_FORMAT_PCM_32 as int, - FormatPcmU8 = ffi::SF_FORMAT_PCM_U8 as int, - FormatFloat = ffi::SF_FORMAT_FLOAT as int, - FormatDouble = ffi::SF_FORMAT_DOUBLE as int, - FormatUlaw = ffi::SF_FORMAT_ULAW as int, - FormatAlaw = ffi::SF_FORMAT_ALAW as int, - FormatImaAdpcm = ffi::SF_FORMAT_IMA_ADPCM as int, - FormatApcm = ffi::SF_FORMAT_MS_ADPCM as int, - FormatGsm610 = ffi::SF_FORMAT_GSM610 as int, - FormatVoxAdpcm = ffi::SF_FORMAT_VOX_ADPCM as int, - FormatG72132 = ffi::SF_FORMAT_G721_32 as int, - FormatG72324 = ffi::SF_FORMAT_G723_24 as int, - FormatG72340 = ffi::SF_FORMAT_G723_40 as int, - FormatDww12 = ffi::SF_FORMAT_DWVW_12 as int, - FormatDww16 = ffi::SF_FORMAT_DWVW_16 as int, - FormatDww24 = ffi::SF_FORMAT_DWVW_24 as int, - FormatDwwN = ffi::SF_FORMAT_DWVW_N as int, - FormatDpcm8 = ffi::SF_FORMAT_DPCM_8 as int, - FormatDpcm16 = ffi::SF_FORMAT_DPCM_16 as int, - FormatVorbis = ffi::SF_FORMAT_VORBIS as int, - EndianFile = ffi::SF_ENDIAN_FILE as int, - EndianLittle = ffi::SF_ENDIAN_LITTLE as int, - EndianBig = ffi::SF_ENDIAN_BIG as int, - EndianCpu = ffi::SF_ENDIAN_CPU as int, - FormatSubMask = ffi::SF_FORMAT_SUBMASK as int, - FormatTypeMask = ffi::SF_FORMAT_TYPEMASK as int, + FormatWav = ffi::SF_FORMAT_WAV as isize, + FormatAiff = ffi::SF_FORMAT_AIFF as isize, + FormatAu = ffi::SF_FORMAT_AU as isize, + FormatRaw = ffi::SF_FORMAT_RAW as isize, + FormatPaf = ffi::SF_FORMAT_PAF as isize, + FormatSvx = ffi::SF_FORMAT_SVX as isize, + FormatNist = ffi::SF_FORMAT_NIST as isize, + FormatVoc = ffi::SF_FORMAT_VOC as isize, + FormatIrcam = ffi::SF_FORMAT_IRCAM as isize, + FormatW64 = ffi::SF_FORMAT_W64 as isize, + FormatMat4 = ffi::SF_FORMAT_MAT4 as isize, + FormatMat5 = ffi::SF_FORMAT_MAT5 as isize, + FormatPvf = ffi::SF_FORMAT_PVF as isize, + FormatXi = ffi::SF_FORMAT_XI as isize, + FormatHtk = ffi::SF_FORMAT_HTK as isize, + FormatSds = ffi::SF_FORMAT_SDS as isize, + FormatAvr = ffi::SF_FORMAT_AVR as isize, + FormatWavex = ffi::SF_FORMAT_WAVEX as isize, + FormatSd2 = ffi::SF_FORMAT_SD2 as isize, + FormatFlac = ffi::SF_FORMAT_FLAC as isize, + FormatCaf = ffi::SF_FORMAT_CAF as isize, + FormatWve = ffi::SF_FORMAT_WVE as isize, + FormatOgg = ffi::SF_FORMAT_OGG as isize, + FormatMpc2k = ffi::SF_FORMAT_MPC2K as isize, + FormatRf64 = ffi::SF_FORMAT_RF64 as isize, + FormatPcmS8 = ffi::SF_FORMAT_PCM_S8 as isize, + FormatPcm16 = ffi::SF_FORMAT_PCM_16 as isize, + FormatPcm24 = ffi::SF_FORMAT_PCM_24 as isize, + FormatPcm32 = ffi::SF_FORMAT_PCM_32 as isize, + FormatPcmU8 = ffi::SF_FORMAT_PCM_U8 as isize, + FormatFloat = ffi::SF_FORMAT_FLOAT as isize, + FormatDouble = ffi::SF_FORMAT_DOUBLE as isize, + FormatUlaw = ffi::SF_FORMAT_ULAW as isize, + FormatAlaw = ffi::SF_FORMAT_ALAW as isize, + FormatImaAdpcm = ffi::SF_FORMAT_IMA_ADPCM as isize, + FormatApcm = ffi::SF_FORMAT_MS_ADPCM as isize, + FormatGsm610 = ffi::SF_FORMAT_GSM610 as isize, + FormatVoxAdpcm = ffi::SF_FORMAT_VOX_ADPCM as isize, + FormatG72132 = ffi::SF_FORMAT_G721_32 as isize, + FormatG72324 = ffi::SF_FORMAT_G723_24 as isize, + FormatG72340 = ffi::SF_FORMAT_G723_40 as isize, + FormatDww12 = ffi::SF_FORMAT_DWVW_12 as isize, + FormatDww16 = ffi::SF_FORMAT_DWVW_16 as isize, + FormatDww24 = ffi::SF_FORMAT_DWVW_24 as isize, + FormatDwwN = ffi::SF_FORMAT_DWVW_N as isize, + FormatDpcm8 = ffi::SF_FORMAT_DPCM_8 as isize, + FormatDpcm16 = ffi::SF_FORMAT_DPCM_16 as isize, + FormatVorbis = ffi::SF_FORMAT_VORBIS as isize, + EndianFile = ffi::SF_ENDIAN_FILE as isize, + EndianLittle = ffi::SF_ENDIAN_LITTLE as isize, + EndianBig = ffi::SF_ENDIAN_BIG as isize, + EndianCpu = ffi::SF_ENDIAN_CPU as isize, + FormatSubMask = ffi::SF_FORMAT_SUBMASK as isize, + FormatTypeMask = ffi::SF_FORMAT_TYPEMASK as isize, } -impl BitOr for FormatType { - fn bitor(&self, _rhs: &FormatType) -> int { - (*self as int) | (*_rhs as int) +impl BitOr for FormatType { + type Output = FormatType; + fn bitor(self, _rhs: FormatType) -> Self::Output { + unsafe { transmute(((self as isize) | (_rhs as isize)))} } + //fn bitor(self, rhs: RHS) -> Self::Output; } /// SndFile object, used to load/store sound from a file path or an fd. pub struct SndFile { - handle : *mut ffi::SNDFILE, + handle : ffi::SNDFILEhandle, //*const ffi::SNDFILE, info : Box } @@ -256,20 +265,21 @@ impl SndFile { * the error otherwise. */ pub fn new(path : &str, mode : OpenMode) -> Result { - let mut info = box SndInfo { + let mut info = Box::new(SndInfo { frames : 0, samplerate : 0, channels : 0, format : 0, sections : 0, seekable : 0 - }; - let tmp_sndfile = path.with_c_str(|c_path| { - unsafe {ffi::sf_open(c_path as *mut i8, mode as i32, &mut *info) } }); - if tmp_sndfile.is_null() { + let c_path = CString::new(path).unwrap(); + let tmp_sndfile = { + unsafe {ffi::sf_open(c_path.as_ptr() as *mut i8, mode as i32, &mut *info) } + }; + if tmp_sndfile == 0 { Err(unsafe { - CString::new(ffi::sf_strerror(ptr::null_mut()) as *const i8, false).as_str().unwrap().to_string() + from_utf8(CStr::from_ptr(ffi::sf_strerror(0) as *const i8).to_bytes()).unwrap().to_owned() }) } else { Ok(SndFile { @@ -291,12 +301,13 @@ impl SndFile { * the error otherwise. */ pub fn new_with_info(path : &str, mode : OpenMode, mut info: Box) -> Result { - let tmp_sndfile = path.with_c_str(|c_path| { - unsafe {ffi::sf_open(c_path as *mut i8, mode as i32, &mut *info) } - }); - if tmp_sndfile.is_null() { + let c_path = CString::new(path).unwrap(); + let tmp_sndfile = { + unsafe {ffi::sf_open(c_path.as_ptr() as *mut i8, mode as i32, &mut *info) } + }; + if tmp_sndfile == 0 { Err(unsafe { - CString::new(ffi::sf_strerror(ptr::null_mut()) as *const i8, false).as_str().unwrap().to_string() + from_utf8(CStr::from_ptr(ffi::sf_strerror(0) as *const i8).to_bytes()).unwrap().to_owned() }) } else { Ok(SndFile { @@ -322,14 +333,14 @@ impl SndFile { mode : OpenMode, close_desc : bool) -> Result { - let mut info = box SndInfo { + let mut info = Box::new(SndInfo { frames : 0, samplerate : 0, channels : 0, format : 0, sections : 0, seekable : 0 - }; + }); let tmp_sndfile = match close_desc { true => unsafe { ffi::sf_open_fd(fd, mode as i32, &mut *info, ffi::SF_TRUE) @@ -338,9 +349,9 @@ impl SndFile { ffi::sf_open_fd(fd, mode as i32, &mut *info, ffi::SF_FALSE) } }; - if tmp_sndfile.is_null() { + if tmp_sndfile == 0 { Err(unsafe { - CString::new(ffi::sf_strerror(ptr::null_mut()) as *const i8, false).as_str().unwrap().to_string() + from_utf8(CStr::from_ptr(ffi::sf_strerror(0) as *const i8).to_bytes()).unwrap().to_owned() }) } else { Ok(SndFile { @@ -367,11 +378,12 @@ impl SndFile { let c_string = unsafe { ffi::sf_get_string(self.handle, string_type as i32) }; - if c_string.is_null() { + if c_string == ptr::null_mut() { None } else { Some(unsafe { - CString::new(c_string as *const i8, false).as_str().unwrap().to_string() + from_utf8(CStr::from_ptr(c_string as *const i8).to_bytes()).unwrap().to_owned() + //CString::new(c_string as *const i8, false).as_str().unwrap().to_string() }) } } @@ -388,10 +400,11 @@ impl SndFile { pub fn set_string(&mut self, string_type : StringSoundType, string : String) -> Error { + //let c_string = CString::new(string).unwrap(); unsafe { ffi::sf_set_string(self.handle, string_type as i32, - string.to_c_str().into_inner() as *mut i8) + string.as_ptr() as *mut i8) } } @@ -467,7 +480,7 @@ impl SndFile { * * Return the count of items. */ - pub fn read_i32<'r>(&'r mut self, array : &'r mut [i32], items : i64) -> i64 { + pub fn read_int<'r>(&'r mut self, array : &'r mut [i32], items : i64) -> i64 { unsafe { ffi::sf_read_int(self.handle, array.as_mut_ptr(), items) } @@ -527,7 +540,7 @@ impl SndFile { * * Return the count of frames. */ - pub fn readf_i32<'r>(&'r mut self, array : &'r mut [i32], frames : i64) -> i64 { + pub fn readf_int<'r>(&'r mut self, array : &'r mut [i32], frames : i64) -> i64 { unsafe { ffi::sf_readf_int(self.handle, array.as_mut_ptr(), frames) } @@ -587,7 +600,7 @@ impl SndFile { * * Return the count of wrote items. */ - pub fn write_i32<'r>(&'r mut self, array : &'r mut [i32], items : i64) -> i64 { + pub fn write_int<'r>(&'r mut self, array : &'r mut [i32], items : i64) -> i64 { unsafe { ffi::sf_write_int(self.handle, array.as_mut_ptr(), items) } @@ -647,7 +660,7 @@ impl SndFile { * * Return the count of wrote frames. */ - pub fn writef_i32<'r>(&'r mut self, array : &'r mut [i32], frames : i64) -> i64 { + pub fn writef_int<'r>(&'r mut self, array : &'r mut [i32], frames : i64) -> i64 { unsafe { ffi::sf_writef_int(self.handle, array.as_mut_ptr(), frames) } @@ -701,7 +714,8 @@ impl SndFile { */ pub fn string_error(&self) -> String { unsafe { - CString::new(ffi::sf_strerror(self.handle) as *const i8, false).as_str().unwrap().to_string() + from_utf8(CStr::from_ptr(ffi::sf_strerror(self.handle) as *const i8).to_bytes()).unwrap().to_owned() + //CString::new(ffi::sf_strerror(self.handle) as *const i8).as_str().unwrap().to_string() } } @@ -712,7 +726,8 @@ impl SndFile { */ pub fn error_number(error_num : Error) -> String { unsafe { - CString::new(ffi::sf_error_number(error_num as i32) as *const i8, false).as_str().unwrap().to_string() + from_utf8(CStr::from_ptr(ffi::sf_error_number(error_num as i32) as *const i8).to_bytes()).unwrap().to_owned() + //CString::new(ffi::sf_error_number(error_num as i32) as *const i8, false).as_str().unwrap().to_string() } } diff --git a/src/sndfile_ffi.rs b/src/sndfile_ffi.rs index 24c1719..ac85374 100644 --- a/src/sndfile_ffi.rs +++ b/src/sndfile_ffi.rs @@ -22,7 +22,7 @@ #![allow(dead_code, non_camel_case_types)] use super::{SndInfo, Error}; -use libc::{c_char, c_void}; +use libc::{c_char, c_void, intptr_t}; pub type SF_MODE = i32; pub const SFM_READ : SF_MODE = 0x10; @@ -120,6 +120,7 @@ pub const SF_FORMAT_TYPEMASK : FORMAT_TYPE = 0x0FFF0000; pub const SF_FORMAT_ENDMASK : FORMAT_TYPE = 0x30000000; pub type SNDFILE = c_void; +pub type SNDFILEhandle = intptr_t; #[repr(C)] pub struct FormatInfo { @@ -129,47 +130,47 @@ pub struct FormatInfo { } extern "C" { - pub fn sf_open(path : *mut c_char, mode : SF_MODE, info : *mut SndInfo) -> *mut SNDFILE; - pub fn sf_open_fd(fd : i32, mode : SF_MODE, info : *mut SndInfo, close_desc : SF_BOOL) -> *mut SNDFILE; + pub fn sf_open(path : *mut c_char, mode : SF_MODE, info : *mut SndInfo) -> SNDFILEhandle; + pub fn sf_open_fd(fd : i32, mode : SF_MODE, info : *mut SndInfo, close_desc : SF_BOOL) -> SNDFILEhandle; pub fn sf_format_check(info : *mut SndInfo) -> SF_BOOL; - pub fn sf_seek(sndfile : *mut SNDFILE, frames : i64, whence : i32) -> i64; - pub fn sf_command(sndfile : *mut SNDFILE, cmd : i32, data : *mut c_void, datasize : i32) -> Error; + pub fn sf_seek(sndfile : SNDFILEhandle, frames : i64, whence : i32) -> i64; + pub fn sf_command(sndfile : SNDFILEhandle, cmd : i32, data : *mut c_void, datasize : i32) -> Error; - pub fn sf_error(sndfile : *mut SNDFILE) -> Error; - pub fn sf_strerror(sndfile : *mut SNDFILE) -> *mut c_char; + pub fn sf_error(sndfile : SNDFILEhandle) -> Error; + pub fn sf_strerror(sndfile : SNDFILEhandle) -> *mut c_char; pub fn sf_error_number(errnum : i32) -> *mut c_char; - pub fn sf_perror(sndfile : *mut SNDFILE) -> Error; - pub fn sf_error_str(sndfile : *mut SNDFILE, string : *mut c_char, len : i64) ; - - pub fn sf_close(sndfile : *mut SNDFILE) -> Error; - pub fn sf_write_sync(sndfile : *mut SNDFILE) -> (); - - pub fn sf_read_short(sndfile : *mut SNDFILE, ptr : *mut i16, items : i64) -> i64; - pub fn sf_read_int(sndfile : *mut SNDFILE, ptr : *mut i32, items : i64) -> i64; - pub fn sf_read_float(sndfile : *mut SNDFILE, ptr : *mut f32, items : i64) -> i64; - pub fn sf_read_double(sndfile : *mut SNDFILE, ptr : *mut f64, items : i64) -> i64; - - pub fn sf_readf_short(sndfile : *mut SNDFILE, ptr : *mut i16, frames : i64) -> i64; - pub fn sf_readf_int(sndfile : *mut SNDFILE, ptr : *mut i32, frames : i64) -> i64; - pub fn sf_readf_float(sndfile : *mut SNDFILE, ptr : *mut f32, frames : i64) -> i64; - pub fn sf_readf_double(sndfile : *mut SNDFILE, ptr : *mut f64, frames : i64) -> i64; - - pub fn sf_write_short(sndfile : *mut SNDFILE, ptr : *mut i16, items : i64) -> i64; - pub fn sf_write_int(sndfile : *mut SNDFILE, ptr : *mut i32, items : i64) -> i64; - pub fn sf_write_float(sndfile : *mut SNDFILE, ptr : *mut f32, items : i64) -> i64; - pub fn sf_write_double(sndfile : *mut SNDFILE, ptr : *mut f64, items : i64) -> i64; - - pub fn sf_writef_short(sndfile : *mut SNDFILE, ptr : *mut i16, frames : i64) -> i64; - pub fn sf_writef_int(sndfile : *mut SNDFILE, ptr : *mut i32, frames : i64) -> i64; - pub fn sf_writef_float(sndfile : *mut SNDFILE, ptr : *mut f32, frames : i64) -> i64; - pub fn sf_writef_double(sndfile : *mut SNDFILE, ptr : *mut f64, frames : i64) -> i64; - - pub fn sf_read_raw(sndfile : *mut SNDFILE, ptr : *mut c_void, bytes : i64) -> i64; - pub fn sf_write_raw(sndfile : *mut SNDFILE, ptr : *mut c_void, bytes : i64) -> i64; - - pub fn sf_get_string(sndfile : *mut SNDFILE, str_type : i32) -> *mut c_char; - pub fn sf_set_string(sndfile : *mut SNDFILE, str_type : i32, string : *mut c_char) -> Error; + pub fn sf_perror(sndfile : SNDFILEhandle) -> Error; + pub fn sf_error_str(sndfile : SNDFILEhandle, string : *mut c_char, len : i64) ; + + pub fn sf_close(sndfile : SNDFILEhandle) -> Error; + pub fn sf_write_sync(sndfile : SNDFILEhandle) -> (); + + pub fn sf_read_short(sndfile : SNDFILEhandle, ptr : *mut i16, items : i64) -> i64; + pub fn sf_read_int(sndfile : SNDFILEhandle, ptr : *mut i32, items : i64) -> i64; + pub fn sf_read_float(sndfile : SNDFILEhandle, ptr : *mut f32, items : i64) -> i64; + pub fn sf_read_double(sndfile : SNDFILEhandle, ptr : *mut f64, items : i64) -> i64; + + pub fn sf_readf_short(sndfile : SNDFILEhandle, ptr : *mut i16, frames : i64) -> i64; + pub fn sf_readf_int(sndfile : SNDFILEhandle, ptr : *mut i32, frames : i64) -> i64; + pub fn sf_readf_float(sndfile : SNDFILEhandle, ptr : *mut f32, frames : i64) -> i64; + pub fn sf_readf_double(sndfile : SNDFILEhandle, ptr : *mut f64, frames : i64) -> i64; + + pub fn sf_write_short(sndfile : SNDFILEhandle, ptr : *mut i16, items : i64) -> i64; + pub fn sf_write_int(sndfile : SNDFILEhandle, ptr : *mut i32, items : i64) -> i64; + pub fn sf_write_float(sndfile : SNDFILEhandle, ptr : *mut f32, items : i64) -> i64; + pub fn sf_write_double(sndfile : SNDFILEhandle, ptr : *mut f64, items : i64) -> i64; + + pub fn sf_writef_short(sndfile : SNDFILEhandle, ptr : *mut i16, frames : i64) -> i64; + pub fn sf_writef_int(sndfile : SNDFILEhandle, ptr : *mut i32, frames : i64) -> i64; + pub fn sf_writef_float(sndfile : SNDFILEhandle, ptr : *mut f32, frames : i64) -> i64; + pub fn sf_writef_double(sndfile : SNDFILEhandle, ptr : *mut f64, frames : i64) -> i64; + + pub fn sf_read_raw(sndfile : SNDFILEhandle, ptr : *mut c_void, bytes : i64) -> i64; + pub fn sf_write_raw(sndfile : SNDFILEhandle, ptr : *mut c_void, bytes : i64) -> i64; + + pub fn sf_get_string(sndfile : SNDFILEhandle, str_type : i32) -> *mut c_char; + pub fn sf_set_string(sndfile : SNDFILEhandle, str_type : i32, string : *mut c_char) -> Error; } diff --git a/src/sound.rs b/src/sound.rs index 769be80..96a305c 100644 --- a/src/sound.rs +++ b/src/sound.rs @@ -25,13 +25,15 @@ use std::rc::Rc; use std::cell::RefCell; use internal::OpenAlData; -use sound_data::{mod, SoundData}; +use sound_data;//::*;//{SoundData}; +use sound_data::{SoundData}; use openal::{ffi, al}; use states::State; use states::State::{Initial, Playing, Paused, Stopped}; use audio_controller::AudioController; use audio_tags::{AudioTags, Tags}; + /** * Play Sounds easily. * @@ -535,7 +537,7 @@ impl AudioController for Sound { * * `position` - A three dimensional vector of f32 containing the position * of the listener [x, y, z]. */ - fn set_position(&mut self, position: [f32, ..3]) -> () { + fn set_position(&mut self, position: [f32; 3]) -> () { check_openal_context!(()); al::alSourcefv(self.al_source, ffi::AL_POSITION, &position[0]); @@ -548,10 +550,10 @@ impl AudioController for Sound { * A three dimensional vector of f32 containing the position of the * listener [x, y, z]. */ - fn get_position(&self) -> [f32, ..3] { - check_openal_context!([0., ..3]); + fn get_position(&self) -> [f32; 3] { + check_openal_context!([0.; 3]); - let mut position : [f32, ..3] = [0., ..3]; + let mut position : [f32; 3] = [0.; 3]; al::alGetSourcefv(self.al_source, ffi::AL_POSITION, &mut position[0]); position } @@ -566,7 +568,7 @@ impl AudioController for Sound { * # Argument * `direction` - The new direction of the Sound. */ - fn set_direction(&mut self, direction: [f32, ..3]) -> () { + fn set_direction(&mut self, direction: [f32; 3]) -> () { check_openal_context!(()); al::alSourcefv(self.al_source, ffi::AL_DIRECTION, &direction[0]); @@ -578,10 +580,10 @@ impl AudioController for Sound { * # Return * The current direction of the Sound. */ - fn get_direction(&self) -> [f32, ..3] { - check_openal_context!([0., ..3]); + fn get_direction(&self) -> [f32; 3] { + check_openal_context!([0.; 3]); - let mut direction : [f32, ..3] = [0., ..3]; + let mut direction : [f32; 3] = [0.; 3]; al::alGetSourcefv(self.al_source, ffi::AL_DIRECTION, &mut direction[0]); direction } @@ -689,7 +691,7 @@ impl AudioController for Sound { } -#[unsafe_destructor] +//#[unsafe_destructor] impl Drop for Sound { ///Destroy all the resources attached to the Sound. fn drop(&mut self) -> () { @@ -783,7 +785,7 @@ mod test { // should fail > 1. // #[test] - // #[should_fail] + // #[should_panic] // fn sound_set_volume_high_FAIL() -> () { // let mut snd = Sound::new("shot.wav").expect("Cannot create sound"); @@ -792,7 +794,7 @@ mod test { // } #[test] - #[should_fail] + #[should_panic] fn sound_set_volume_low_FAIL() -> () { let mut snd = Sound::new("res/shot.wav").expect("Cannot create sound"); @@ -809,7 +811,7 @@ mod test { } #[test] - #[should_fail] + #[should_panic] fn sound_set_min_volume_high_FAIL() -> () { let mut snd = Sound::new("res/shot.wav").expect("Cannot create sound"); @@ -818,7 +820,7 @@ mod test { } #[test] - #[should_fail] + #[should_panic] fn sound_set_min_volume_low_FAIL() -> () { let mut snd = Sound::new("res/shot.wav").expect("Cannot create sound"); @@ -835,7 +837,7 @@ mod test { } #[test] - #[should_fail] + #[should_panic] fn sound_set_max_volume_high_FAIL() -> () { let mut snd = Sound::new("res/shot.wav").expect("Cannot create sound"); @@ -844,7 +846,7 @@ mod test { } #[test] - #[should_fail] + #[should_panic] fn sound_set_max_volume_low_FAIL() -> () { let mut snd = Sound::new("res/shot.wav").expect("Cannot create sound"); @@ -877,7 +879,7 @@ mod test { } #[test] - #[should_fail] + #[should_panic] fn sound_set_pitch_too_low_FAIL() -> () { let mut snd = Sound::new("res/shot.wav").expect("Cannot create sound"); @@ -887,7 +889,7 @@ mod test { // shoud fail > 2. // #[test] - // #[should_fail] + // #[should_panic] // fn sound_set_pitch_too_high_FAIL() -> () { // let mut snd = Sound::new("shot.wav").expect("Cannot create sound"); @@ -919,7 +921,7 @@ mod test { snd.set_position([50f32, 150f32, 250f32]); let res = snd.get_position(); - assert_eq!([res[0], res[1], res[2]][], [50f32, 150f32, 250f32][]); + assert_eq!([res[0], res[1], res[2]], [50f32, 150f32, 250f32]); } #[test] @@ -928,7 +930,7 @@ mod test { snd.set_direction([50f32, 150f32, 250f32]); let res = snd.get_direction(); - assert_eq!([res[0], res[1], res[2]][], [50f32, 150f32, 250f32][]); + assert_eq!([res[0], res[1], res[2]], [50f32, 150f32, 250f32]); } @@ -941,7 +943,7 @@ mod test { } #[test] - #[should_fail] + #[should_panic] fn sound_set_max_distance_FAIL() -> () { let mut snd = Sound::new("res/shot.wav").expect("Cannot create sound"); @@ -958,7 +960,7 @@ mod test { } #[test] - #[should_fail] + #[should_panic] fn sound_set_reference_distance_FAIL() -> () { let mut snd = Sound::new("res/shot.wav").expect("Cannot create sound"); @@ -975,7 +977,7 @@ mod test { } #[test] - #[should_fail] + #[should_panic] fn sound_set_attenuation_FAIL() -> () { let mut snd = Sound::new("res/shot.wav").expect("Cannot create sound"); diff --git a/src/sound_data.rs b/src/sound_data.rs index ea3da9b..e20d353 100644 --- a/src/sound_data.rs +++ b/src/sound_data.rs @@ -100,8 +100,8 @@ impl SoundData { let nb_sample = infos.channels as i64 * infos.frames; - let mut samples = Vec::from_elem(nb_sample as uint, 0i16); - file.read_i16(samples.as_mut_slice(), nb_sample as i64); + let mut samples = vec![0i16; nb_sample as usize]; + file.read_i16(&mut samples[..], nb_sample as i64); let mut buffer_id = 0; let len = mem::size_of::() * (samples.len()); @@ -110,7 +110,7 @@ impl SoundData { let format = match al::get_channels_format(infos.channels) { Some(fmt) => fmt, None => { - println!("Internal error : unrecognized format."); + println!("internal error : unrecognized format."); return None; } }; @@ -197,7 +197,7 @@ mod test { } #[test] - #[should_fail] + #[should_panic] fn sounddata_create_FAIL() -> () { #![allow(unused_variables)] let snd_data = SoundData::new("toto.wav").unwrap(); diff --git a/src/states.rs b/src/states.rs index 3cb56ba..af4eb7f 100644 --- a/src/states.rs +++ b/src/states.rs @@ -22,7 +22,7 @@ //! The states of a Sound or a Music /// The differents states in which a sound can be. -#[deriving(Clone, PartialEq, PartialOrd, Show, Copy)] +#[derive(PartialEq, PartialOrd, Debug, Copy, Clone)] pub enum State { /// Initial state of the sound or music Initial,