diff options
Diffstat (limited to 'src/audio.c')
| -rw-r--r-- | src/audio.c | 506 |
1 files changed, 265 insertions, 241 deletions
diff --git a/src/audio.c b/src/audio.c index ad1d7eba..38fefd12 100644 --- a/src/audio.c +++ b/src/audio.c @@ -2,13 +2,26 @@ * * raylib.audio * -* Basic functions to manage Audio: InitAudioDevice, LoadAudioFiles, PlayAudioFiles +* Basic functions to manage Audio: +* Manage audio device (init/close) +* Load and Unload audio files +* Play/Stop/Pause/Resume loaded audio +* Manage mixing channels +* Manage raw audio context * * Uses external lib: * OpenAL Soft - Audio device management lib (http://kcat.strangesoft.net/openal.html) * stb_vorbis - Ogg audio files loading (http://www.nothings.org/stb_vorbis/) +* jar_xm - XM module file loading +* jar_mod - MOD audio file loading * -* Copyright (c) 2014 Ramon Santamaria (@raysan5) +* Many thanks to Joshua Reisenauer (github: @kd7tck) for the following additions: +* XM audio module support (jar_xm) +* MOD audio module support (jar_mod) +* Mixing channels support +* Raw audio context support +* +* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. @@ -37,12 +50,18 @@ #include "AL/al.h" // OpenAL basic header #include "AL/alc.h" // OpenAL context header (like OpenGL, OpenAL requires a context to work) -#include "AL/alext.h" // OpenAL extensions for other format types #include <stdlib.h> // Required for: malloc(), free() #include <string.h> // Required for: strcmp(), strncmp() #include <stdio.h> // Required for: FILE, fopen(), fclose(), fread() +#ifndef AL_FORMAT_MONO_FLOAT32 + #define AL_FORMAT_MONO_FLOAT32 0x10010 +#endif +#ifndef AL_FORMAT_STEREO_FLOAT32 + #define AL_FORMAT_STEREO_FLOAT32 0x10011 +#endif + #if defined(AUDIO_STANDALONE) #include <stdarg.h> // Required for: va_list, va_start(), vfprintf(), va_end() #else @@ -62,9 +81,9 @@ //---------------------------------------------------------------------------------- // Defines and Macros //---------------------------------------------------------------------------------- -#define MAX_STREAM_BUFFERS 2 // Number of buffers for each alSource -#define MAX_MIX_CHANNELS 4 // Number of open AL sources +#define MAX_STREAM_BUFFERS 2 // Number of buffers for each source #define MAX_MUSIC_STREAMS 2 // Number of simultanious music sources +#define MAX_MIX_CHANNELS 4 // Number of mix channels (OpenAL sources) #if defined(PLATFORM_RPI) || defined(PLATFORM_ANDROID) // NOTE: On RPI and Android should be lower to avoid frame-stalls @@ -80,10 +99,10 @@ // Types and Structures Definition //---------------------------------------------------------------------------------- -// Used to create custom audio streams that are not bound to a specific file. There can be -// no more than 4 concurrent mixchannels in use. This is due to each active mixc being tied to -// a dedicated mix channel. -typedef struct MixChannel_t { +// Used to create custom audio streams that are not bound to a specific file. +// There can be no more than 4 concurrent mixchannels in use. +// This is due to each active mixc being tied to a dedicated mix channel. +typedef struct MixChannel { unsigned short sampleRate; // default is 48000 unsigned char channels; // 1=mono,2=stereo unsigned char mixChannel; // 0-3 or mixA-mixD, each mix channel can receive up to one dedicated audio stream @@ -93,39 +112,40 @@ typedef struct MixChannel_t { ALenum alFormat; // OpenAL format specifier ALuint alSource; // OpenAL source ALuint alBuffer[MAX_STREAM_BUFFERS]; // OpenAL sample buffer -} MixChannel_t; +} MixChannel; // Music type (file streaming from memory) // NOTE: Anything longer than ~10 seconds should be streamed into a mix channel... typedef struct Music { stb_vorbis *stream; - jar_xm_context_t *xmctx; // XM chiptune context - jar_mod_context_t modctx; // MOD chiptune context - MixChannel_t *mixc; // mix channel + jar_xm_context_t *xmctx; // XM chiptune context + jar_mod_context_t modctx; // MOD chiptune context + MixChannel *mixc; // Mix channel unsigned int totalSamplesLeft; float totalLengthSeconds; bool loop; - bool chipTune; // chiptune is loaded? + bool chipTune; // chiptune is loaded? + bool enabled; } Music; // Audio errors registered typedef enum { - ERROR_RAW_CONTEXT_CREATION = 1, - ERROR_XM_CONTEXT_CREATION = 2, - ERROR_MOD_CONTEXT_CREATION = 4, - ERROR_MIX_CHANNEL_CREATION = 8, - ERROR_MUSIC_CHANNEL_CREATION = 16, - ERROR_LOADING_XM = 32, - ERROR_LOADING_MOD = 64, - ERROR_LOADING_WAV = 128, - ERROR_LOADING_OGG = 256, - ERROR_OUT_OF_MIX_CHANNELS = 512, - ERROR_EXTENSION_NOT_RECOGNIZED = 1024, - ERROR_UNABLE_TO_OPEN_RRES_FILE = 2048, - ERROR_INVALID_RRES_FILE = 4096, - ERROR_INVALID_RRES_RESOURCE = 8192, - ERROR_UNINITIALIZED_CHANNELS = 16384 + ERROR_RAW_CONTEXT_CREATION = 1, + ERROR_XM_CONTEXT_CREATION = 2, + ERROR_MOD_CONTEXT_CREATION = 4, + ERROR_MIX_CHANNEL_CREATION = 8, + ERROR_MUSIC_CHANNEL_CREATION = 16, + ERROR_LOADING_XM = 32, + ERROR_LOADING_MOD = 64, + ERROR_LOADING_WAV = 128, + ERROR_LOADING_OGG = 256, + ERROR_OUT_OF_MIX_CHANNELS = 512, + ERROR_EXTENSION_NOT_RECOGNIZED = 1024, + ERROR_UNABLE_TO_OPEN_RRES_FILE = 2048, + ERROR_INVALID_RRES_FILE = 4096, + ERROR_INVALID_RRES_RESOURCE = 8192, + ERROR_UNINITIALIZED_CHANNELS = 16384 } AudioError; #if defined(AUDIO_STANDALONE) @@ -135,11 +155,10 @@ typedef enum { INFO = 0, ERROR, WARNING, DEBUG, OTHER } TraceLogType; //---------------------------------------------------------------------------------- // Global Variables Definition //---------------------------------------------------------------------------------- -static Music musicChannels_g[MAX_MUSIC_STREAMS]; // Current music loaded, up to two can play at the same time -static MixChannel_t *mixChannels_g[MAX_MIX_CHANNELS]; // What mix channels are currently active -static bool musicEnabled_g = false; +static Music musicStreams[MAX_MUSIC_STREAMS]; // Current music loaded, up to two can play at the same time +static MixChannel *mixChannels[MAX_MIX_CHANNELS]; // Mix channels currently active (from music streams) -static int lastAudioError = 0; // Registers last audio error +static int lastAudioError = 0; // Registers last audio error //---------------------------------------------------------------------------------- // Module specific Functions Declaration @@ -151,13 +170,11 @@ static void UnloadWave(Wave wave); // Unload wave data static bool BufferMusicStream(int index, int numBuffers); // Fill music buffers with data static void EmptyMusicStream(int index); // Empty music buffers -static MixChannel_t *InitMixChannel(unsigned short sampleRate, unsigned char mixChannel, unsigned char channels, bool floatingPoint); // For streaming into mix channels. -static void CloseMixChannel(MixChannel_t *mixc); // Frees mix channel -static int BufferMixChannel(MixChannel_t *mixc, void *data, int numberElements); // Pushes more audio data into mixc mix channel, if NULL is passed it pauses -static int FillAlBufferWithSilence(MixChannel_t *mixc, ALuint buffer); // Fill buffer with zeros, returns number processed -static void ResampleShortToFloat(short *shorts, float *floats, unsigned short len); // Pass two arrays of the same legnth in -static void ResampleByteToFloat(char *chars, float *floats, unsigned short len); // Pass two arrays of same length in -static int IsMusicStreamReadyForBuffering(int index); // Checks if music buffer is ready to be refilled +static MixChannel *InitMixChannel(unsigned short sampleRate, unsigned char mixChannel, unsigned char channels, bool floatingPoint); +static void CloseMixChannel(MixChannel *mixc); // Frees mix channel +static int BufferMixChannel(MixChannel *mixc, void *data, int numberElements); // Pushes more audio data into mix channel +//static void ResampleShortToFloat(short *shorts, float *floats, unsigned short len); // Pass two arrays of the same legnth in +//static void ResampleByteToFloat(char *chars, float *floats, unsigned short len); // Pass two arrays of same length in #if defined(AUDIO_STANDALONE) const char *GetExtension(const char *fileName); // Get the extension for a filename @@ -198,9 +215,9 @@ void InitAudioDevice(void) // Close the audio device for all contexts void CloseAudioDevice(void) { - for (int index=0; index<MAX_MUSIC_STREAMS; index++) + for (int index = 0; index < MAX_MUSIC_STREAMS; index++) { - if (musicChannels_g[index].mixc) StopMusicStream(index); // Stop music streaming and close current stream + if (musicStreams[index].mixc) StopMusicStream(index); // Stop music streaming and close current stream } ALCdevice *device; @@ -215,7 +232,7 @@ void CloseAudioDevice(void) alcCloseDevice(device); } -// True if call to InitAudioDevice() was successful and CloseAudioDevice() has not been called yet +// Check if device has been initialized successfully bool IsAudioDeviceReady(void) { ALCcontext *context = alcGetCurrentContext(); @@ -234,22 +251,22 @@ bool IsAudioDeviceReady(void) // Module Functions Definition - Custom audio output //---------------------------------------------------------------------------------- -// For streaming into mix channels. -// The mixChannel is what audio muxing channel you want to operate on, 0-3 are the ones available. Each mix channel can only be used one at a time. -// exmple usage is InitMixChannel(48000, 0, 2, true); // mixchannel 1, 48khz, stereo, floating point -static MixChannel_t *InitMixChannel(unsigned short sampleRate, unsigned char mixChannel, unsigned char channels, bool floatingPoint) +// Init mix channel for streaming +// The mixChannel is what audio muxing channel you want to operate on, 0-3 are the ones available. +// Each mix channel can only be used one at a time. +static MixChannel *InitMixChannel(unsigned short sampleRate, unsigned char mixChannel, unsigned char channels, bool floatingPoint) { if (mixChannel >= MAX_MIX_CHANNELS) return NULL; if (!IsAudioDeviceReady()) InitAudioDevice(); - if (!mixChannels_g[mixChannel]) + if (!mixChannels[mixChannel]) { - MixChannel_t *mixc = (MixChannel_t *)malloc(sizeof(MixChannel_t)); + MixChannel *mixc = (MixChannel *)malloc(sizeof(MixChannel)); mixc->sampleRate = sampleRate; mixc->channels = channels; mixc->mixChannel = mixChannel; mixc->floatingPoint = floatingPoint; - mixChannels_g[mixChannel] = mixc; + mixChannels[mixChannel] = mixc; // Setup OpenAL format if (channels == 1) @@ -274,7 +291,20 @@ static MixChannel_t *InitMixChannel(unsigned short sampleRate, unsigned char mix alGenBuffers(MAX_STREAM_BUFFERS, mixc->alBuffer); // Fill buffers - for (int i = 0; i < MAX_STREAM_BUFFERS; i++) FillAlBufferWithSilence(mixc, mixc->alBuffer[i]); + for (int i = 0; i < MAX_STREAM_BUFFERS; i++) + { + // Initialize buffer with zeros by default + if (mixc->floatingPoint) + { + float pcm[MUSIC_BUFFER_SIZE_FLOAT] = { 0.0f }; + alBufferData(mixc->alBuffer[i], mixc->alFormat, pcm, MUSIC_BUFFER_SIZE_FLOAT*sizeof(float), mixc->sampleRate); + } + else + { + short pcm[MUSIC_BUFFER_SIZE_SHORT] = { 0 }; + alBufferData(mixc->alBuffer[i], mixc->alFormat, pcm, MUSIC_BUFFER_SIZE_SHORT*sizeof(short), mixc->sampleRate); + } + } alSourceQueueBuffers(mixc->alSource, MAX_STREAM_BUFFERS, mixc->alBuffer); mixc->playing = true; @@ -287,7 +317,7 @@ static MixChannel_t *InitMixChannel(unsigned short sampleRate, unsigned char mix } // Frees buffer in mix channel -static void CloseMixChannel(MixChannel_t *mixc) +static void CloseMixChannel(MixChannel *mixc) { if (mixc) { @@ -308,18 +338,18 @@ static void CloseMixChannel(MixChannel_t *mixc) // Delete source and buffers alDeleteSources(1, &mixc->alSource); alDeleteBuffers(MAX_STREAM_BUFFERS, mixc->alBuffer); - mixChannels_g[mixc->mixChannel] = NULL; + mixChannels[mixc->mixChannel] = NULL; free(mixc); mixc = NULL; } } -// Pushes more audio data into mixc mix channel, only one buffer per call +// Pushes more audio data into mix channel, only one buffer per call // Call "BufferMixChannel(mixc, NULL, 0)" if you want to pause the audio. -// @Returns number of samples that where processed. -static int BufferMixChannel(MixChannel_t *mixc, void *data, int numberElements) +// Returns number of samples that where processed. +static int BufferMixChannel(MixChannel *mixc, void *data, int numberElements) { - if (!mixc || (mixChannels_g[mixc->mixChannel] != mixc)) return 0; // When there is two channels there must be an even number of samples + if (!mixc || (mixChannels[mixc->mixChannel] != mixc)) return 0; // When there is two channels there must be an even number of samples if (!data || !numberElements) { @@ -362,28 +392,11 @@ static int BufferMixChannel(MixChannel_t *mixc, void *data, int numberElements) return numberElements; } -// fill buffer with zeros, returns number processed -static int FillAlBufferWithSilence(MixChannel_t *mixc, ALuint buffer) -{ - if (mixc->floatingPoint) - { - float pcm[MUSIC_BUFFER_SIZE_FLOAT] = { 0.0f }; - alBufferData(buffer, mixc->alFormat, pcm, MUSIC_BUFFER_SIZE_FLOAT*sizeof(float), mixc->sampleRate); - - return MUSIC_BUFFER_SIZE_FLOAT; - } - else - { - short pcm[MUSIC_BUFFER_SIZE_SHORT] = { 0 }; - alBufferData(buffer, mixc->alFormat, pcm, MUSIC_BUFFER_SIZE_SHORT*sizeof(short), mixc->sampleRate); - - return MUSIC_BUFFER_SIZE_SHORT; - } -} - +/* +// Convert data from short to float // example usage: -// short sh[3] = {1,2,3};float fl[3]; -// ResampleShortToFloat(sh,fl,3); +// short sh[3] = {1,2,3};float fl[3]; +// ResampleShortToFloat(sh,fl,3); static void ResampleShortToFloat(short *shorts, float *floats, unsigned short len) { for (int i = 0; i < len; i++) @@ -393,9 +406,10 @@ static void ResampleShortToFloat(short *shorts, float *floats, unsigned short le } } +// Convert data from float to short // example usage: -// char ch[3] = {1,2,3};float fl[3]; -// ResampleByteToFloat(ch,fl,3); +// char ch[3] = {1,2,3};float fl[3]; +// ResampleByteToFloat(ch,fl,3); static void ResampleByteToFloat(char *chars, float *floats, unsigned short len) { for (int i = 0; i < len; i++) @@ -404,43 +418,55 @@ static void ResampleByteToFloat(char *chars, float *floats, unsigned short len) else floats[i] = (float)chars[i]/128.0f; } } +*/ -// used to output raw audio streams, returns negative numbers on error, + number represents the mix channel index -// if floating point is false the data size is 16bit short, otherwise it is float 32bit -RawAudioContext InitRawAudioContext(int sampleRate, int channels, bool floatingPoint) +// Initialize raw audio mix channel for audio buffering +// NOTE: Returns mix channel index or -1 if it fails (errors are registered on lastAudioError) +int InitRawMixChannel(int sampleRate, int channels, bool floatingPoint) { int mixIndex; + for (mixIndex = 0; mixIndex < MAX_MIX_CHANNELS; mixIndex++) // find empty mix channel slot { - if (mixChannels_g[mixIndex] == NULL) break; - else if (mixIndex == (MAX_MIX_CHANNELS - 1)) return ERROR_OUT_OF_MIX_CHANNELS; // error + if (mixChannels[mixIndex] == NULL) break; + else if (mixIndex == (MAX_MIX_CHANNELS - 1)) + { + lastAudioError = ERROR_OUT_OF_MIX_CHANNELS; + return -1; + } } if (InitMixChannel(sampleRate, mixIndex, channels, floatingPoint)) return mixIndex; - else return ERROR_RAW_CONTEXT_CREATION; // error -} - -void CloseRawAudioContext(RawAudioContext ctx) -{ - if (mixChannels_g[ctx]) CloseMixChannel(mixChannels_g[ctx]); + else + { + lastAudioError = ERROR_RAW_CONTEXT_CREATION; + return -1; + } } -// if 0 is returned, the buffers are still full and you need to keep trying with the same data until a + number is returned. -// any + number returned is the number of samples that was processed and passed into buffer. -// data either needs to be array of floats or shorts. -int BufferRawAudioContext(RawAudioContext ctx, void *data, unsigned short numberElements) +// Buffers data directly to raw mix channel +// if 0 is returned, buffers are still full and you need to keep trying with the same data +// otherwise it will return number of samples buffered. +// NOTE: Data could be either be an array of floats or shorts, depending on the created context +int BufferRawAudioContext(int ctx, void *data, unsigned short numberElements) { int numBuffered = 0; if (ctx >= 0) { - MixChannel_t* mixc = mixChannels_g[ctx]; + MixChannel *mixc = mixChannels[ctx]; numBuffered = BufferMixChannel(mixc, data, numberElements); } return numBuffered; } +// Closes and frees raw mix channel +void CloseRawAudioContext(int ctx) +{ + if (mixChannels[ctx]) CloseMixChannel(mixChannels[ctx]); +} + //---------------------------------------------------------------------------------- // Module Functions Definition - Sounds loading and playing (.WAV) //---------------------------------------------------------------------------------- @@ -798,25 +824,25 @@ void SetSoundPitch(Sound sound, float pitch) //---------------------------------------------------------------------------------- // Start music playing (open stream) -// returns 0 on success +// returns 0 on success or error code int PlayMusicStream(int index, char *fileName) { int mixIndex; - if (musicChannels_g[index].stream || musicChannels_g[index].xmctx) return ERROR_UNINITIALIZED_CHANNELS; // error + if (musicStreams[index].stream || musicStreams[index].xmctx) return ERROR_UNINITIALIZED_CHANNELS; // error for (mixIndex = 0; mixIndex < MAX_MIX_CHANNELS; mixIndex++) // find empty mix channel slot { - if (mixChannels_g[mixIndex] == NULL) break; + if (mixChannels[mixIndex] == NULL) break; else if (mixIndex == (MAX_MIX_CHANNELS - 1)) return ERROR_OUT_OF_MIX_CHANNELS; // error } if (strcmp(GetExtension(fileName),"ogg") == 0) { // Open audio stream - musicChannels_g[index].stream = stb_vorbis_open_filename(fileName, NULL, NULL); + musicStreams[index].stream = stb_vorbis_open_filename(fileName, NULL, NULL); - if (musicChannels_g[index].stream == NULL) + if (musicStreams[index].stream == NULL) { TraceLog(WARNING, "[%s] OGG audio file could not be opened", fileName); return ERROR_LOADING_OGG; // error @@ -824,53 +850,53 @@ int PlayMusicStream(int index, char *fileName) else { // Get file info - stb_vorbis_info info = stb_vorbis_get_info(musicChannels_g[index].stream); + stb_vorbis_info info = stb_vorbis_get_info(musicStreams[index].stream); TraceLog(INFO, "[%s] Ogg sample rate: %i", fileName, info.sample_rate); TraceLog(INFO, "[%s] Ogg channels: %i", fileName, info.channels); TraceLog(DEBUG, "[%s] Temp memory required: %i", fileName, info.temp_memory_required); - musicChannels_g[index].loop = true; // We loop by default - musicEnabled_g = true; + musicStreams[index].loop = true; // We loop by default + musicStreams[index].enabled = true; - musicChannels_g[index].totalSamplesLeft = (unsigned int)stb_vorbis_stream_length_in_samples(musicChannels_g[index].stream) * info.channels; - musicChannels_g[index].totalLengthSeconds = stb_vorbis_stream_length_in_seconds(musicChannels_g[index].stream); + musicStreams[index].totalSamplesLeft = (unsigned int)stb_vorbis_stream_length_in_samples(musicStreams[index].stream) * info.channels; + musicStreams[index].totalLengthSeconds = stb_vorbis_stream_length_in_seconds(musicStreams[index].stream); if (info.channels == 2) { - musicChannels_g[index].mixc = InitMixChannel(info.sample_rate, mixIndex, 2, false); - musicChannels_g[index].mixc->playing = true; + musicStreams[index].mixc = InitMixChannel(info.sample_rate, mixIndex, 2, false); + musicStreams[index].mixc->playing = true; } else { - musicChannels_g[index].mixc = InitMixChannel(info.sample_rate, mixIndex, 1, false); - musicChannels_g[index].mixc->playing = true; + musicStreams[index].mixc = InitMixChannel(info.sample_rate, mixIndex, 1, false); + musicStreams[index].mixc->playing = true; } - if (!musicChannels_g[index].mixc) return ERROR_LOADING_OGG; // error + if (!musicStreams[index].mixc) return ERROR_LOADING_OGG; // error } } else if (strcmp(GetExtension(fileName),"xm") == 0) { // only stereo is supported for xm - if (!jar_xm_create_context_from_file(&musicChannels_g[index].xmctx, 48000, fileName)) + if (!jar_xm_create_context_from_file(&musicStreams[index].xmctx, 48000, fileName)) { - musicChannels_g[index].chipTune = true; - musicChannels_g[index].loop = true; - jar_xm_set_max_loop_count(musicChannels_g[index].xmctx, 0); // infinite number of loops - musicChannels_g[index].totalSamplesLeft = (unsigned int)jar_xm_get_remaining_samples(musicChannels_g[index].xmctx); - musicChannels_g[index].totalLengthSeconds = ((float)musicChannels_g[index].totalSamplesLeft) / 48000.f; - musicEnabled_g = true; + musicStreams[index].chipTune = true; + musicStreams[index].loop = true; + jar_xm_set_max_loop_count(musicStreams[index].xmctx, 0); // infinite number of loops + musicStreams[index].totalSamplesLeft = (unsigned int)jar_xm_get_remaining_samples(musicStreams[index].xmctx); + musicStreams[index].totalLengthSeconds = ((float)musicStreams[index].totalSamplesLeft)/48000.0f; + musicStreams[index].enabled = true; - TraceLog(INFO, "[%s] XM number of samples: %i", fileName, musicChannels_g[index].totalSamplesLeft); - TraceLog(INFO, "[%s] XM track length: %11.6f sec", fileName, musicChannels_g[index].totalLengthSeconds); + TraceLog(INFO, "[%s] XM number of samples: %i", fileName, musicStreams[index].totalSamplesLeft); + TraceLog(INFO, "[%s] XM track length: %11.6f sec", fileName, musicStreams[index].totalLengthSeconds); - musicChannels_g[index].mixc = InitMixChannel(48000, mixIndex, 2, true); + musicStreams[index].mixc = InitMixChannel(48000, mixIndex, 2, true); - if (!musicChannels_g[index].mixc) return ERROR_XM_CONTEXT_CREATION; // error + if (!musicStreams[index].mixc) return ERROR_XM_CONTEXT_CREATION; // error - musicChannels_g[index].mixc->playing = true; + musicStreams[index].mixc->playing = true; } else { @@ -880,24 +906,24 @@ int PlayMusicStream(int index, char *fileName) } else if (strcmp(GetExtension(fileName),"mod") == 0) { - jar_mod_init(&musicChannels_g[index].modctx); + jar_mod_init(&musicStreams[index].modctx); - if (jar_mod_load_file(&musicChannels_g[index].modctx, fileName)) + if (jar_mod_load_file(&musicStreams[index].modctx, fileName)) { - musicChannels_g[index].chipTune = true; - musicChannels_g[index].loop = true; - musicChannels_g[index].totalSamplesLeft = (unsigned int)jar_mod_max_samples(&musicChannels_g[index].modctx); - musicChannels_g[index].totalLengthSeconds = ((float)musicChannels_g[index].totalSamplesLeft) / 48000.f; - musicEnabled_g = true; + musicStreams[index].chipTune = true; + musicStreams[index].loop = true; + musicStreams[index].totalSamplesLeft = (unsigned int)jar_mod_max_samples(&musicStreams[index].modctx); + musicStreams[index].totalLengthSeconds = ((float)musicStreams[index].totalSamplesLeft)/48000.0f; + musicStreams[index].enabled = true; - TraceLog(INFO, "[%s] MOD number of samples: %i", fileName, musicChannels_g[index].totalSamplesLeft); - TraceLog(INFO, "[%s] MOD track length: %11.6f sec", fileName, musicChannels_g[index].totalLengthSeconds); + TraceLog(INFO, "[%s] MOD number of samples: %i", fileName, musicStreams[index].totalSamplesLeft); + TraceLog(INFO, "[%s] MOD track length: %11.6f sec", fileName, musicStreams[index].totalLengthSeconds); - musicChannels_g[index].mixc = InitMixChannel(48000, mixIndex, 2, false); + musicStreams[index].mixc = InitMixChannel(48000, mixIndex, 2, false); - if (!musicChannels_g[index].mixc) return ERROR_MOD_CONTEXT_CREATION; // error + if (!musicStreams[index].mixc) return ERROR_MOD_CONTEXT_CREATION; // error - musicChannels_g[index].mixc->playing = true; + musicStreams[index].mixc->playing = true; } else { @@ -914,28 +940,72 @@ int PlayMusicStream(int index, char *fileName) return 0; // normal return } -// Stop music playing for individual music index of musicChannels_g array (close stream) +// Stop music playing for individual music index of musicStreams array (close stream) void StopMusicStream(int index) { - if (index < MAX_MUSIC_STREAMS && musicChannels_g[index].mixc) + if (index < MAX_MUSIC_STREAMS && musicStreams[index].mixc) { - CloseMixChannel(musicChannels_g[index].mixc); + CloseMixChannel(musicStreams[index].mixc); + + if (musicStreams[index].xmctx) + jar_xm_free_context(musicStreams[index].xmctx); + else if (musicStreams[index].modctx.mod_loaded) + jar_mod_unload(&musicStreams[index].modctx); + else + stb_vorbis_close(musicStreams[index].stream); + + musicStreams[index].enabled = false; - if (musicChannels_g[index].chipTune && musicChannels_g[index].xmctx) + if (musicStreams[index].stream || musicStreams[index].xmctx) { - jar_xm_free_context(musicChannels_g[index].xmctx); - musicChannels_g[index].xmctx = 0; + musicStreams[index].stream = NULL; + musicStreams[index].xmctx = NULL; } - else if (musicChannels_g[index].chipTune && musicChannels_g[index].modctx.mod_loaded) jar_mod_unload(&musicChannels_g[index].modctx); - else stb_vorbis_close(musicChannels_g[index].stream); - - if (!GetMusicStreamCount()) musicEnabled_g = false; + } +} + +// Update (re-fill) music buffers if data already processed +void UpdateMusicStream(int index) +{ + ALenum state; + bool active = true; + ALint processed = 0; + + // Determine if music stream is ready to be written + alGetSourcei(musicStreams[index].mixc->alSource, AL_BUFFERS_PROCESSED, &processed); + + if (musicStreams[index].mixc->playing && (index < MAX_MUSIC_STREAMS) && musicStreams[index].enabled && musicStreams[index].mixc && (processed > 0)) + { + active = BufferMusicStream(index, processed); - if (musicChannels_g[index].stream || musicChannels_g[index].xmctx) + if (!active && musicStreams[index].loop) { - musicChannels_g[index].stream = NULL; - musicChannels_g[index].xmctx = NULL; + if (musicStreams[index].chipTune) + { + if(musicStreams[index].modctx.mod_loaded) jar_mod_seek_start(&musicStreams[index].modctx); + + musicStreams[index].totalSamplesLeft = musicStreams[index].totalLengthSeconds*48000.0f; + } + else + { + stb_vorbis_seek_start(musicStreams[index].stream); + musicStreams[index].totalSamplesLeft = stb_vorbis_stream_length_in_samples(musicStreams[index].stream)*musicStreams[index].mixc->channels; + } + + // Determine if music stream is ready to be written + alGetSourcei(musicStreams[index].mixc->alSource, AL_BUFFERS_PROCESSED, &processed); + + active = BufferMusicStream(index, processed); } + + if (alGetError() != AL_NO_ERROR) TraceLog(WARNING, "Error buffering data..."); + + alGetSourcei(musicStreams[index].mixc->alSource, AL_SOURCE_STATE, &state); + + if (state != AL_PLAYING && active) alSourcePlay(musicStreams[index].mixc->alSource); + + if (!active) StopMusicStream(index); + } } @@ -947,7 +1017,7 @@ int GetMusicStreamCount(void) // Find empty music slot for (int musicIndex = 0; musicIndex < MAX_MUSIC_STREAMS; musicIndex++) { - if(musicChannels_g[musicIndex].stream != NULL || musicChannels_g[musicIndex].chipTune) musicCount++; + if(musicStreams[musicIndex].stream != NULL || musicStreams[musicIndex].chipTune) musicCount++; } return musicCount; @@ -957,11 +1027,11 @@ int GetMusicStreamCount(void) void PauseMusicStream(int index) { // Pause music stream if music available! - if (index < MAX_MUSIC_STREAMS && musicChannels_g[index].mixc && musicEnabled_g) + if (index < MAX_MUSIC_STREAMS && musicStreams[index].mixc && musicStreams[index].enabled) { TraceLog(INFO, "Pausing music stream"); - alSourcePause(musicChannels_g[index].mixc->alSource); - musicChannels_g[index].mixc->playing = false; + alSourcePause(musicStreams[index].mixc->alSource); + musicStreams[index].mixc->playing = false; } } @@ -971,15 +1041,15 @@ void ResumeMusicStream(int index) // Resume music playing... if music available! ALenum state; - if (index < MAX_MUSIC_STREAMS && musicChannels_g[index].mixc) + if (index < MAX_MUSIC_STREAMS && musicStreams[index].mixc) { - alGetSourcei(musicChannels_g[index].mixc->alSource, AL_SOURCE_STATE, &state); + alGetSourcei(musicStreams[index].mixc->alSource, AL_SOURCE_STATE, &state); if (state == AL_PAUSED) { TraceLog(INFO, "Resuming music stream"); - alSourcePlay(musicChannels_g[index].mixc->alSource); - musicChannels_g[index].mixc->playing = true; + alSourcePlay(musicStreams[index].mixc->alSource); + musicStreams[index].mixc->playing = true; } } } @@ -990,9 +1060,9 @@ bool IsMusicPlaying(int index) bool playing = false; ALint state; - if (index < MAX_MUSIC_STREAMS && musicChannels_g[index].mixc) + if (index < MAX_MUSIC_STREAMS && musicStreams[index].mixc) { - alGetSourcei(musicChannels_g[index].mixc->alSource, AL_SOURCE_STATE, &state); + alGetSourcei(musicStreams[index].mixc->alSource, AL_SOURCE_STATE, &state); if (state == AL_PLAYING) playing = true; } @@ -1003,18 +1073,18 @@ bool IsMusicPlaying(int index) // Set volume for music void SetMusicVolume(int index, float volume) { - if (index < MAX_MUSIC_STREAMS && musicChannels_g[index].mixc) + if (index < MAX_MUSIC_STREAMS && musicStreams[index].mixc) { - alSourcef(musicChannels_g[index].mixc->alSource, AL_GAIN, volume); + alSourcef(musicStreams[index].mixc->alSource, AL_GAIN, volume); } } // Set pitch for music void SetMusicPitch(int index, float pitch) { - if (index < MAX_MUSIC_STREAMS && musicChannels_g[index].mixc) + if (index < MAX_MUSIC_STREAMS && musicStreams[index].mixc) { - alSourcef(musicChannels_g[index].mixc->alSource, AL_PITCH, pitch); + alSourcef(musicStreams[index].mixc->alSource, AL_PITCH, pitch); } } @@ -1023,8 +1093,8 @@ float GetMusicTimeLength(int index) { float totalSeconds; - if (musicChannels_g[index].chipTune) totalSeconds = (float)musicChannels_g[index].totalLengthSeconds; - else totalSeconds = stb_vorbis_stream_length_in_seconds(musicChannels_g[index].stream); + if (musicStreams[index].chipTune) totalSeconds = (float)musicStreams[index].totalLengthSeconds; + else totalSeconds = stb_vorbis_stream_length_in_seconds(musicStreams[index].stream); return totalSeconds; } @@ -1034,24 +1104,24 @@ float GetMusicTimePlayed(int index) { float secondsPlayed = 0.0f; - if (index < MAX_MUSIC_STREAMS && musicChannels_g[index].mixc) + if (index < MAX_MUSIC_STREAMS && musicStreams[index].mixc) { - if (musicChannels_g[index].chipTune && musicChannels_g[index].xmctx) + if (musicStreams[index].chipTune && musicStreams[index].xmctx) { uint64_t samples; - jar_xm_get_position(musicChannels_g[index].xmctx, NULL, NULL, NULL, &samples); - secondsPlayed = (float)samples / (48000.f * musicChannels_g[index].mixc->channels); // Not sure if this is the correct value + jar_xm_get_position(musicStreams[index].xmctx, NULL, NULL, NULL, &samples); + secondsPlayed = (float)samples/(48000.0f*musicStreams[index].mixc->channels); // Not sure if this is the correct value } - else if(musicChannels_g[index].chipTune && musicChannels_g[index].modctx.mod_loaded) + else if(musicStreams[index].chipTune && musicStreams[index].modctx.mod_loaded) { - long numsamp = jar_mod_current_samples(&musicChannels_g[index].modctx); - secondsPlayed = (float)numsamp / (48000.f); + long numsamp = jar_mod_current_samples(&musicStreams[index].modctx); + secondsPlayed = (float)numsamp/(48000.0f); } else { - int totalSamples = stb_vorbis_stream_length_in_samples(musicChannels_g[index].stream) * musicChannels_g[index].mixc->channels; - int samplesPlayed = totalSamples - musicChannels_g[index].totalSamplesLeft; - secondsPlayed = (float)samplesPlayed / (musicChannels_g[index].mixc->sampleRate * musicChannels_g[index].mixc->channels); + int totalSamples = stb_vorbis_stream_length_in_samples(musicStreams[index].stream)*musicStreams[index].mixc->channels; + int samplesPlayed = totalSamples - musicStreams[index].totalSamplesLeft; + secondsPlayed = (float)samplesPlayed/(musicStreams[index].mixc->sampleRate*musicStreams[index].mixc->channels); } } @@ -1071,30 +1141,30 @@ static bool BufferMusicStream(int index, int numBuffers) int size = 0; // Total size of data steamed in L+R samples for xm floats, individual L or R for ogg shorts bool active = true; // We can get more data from stream (not finished) - if (musicChannels_g[index].chipTune) // There is no end of stream for xmfiles, once the end is reached zeros are generated for non looped chiptunes. + if (musicStreams[index].chipTune) // There is no end of stream for xmfiles, once the end is reached zeros are generated for non looped chiptunes. { for (int i = 0; i < numBuffers; i++) { - if (musicChannels_g[index].modctx.mod_loaded) + if (musicStreams[index].modctx.mod_loaded) { - if (musicChannels_g[index].totalSamplesLeft >= MUSIC_BUFFER_SIZE_SHORT) size = MUSIC_BUFFER_SIZE_SHORT/2; - else size = musicChannels_g[index].totalSamplesLeft/2; + if (musicStreams[index].totalSamplesLeft >= MUSIC_BUFFER_SIZE_SHORT) size = MUSIC_BUFFER_SIZE_SHORT/2; + else size = musicStreams[index].totalSamplesLeft/2; - jar_mod_fillbuffer(&musicChannels_g[index].modctx, pcm, size, 0 ); - BufferMixChannel(musicChannels_g[index].mixc, pcm, size*2); + jar_mod_fillbuffer(&musicStreams[index].modctx, pcm, size, 0 ); + BufferMixChannel(musicStreams[index].mixc, pcm, size*2); } - else if (musicChannels_g[index].xmctx) + else if (musicStreams[index].xmctx) { - if (musicChannels_g[index].totalSamplesLeft >= MUSIC_BUFFER_SIZE_FLOAT) size = MUSIC_BUFFER_SIZE_FLOAT/2; - else size = musicChannels_g[index].totalSamplesLeft/2; + if (musicStreams[index].totalSamplesLeft >= MUSIC_BUFFER_SIZE_FLOAT) size = MUSIC_BUFFER_SIZE_FLOAT/2; + else size = musicStreams[index].totalSamplesLeft/2; - jar_xm_generate_samples(musicChannels_g[index].xmctx, pcmf, size); // reads 2*readlen shorts and moves them to buffer+size memory location - BufferMixChannel(musicChannels_g[index].mixc, pcmf, size*2); + jar_xm_generate_samples(musicStreams[index].xmctx, pcmf, size); // reads 2*readlen shorts and moves them to buffer+size memory location + BufferMixChannel(musicStreams[index].mixc, pcmf, size*2); } - musicChannels_g[index].totalSamplesLeft -= size; + musicStreams[index].totalSamplesLeft -= size; - if (musicChannels_g[index].totalSamplesLeft <= 0) + if (musicStreams[index].totalSamplesLeft <= 0) { active = false; break; @@ -1103,16 +1173,16 @@ static bool BufferMusicStream(int index, int numBuffers) } else { - if (musicChannels_g[index].totalSamplesLeft >= MUSIC_BUFFER_SIZE_SHORT) size = MUSIC_BUFFER_SIZE_SHORT; - else size = musicChannels_g[index].totalSamplesLeft; + if (musicStreams[index].totalSamplesLeft >= MUSIC_BUFFER_SIZE_SHORT) size = MUSIC_BUFFER_SIZE_SHORT; + else size = musicStreams[index].totalSamplesLeft; for (int i = 0; i < numBuffers; i++) { - int streamedBytes = stb_vorbis_get_samples_short_interleaved(musicChannels_g[index].stream, musicChannels_g[index].mixc->channels, pcm, size); - BufferMixChannel(musicChannels_g[index].mixc, pcm, streamedBytes * musicChannels_g[index].mixc->channels); - musicChannels_g[index].totalSamplesLeft -= streamedBytes * musicChannels_g[index].mixc->channels; + int streamedBytes = stb_vorbis_get_samples_short_interleaved(musicStreams[index].stream, musicStreams[index].mixc->channels, pcm, size); + BufferMixChannel(musicStreams[index].mixc, pcm, streamedBytes * musicStreams[index].mixc->channels); + musicStreams[index].totalSamplesLeft -= streamedBytes * musicStreams[index].mixc->channels; - if (musicChannels_g[index].totalSamplesLeft <= 0) + if (musicStreams[index].totalSamplesLeft <= 0) { active = false; break; @@ -1129,62 +1199,16 @@ static void EmptyMusicStream(int index) ALuint buffer = 0; int queued = 0; - alGetSourcei(musicChannels_g[index].mixc->alSource, AL_BUFFERS_QUEUED, &queued); + alGetSourcei(musicStreams[index].mixc->alSource, AL_BUFFERS_QUEUED, &queued); while (queued > 0) { - alSourceUnqueueBuffers(musicChannels_g[index].mixc->alSource, 1, &buffer); + alSourceUnqueueBuffers(musicStreams[index].mixc->alSource, 1, &buffer); queued--; } } -// Determine if a music stream is ready to be written -static int IsMusicStreamReadyForBuffering(int index) -{ - ALint processed = 0; - alGetSourcei(musicChannels_g[index].mixc->alSource, AL_BUFFERS_PROCESSED, &processed); - return processed; -} - -// Update (re-fill) music buffers if data already processed -void UpdateMusicStream(int index) -{ - ALenum state; - bool active = true; - int numBuffers = IsMusicStreamReadyForBuffering(index); - - if (musicChannels_g[index].mixc->playing && (index < MAX_MUSIC_STREAMS) && musicEnabled_g && musicChannels_g[index].mixc && numBuffers) - { - active = BufferMusicStream(index, numBuffers); - - if (!active && musicChannels_g[index].loop) - { - if (musicChannels_g[index].chipTune) - { - if(musicChannels_g[index].modctx.mod_loaded) jar_mod_seek_start(&musicChannels_g[index].modctx); - musicChannels_g[index].totalSamplesLeft = musicChannels_g[index].totalLengthSeconds * 48000; - } - else - { - stb_vorbis_seek_start(musicChannels_g[index].stream); - musicChannels_g[index].totalSamplesLeft = stb_vorbis_stream_length_in_samples(musicChannels_g[index].stream) * musicChannels_g[index].mixc->channels; - } - - active = true; - } - - if (alGetError() != AL_NO_ERROR) TraceLog(WARNING, "Error buffering data..."); - - alGetSourcei(musicChannels_g[index].mixc->alSource, AL_SOURCE_STATE, &state); - - if (state != AL_PLAYING && active) alSourcePlay(musicChannels_g[index].mixc->alSource); - - if (!active) StopMusicStream(index); - - } -} - // Load WAV file into Wave structure static Wave LoadWAV(const char *fileName) { |
