summaryrefslogtreecommitdiff
path: root/libs/raylib/src/raudio.c
diff options
context:
space:
mode:
Diffstat (limited to 'libs/raylib/src/raudio.c')
-rw-r--r--libs/raylib/src/raudio.c1132
1 files changed, 704 insertions, 428 deletions
diff --git a/libs/raylib/src/raudio.c b/libs/raylib/src/raudio.c
index 6313b16..2b6b0a1 100644
--- a/libs/raylib/src/raudio.c
+++ b/libs/raylib/src/raudio.c
@@ -1,6 +1,6 @@
/**********************************************************************************************
*
-* raudio - A simple and easy-to-use audio library based on miniaudio
+* raudio v1.0 - A simple and easy-to-use audio library based on miniaudio
*
* FEATURES:
* - Manage audio device (init/close)
@@ -46,7 +46,7 @@
*
* LICENSE: zlib/libpng
*
-* Copyright (c) 2013-2020 Ramon Santamaria (@raysan5)
+* Copyright (c) 2013-2021 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.
@@ -159,7 +159,11 @@ typedef struct tagBITMAPINFOHEADER {
#define MA_FREE RL_FREE
#define MA_NO_JACK
+#define MA_NO_WAV
+#define MA_NO_FLAC
+#define MA_NO_MP3
#define MINIAUDIO_IMPLEMENTATION
+//#define MA_DEBUG_OUTPUT
#include "external/miniaudio.h" // miniaudio library
#undef PlaySound // Win32 API: windows.h > mmsystem.h defines PlaySound macro
@@ -172,6 +176,20 @@ typedef struct tagBITMAPINFOHEADER {
#if !defined(TRACELOG)
#define TRACELOG(level, ...) (void)0
#endif
+
+ // Allow custom memory allocators
+ #ifndef RL_MALLOC
+ #define RL_MALLOC(sz) malloc(sz)
+ #endif
+ #ifndef RL_CALLOC
+ #define RL_CALLOC(n,sz) calloc(n,sz)
+ #endif
+ #ifndef RL_REALLOC
+ #define RL_REALLOC(ptr,sz) realloc(ptr,sz)
+ #endif
+ #ifndef RL_FREE
+ #define RL_FREE(ptr) free(ptr)
+ #endif
#endif
#if defined(SUPPORT_FILEFORMAT_OGG)
@@ -197,14 +215,13 @@ typedef struct tagBITMAPINFOHEADER {
#include "external/jar_mod.h" // MOD loading functions
#endif
-#if defined(SUPPORT_FILEFORMAT_FLAC)
- #define DRFLAC_MALLOC RL_MALLOC
- #define DRFLAC_REALLOC RL_REALLOC
- #define DRFLAC_FREE RL_FREE
+#if defined(SUPPORT_FILEFORMAT_WAV)
+ #define DRWAV_MALLOC RL_MALLOC
+ #define DRWAV_REALLOC RL_REALLOC
+ #define DRWAV_FREE RL_FREE
- #define DR_FLAC_IMPLEMENTATION
- #define DR_FLAC_NO_WIN32_IO
- #include "external/dr_flac.h" // FLAC loading functions
+ #define DR_WAV_IMPLEMENTATION
+ #include "external/dr_wav.h" // WAV loading functions
#endif
#if defined(SUPPORT_FILEFORMAT_MP3)
@@ -216,6 +233,16 @@ typedef struct tagBITMAPINFOHEADER {
#include "external/dr_mp3.h" // MP3 loading functions
#endif
+#if defined(SUPPORT_FILEFORMAT_FLAC)
+ #define DRFLAC_MALLOC RL_MALLOC
+ #define DRFLAC_REALLOC RL_REALLOC
+ #define DRFLAC_FREE RL_FREE
+
+ #define DR_FLAC_IMPLEMENTATION
+ #define DR_FLAC_NO_WIN32_IO
+ #include "external/dr_flac.h" // FLAC loading functions
+#endif
+
#if defined(_MSC_VER)
#undef bool
#endif
@@ -223,11 +250,23 @@ typedef struct tagBITMAPINFOHEADER {
//----------------------------------------------------------------------------------
// Defines and Macros
//----------------------------------------------------------------------------------
-#define AUDIO_DEVICE_FORMAT ma_format_f32
-#define AUDIO_DEVICE_CHANNELS 2
-#define AUDIO_DEVICE_SAMPLE_RATE 44100
+#ifndef AUDIO_DEVICE_FORMAT
+ #define AUDIO_DEVICE_FORMAT ma_format_f32 // Device output format (float-32bit)
+#endif
+#ifndef AUDIO_DEVICE_CHANNELS
+ #define AUDIO_DEVICE_CHANNELS 2 // Device output channels: stereo
+#endif
+
+#ifndef AUDIO_DEVICE_SAMPLE_RATE
+ #define AUDIO_DEVICE_SAMPLE_RATE 0 // Device output channels: stereo
+#endif
+#ifndef MAX_AUDIO_BUFFER_POOL_CHANNELS
+ #define MAX_AUDIO_BUFFER_POOL_CHANNELS 16 // Audio pool channels
+#endif
+#ifndef DEFAULT_AUDIO_BUFFER_SIZE
+ #define DEFAULT_AUDIO_BUFFER_SIZE 4096 // Default audio buffer size
+#endif
-#define MAX_AUDIO_BUFFER_POOL_CHANNELS 16
//----------------------------------------------------------------------------------
// Types and Structures Definition
@@ -237,7 +276,8 @@ typedef struct tagBITMAPINFOHEADER {
// NOTE: Depends on data structure provided by the library
// in charge of reading the different file types
typedef enum {
- MUSIC_AUDIO_WAV = 0,
+ MUSIC_AUDIO_NONE = 0,
+ MUSIC_AUDIO_WAV,
MUSIC_AUDIO_OGG,
MUSIC_AUDIO_FLAC,
MUSIC_AUDIO_MP3,
@@ -255,7 +295,7 @@ typedef enum {
LOG_ERROR,
LOG_FATAL,
LOG_NONE
-} TraceLogType;
+} TraceLogLevel;
#endif
// NOTE: Different logic is used when feeding data to the playback device
@@ -304,8 +344,8 @@ typedef struct AudioData {
int defaultSize; // Default audio buffer size for audio streams
} Buffer;
struct {
- AudioBuffer *pool[MAX_AUDIO_BUFFER_POOL_CHANNELS]; // Multichannel AudioBuffer pointers pool
unsigned int poolCounter; // AudioBuffer pointers pool counter
+ AudioBuffer *pool[MAX_AUDIO_BUFFER_POOL_CHANNELS]; // Multichannel AudioBuffer pointers pool
unsigned int channels[MAX_AUDIO_BUFFER_POOL_CHANNELS]; // AudioBuffer pool channels
} MultiChannel;
} AudioData;
@@ -319,7 +359,7 @@ static AudioData AUDIO = { // Global AUDIO context
// After some math, considering a sampleRate of 48000, a buffer refill rate of 1/60 seconds and a
// standard double-buffering system, a 4096 samples buffer has been chosen, it should be enough
// In case of music-stalls, just increase this number
- .Buffer.defaultSize = 4096
+ .Buffer.defaultSize = 0
};
//----------------------------------------------------------------------------------
@@ -329,26 +369,25 @@ static void OnLog(ma_context *pContext, ma_device *pDevice, ma_uint32 logLevel,
static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const void *pFramesInput, ma_uint32 frameCount);
static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 frameCount, float localVolume);
-static void InitAudioBufferPool(void); // Initialise the multichannel buffer pool
-static void CloseAudioBufferPool(void); // Close the audio buffers pool
-
#if defined(SUPPORT_FILEFORMAT_WAV)
-static Wave LoadWAV(const char *fileName); // Load WAV file
+static Wave LoadWAV(const unsigned char *fileData, unsigned int fileSize); // Load WAV file
static int SaveWAV(Wave wave, const char *fileName); // Save wave data as WAV file
#endif
#if defined(SUPPORT_FILEFORMAT_OGG)
-static Wave LoadOGG(const char *fileName); // Load OGG file
+static Wave LoadOGG(const unsigned char *fileData, unsigned int fileSize); // Load OGG file
#endif
#if defined(SUPPORT_FILEFORMAT_FLAC)
-static Wave LoadFLAC(const char *fileName); // Load FLAC file
+static Wave LoadFLAC(const unsigned char *fileData, unsigned int fileSize); // Load FLAC file
#endif
#if defined(SUPPORT_FILEFORMAT_MP3)
-static Wave LoadMP3(const char *fileName); // Load MP3 file
+static Wave LoadMP3(const unsigned char *fileData, unsigned int fileSize); // Load MP3 file
#endif
#if defined(RAUDIO_STANDALONE)
-bool IsFileExtension(const char *fileName, const char *ext);// Check file extension
-void TraceLog(int msgType, const char *text, ...); // Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG)
+static bool IsFileExtension(const char *fileName, const char *ext); // Check file extension
+static unsigned char *LoadFileData(const char *fileName, unsigned int *bytesRead); // Load file data as byte array (read)
+static bool SaveFileData(const char *fileName, void *data, unsigned int bytesToWrite); // Save data to file from byte array (write)
+static bool SaveFileText(const char *fileName, char *text); // Save text data to file (write), string must be '\0' terminated
#endif
//----------------------------------------------------------------------------------
@@ -367,6 +406,7 @@ void SetAudioBufferVolume(AudioBuffer *buffer, float volume);
void SetAudioBufferPitch(AudioBuffer *buffer, float pitch);
void TrackAudioBuffer(AudioBuffer *buffer);
void UntrackAudioBuffer(AudioBuffer *buffer);
+int GetAudioStreamBufferSizeDefault();
//----------------------------------------------------------------------------------
// Module Functions Definition - Audio Device initialization and Closing
@@ -383,7 +423,7 @@ void InitAudioDevice(void)
ma_result result = ma_context_init(NULL, 0, &ctxConfig, &AUDIO.System.context);
if (result != MA_SUCCESS)
{
- TRACELOG(LOG_ERROR, "AUDIO: Failed to initialize context");
+ TRACELOG(LOG_WARNING, "AUDIO: Failed to initialize context");
return;
}
@@ -391,19 +431,19 @@ void InitAudioDevice(void)
// NOTE: Using the default device. Format is floating point because it simplifies mixing.
ma_device_config config = ma_device_config_init(ma_device_type_playback);
config.playback.pDeviceID = NULL; // NULL for the default playback AUDIO.System.device.
- config.playback.format = AUDIO_DEVICE_FORMAT;
- config.playback.channels = AUDIO_DEVICE_CHANNELS;
- config.capture.pDeviceID = NULL; // NULL for the default capture AUDIO.System.device.
- config.capture.format = ma_format_s16;
- config.capture.channels = 1;
- config.sampleRate = AUDIO_DEVICE_SAMPLE_RATE;
- config.dataCallback = OnSendAudioDataToDevice;
- config.pUserData = NULL;
+ config.playback.format = AUDIO_DEVICE_FORMAT;
+ config.playback.channels = AUDIO_DEVICE_CHANNELS;
+ config.capture.pDeviceID = NULL; // NULL for the default capture AUDIO.System.device.
+ config.capture.format = ma_format_s16;
+ config.capture.channels = 1;
+ config.sampleRate = AUDIO_DEVICE_SAMPLE_RATE;
+ config.dataCallback = OnSendAudioDataToDevice;
+ config.pUserData = NULL;
result = ma_device_init(&AUDIO.System.context, &config, &AUDIO.System.device);
if (result != MA_SUCCESS)
{
- TRACELOG(LOG_ERROR, "AUDIO: Failed to initialize playback device");
+ TRACELOG(LOG_WARNING, "AUDIO: Failed to initialize playback device");
ma_context_uninit(&AUDIO.System.context);
return;
}
@@ -413,7 +453,7 @@ void InitAudioDevice(void)
result = ma_device_start(&AUDIO.System.device);
if (result != MA_SUCCESS)
{
- TRACELOG(LOG_ERROR, "AUDIO: Failed to start playback device");
+ TRACELOG(LOG_WARNING, "AUDIO: Failed to start playback device");
ma_device_uninit(&AUDIO.System.device);
ma_context_uninit(&AUDIO.System.context);
return;
@@ -421,22 +461,28 @@ void InitAudioDevice(void)
// Mixing happens on a seperate thread which means we need to synchronize. I'm using a mutex here to make things simple, but may
// want to look at something a bit smarter later on to keep everything real-time, if that's necessary.
- if (ma_mutex_init(&AUDIO.System.context, &AUDIO.System.lock) != MA_SUCCESS)
+ if (ma_mutex_init(&AUDIO.System.lock) != MA_SUCCESS)
{
- TRACELOG(LOG_ERROR, "AUDIO: Failed to create mutex for mixing");
+ TRACELOG(LOG_WARNING, "AUDIO: Failed to create mutex for mixing");
ma_device_uninit(&AUDIO.System.device);
ma_context_uninit(&AUDIO.System.context);
return;
}
- TRACELOG(LOG_INFO, "AUDIO: Device initialized successfully");
- TRACELOG(LOG_INFO, " > Backend: miniaudio / %s", ma_get_backend_name(AUDIO.System.context.backend));
- TRACELOG(LOG_INFO, " > Format: %s -> %s", ma_get_format_name(AUDIO.System.device.playback.format), ma_get_format_name(AUDIO.System.device.playback.internalFormat));
- TRACELOG(LOG_INFO, " > Channels: %d -> %d", AUDIO.System.device.playback.channels, AUDIO.System.device.playback.internalChannels);
- TRACELOG(LOG_INFO, " > Sample rate: %d -> %d", AUDIO.System.device.sampleRate, AUDIO.System.device.playback.internalSampleRate);
- TRACELOG(LOG_INFO, " > Periods size: %d", AUDIO.System.device.playback.internalPeriodSizeInFrames*AUDIO.System.device.playback.internalPeriods);
+ // Init dummy audio buffers pool for multichannel sound playing
+ for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
+ {
+ // WARNING: An empty audioBuffer is created (data = 0)
+ // AudioBuffer data just points to loaded sound data
+ AUDIO.MultiChannel.pool[i] = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, 0, AUDIO_BUFFER_USAGE_STATIC);
+ }
- InitAudioBufferPool();
+ TRACELOG(LOG_INFO, "AUDIO: Device initialized successfully");
+ TRACELOG(LOG_INFO, " > Backend: miniaudio / %s", ma_get_backend_name(AUDIO.System.context.backend));
+ TRACELOG(LOG_INFO, " > Format: %s -> %s", ma_get_format_name(AUDIO.System.device.playback.format), ma_get_format_name(AUDIO.System.device.playback.internalFormat));
+ TRACELOG(LOG_INFO, " > Channels: %d -> %d", AUDIO.System.device.playback.channels, AUDIO.System.device.playback.internalChannels);
+ TRACELOG(LOG_INFO, " > Sample rate: %d -> %d", AUDIO.System.device.sampleRate, AUDIO.System.device.playback.internalSampleRate);
+ TRACELOG(LOG_INFO, " > Periods size: %d", AUDIO.System.device.playback.internalPeriodSizeInFrames*AUDIO.System.device.playback.internalPeriods);
AUDIO.System.isReady = true;
}
@@ -446,11 +492,25 @@ void CloseAudioDevice(void)
{
if (AUDIO.System.isReady)
{
+ // Unload dummy audio buffers pool
+ // WARNING: They can be pointing to already unloaded data
+ for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
+ {
+ //UnloadAudioBuffer(AUDIO.MultiChannel.pool[i]);
+ if (AUDIO.MultiChannel.pool[i] != NULL)
+ {
+ ma_data_converter_uninit(&AUDIO.MultiChannel.pool[i]->converter);
+ UntrackAudioBuffer(AUDIO.MultiChannel.pool[i]);
+ //RL_FREE(buffer->data); // Already unloaded by UnloadSound()
+ RL_FREE(AUDIO.MultiChannel.pool[i]);
+ }
+ }
+
ma_mutex_uninit(&AUDIO.System.lock);
ma_device_uninit(&AUDIO.System.device);
ma_context_uninit(&AUDIO.System.context);
- CloseAudioBufferPool();
+ AUDIO.System.isReady = false;
TRACELOG(LOG_INFO, "AUDIO: Device closed successfully");
}
@@ -480,21 +540,21 @@ AudioBuffer *LoadAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sam
if (audioBuffer == NULL)
{
- TRACELOG(LOG_ERROR, "AUDIO: Failed to allocate memory for buffer");
+ TRACELOG(LOG_WARNING, "AUDIO: Failed to allocate memory for buffer");
return NULL;
}
- audioBuffer->data = RL_CALLOC(sizeInFrames*channels*ma_get_bytes_per_sample(format), 1);
+ if (sizeInFrames > 0) audioBuffer->data = RL_CALLOC(sizeInFrames*channels*ma_get_bytes_per_sample(format), 1);
// Audio data runs through a format converter
- ma_data_converter_config converterConfig = ma_data_converter_config_init(format, AUDIO_DEVICE_FORMAT, channels, AUDIO_DEVICE_CHANNELS, sampleRate, AUDIO_DEVICE_SAMPLE_RATE);
+ ma_data_converter_config converterConfig = ma_data_converter_config_init(format, AUDIO_DEVICE_FORMAT, channels, AUDIO_DEVICE_CHANNELS, sampleRate, AUDIO.System.device.sampleRate);
converterConfig.resampling.allowDynamicSampleRate = true; // Required for pitch shifting
ma_result result = ma_data_converter_init(&converterConfig, &audioBuffer->converter);
if (result != MA_SUCCESS)
{
- TRACELOG(LOG_ERROR, "AUDIO: Failed to create data conversion pipeline");
+ TRACELOG(LOG_WARNING, "AUDIO: Failed to create data conversion pipeline");
RL_FREE(audioBuffer);
return NULL;
}
@@ -593,18 +653,16 @@ void SetAudioBufferVolume(AudioBuffer *buffer, float volume)
// Set pitch for an audio buffer
void SetAudioBufferPitch(AudioBuffer *buffer, float pitch)
{
- if (buffer != NULL)
+ if ((buffer != NULL) && (pitch > 0.0f))
{
- float pitchMul = pitch/buffer->pitch;
-
// Pitching is just an adjustment of the sample rate.
// Note that this changes the duration of the sound:
// - higher pitches will make the sound faster
// - lower pitches make it slower
- ma_uint32 newOutputSampleRate = (ma_uint32)((float)buffer->converter.config.sampleRateOut/pitchMul);
- buffer->pitch *= (float)buffer->converter.config.sampleRateOut/newOutputSampleRate;
+ ma_uint32 outputSampleRate = (ma_uint32)((float)buffer->converter.config.sampleRateOut/pitch);
+ ma_data_converter_set_rate(&buffer->converter, buffer->converter.config.sampleRateIn, outputSampleRate);
- ma_data_converter_set_rate(&buffer->converter, buffer->converter.config.sampleRateIn, newOutputSampleRate);
+ buffer->pitch = pitch;
}
}
@@ -651,20 +709,43 @@ Wave LoadWave(const char *fileName)
{
Wave wave = { 0 };
+ // Loading file to memory
+ unsigned int fileSize = 0;
+ unsigned char *fileData = LoadFileData(fileName, &fileSize);
+
+ if (fileData != NULL)
+ {
+ // Loading wave from memory data
+ wave = LoadWaveFromMemory(GetFileExtension(fileName), fileData, fileSize);
+
+ RL_FREE(fileData);
+ }
+
+ return wave;
+}
+
+// Load wave from memory buffer, fileType refers to extension: i.e. ".wav"
+Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int dataSize)
+{
+ Wave wave = { 0 };
+
+ char fileExtLower[16] = { 0 };
+ strcpy(fileExtLower, TextToLower(fileType));
+
if (false) { }
#if defined(SUPPORT_FILEFORMAT_WAV)
- else if (IsFileExtension(fileName, ".wav")) wave = LoadWAV(fileName);
+ else if (TextIsEqual(fileExtLower, ".wav")) wave = LoadWAV(fileData, dataSize);
#endif
#if defined(SUPPORT_FILEFORMAT_OGG)
- else if (IsFileExtension(fileName, ".ogg")) wave = LoadOGG(fileName);
+ else if (TextIsEqual(fileExtLower, ".ogg")) wave = LoadOGG(fileData, dataSize);
#endif
#if defined(SUPPORT_FILEFORMAT_FLAC)
- else if (IsFileExtension(fileName, ".flac")) wave = LoadFLAC(fileName);
+ else if (TextIsEqual(fileExtLower, ".flac")) wave = LoadFLAC(fileData, dataSize);
#endif
#if defined(SUPPORT_FILEFORMAT_MP3)
- else if (IsFileExtension(fileName, ".mp3")) wave = LoadMP3(fileName);
+ else if (TextIsEqual(fileExtLower, ".mp3")) wave = LoadMP3(fileData, dataSize);
#endif
- else TRACELOG(LOG_WARNING, "FILEIO: [%s] File format not supported", fileName);
+ else TRACELOG(LOG_WARNING, "WAVE: File format not supported");
return wave;
}
@@ -702,17 +783,21 @@ Sound LoadSoundFromWave(Wave wave)
ma_format formatIn = ((wave.sampleSize == 8)? ma_format_u8 : ((wave.sampleSize == 16)? ma_format_s16 : ma_format_f32));
ma_uint32 frameCountIn = wave.sampleCount/wave.channels;
- ma_uint32 frameCount = (ma_uint32)ma_convert_frames(NULL, 0, AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO_DEVICE_SAMPLE_RATE, NULL, frameCountIn, formatIn, wave.channels, wave.sampleRate);
+ ma_uint32 frameCount = (ma_uint32)ma_convert_frames(NULL, 0, AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, NULL, frameCountIn, formatIn, wave.channels, wave.sampleRate);
if (frameCount == 0) TRACELOG(LOG_WARNING, "SOUND: Failed to get frame count for format conversion");
- AudioBuffer *audioBuffer = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO_DEVICE_SAMPLE_RATE, frameCount, AUDIO_BUFFER_USAGE_STATIC);
- if (audioBuffer == NULL) TRACELOG(LOG_WARNING, "SOUND: Failed to create buffer");
+ AudioBuffer *audioBuffer = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, frameCount, AUDIO_BUFFER_USAGE_STATIC);
+ if (audioBuffer == NULL)
+ {
+ TRACELOG(LOG_WARNING, "SOUND: Failed to create buffer");
+ return sound; // early return to avoid dereferencing the audioBuffer null pointer
+ }
- frameCount = (ma_uint32)ma_convert_frames(audioBuffer->data, frameCount, AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO_DEVICE_SAMPLE_RATE, wave.data, frameCountIn, formatIn, wave.channels, wave.sampleRate);
+ frameCount = (ma_uint32)ma_convert_frames(audioBuffer->data, frameCount, AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, wave.data, frameCountIn, formatIn, wave.channels, wave.sampleRate);
if (frameCount == 0) TRACELOG(LOG_WARNING, "SOUND: Failed format conversion");
sound.sampleCount = frameCount*AUDIO_DEVICE_CHANNELS;
- sound.stream.sampleRate = AUDIO_DEVICE_SAMPLE_RATE;
+ sound.stream.sampleRate = AUDIO.System.device.sampleRate;
sound.stream.sampleSize = 32;
sound.stream.channels = AUDIO_DEVICE_CHANNELS;
sound.stream.buffer = audioBuffer;
@@ -750,7 +835,7 @@ void UpdateSound(Sound sound, const void *data, int samplesCount)
}
// Export wave data to file
-void ExportWave(Wave wave, const char *fileName)
+bool ExportWave(Wave wave, const char *fileName)
{
bool success = false;
@@ -762,58 +847,68 @@ void ExportWave(Wave wave, const char *fileName)
{
// Export raw sample data (without header)
// NOTE: It's up to the user to track wave parameters
- SaveFileData(fileName, wave.data, wave.sampleCount*wave.channels*wave.sampleSize/8);
- success = true;
+ success = SaveFileData(fileName, wave.data, wave.sampleCount*wave.sampleSize/8);
}
if (success) TRACELOG(LOG_INFO, "FILEIO: [%s] Wave data exported successfully", fileName);
else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export wave data", fileName);
+
+ return success;
}
// Export wave sample data to code (.h)
-void ExportWaveAsCode(Wave wave, const char *fileName)
+bool ExportWaveAsCode(Wave wave, const char *fileName)
{
- #define BYTES_TEXT_PER_LINE 20
+ bool success = false;
- char varFileName[256] = { 0 };
- int dataSize = wave.sampleCount*wave.channels*wave.sampleSize/8;
+#ifndef TEXT_BYTES_PER_LINE
+ #define TEXT_BYTES_PER_LINE 20
+#endif
- FILE *txtFile = fopen(fileName, "wt");
+ int waveDataSize = wave.sampleCount*wave.channels*wave.sampleSize/8;
- if (txtFile != NULL)
- {
- fprintf(txtFile, "\n//////////////////////////////////////////////////////////////////////////////////\n");
- fprintf(txtFile, "// //\n");
- fprintf(txtFile, "// WaveAsCode exporter v1.0 - Wave data exported as an array of bytes //\n");
- fprintf(txtFile, "// //\n");
- fprintf(txtFile, "// more info and bugs-report: github.com/raysan5/raylib //\n");
- fprintf(txtFile, "// feedback and support: ray[at]raylib.com //\n");
- fprintf(txtFile, "// //\n");
- fprintf(txtFile, "// Copyright (c) 2018 Ramon Santamaria (@raysan5) //\n");
- fprintf(txtFile, "// //\n");
- fprintf(txtFile, "//////////////////////////////////////////////////////////////////////////////////\n\n");
+ // NOTE: Text data buffer size is estimated considering wave data size in bytes
+ // and requiring 6 char bytes for every byte: "0x00, "
+ char *txtData = (char *)RL_CALLOC(6*waveDataSize + 2000, sizeof(char));
+ int bytesCount = 0;
+ bytesCount += sprintf(txtData + bytesCount, "\n//////////////////////////////////////////////////////////////////////////////////\n");
+ bytesCount += sprintf(txtData + bytesCount, "// //\n");
+ bytesCount += sprintf(txtData + bytesCount, "// WaveAsCode exporter v1.0 - Wave data exported as an array of bytes //\n");
+ bytesCount += sprintf(txtData + bytesCount, "// //\n");
+ bytesCount += sprintf(txtData + bytesCount, "// more info and bugs-report: github.com/raysan5/raylib //\n");
+ bytesCount += sprintf(txtData + bytesCount, "// feedback and support: ray[at]raylib.com //\n");
+ bytesCount += sprintf(txtData + bytesCount, "// //\n");
+ bytesCount += sprintf(txtData + bytesCount, "// Copyright (c) 2018 Ramon Santamaria (@raysan5) //\n");
+ bytesCount += sprintf(txtData + bytesCount, "// //\n");
+ bytesCount += sprintf(txtData + bytesCount, "//////////////////////////////////////////////////////////////////////////////////\n\n");
+
+ char varFileName[256] = { 0 };
#if !defined(RAUDIO_STANDALONE)
- // Get file name from path and convert variable name to uppercase
- strcpy(varFileName, GetFileNameWithoutExt(fileName));
- for (int i = 0; varFileName[i] != '\0'; i++) if (varFileName[i] >= 'a' && varFileName[i] <= 'z') { varFileName[i] = varFileName[i] - 32; }
+ // Get file name from path and convert variable name to uppercase
+ strcpy(varFileName, GetFileNameWithoutExt(fileName));
+ for (int i = 0; varFileName[i] != '\0'; i++) if (varFileName[i] >= 'a' && varFileName[i] <= 'z') { varFileName[i] = varFileName[i] - 32; }
#else
- strcpy(varFileName, fileName);
+ strcpy(varFileName, fileName);
#endif
- fprintf(txtFile, "// Wave data information\n");
- fprintf(txtFile, "#define %s_SAMPLE_COUNT %u\n", varFileName, wave.sampleCount);
- fprintf(txtFile, "#define %s_SAMPLE_RATE %u\n", varFileName, wave.sampleRate);
- fprintf(txtFile, "#define %s_SAMPLE_SIZE %u\n", varFileName, wave.sampleSize);
- fprintf(txtFile, "#define %s_CHANNELS %u\n\n", varFileName, wave.channels);
+ bytesCount += sprintf(txtData + bytesCount, "// Wave data information\n");
+ bytesCount += sprintf(txtData + bytesCount, "#define %s_SAMPLE_COUNT %u\n", varFileName, wave.sampleCount);
+ bytesCount += sprintf(txtData + bytesCount, "#define %s_SAMPLE_RATE %u\n", varFileName, wave.sampleRate);
+ bytesCount += sprintf(txtData + bytesCount, "#define %s_SAMPLE_SIZE %u\n", varFileName, wave.sampleSize);
+ bytesCount += sprintf(txtData + bytesCount, "#define %s_CHANNELS %u\n\n", varFileName, wave.channels);
- // Write byte data as hexadecimal text
- fprintf(txtFile, "static unsigned char %s_DATA[%i] = { ", varFileName, dataSize);
- for (int i = 0; i < dataSize - 1; i++) fprintf(txtFile, ((i%BYTES_TEXT_PER_LINE == 0)? "0x%x,\n" : "0x%x, "), ((unsigned char *)wave.data)[i]);
- fprintf(txtFile, "0x%x };\n", ((unsigned char *)wave.data)[dataSize - 1]);
+ // Write byte data as hexadecimal text
+ bytesCount += sprintf(txtData + bytesCount, "static unsigned char %s_DATA[%i] = { ", varFileName, waveDataSize);
+ for (int i = 0; i < waveDataSize - 1; i++) bytesCount += sprintf(txtData + bytesCount, ((i%TEXT_BYTES_PER_LINE == 0)? "0x%x,\n" : "0x%x, "), ((unsigned char *)wave.data)[i]);
+ bytesCount += sprintf(txtData + bytesCount, "0x%x };\n", ((unsigned char *)wave.data)[waveDataSize - 1]);
- fclose(txtFile);
- }
+ // NOTE: Text data length exported is determined by '\0' (NULL) character
+ success = SaveFileText(fileName, txtData);
+
+ RL_FREE(txtData);
+
+ return success;
}
// Play a sound
@@ -940,10 +1035,10 @@ void SetSoundPitch(Sound sound, float pitch)
// Convert wave data to desired format
void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels)
{
- ma_format formatIn = ((wave->sampleSize == 8)? ma_format_u8 : ((wave->sampleSize == 16)? ma_format_s16 : ma_format_f32));
- ma_format formatOut = (( sampleSize == 8)? ma_format_u8 : (( sampleSize == 16)? ma_format_s16 : ma_format_f32));
+ ma_format formatIn = ((wave->sampleSize == 8)? ma_format_u8 : ((wave->sampleSize == 16)? ma_format_s16 : ma_format_f32));
+ ma_format formatOut = ((sampleSize == 8)? ma_format_u8 : ((sampleSize == 16)? ma_format_s16 : ma_format_f32));
- ma_uint32 frameCountIn = wave->sampleCount; // Is wave->sampleCount actually the frame count? That terminology needs to change, if so.
+ ma_uint32 frameCountIn = wave->sampleCount/wave->channels;
ma_uint32 frameCount = (ma_uint32)ma_convert_frames(NULL, 0, formatOut, channels, sampleRate, NULL, frameCountIn, formatIn, wave->channels, wave->sampleRate);
if (frameCount == 0)
@@ -961,7 +1056,7 @@ void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels)
return;
}
- wave->sampleCount = frameCount;
+ wave->sampleCount = frameCount*channels;
wave->sampleSize = sampleSize;
wave->sampleRate = sampleRate;
wave->channels = channels;
@@ -974,12 +1069,12 @@ Wave WaveCopy(Wave wave)
{
Wave newWave = { 0 };
- newWave.data = RL_MALLOC(wave.sampleCount*wave.sampleSize/8*wave.channels);
+ newWave.data = RL_MALLOC(wave.sampleCount*wave.sampleSize/8);
if (newWave.data != NULL)
{
// NOTE: Size must be provided in bytes
- memcpy(newWave.data, wave.data, wave.sampleCount*wave.channels*wave.sampleSize/8);
+ memcpy(newWave.data, wave.data, wave.sampleCount*wave.sampleSize/8);
newWave.sampleCount = wave.sampleCount;
newWave.sampleRate = wave.sampleRate;
@@ -999,9 +1094,9 @@ void WaveCrop(Wave *wave, int initSample, int finalSample)
{
int sampleCount = finalSample - initSample;
- void *data = RL_MALLOC(sampleCount*wave->sampleSize/8*wave->channels);
+ void *data = RL_MALLOC(sampleCount*wave->sampleSize/8);
- memcpy(data, (unsigned char *)wave->data + (initSample*wave->channels*wave->sampleSize/8), sampleCount*wave->channels*wave->sampleSize/8);
+ memcpy(data, (unsigned char *)wave->data + (initSample*wave->channels*wave->sampleSize/8), sampleCount*wave->sampleSize/8);
RL_FREE(wave->data);
wave->data = data;
@@ -1009,25 +1104,31 @@ void WaveCrop(Wave *wave, int initSample, int finalSample)
else TRACELOG(LOG_WARNING, "WAVE: Crop range out of bounds");
}
-// Get samples data from wave as a floats array
-// NOTE: Returned sample values are normalized to range [-1..1]
-float *GetWaveData(Wave wave)
+// Load samples data from wave as a floats array
+// NOTE 1: Returned sample values are normalized to range [-1..1]
+// NOTE 2: Sample data allocated should be freed with UnloadWaveSamples()
+float *LoadWaveSamples(Wave wave)
{
- float *samples = (float *)RL_MALLOC(wave.sampleCount*wave.channels*sizeof(float));
+ float *samples = (float *)RL_MALLOC(wave.sampleCount*sizeof(float));
+
+ // NOTE: sampleCount is the total number of interlaced samples (including channels)
for (unsigned int i = 0; i < wave.sampleCount; i++)
{
- for (unsigned int j = 0; j < wave.channels; j++)
- {
- if (wave.sampleSize == 8) samples[wave.channels*i + j] = (float)(((unsigned char *)wave.data)[wave.channels*i + j] - 127)/256.0f;
- else if (wave.sampleSize == 16) samples[wave.channels*i + j] = (float)((short *)wave.data)[wave.channels*i + j]/32767.0f;
- else if (wave.sampleSize == 32) samples[wave.channels*i + j] = ((float *)wave.data)[wave.channels*i + j];
- }
+ if (wave.sampleSize == 8) samples[i] = (float)(((unsigned char *)wave.data)[i] - 127)/256.0f;
+ else if (wave.sampleSize == 16) samples[i] = (float)(((short *)wave.data)[i])/32767.0f;
+ else if (wave.sampleSize == 32) samples[i] = ((float *)wave.data)[i];
}
return samples;
}
+// Unload samples data loaded with LoadWaveSamples()
+void UnloadWaveSamples(float *samples)
+{
+ RL_FREE(samples);
+}
+
//----------------------------------------------------------------------------------
// Module Functions Definition - Music loading and stream playing (.OGG)
//----------------------------------------------------------------------------------
@@ -1039,21 +1140,44 @@ Music LoadMusicStream(const char *fileName)
bool musicLoaded = false;
if (false) { }
+#if defined(SUPPORT_FILEFORMAT_WAV)
+ else if (IsFileExtension(fileName, ".wav"))
+ {
+ drwav *ctxWav = RL_CALLOC(1, sizeof(drwav));
+ bool success = drwav_init_file(ctxWav, fileName, NULL);
+
+ music.ctxType = MUSIC_AUDIO_WAV;
+ music.ctxData = ctxWav;
+
+ if (success)
+ {
+ int sampleSize = ctxWav->bitsPerSample;
+ if (ctxWav->bitsPerSample == 24) sampleSize = 16; // Forcing conversion to s16 on UpdateMusicStream()
+
+ music.stream = InitAudioStream(ctxWav->sampleRate, sampleSize, ctxWav->channels);
+ music.sampleCount = (unsigned int)ctxWav->totalPCMFrameCount*ctxWav->channels;
+ music.looping = true; // Looping enabled by default
+ musicLoaded = true;
+ }
+ }
+#endif
#if defined(SUPPORT_FILEFORMAT_OGG)
else if (IsFileExtension(fileName, ".ogg"))
{
// Open ogg audio stream
+ music.ctxType = MUSIC_AUDIO_OGG;
music.ctxData = stb_vorbis_open_filename(fileName, NULL, NULL);
if (music.ctxData != NULL)
{
- music.ctxType = MUSIC_AUDIO_OGG;
stb_vorbis_info info = stb_vorbis_get_info((stb_vorbis *)music.ctxData); // Get Ogg file info
// OGG bit rate defaults to 16 bit, it's enough for compressed format
music.stream = InitAudioStream(info.sample_rate, 16, info.channels);
+
+ // WARNING: It seems this function returns length in frames, not samples, so we multiply by channels
music.sampleCount = (unsigned int)stb_vorbis_stream_length_in_samples((stb_vorbis *)music.ctxData)*info.channels;
- music.loopCount = 0; // Infinite loop by default
+ music.looping = true; // Looping enabled by default
musicLoaded = true;
}
}
@@ -1061,16 +1185,16 @@ Music LoadMusicStream(const char *fileName)
#if defined(SUPPORT_FILEFORMAT_FLAC)
else if (IsFileExtension(fileName, ".flac"))
{
- music.ctxData = drflac_open_file(fileName);
+ music.ctxType = MUSIC_AUDIO_FLAC;
+ music.ctxData = drflac_open_file(fileName, NULL);
if (music.ctxData != NULL)
{
- music.ctxType = MUSIC_AUDIO_FLAC;
drflac *ctxFlac = (drflac *)music.ctxData;
music.stream = InitAudioStream(ctxFlac->sampleRate, ctxFlac->bitsPerSample, ctxFlac->channels);
- music.sampleCount = (unsigned int)ctxFlac->totalSampleCount;
- music.loopCount = 0; // Infinite loop by default
+ music.sampleCount = (unsigned int)ctxFlac->totalPCMFrameCount*ctxFlac->channels;
+ music.looping = true; // Looping enabled by default
musicLoaded = true;
}
}
@@ -1078,18 +1202,17 @@ Music LoadMusicStream(const char *fileName)
#if defined(SUPPORT_FILEFORMAT_MP3)
else if (IsFileExtension(fileName, ".mp3"))
{
- drmp3 *ctxMp3 = RL_MALLOC(sizeof(drmp3));
- music.ctxData = ctxMp3;
-
+ drmp3 *ctxMp3 = RL_CALLOC(1, sizeof(drmp3));
int result = drmp3_init_file(ctxMp3, fileName, NULL);
+ music.ctxType = MUSIC_AUDIO_MP3;
+ music.ctxData = ctxMp3;
+
if (result > 0)
{
- music.ctxType = MUSIC_AUDIO_MP3;
-
music.stream = InitAudioStream(ctxMp3->sampleRate, 32, ctxMp3->channels);
music.sampleCount = (unsigned int)drmp3_get_pcm_frame_count(ctxMp3)*ctxMp3->channels;
- music.loopCount = 0; // Infinite loop by default
+ music.looping = true; // Looping enabled by default
musicLoaded = true;
}
}
@@ -1098,60 +1221,261 @@ Music LoadMusicStream(const char *fileName)
else if (IsFileExtension(fileName, ".xm"))
{
jar_xm_context_t *ctxXm = NULL;
+ int result = jar_xm_create_context_from_file(&ctxXm, AUDIO.System.device.sampleRate, fileName);
- int result = jar_xm_create_context_from_file(&ctxXm, 48000, fileName);
+ music.ctxType = MUSIC_MODULE_XM;
+ music.ctxData = ctxXm;
if (result == 0) // XM AUDIO.System.context created successfully
{
- music.ctxType = MUSIC_MODULE_XM;
jar_xm_set_max_loop_count(ctxXm, 0); // Set infinite number of loops
+ unsigned int bits = 32;
+ if (AUDIO_DEVICE_FORMAT == ma_format_s16)
+ bits = 16;
+ else if (AUDIO_DEVICE_FORMAT == ma_format_u8)
+ bits = 8;
+
// NOTE: Only stereo is supported for XM
- music.stream = InitAudioStream(48000, 16, 2);
- music.sampleCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm)*2;
- music.loopCount = 0; // Infinite loop by default
+ music.stream = InitAudioStream(AUDIO.System.device.sampleRate, bits, AUDIO_DEVICE_CHANNELS);
+ music.sampleCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm)*2; // 2 channels
+ music.looping = true; // Looping enabled by default
jar_xm_reset(ctxXm); // make sure we start at the beginning of the song
musicLoaded = true;
+ }
+ }
+#endif
+#if defined(SUPPORT_FILEFORMAT_MOD)
+ else if (IsFileExtension(fileName, ".mod"))
+ {
+ jar_mod_context_t *ctxMod = RL_CALLOC(1, sizeof(jar_mod_context_t));
+ jar_mod_init(ctxMod);
+ int result = jar_mod_load_file(ctxMod, fileName);
+
+ music.ctxType = MUSIC_MODULE_MOD;
+ music.ctxData = ctxMod;
+
+ if (result > 0)
+ {
+ // NOTE: Only stereo is supported for MOD
+ music.stream = InitAudioStream(AUDIO.System.device.sampleRate, 16, AUDIO_DEVICE_CHANNELS);
+ music.sampleCount = (unsigned int)jar_mod_max_samples(ctxMod)*2; // 2 channels
+ music.looping = true; // Looping enabled by default
+ musicLoaded = true;
+ }
+ }
+#endif
+ else TRACELOG(LOG_WARNING, "STREAM: [%s] Fileformat not supported", fileName);
+
+ if (!musicLoaded)
+ {
+ if (false) { }
+ #if defined(SUPPORT_FILEFORMAT_WAV)
+ else if (music.ctxType == MUSIC_AUDIO_WAV) drwav_uninit((drwav *)music.ctxData);
+ #endif
+ #if defined(SUPPORT_FILEFORMAT_OGG)
+ else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData);
+ #endif
+ #if defined(SUPPORT_FILEFORMAT_FLAC)
+ else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData, NULL);
+ #endif
+ #if defined(SUPPORT_FILEFORMAT_MP3)
+ else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); }
+ #endif
+ #if defined(SUPPORT_FILEFORMAT_XM)
+ else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData);
+ #endif
+ #if defined(SUPPORT_FILEFORMAT_MOD)
+ else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); }
+ #endif
+
+ music.ctxData = NULL;
+ TRACELOG(LOG_WARNING, "FILEIO: [%s] Music file could not be opened", fileName);
+ }
+ else
+ {
+ // Show some music stream info
+ TRACELOG(LOG_INFO, "FILEIO: [%s] Music file successfully loaded:", fileName);
+ TRACELOG(LOG_INFO, " > Total samples: %i", music.sampleCount);
+ TRACELOG(LOG_INFO, " > Sample rate: %i Hz", music.stream.sampleRate);
+ TRACELOG(LOG_INFO, " > Sample size: %i bits", music.stream.sampleSize);
+ TRACELOG(LOG_INFO, " > Channels: %i (%s)", music.stream.channels, (music.stream.channels == 1)? "Mono" : (music.stream.channels == 2)? "Stereo" : "Multi");
+ }
+
+ return music;
+}
+
+// extension including period ".mod"
+Music LoadMusicStreamFromMemory(const char *fileType, unsigned char* data, int dataSize)
+{
+ Music music = { 0 };
+ bool musicLoaded = false;
+
+ char fileExtLower[16] = { 0 };
+ strcpy(fileExtLower, TextToLower(fileType));
+
+ if (false) { }
+#if defined(SUPPORT_FILEFORMAT_WAV)
+ else if (TextIsEqual(fileExtLower, ".wav"))
+ {
+ drwav *ctxWav = RL_CALLOC(1, sizeof(drwav));
+
+ bool success = drwav_init_memory(ctxWav, (const void*)data, dataSize, NULL);
+
+ music.ctxType = MUSIC_AUDIO_WAV;
+ music.ctxData = ctxWav;
+
+ if (success)
+ {
+ int sampleSize = ctxWav->bitsPerSample;
+ if (ctxWav->bitsPerSample == 24) sampleSize = 16; // Forcing conversion to s16 on UpdateMusicStream()
+
+ music.stream = InitAudioStream(ctxWav->sampleRate, sampleSize, ctxWav->channels);
+ music.sampleCount = (unsigned int)ctxWav->totalPCMFrameCount*ctxWav->channels;
+ music.looping = true; // Looping enabled by default
+ musicLoaded = true;
+ }
+ }
+#endif
+#if defined(SUPPORT_FILEFORMAT_FLAC)
+ else if (TextIsEqual(fileExtLower, ".flac"))
+ {
+ music.ctxType = MUSIC_AUDIO_FLAC;
+ music.ctxData = drflac_open_memory((const void*)data, dataSize, NULL);
+
+ if (music.ctxData != NULL)
+ {
+ drflac *ctxFlac = (drflac *)music.ctxData;
+
+ music.stream = InitAudioStream(ctxFlac->sampleRate, ctxFlac->bitsPerSample, ctxFlac->channels);
+ music.sampleCount = (unsigned int)ctxFlac->totalPCMFrameCount*ctxFlac->channels;
+ music.looping = true; // Looping enabled by default
+ musicLoaded = true;
+ }
+ }
+#endif
+#if defined(SUPPORT_FILEFORMAT_MP3)
+ else if (TextIsEqual(fileExtLower, ".mp3"))
+ {
+ drmp3 *ctxMp3 = RL_CALLOC(1, sizeof(drmp3));
+ int success = drmp3_init_memory(ctxMp3, (const void*)data, dataSize, NULL);
+
+ music.ctxType = MUSIC_AUDIO_MP3;
+ music.ctxData = ctxMp3;
+
+ if (success)
+ {
+ music.stream = InitAudioStream(ctxMp3->sampleRate, 32, ctxMp3->channels);
+ music.sampleCount = (unsigned int)drmp3_get_pcm_frame_count(ctxMp3)*ctxMp3->channels;
+ music.looping = true; // Looping enabled by default
+ musicLoaded = true;
+ }
+ }
+#endif
+#if defined(SUPPORT_FILEFORMAT_OGG)
+ else if (TextIsEqual(fileExtLower, ".ogg"))
+ {
+ // Open ogg audio stream
+ music.ctxType = MUSIC_AUDIO_OGG;
+ //music.ctxData = stb_vorbis_open_filename(fileName, NULL, NULL);
+ music.ctxData = stb_vorbis_open_memory((const unsigned char*)data, dataSize, NULL, NULL);
+
+ if (music.ctxData != NULL)
+ {
+ stb_vorbis_info info = stb_vorbis_get_info((stb_vorbis *)music.ctxData); // Get Ogg file info
+
+ // OGG bit rate defaults to 16 bit, it's enough for compressed format
+ music.stream = InitAudioStream(info.sample_rate, 16, info.channels);
+
+ // WARNING: It seems this function returns length in frames, not samples, so we multiply by channels
+ music.sampleCount = (unsigned int)stb_vorbis_stream_length_in_samples((stb_vorbis *)music.ctxData)*info.channels;
+ music.looping = true; // Looping enabled by default
+ musicLoaded = true;
+ }
+ }
+#endif
+#if defined(SUPPORT_FILEFORMAT_XM)
+ else if (TextIsEqual(fileExtLower, ".xm"))
+ {
+ jar_xm_context_t *ctxXm = NULL;
+ int result = jar_xm_create_context_safe(&ctxXm, (const char*)data, dataSize, AUDIO.System.device.sampleRate);
+ if (result == 0) // XM AUDIO.System.context created successfully
+ {
+ music.ctxType = MUSIC_MODULE_XM;
+ jar_xm_set_max_loop_count(ctxXm, 0); // Set infinite number of loops
+
+ unsigned int bits = 32;
+ if (AUDIO_DEVICE_FORMAT == ma_format_s16)
+ bits = 16;
+ else if (AUDIO_DEVICE_FORMAT == ma_format_u8)
+ bits = 8;
+
+ // NOTE: Only stereo is supported for XM
+ music.stream = InitAudioStream(AUDIO.System.device.sampleRate, bits, 2);
+ music.sampleCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm)*2; // 2 channels
+ music.looping = true; // Looping enabled by default
+ jar_xm_reset(ctxXm); // make sure we start at the beginning of the song
music.ctxData = ctxXm;
+ musicLoaded = true;
}
}
#endif
#if defined(SUPPORT_FILEFORMAT_MOD)
- else if (IsFileExtension(fileName, ".mod"))
+ else if (TextIsEqual(fileExtLower, ".mod"))
{
jar_mod_context_t *ctxMod = RL_MALLOC(sizeof(jar_mod_context_t));
+ int result = 0;
jar_mod_init(ctxMod);
- int result = jar_mod_load_file(ctxMod, fileName);
+
+ // copy data to allocated memory for default UnloadMusicStream
+ unsigned char *newData = RL_MALLOC(dataSize);
+ int it = dataSize/sizeof(unsigned char);
+ for (int i = 0; i < it; i++){
+ newData[i] = data[i];
+ }
+
+ // Memory loaded version for jar_mod_load_file()
+ if (dataSize && dataSize < 32*1024*1024)
+ {
+ ctxMod->modfilesize = dataSize;
+ ctxMod->modfile = newData;
+ if (jar_mod_load(ctxMod, (void *)ctxMod->modfile, dataSize)) result = dataSize;
+ }
if (result > 0)
{
music.ctxType = MUSIC_MODULE_MOD;
// NOTE: Only stereo is supported for MOD
- music.stream = InitAudioStream(48000, 16, 2);
- music.sampleCount = (unsigned int)jar_mod_max_samples(ctxMod)*2;
- music.loopCount = 0; // Infinite loop by default
+ music.stream = InitAudioStream(AUDIO.System.device.sampleRate, 16, 2);
+ music.sampleCount = (unsigned int)jar_mod_max_samples(ctxMod)*2; // 2 channels
+ music.looping = true; // Looping enabled by default
musicLoaded = true;
music.ctxData = ctxMod;
+ musicLoaded = true;
}
}
#endif
+ else TRACELOG(LOG_WARNING, "STREAM: [%s] Fileformat not supported", fileType);
if (!musicLoaded)
{
if (false) { }
- #if defined(SUPPORT_FILEFORMAT_OGG)
- else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData);
+ #if defined(SUPPORT_FILEFORMAT_WAV)
+ else if (music.ctxType == MUSIC_AUDIO_WAV) drwav_uninit((drwav *)music.ctxData);
#endif
#if defined(SUPPORT_FILEFORMAT_FLAC)
- else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData);
+ else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData, NULL);
#endif
#if defined(SUPPORT_FILEFORMAT_MP3)
else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); }
#endif
+ #if defined(SUPPORT_FILEFORMAT_OGG)
+ else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData);
+ #endif
#if defined(SUPPORT_FILEFORMAT_XM)
else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData);
#endif
@@ -1159,12 +1483,13 @@ Music LoadMusicStream(const char *fileName)
else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); }
#endif
- TRACELOG(LOG_WARNING, "FILEIO: [%s] Music file could not be opened", fileName);
+ music.ctxData = NULL;
+ TRACELOG(LOG_WARNING, "FILEIO: [%s] Music memory could not be opened", fileType);
}
else
{
// Show some music stream info
- TRACELOG(LOG_INFO, "FILEIO: [%s] Music file successfully loaded:", fileName);
+ TRACELOG(LOG_INFO, "FILEIO: [%s] Music memory successfully loaded:", fileType);
TRACELOG(LOG_INFO, " > Total samples: %i", music.sampleCount);
TRACELOG(LOG_INFO, " > Sample rate: %i Hz", music.stream.sampleRate);
TRACELOG(LOG_INFO, " > Sample size: %i bits", music.stream.sampleSize);
@@ -1179,22 +1504,28 @@ void UnloadMusicStream(Music music)
{
CloseAudioStream(music.stream);
- if (false) { }
+ if (music.ctxData != NULL)
+ {
+ if (false) { }
+#if defined(SUPPORT_FILEFORMAT_WAV)
+ else if (music.ctxType == MUSIC_AUDIO_WAV) drwav_uninit((drwav *)music.ctxData);
+#endif
#if defined(SUPPORT_FILEFORMAT_OGG)
- else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData);
+ else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData);
#endif
#if defined(SUPPORT_FILEFORMAT_FLAC)
- else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData);
+ else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData, NULL);
#endif
#if defined(SUPPORT_FILEFORMAT_MP3)
else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); }
#endif
#if defined(SUPPORT_FILEFORMAT_XM)
- else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData);
+ else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData);
#endif
#if defined(SUPPORT_FILEFORMAT_MOD)
- else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); }
+ else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); }
#endif
+ }
}
// Start music playing (open stream)
@@ -1231,6 +1562,9 @@ void StopMusicStream(Music music)
switch (music.ctxType)
{
+#if defined(SUPPORT_FILEFORMAT_WAV)
+ case MUSIC_AUDIO_WAV: drwav_seek_to_pcm_frame((drwav *)music.ctxData, 0); break;
+#endif
#if defined(SUPPORT_FILEFORMAT_OGG)
case MUSIC_AUDIO_OGG: stb_vorbis_seek_start((stb_vorbis *)music.ctxData); break;
#endif
@@ -1253,7 +1587,11 @@ void StopMusicStream(Music music)
// Update (re-fill) music buffers if data already processed
void UpdateMusicStream(Music music)
{
- if (music.stream.buffer == NULL) return;
+ if (music.stream.buffer == NULL)
+ return;
+
+ if (music.ctxType == MUSIC_MODULE_XM)
+ jar_xm_set_max_loop_count(music.ctxData, music.looping ? 0 : 1);
bool streamEnding = false;
@@ -1268,6 +1606,8 @@ void UpdateMusicStream(Music music)
//ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(music.stream.buffer->dsp.formatConverterIn.config.formatIn)*music.stream.buffer->dsp.formatConverterIn.config.channels;
int sampleLeft = music.sampleCount - (music.stream.buffer->totalFramesProcessed*music.stream.channels);
+ if (music.ctxType == MUSIC_MODULE_XM && music.looping) sampleLeft = subBufferSizeInFrames*4;
+
while (IsAudioStreamProcessed(music.stream))
{
if ((sampleLeft/music.stream.channels) >= subBufferSizeInFrames) samplesCount = subBufferSizeInFrames*music.stream.channels;
@@ -1275,6 +1615,15 @@ void UpdateMusicStream(Music music)
switch (music.ctxType)
{
+ #if defined(SUPPORT_FILEFORMAT_WAV)
+ case MUSIC_AUDIO_WAV:
+ {
+ // NOTE: Returns the number of samples to process (not required)
+ if (music.stream.sampleSize == 16) drwav_read_pcm_frames_s16((drwav *)music.ctxData, samplesCount/music.stream.channels, (short *)pcm);
+ else if (music.stream.sampleSize == 32) drwav_read_pcm_frames_f32((drwav *)music.ctxData, samplesCount/music.stream.channels, (float *)pcm);
+
+ } break;
+ #endif
#if defined(SUPPORT_FILEFORMAT_OGG)
case MUSIC_AUDIO_OGG:
{
@@ -1302,8 +1651,24 @@ void UpdateMusicStream(Music music)
#if defined(SUPPORT_FILEFORMAT_XM)
case MUSIC_MODULE_XM:
{
- // NOTE: Internally this function considers 2 channels generation, so samplesCount/2
- jar_xm_generate_samples_16bit((jar_xm_context_t *)music.ctxData, (short *)pcm, samplesCount/2);
+ switch (AUDIO_DEVICE_FORMAT)
+ {
+ case ma_format_f32:
+ // NOTE: Internally this function considers 2 channels generation, so samplesCount/2
+ jar_xm_generate_samples((jar_xm_context_t*)music.ctxData, (float*)pcm, samplesCount / 2);
+ break;
+
+ case ma_format_s16:
+ // NOTE: Internally this function considers 2 channels generation, so samplesCount/2
+ jar_xm_generate_samples_16bit((jar_xm_context_t*)music.ctxData, (short*)pcm, samplesCount / 2);
+ break;
+
+ case ma_format_u8:
+ // NOTE: Internally this function considers 2 channels generation, so samplesCount/2
+ jar_xm_generate_samples_8bit((jar_xm_context_t*)music.ctxData, (char*)pcm, samplesCount / 2);
+ break;
+ }
+
} break;
#endif
#if defined(SUPPORT_FILEFORMAT_MOD)
@@ -1318,7 +1683,7 @@ void UpdateMusicStream(Music music)
UpdateAudioStream(music.stream, pcm, samplesCount);
- if ((music.ctxType == MUSIC_MODULE_XM) || (music.ctxType == MUSIC_MODULE_MOD))
+ if ((music.ctxType == MUSIC_MODULE_XM) || music.ctxType == MUSIC_MODULE_MOD)
{
if (samplesCount > 1) sampleLeft -= samplesCount/2;
else sampleLeft -= samplesCount;
@@ -1338,15 +1703,8 @@ void UpdateMusicStream(Music music)
// Reset audio stream for looping
if (streamEnding)
{
- StopMusicStream(music); // Stop music (and reset)
-
- // Decrease loopCount to stop when required
- if (music.loopCount > 1)
- {
- music.loopCount--; // Decrease loop count
- PlayMusicStream(music); // Play again
- }
- else if (music.loopCount == 0) PlayMusicStream(music);
+ StopMusicStream(music); // Stop music (and reset)
+ if (music.looping) PlayMusicStream(music); // Play again
}
else
{
@@ -1371,14 +1729,7 @@ void SetMusicVolume(Music music, float volume)
// Set pitch for music
void SetMusicPitch(Music music, float pitch)
{
- SetAudioStreamPitch(music.stream, pitch);
-}
-
-// Set music loop count (loop repeats)
-// NOTE: If set to 0, means infinite loop
-void SetMusicLoopCount(Music music, int count)
-{
- music.loopCount = count;
+ SetAudioBufferPitch(music.stream.buffer, pitch);
}
// Get music time length (in seconds)
@@ -1394,13 +1745,22 @@ float GetMusicTimeLength(Music music)
// Get current music time played (in seconds)
float GetMusicTimePlayed(Music music)
{
- float secondsPlayed = 0.0f;
+#if defined(SUPPORT_FILEFORMAT_XM)
+ if (music.ctxType == MUSIC_MODULE_XM)
+ {
+ uint64_t samples = 0;
+ jar_xm_get_position(music.ctxData, NULL, NULL, NULL, &samples);
+ samples = samples % (music.sampleCount);
+ return (float)(samples)/(music.stream.sampleRate*music.stream.channels);
+ }
+#endif
+ float secondsPlayed = 0.0f;
if (music.stream.buffer != NULL)
{
//ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(music.stream.buffer->dsp.formatConverterIn.config.formatIn)*music.stream.buffer->dsp.formatConverterIn.config.channels;
unsigned int samplesPlayed = music.stream.buffer->totalFramesProcessed*music.stream.channels;
- secondsPlayed = (float)samplesPlayed / (music.stream.sampleRate*music.stream.channels);
+ secondsPlayed = (float)samplesPlayed/(music.stream.sampleRate*music.stream.channels);
}
return secondsPlayed;
@@ -1419,7 +1779,7 @@ AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, un
// The size of a streaming buffer must be at least double the size of a period
unsigned int periodSize = AUDIO.System.device.playback.internalPeriodSizeInFrames;
- unsigned int subBufferSize = AUDIO.Buffer.defaultSize; // Default buffer size (audio stream)
+ unsigned int subBufferSize = GetAudioStreamBufferSizeDefault();
if (subBufferSize < periodSize) subBufferSize = periodSize;
@@ -1554,6 +1914,15 @@ void SetAudioStreamBufferSizeDefault(int size)
AUDIO.Buffer.defaultSize = size;
}
+int GetAudioStreamBufferSizeDefault()
+{
+ // if the buffer is not set, compute one that would give us a buffer good enough for a decent frame rate
+ if (AUDIO.Buffer.defaultSize == 0)
+ AUDIO.Buffer.defaultSize = AUDIO.System.device.sampleRate/30;
+
+ return AUDIO.Buffer.defaultSize;
+}
+
//----------------------------------------------------------------------------------
// Module specific Functions Definition
//----------------------------------------------------------------------------------
@@ -1564,7 +1933,7 @@ static void OnLog(ma_context *pContext, ma_device *pDevice, ma_uint32 logLevel,
(void)pContext;
(void)pDevice;
- TRACELOG(LOG_ERROR, "miniaudio: %s", message); // All log messages from miniaudio are errors
+ TRACELOG(LOG_WARNING, "miniaudio: %s", message); // All log messages from miniaudio are errors
}
// Reads audio data from an AudioBuffer object in internal format.
@@ -1661,7 +2030,7 @@ static ma_uint32 ReadAudioBufferFramesInMixingFormat(AudioBuffer *audioBuffer, f
// detail to remember here is that we never, ever attempt to read more input data than is required for the specified number of output
// frames. This can be achieved with ma_data_converter_get_required_input_frame_count().
ma_uint8 inputBuffer[4096];
- ma_uint32 inputBufferFrameCap = sizeof(inputBuffer) / ma_get_bytes_per_frame(audioBuffer->converter.config.formatIn, audioBuffer->converter.config.channelsIn);
+ ma_uint32 inputBufferFrameCap = sizeof(inputBuffer)/ma_get_bytes_per_frame(audioBuffer->converter.config.formatIn, audioBuffer->converter.config.channelsIn);
ma_uint32 totalOutputFramesProcessed = 0;
while (totalOutputFramesProcessed < frameCount)
@@ -1674,7 +2043,7 @@ static ma_uint32 ReadAudioBufferFramesInMixingFormat(AudioBuffer *audioBuffer, f
inputFramesToProcessThisIteration = inputBufferFrameCap;
}
- float *runningFramesOut = framesOut + (totalOutputFramesProcessed * audioBuffer->converter.config.channelsOut);
+ float *runningFramesOut = framesOut + (totalOutputFramesProcessed*audioBuffer->converter.config.channelsOut);
/* At this point we can convert the data to our mixing format. */
ma_uint64 inputFramesProcessedThisIteration = ReadAudioBufferFramesInInternalFormat(audioBuffer, inputBuffer, (ma_uint32)inputFramesToProcessThisIteration); /* Safe cast. */
@@ -1798,322 +2167,146 @@ static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 fr
}
}
-// Initialise the multichannel buffer pool
-static void InitAudioBufferPool(void)
-{
- // Dummy buffers
- for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
- {
- AUDIO.MultiChannel.pool[i] = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO_DEVICE_SAMPLE_RATE, 0, AUDIO_BUFFER_USAGE_STATIC);
- }
-
- // TODO: Verification required for log
- TRACELOG(LOG_INFO, "AUDIO: Multichannel pool size: %i", MAX_AUDIO_BUFFER_POOL_CHANNELS);
-}
-
-// Close the audio buffers pool
-static void CloseAudioBufferPool(void)
-{
- for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
- {
- RL_FREE(AUDIO.MultiChannel.pool[i]->data);
- RL_FREE(AUDIO.MultiChannel.pool[i]);
- }
-}
-
#if defined(SUPPORT_FILEFORMAT_WAV)
-// Load WAV file into Wave structure
-static Wave LoadWAV(const char *fileName)
-{
- // Basic WAV headers structs
- typedef struct {
- char chunkID[4];
- int chunkSize;
- char format[4];
- } WAVRiffHeader;
-
- typedef struct {
- char subChunkID[4];
- int subChunkSize;
- short audioFormat;
- short numChannels;
- int sampleRate;
- int byteRate;
- short blockAlign;
- short bitsPerSample;
- } WAVFormat;
-
- typedef struct {
- char subChunkID[4];
- int subChunkSize;
- } WAVData;
-
- WAVRiffHeader wavRiffHeader = { 0 };
- WAVFormat wavFormat = { 0 };
- WAVData wavData = { 0 };
-
+// Load WAV file data into Wave structure
+// NOTE: Using dr_wav library
+static Wave LoadWAV(const unsigned char *fileData, unsigned int fileSize)
+{
Wave wave = { 0 };
- FILE *wavFile = NULL;
+ drwav wav = { 0 };
- wavFile = fopen(fileName, "rb");
+ bool success = drwav_init_memory(&wav, fileData, fileSize, NULL);
- if (wavFile == NULL)
+ if (success)
{
- TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open WAV file", fileName);
- wave.data = NULL;
+ wave.sampleCount = (unsigned int)wav.totalPCMFrameCount*wav.channels;
+ wave.sampleRate = wav.sampleRate;
+ wave.sampleSize = 16; // NOTE: We are forcing conversion to 16bit
+ wave.channels = wav.channels;
+ wave.data = (short *)RL_MALLOC(wave.sampleCount*sizeof(short));
+ drwav_read_pcm_frames_s16(&wav, wav.totalPCMFrameCount, wave.data);
}
- else
- {
- // Read in the first chunk into the struct
- fread(&wavRiffHeader, sizeof(WAVRiffHeader), 1, wavFile);
-
- // Check for RIFF and WAVE tags
- if ((wavRiffHeader.chunkID[0] != 'R') ||
- (wavRiffHeader.chunkID[1] != 'I') ||
- (wavRiffHeader.chunkID[2] != 'F') ||
- (wavRiffHeader.chunkID[3] != 'F') ||
- (wavRiffHeader.format[0] != 'W') ||
- (wavRiffHeader.format[1] != 'A') ||
- (wavRiffHeader.format[2] != 'V') ||
- (wavRiffHeader.format[3] != 'E'))
- {
- TRACELOG(LOG_WARNING, "WAVE: [%s] RIFF or WAVE header are not valid", fileName);
- }
- else
- {
- // Read in the 2nd chunk for the wave info
- fread(&wavFormat, sizeof(WAVFormat), 1, wavFile);
-
- // Check for fmt tag
- if ((wavFormat.subChunkID[0] != 'f') || (wavFormat.subChunkID[1] != 'm') ||
- (wavFormat.subChunkID[2] != 't') || (wavFormat.subChunkID[3] != ' '))
- {
- TRACELOG(LOG_WARNING, "WAVE: [%s] Wave format header is not valid", fileName);
- }
- else
- {
- // Check for extra parameters;
- if (wavFormat.subChunkSize > 16) fseek(wavFile, sizeof(short), SEEK_CUR);
-
- // Read in the the last byte of data before the sound file
- fread(&wavData, sizeof(WAVData), 1, wavFile);
-
- // Check for data tag
- if ((wavData.subChunkID[0] != 'd') || (wavData.subChunkID[1] != 'a') ||
- (wavData.subChunkID[2] != 't') || (wavData.subChunkID[3] != 'a'))
- {
- TRACELOG(LOG_WARNING, "WAVE: [%s] Data header is not valid", fileName);
- }
- else
- {
- // Allocate memory for data
- wave.data = RL_MALLOC(wavData.subChunkSize);
-
- // Read in the sound data into the soundData variable
- fread(wave.data, wavData.subChunkSize, 1, wavFile);
+ else TRACELOG(LOG_WARNING, "WAVE: Failed to load WAV data");
- // Store wave parameters
- wave.sampleRate = wavFormat.sampleRate;
- wave.sampleSize = wavFormat.bitsPerSample;
- wave.channels = wavFormat.numChannels;
-
- // NOTE: Only support 8 bit, 16 bit and 32 bit sample sizes
- if ((wave.sampleSize != 8) && (wave.sampleSize != 16) && (wave.sampleSize != 32))
- {
- TRACELOG(LOG_WARNING, "WAVE: [%s] Sample size (%ibit) not supported, converted to 16bit", fileName, wave.sampleSize);
- WaveFormat(&wave, wave.sampleRate, 16, wave.channels);
- }
-
- // NOTE: Only support up to 2 channels (mono, stereo)
- if (wave.channels > 2)
- {
- WaveFormat(&wave, wave.sampleRate, wave.sampleSize, 2);
- TRACELOG(LOG_WARNING, "WAVE: [%s] Channels number (%i) not supported, converted to 2 channels", fileName, wave.channels);
- }
-
- // NOTE: subChunkSize comes in bytes, we need to translate it to number of samples
- wave.sampleCount = (wavData.subChunkSize/(wave.sampleSize/8))/wave.channels;
-
- TRACELOG(LOG_INFO, "WAVE: [%s] File loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
- }
- }
- }
-
- fclose(wavFile);
- }
+ drwav_uninit(&wav);
return wave;
}
// Save wave data as WAV file
+// NOTE: Using dr_wav library
static int SaveWAV(Wave wave, const char *fileName)
{
- int success = 0;
- int dataSize = wave.sampleCount*wave.channels*wave.sampleSize/8;
-
- // Basic WAV headers structs
- typedef struct {
- char chunkID[4];
- int chunkSize;
- char format[4];
- } RiffHeader;
-
- typedef struct {
- char subChunkID[4];
- int subChunkSize;
- short audioFormat;
- short numChannels;
- int sampleRate;
- int byteRate;
- short blockAlign;
- short bitsPerSample;
- } WaveFormat;
-
- typedef struct {
- char subChunkID[4];
- int subChunkSize;
- } WaveData;
-
- FILE *wavFile = fopen(fileName, "wb");
-
- if (wavFile == NULL) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open audio file", fileName);
- else
- {
- RiffHeader riffHeader;
- WaveFormat waveFormat;
- WaveData waveData;
-
- // Fill structs with data
- riffHeader.chunkID[0] = 'R';
- riffHeader.chunkID[1] = 'I';
- riffHeader.chunkID[2] = 'F';
- riffHeader.chunkID[3] = 'F';
- riffHeader.chunkSize = 44 - 4 + wave.sampleCount*wave.sampleSize/8;
- riffHeader.format[0] = 'W';
- riffHeader.format[1] = 'A';
- riffHeader.format[2] = 'V';
- riffHeader.format[3] = 'E';
-
- waveFormat.subChunkID[0] = 'f';
- waveFormat.subChunkID[1] = 'm';
- waveFormat.subChunkID[2] = 't';
- waveFormat.subChunkID[3] = ' ';
- waveFormat.subChunkSize = 16;
- waveFormat.audioFormat = 1;
- waveFormat.numChannels = wave.channels;
- waveFormat.sampleRate = wave.sampleRate;
- waveFormat.byteRate = wave.sampleRate*wave.sampleSize/8;
- waveFormat.blockAlign = wave.sampleSize/8;
- waveFormat.bitsPerSample = wave.sampleSize;
-
- waveData.subChunkID[0] = 'd';
- waveData.subChunkID[1] = 'a';
- waveData.subChunkID[2] = 't';
- waveData.subChunkID[3] = 'a';
- waveData.subChunkSize = dataSize;
-
- fwrite(&riffHeader, sizeof(RiffHeader), 1, wavFile);
- fwrite(&waveFormat, sizeof(WaveFormat), 1, wavFile);
- fwrite(&waveData, sizeof(WaveData), 1, wavFile);
-
- success = fwrite(wave.data, dataSize, 1, wavFile);
-
- fclose(wavFile);
- }
-
- // If all data has been written correctly to file, success = 1
+ int success = false;
+
+ drwav wav = { 0 };
+ drwav_data_format format = { 0 };
+ format.container = drwav_container_riff;
+ format.format = DR_WAVE_FORMAT_PCM;
+ format.channels = wave.channels;
+ format.sampleRate = wave.sampleRate;
+ format.bitsPerSample = wave.sampleSize;
+
+ void *fileData = NULL;
+ size_t fileDataSize = 0;
+ success = drwav_init_memory_write(&wav, &fileData, &fileDataSize, &format, NULL);
+ if (success) success = (int)drwav_write_pcm_frames(&wav, wave.sampleCount/wave.channels, wave.data);
+ drwav_result result = drwav_uninit(&wav);
+
+ if (result == DRWAV_SUCCESS) success = SaveFileData(fileName, (unsigned char *)fileData, (unsigned int)fileDataSize);
+
+ drwav_free(fileData, NULL);
+
return success;
}
#endif
#if defined(SUPPORT_FILEFORMAT_OGG)
-// Load OGG file into Wave structure
+// Load OGG file data into Wave structure
// NOTE: Using stb_vorbis library
-static Wave LoadOGG(const char *fileName)
+static Wave LoadOGG(const unsigned char *fileData, unsigned int fileSize)
{
Wave wave = { 0 };
- stb_vorbis *oggFile = stb_vorbis_open_filename(fileName, NULL, NULL);
+ stb_vorbis *oggData = stb_vorbis_open_memory((unsigned char *)fileData, fileSize, NULL, NULL);
- if (oggFile == NULL) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open OGG file", fileName);
- else
+ if (oggData != NULL)
{
- stb_vorbis_info info = stb_vorbis_get_info(oggFile);
+ stb_vorbis_info info = stb_vorbis_get_info(oggData);
wave.sampleRate = info.sample_rate;
wave.sampleSize = 16; // 16 bit per sample (short)
wave.channels = info.channels;
- wave.sampleCount = (unsigned int)stb_vorbis_stream_length_in_samples(oggFile)*info.channels; // Independent by channel
+ wave.sampleCount = (unsigned int)stb_vorbis_stream_length_in_samples(oggData)*info.channels; // Independent by channel
- float totalSeconds = stb_vorbis_stream_length_in_seconds(oggFile);
- if (totalSeconds > 10) TRACELOG(LOG_WARNING, "WAVE: [%s] Ogg audio length larger than 10 seconds (%f), that's a big file in memory, consider music streaming", fileName, totalSeconds);
+ float totalSeconds = stb_vorbis_stream_length_in_seconds(oggData);
+ if (totalSeconds > 10) TRACELOG(LOG_WARNING, "WAVE: OGG audio length larger than 10 seconds (%f sec.), that's a big file in memory, consider music streaming", totalSeconds);
- wave.data = (short *)RL_MALLOC(wave.sampleCount*wave.channels*sizeof(short));
+ wave.data = (short *)RL_MALLOC(wave.sampleCount*sizeof(short));
// NOTE: Returns the number of samples to process (be careful! we ask for number of shorts!)
- stb_vorbis_get_samples_short_interleaved(oggFile, info.channels, (short *)wave.data, wave.sampleCount*wave.channels);
- TRACELOG(LOG_INFO, "WAVE: [%s] OGG file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
+ stb_vorbis_get_samples_short_interleaved(oggData, info.channels, (short *)wave.data, wave.sampleCount);
+ TRACELOG(LOG_INFO, "WAVE: OGG data loaded successfully (%i Hz, %i bit, %s)", wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
- stb_vorbis_close(oggFile);
+ stb_vorbis_close(oggData);
}
+ else TRACELOG(LOG_WARNING, "WAVE: Failed to load OGG data");
return wave;
}
#endif
#if defined(SUPPORT_FILEFORMAT_FLAC)
-// Load FLAC file into Wave structure
+// Load FLAC file data into Wave structure
// NOTE: Using dr_flac library
-static Wave LoadFLAC(const char *fileName)
+static Wave LoadFLAC(const unsigned char *fileData, unsigned int fileSize)
{
Wave wave = { 0 };
- // Decode an entire FLAC file in one go
- unsigned long long int totalSampleCount = 0;
- wave.data = drflac_open_file_and_read_pcm_frames_s16(fileName, &wave.channels, &wave.sampleRate, &totalSampleCount);
+ // Decode the entire FLAC file in one go
+ unsigned long long int totalFrameCount = 0;
+ wave.data = drflac_open_memory_and_read_pcm_frames_s16(fileData, fileSize, &wave.channels, &wave.sampleRate, &totalFrameCount, NULL);
- if (wave.data == NULL) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to load FLAC data", fileName);
- else
+ if (wave.data != NULL)
{
- wave.sampleCount = (unsigned int)totalSampleCount;
+ wave.sampleCount = (unsigned int)totalFrameCount*wave.channels;
wave.sampleSize = 16;
- // NOTE: Only support up to 2 channels (mono, stereo)
- if (wave.channels > 2) TRACELOG(LOG_WARNING, "WAVE: [%s] FLAC channels number (%i) not supported", fileName, wave.channels);
-
- TRACELOG(LOG_INFO, "WAVE: [%s] FLAC file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
+ TRACELOG(LOG_INFO, "WAVE: FLAC data loaded successfully (%i Hz, %i bit, %s)", wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
}
-
+ else TRACELOG(LOG_WARNING, "WAVE: Failed to load FLAC data");
+
return wave;
}
#endif
#if defined(SUPPORT_FILEFORMAT_MP3)
-// Load MP3 file into Wave structure
+// Load MP3 file data into Wave structure
// NOTE: Using dr_mp3 library
-static Wave LoadMP3(const char *fileName)
+static Wave LoadMP3(const unsigned char *fileData, unsigned int fileSize)
{
Wave wave = { 0 };
+ drmp3_config config = { 0 };
- // Decode an entire MP3 file in one go
+ // Decode the entire MP3 file in one go
unsigned long long int totalFrameCount = 0;
- drmp3_config config = { 0 };
- wave.data = drmp3_open_file_and_read_f32(fileName, &config, &totalFrameCount);
+ wave.data = drmp3_open_memory_and_read_pcm_frames_f32(fileData, fileSize, &config, &totalFrameCount, NULL);
- if (wave.data == NULL) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to load MP3 data", fileName);
- else
+ if (wave.data != NULL)
{
- wave.channels = config.outputChannels;
- wave.sampleRate = config.outputSampleRate;
+ wave.channels = config.channels;
+ wave.sampleRate = config.sampleRate;
wave.sampleCount = (int)totalFrameCount*wave.channels;
wave.sampleSize = 32;
// NOTE: Only support up to 2 channels (mono, stereo)
- if (wave.channels > 2) TRACELOG(LOG_WARNING, "WAVE: [%s] MP3 channels number (%i) not supported", fileName, wave.channels);
+ // TODO: Really?
+ if (wave.channels > 2) TRACELOG(LOG_WARNING, "WAVE: MP3 channels number (%i) not supported", wave.channels);
- TRACELOG(LOG_INFO, "WAVE: [%s] MP3 file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
+ TRACELOG(LOG_INFO, "WAVE: MP3 file loaded successfully (%i Hz, %i bit, %s)", wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
}
-
+ else TRACELOG(LOG_WARNING, "WAVE: Failed to load MP3 data");
+
return wave;
}
#endif
@@ -2121,7 +2314,7 @@ static Wave LoadMP3(const char *fileName)
// Some required functions for audio standalone module version
#if defined(RAUDIO_STANDALONE)
// Check file extension
-bool IsFileExtension(const char *fileName, const char *ext)
+static bool IsFileExtension(const char *fileName, const char *ext)
{
bool result = false;
const char *fileExt;
@@ -2133,6 +2326,89 @@ bool IsFileExtension(const char *fileName, const char *ext)
return result;
}
+
+// Load data from file into a buffer
+static unsigned char *LoadFileData(const char *fileName, unsigned int *bytesRead)
+{
+ unsigned char *data = NULL;
+ *bytesRead = 0;
+
+ if (fileName != NULL)
+ {
+ FILE *file = fopen(fileName, "rb");
+
+ if (file != NULL)
+ {
+ // WARNING: On binary streams SEEK_END could not be found,
+ // using fseek() and ftell() could not work in some (rare) cases
+ fseek(file, 0, SEEK_END);
+ int size = ftell(file);
+ fseek(file, 0, SEEK_SET);
+
+ if (size > 0)
+ {
+ data = (unsigned char *)RL_MALLOC(size*sizeof(unsigned char));
+
+ // NOTE: fread() returns number of read elements instead of bytes, so we read [1 byte, size elements]
+ unsigned int count = (unsigned int)fread(data, sizeof(unsigned char), size, file);
+ *bytesRead = count;
+
+ if (count != size) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially loaded", fileName);
+ else TRACELOG(LOG_INFO, "FILEIO: [%s] File loaded successfully", fileName);
+ }
+ else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to read file", fileName);
+
+ fclose(file);
+ }
+ else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName);
+ }
+ else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
+
+ return data;
+}
+
+// Save data to file from buffer
+static bool SaveFileData(const char *fileName, void *data, unsigned int bytesToWrite)
+{
+ if (fileName != NULL)
+ {
+ FILE *file = fopen(fileName, "wb");
+
+ if (file != NULL)
+ {
+ unsigned int count = (unsigned int)fwrite(data, sizeof(unsigned char), bytesToWrite, file);
+
+ if (count == 0) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to write file", fileName);
+ else if (count != bytesToWrite) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially written", fileName);
+ else TRACELOG(LOG_INFO, "FILEIO: [%s] File saved successfully", fileName);
+
+ fclose(file);
+ }
+ else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName);
+ }
+ else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
+}
+
+// Save text data to file (write), string must be '\0' terminated
+static bool SaveFileText(const char *fileName, char *text)
+{
+ if (fileName != NULL)
+ {
+ FILE *file = fopen(fileName, "wt");
+
+ if (file != NULL)
+ {
+ int count = fprintf(file, "%s", text);
+
+ if (count == 0) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to write text file", fileName);
+ else TRACELOG(LOG_INFO, "FILEIO: [%s] Text file saved successfully", fileName);
+
+ fclose(file);
+ }
+ else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open text file", fileName);
+ }
+ else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
+}
#endif
#undef AudioBuffer