Skip to content

Add better support for loading SDL2 mixer sounds and music from memory #1483

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions examples/mixer-demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,30 @@ fn demo(music_file: &Path, sound_file: Option<&Path>) -> Result<(), String> {

timer.delay(5_000);
sdl2::mixer::Music::halt();

println!("playing sound from memory...");
let sound_as_bytes = include_bytes!("../assets/sine.wav");
let chunk = sdl2::mixer::Chunk::from_bytes(sound_as_bytes)?;
sdl2::mixer::Channel::all().play(&chunk, 0)?;
timer.delay(1_000);

println!("playing music from static memory...");
let music_as_bytes = include_bytes!("../assets/sine.wav");

let mus = sdl2::mixer::Music::from_static_bytes(music_as_bytes)?;
mus.play(-1);
timer.delay(1_000);
sdl2::mixer::Music::halt();
timer.delay(0_500);

println!("playing music from owned memory...");

let mus = sdl2::mixer::Music::from_owned_bytes(music_as_bytes.clone().into())?;
mus.play(-1);
timer.delay(1_000);

sdl2::mixer::Music::halt();

timer.delay(1_000);

println!("quitting sdl");
Expand Down
48 changes: 44 additions & 4 deletions src/sdl2/mixer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,17 @@ impl Drop for Chunk {
}

impl Chunk {
/// Load a sample from memory directly.
///
/// This works the same way as [Chunk::from_file] except with bytes instead of a file path.
/// If you have read your sound files (.wav, .ogg, etc...) from
/// disk to memory as bytes you can use this function
/// to create [Chunk]s from their bytes.
pub fn from_bytes(path: &[u8]) -> Result<Chunk, String> {
let b = RWops::from_bytes(path)?;
b.load_wav()
}

/// Load file for use as a sample.
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Chunk, String> {
let raw = unsafe { mixer::Mix_LoadWAV_RW(RWops::from_file(path, "rb")?.raw(), 0) };
Expand Down Expand Up @@ -363,6 +374,7 @@ impl<'a> LoaderRWops<'a> for RWops<'a> {
Ok(Music {
raw,
owned: true,
owned_data: None,
_marker: PhantomData,
})
}
Expand Down Expand Up @@ -799,6 +811,7 @@ extern "C" fn c_music_finished_hook() {
pub struct Music<'a> {
pub raw: *mut mixer::Mix_Music,
pub owned: bool,
pub owned_data: Option<Box<[u8]>>,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should not be pub (other fields too but unrelated to this PR, if you want you can make them private too), also I am unsure if you can keep the Box here without invalidating other pointers to its data when Music is moved in memory, I would prefer Option<NonNull<[u8]>> here (that needs manual dealloc using Box::from_raw).

_marker: PhantomData<&'a ()>,
}

Expand All @@ -818,7 +831,28 @@ impl<'a> fmt::Debug for Music<'a> {
}

impl<'a> Music<'a> {
pub fn from_static_bytes(buf: &'static [u8]) -> Result<Music<'static>, String> {
let rw =
unsafe { sys::SDL_RWFromConstMem(buf.as_ptr() as *const c_void, buf.len() as c_int) };
if rw.is_null() {
return Err(get_error());
}
let raw = unsafe { mixer::Mix_LoadMUS_RW(rw, 0) };
if raw.is_null() {
Err(get_error())
} else {
Ok(Music {
raw,
owned: true,
owned_data: None,
_marker: PhantomData,
})
}
}
Comment on lines +834 to +851
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is very similar to from_owned_bytes, can you maybe factor out a function that does the unsafe stuff?


/// Load music file to use.
///
/// The music is streamed directly from the file when played.
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Music<'static>, String> {
let raw = unsafe {
let c_path = CString::new(path.as_ref().to_str().unwrap()).unwrap();
Expand All @@ -830,28 +864,34 @@ impl<'a> Music<'a> {
Ok(Music {
raw,
owned: true,
owned_data: None,
_marker: PhantomData,
})
}
}

/// Load music from a static byte buffer.
/// Load music from an owned byte buffer.
///
/// The returned [Music] instance takes ownership of the given buffer
/// and drops it along with itself.
///
/// Loading the whole music data to memory can be wasteful if the music can be streamed directly from
/// a file instead. Consider using [Music::from_file] when possible.
#[doc(alias = "SDL_RWFromConstMem")]
pub fn from_static_bytes(buf: &'static [u8]) -> Result<Music<'static>, String> {
pub fn from_owned_bytes(mut buf: Box<[u8]>) -> Result<Music<'static>, String> {
let rw =
unsafe { sys::SDL_RWFromConstMem(buf.as_ptr() as *const c_void, buf.len() as c_int) };

if rw.is_null() {
return Err(get_error());
}

let raw = unsafe { mixer::Mix_LoadMUS_RW(rw, 0) };
if raw.is_null() {
Err(get_error())
} else {
Ok(Music {
raw,
owned: true,
owned_data: Some(buf),
_marker: PhantomData,
})
}
Expand Down
Loading