]> git.sesse.net Git - pistorm/blob - raylib/raudio.c
Add Meson build files.
[pistorm] / raylib / raudio.c
1 /**********************************************************************************************
2 *
3 *   raudio v1.0 - A simple and easy-to-use audio library based on miniaudio
4 *
5 *   FEATURES:
6 *       - Manage audio device (init/close)
7 *       - Manage raw audio context
8 *       - Manage mixing channels
9 *       - Load and unload audio files
10 *       - Format wave data (sample rate, size, channels)
11 *       - Play/Stop/Pause/Resume loaded audio
12 *
13 *   CONFIGURATION:
14 *
15 *   #define RAUDIO_STANDALONE
16 *       Define to use the module as standalone library (independently of raylib).
17 *       Required types and functions are defined in the same module.
18 *
19 *   #define SUPPORT_FILEFORMAT_WAV
20 *   #define SUPPORT_FILEFORMAT_OGG
21 *   #define SUPPORT_FILEFORMAT_XM
22 *   #define SUPPORT_FILEFORMAT_MOD
23 *   #define SUPPORT_FILEFORMAT_FLAC
24 *   #define SUPPORT_FILEFORMAT_MP3
25 *       Selected desired fileformats to be supported for loading. Some of those formats are
26 *       supported by default, to remove support, just comment unrequired #define in this module
27 *
28 *   DEPENDENCIES:
29 *       miniaudio.h  - Audio device management lib (https://github.com/dr-soft/miniaudio)
30 *       stb_vorbis.h - Ogg audio files loading (http://www.nothings.org/stb_vorbis/)
31 *       dr_mp3.h     - MP3 audio file loading (https://github.com/mackron/dr_libs)
32 *       dr_flac.h    - FLAC audio file loading (https://github.com/mackron/dr_libs)
33 *       jar_xm.h     - XM module file loading
34 *       jar_mod.h    - MOD audio file loading
35 *
36 *   CONTRIBUTORS:
37 *       David Reid (github: @mackron) (Nov. 2017):
38 *           - Complete port to miniaudio library
39 *
40 *       Joshua Reisenauer (github: @kd7tck) (2015)
41 *           - XM audio module support (jar_xm)
42 *           - MOD audio module support (jar_mod)
43 *           - Mixing channels support
44 *           - Raw audio context support
45 *
46 *
47 *   LICENSE: zlib/libpng
48 *
49 *   Copyright (c) 2013-2021 Ramon Santamaria (@raysan5)
50 *
51 *   This software is provided "as-is", without any express or implied warranty. In no event
52 *   will the authors be held liable for any damages arising from the use of this software.
53 *
54 *   Permission is granted to anyone to use this software for any purpose, including commercial
55 *   applications, and to alter it and redistribute it freely, subject to the following restrictions:
56 *
57 *     1. The origin of this software must not be misrepresented; you must not claim that you
58 *     wrote the original software. If you use this software in a product, an acknowledgment
59 *     in the product documentation would be appreciated but is not required.
60 *
61 *     2. Altered source versions must be plainly marked as such, and must not be misrepresented
62 *     as being the original software.
63 *
64 *     3. This notice may not be removed or altered from any source distribution.
65 *
66 **********************************************************************************************/
67
68 #if defined(RAUDIO_STANDALONE)
69     #include "raudio.h"
70     #include <stdarg.h>         // Required for: va_list, va_start(), vfprintf(), va_end()
71 #else
72     #include "raylib.h"         // Declares module functions
73
74 // Check if config flags have been externally provided on compilation line
75 #if !defined(EXTERNAL_CONFIG_FLAGS)
76     #include "config.h"         // Defines module configuration flags
77 #endif
78     #include "utils.h"          // Required for: fopen() Android mapping
79 #endif
80
81 #if defined(_WIN32)
82 // To avoid conflicting windows.h symbols with raylib, some flags are defined
83 // WARNING: Those flags avoid inclusion of some Win32 headers that could be required
84 // by user at some point and won't be included...
85 //-------------------------------------------------------------------------------------
86
87 // If defined, the following flags inhibit definition of the indicated items.
88 #define NOGDICAPMASKS     // CC_*, LC_*, PC_*, CP_*, TC_*, RC_
89 #define NOVIRTUALKEYCODES // VK_*
90 #define NOWINMESSAGES     // WM_*, EM_*, LB_*, CB_*
91 #define NOWINSTYLES       // WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_*
92 #define NOSYSMETRICS      // SM_*
93 #define NOMENUS           // MF_*
94 #define NOICONS           // IDI_*
95 #define NOKEYSTATES       // MK_*
96 #define NOSYSCOMMANDS     // SC_*
97 #define NORASTEROPS       // Binary and Tertiary raster ops
98 #define NOSHOWWINDOW      // SW_*
99 #define OEMRESOURCE       // OEM Resource values
100 #define NOATOM            // Atom Manager routines
101 #define NOCLIPBOARD       // Clipboard routines
102 #define NOCOLOR           // Screen colors
103 #define NOCTLMGR          // Control and Dialog routines
104 #define NODRAWTEXT        // DrawText() and DT_*
105 #define NOGDI             // All GDI defines and routines
106 #define NOKERNEL          // All KERNEL defines and routines
107 #define NOUSER            // All USER defines and routines
108 //#define NONLS             // All NLS defines and routines
109 #define NOMB              // MB_* and MessageBox()
110 #define NOMEMMGR          // GMEM_*, LMEM_*, GHND, LHND, associated routines
111 #define NOMETAFILE        // typedef METAFILEPICT
112 #define NOMINMAX          // Macros min(a,b) and max(a,b)
113 #define NOMSG             // typedef MSG and associated routines
114 #define NOOPENFILE        // OpenFile(), OemToAnsi, AnsiToOem, and OF_*
115 #define NOSCROLL          // SB_* and scrolling routines
116 #define NOSERVICE         // All Service Controller routines, SERVICE_ equates, etc.
117 #define NOSOUND           // Sound driver routines
118 #define NOTEXTMETRIC      // typedef TEXTMETRIC and associated routines
119 #define NOWH              // SetWindowsHook and WH_*
120 #define NOWINOFFSETS      // GWL_*, GCL_*, associated routines
121 #define NOCOMM            // COMM driver routines
122 #define NOKANJI           // Kanji support stuff.
123 #define NOHELP            // Help engine interface.
124 #define NOPROFILER        // Profiler interface.
125 #define NODEFERWINDOWPOS  // DeferWindowPos routines
126 #define NOMCX             // Modem Configuration Extensions
127
128 // Type required before windows.h inclusion
129 typedef struct tagMSG *LPMSG;
130
131 #include <windows.h>
132
133 // Type required by some unused function...
134 typedef struct tagBITMAPINFOHEADER {
135   DWORD biSize;
136   LONG  biWidth;
137   LONG  biHeight;
138   WORD  biPlanes;
139   WORD  biBitCount;
140   DWORD biCompression;
141   DWORD biSizeImage;
142   LONG  biXPelsPerMeter;
143   LONG  biYPelsPerMeter;
144   DWORD biClrUsed;
145   DWORD biClrImportant;
146 } BITMAPINFOHEADER, *PBITMAPINFOHEADER;
147
148 #include <objbase.h>
149 #include <mmreg.h>
150 #include <mmsystem.h>
151
152 // Some required types defined for MSVC/TinyC compiler
153 #if defined(_MSC_VER) || defined(__TINYC__)
154     #include "propidl.h"
155 #endif
156 #endif
157
158 #define MA_MALLOC RL_MALLOC
159 #define MA_FREE RL_FREE
160
161 #define MA_NO_JACK
162 #define MA_NO_WAV
163 #define MA_NO_FLAC
164 #define MA_NO_MP3
165 #define MINIAUDIO_IMPLEMENTATION
166 //#define MA_DEBUG_OUTPUT
167 #include "external/miniaudio.h"         // miniaudio library
168 #undef PlaySound                        // Win32 API: windows.h > mmsystem.h defines PlaySound macro
169
170 #include <stdlib.h>                     // Required for: malloc(), free()
171 #include <stdio.h>                      // Required for: FILE, fopen(), fclose(), fread()
172
173 #if defined(RAUDIO_STANDALONE)
174     #include <string.h>                 // Required for: strcmp() [Used in IsFileExtension()]
175
176     #if !defined(TRACELOG)
177         #define TRACELOG(level, ...) (void)0
178     #endif
179
180     // Allow custom memory allocators
181     #ifndef RL_MALLOC
182         #define RL_MALLOC(sz)       malloc(sz)
183     #endif
184     #ifndef RL_CALLOC
185         #define RL_CALLOC(n,sz)     calloc(n,sz)
186     #endif
187     #ifndef RL_REALLOC
188         #define RL_REALLOC(ptr,sz)  realloc(ptr,sz)
189     #endif
190     #ifndef RL_FREE
191         #define RL_FREE(ptr)        free(ptr)
192     #endif
193 #endif
194
195 #if defined(SUPPORT_FILEFORMAT_OGG)
196     // TODO: Remap malloc()/free() calls to RL_MALLOC/RL_FREE
197
198     #define STB_VORBIS_IMPLEMENTATION
199     #include "external/stb_vorbis.h"    // OGG loading functions
200 #endif
201
202 #if defined(SUPPORT_FILEFORMAT_XM)
203     #define JARXM_MALLOC RL_MALLOC
204     #define JARXM_FREE RL_FREE
205
206     #define JAR_XM_IMPLEMENTATION
207     #include "external/jar_xm.h"        // XM loading functions
208 #endif
209
210 #if defined(SUPPORT_FILEFORMAT_MOD)
211     #define JARMOD_MALLOC RL_MALLOC
212     #define JARMOD_FREE RL_FREE
213
214     #define JAR_MOD_IMPLEMENTATION
215     #include "external/jar_mod.h"       // MOD loading functions
216 #endif
217
218 #if defined(SUPPORT_FILEFORMAT_WAV)
219     #define DRWAV_MALLOC RL_MALLOC
220     #define DRWAV_REALLOC RL_REALLOC
221     #define DRWAV_FREE RL_FREE
222
223     #define DR_WAV_IMPLEMENTATION
224     #include "external/dr_wav.h"        // WAV loading functions
225 #endif
226
227 #if defined(SUPPORT_FILEFORMAT_MP3)
228     #define DRMP3_MALLOC RL_MALLOC
229     #define DRMP3_REALLOC RL_REALLOC
230     #define DRMP3_FREE RL_FREE
231
232     #define DR_MP3_IMPLEMENTATION
233     #include "external/dr_mp3.h"        // MP3 loading functions
234 #endif
235
236 #if defined(SUPPORT_FILEFORMAT_FLAC)
237     #define DRFLAC_MALLOC RL_MALLOC
238     #define DRFLAC_REALLOC RL_REALLOC
239     #define DRFLAC_FREE RL_FREE
240
241     #define DR_FLAC_IMPLEMENTATION
242     #define DR_FLAC_NO_WIN32_IO
243     #include "external/dr_flac.h"       // FLAC loading functions
244 #endif
245
246 #if defined(_MSC_VER)
247     #undef bool
248 #endif
249
250 //----------------------------------------------------------------------------------
251 // Defines and Macros
252 //----------------------------------------------------------------------------------
253 #ifndef AUDIO_DEVICE_FORMAT
254     #define AUDIO_DEVICE_FORMAT    ma_format_f32    // Device output format (float-32bit)
255 #endif
256 #ifndef AUDIO_DEVICE_CHANNELS
257     #define AUDIO_DEVICE_CHANNELS              2    // Device output channels: stereo
258 #endif
259
260 #ifndef AUDIO_DEVICE_SAMPLE_RATE
261     #define AUDIO_DEVICE_SAMPLE_RATE              0    // Device output channels: stereo
262 #endif
263 #ifndef MAX_AUDIO_BUFFER_POOL_CHANNELS
264     #define MAX_AUDIO_BUFFER_POOL_CHANNELS    16    // Audio pool channels
265 #endif
266 #ifndef DEFAULT_AUDIO_BUFFER_SIZE
267     #define DEFAULT_AUDIO_BUFFER_SIZE       4096    // Default audio buffer size
268 #endif
269
270
271 //----------------------------------------------------------------------------------
272 // Types and Structures Definition
273 //----------------------------------------------------------------------------------
274
275 // Music context type
276 // NOTE: Depends on data structure provided by the library
277 // in charge of reading the different file types
278 typedef enum {
279     MUSIC_AUDIO_NONE = 0,
280     MUSIC_AUDIO_WAV,
281     MUSIC_AUDIO_OGG,
282     MUSIC_AUDIO_FLAC,
283     MUSIC_AUDIO_MP3,
284     MUSIC_MODULE_XM,
285     MUSIC_MODULE_MOD
286 } MusicContextType;
287
288 #if defined(RAUDIO_STANDALONE)
289 typedef enum {
290     LOG_ALL,
291     LOG_TRACE,
292     LOG_DEBUG,
293     LOG_INFO,
294     LOG_WARNING,
295     LOG_ERROR,
296     LOG_FATAL,
297     LOG_NONE
298 } TraceLogLevel;
299 #endif
300
301 // NOTE: Different logic is used when feeding data to the playback device
302 // depending on whether or not data is streamed (Music vs Sound)
303 typedef enum {
304     AUDIO_BUFFER_USAGE_STATIC = 0,
305     AUDIO_BUFFER_USAGE_STREAM
306 } AudioBufferUsage;
307
308 // Audio buffer structure
309 struct rAudioBuffer {
310     ma_data_converter converter;    // Audio data converter
311
312     float volume;                   // Audio buffer volume
313     float pitch;                    // Audio buffer pitch
314
315     bool playing;                   // Audio buffer state: AUDIO_PLAYING
316     bool paused;                    // Audio buffer state: AUDIO_PAUSED
317     bool looping;                   // Audio buffer looping, always true for AudioStreams
318     int usage;                      // Audio buffer usage mode: STATIC or STREAM
319
320     bool isSubBufferProcessed[2];   // SubBuffer processed (virtual double buffer)
321     unsigned int sizeInFrames;      // Total buffer size in frames
322     unsigned int frameCursorPos;    // Frame cursor position
323     unsigned int totalFramesProcessed;  // Total frames processed in this buffer (required for play timing)
324
325     unsigned char *data;            // Data buffer, on music stream keeps filling
326
327     rAudioBuffer *next;             // Next audio buffer on the list
328     rAudioBuffer *prev;             // Previous audio buffer on the list
329 };
330
331 #define AudioBuffer rAudioBuffer    // HACK: To avoid CoreAudio (macOS) symbol collision
332
333 // Audio data context
334 typedef struct AudioData {
335     struct {
336         ma_context context;         // miniaudio context data
337         ma_device device;           // miniaudio device
338         ma_mutex lock;              // miniaudio mutex lock
339         bool isReady;               // Check if audio device is ready
340     } System;
341     struct {
342         AudioBuffer *first;         // Pointer to first AudioBuffer in the list
343         AudioBuffer *last;          // Pointer to last AudioBuffer in the list
344         int defaultSize;            // Default audio buffer size for audio streams
345     } Buffer;
346     struct {
347         unsigned int poolCounter;                               // AudioBuffer pointers pool counter
348         AudioBuffer *pool[MAX_AUDIO_BUFFER_POOL_CHANNELS];      // Multichannel AudioBuffer pointers pool
349         unsigned int channels[MAX_AUDIO_BUFFER_POOL_CHANNELS];  // AudioBuffer pool channels
350     } MultiChannel;
351 } AudioData;
352
353 //----------------------------------------------------------------------------------
354 // Global Variables Definition
355 //----------------------------------------------------------------------------------
356 static AudioData AUDIO = {          // Global AUDIO context
357
358     // NOTE: Music buffer size is defined by number of samples, independent of sample size and channels number
359     // After some math, considering a sampleRate of 48000, a buffer refill rate of 1/60 seconds and a
360     // standard double-buffering system, a 4096 samples buffer has been chosen, it should be enough
361     // In case of music-stalls, just increase this number
362     .Buffer.defaultSize = 0
363 };
364
365 //----------------------------------------------------------------------------------
366 // Module specific Functions Declaration
367 //----------------------------------------------------------------------------------
368 static void OnLog(ma_context *pContext, ma_device *pDevice, ma_uint32 logLevel, const char *message);
369 static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const void *pFramesInput, ma_uint32 frameCount);
370 static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 frameCount, float localVolume);
371
372 #if defined(SUPPORT_FILEFORMAT_WAV)
373 static Wave LoadWAV(const unsigned char *fileData, unsigned int fileSize);   // Load WAV file
374 static int SaveWAV(Wave wave, const char *fileName);    // Save wave data as WAV file
375 #endif
376 #if defined(SUPPORT_FILEFORMAT_OGG)
377 static Wave LoadOGG(const unsigned char *fileData, unsigned int fileSize);   // Load OGG file
378 #endif
379 #if defined(SUPPORT_FILEFORMAT_FLAC)
380 static Wave LoadFLAC(const unsigned char *fileData, unsigned int fileSize);  // Load FLAC file
381 #endif
382 #if defined(SUPPORT_FILEFORMAT_MP3)
383 static Wave LoadMP3(const unsigned char *fileData, unsigned int fileSize);   // Load MP3 file
384 #endif
385
386 #if defined(RAUDIO_STANDALONE)
387 static bool IsFileExtension(const char *fileName, const char *ext); // Check file extension
388 static unsigned char *LoadFileData(const char *fileName, unsigned int *bytesRead);     // Load file data as byte array (read)
389 static bool SaveFileData(const char *fileName, void *data, unsigned int bytesToWrite); // Save data to file from byte array (write)
390 static bool SaveFileText(const char *fileName, char *text);         // Save text data to file (write), string must be '\0' terminated
391 #endif
392
393 //----------------------------------------------------------------------------------
394 // AudioBuffer management functions declaration
395 // NOTE: Those functions are not exposed by raylib... for the moment
396 //----------------------------------------------------------------------------------
397 AudioBuffer *LoadAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 sizeInFrames, int usage);
398 void UnloadAudioBuffer(AudioBuffer *buffer);
399
400 bool IsAudioBufferPlaying(AudioBuffer *buffer);
401 void PlayAudioBuffer(AudioBuffer *buffer);
402 void StopAudioBuffer(AudioBuffer *buffer);
403 void PauseAudioBuffer(AudioBuffer *buffer);
404 void ResumeAudioBuffer(AudioBuffer *buffer);
405 void SetAudioBufferVolume(AudioBuffer *buffer, float volume);
406 void SetAudioBufferPitch(AudioBuffer *buffer, float pitch);
407 void TrackAudioBuffer(AudioBuffer *buffer);
408 void UntrackAudioBuffer(AudioBuffer *buffer);
409 int GetAudioStreamBufferSizeDefault();
410
411 //----------------------------------------------------------------------------------
412 // Module Functions Definition - Audio Device initialization and Closing
413 //----------------------------------------------------------------------------------
414 // Initialize audio device
415 void InitAudioDevice(void)
416 {
417     // TODO: Load AUDIO context memory dynamically?
418
419     // Init audio context
420     ma_context_config ctxConfig = ma_context_config_init();
421     ctxConfig.logCallback = OnLog;
422
423     ma_result result = ma_context_init(NULL, 0, &ctxConfig, &AUDIO.System.context);
424     if (result != MA_SUCCESS)
425     {
426         TRACELOG(LOG_WARNING, "AUDIO: Failed to initialize context");
427         return;
428     }
429
430     // Init audio device
431     // NOTE: Using the default device. Format is floating point because it simplifies mixing.
432     ma_device_config config = ma_device_config_init(ma_device_type_playback);
433     config.playback.pDeviceID = NULL;  // NULL for the default playback AUDIO.System.device.
434     config.playback.format = AUDIO_DEVICE_FORMAT;
435     config.playback.channels = AUDIO_DEVICE_CHANNELS;
436     config.capture.pDeviceID = NULL;  // NULL for the default capture AUDIO.System.device.
437     config.capture.format = ma_format_s16;
438     config.capture.channels = 1;
439     config.sampleRate = AUDIO_DEVICE_SAMPLE_RATE;
440     config.dataCallback = OnSendAudioDataToDevice;
441     config.pUserData = NULL;
442
443     result = ma_device_init(&AUDIO.System.context, &config, &AUDIO.System.device);
444     if (result != MA_SUCCESS)
445     {
446         TRACELOG(LOG_WARNING, "AUDIO: Failed to initialize playback device");
447         ma_context_uninit(&AUDIO.System.context);
448         return;
449     }
450
451     // Keep the device running the whole time. May want to consider doing something a bit smarter and only have the device running
452     // while there's at least one sound being played.
453     result = ma_device_start(&AUDIO.System.device);
454     if (result != MA_SUCCESS)
455     {
456         TRACELOG(LOG_WARNING, "AUDIO: Failed to start playback device");
457         ma_device_uninit(&AUDIO.System.device);
458         ma_context_uninit(&AUDIO.System.context);
459         return;
460     }
461
462     // Mixing happens on a seperate thread which means we need to synchronize. I'm using a mutex here to make things simple, but may
463     // want to look at something a bit smarter later on to keep everything real-time, if that's necessary.
464     if (ma_mutex_init(&AUDIO.System.lock) != MA_SUCCESS)
465     {
466         TRACELOG(LOG_WARNING, "AUDIO: Failed to create mutex for mixing");
467         ma_device_uninit(&AUDIO.System.device);
468         ma_context_uninit(&AUDIO.System.context);
469         return;
470     }
471
472     // Init dummy audio buffers pool for multichannel sound playing
473     for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
474     {
475         // WARNING: An empty audioBuffer is created (data = 0)
476         // AudioBuffer data just points to loaded sound data
477         AUDIO.MultiChannel.pool[i] = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, 0, AUDIO_BUFFER_USAGE_STATIC);
478     }
479
480     TRACELOG(LOG_INFO, "AUDIO: Device initialized successfully");
481     TRACELOG(LOG_INFO, "    > Backend:       miniaudio / %s", ma_get_backend_name(AUDIO.System.context.backend));
482     TRACELOG(LOG_INFO, "    > Format:        %s -> %s", ma_get_format_name(AUDIO.System.device.playback.format), ma_get_format_name(AUDIO.System.device.playback.internalFormat));
483     TRACELOG(LOG_INFO, "    > Channels:      %d -> %d", AUDIO.System.device.playback.channels, AUDIO.System.device.playback.internalChannels);
484     TRACELOG(LOG_INFO, "    > Sample rate:   %d -> %d", AUDIO.System.device.sampleRate, AUDIO.System.device.playback.internalSampleRate);
485     TRACELOG(LOG_INFO, "    > Periods size:  %d", AUDIO.System.device.playback.internalPeriodSizeInFrames*AUDIO.System.device.playback.internalPeriods);
486
487     AUDIO.System.isReady = true;
488 }
489
490 // Close the audio device for all contexts
491 void CloseAudioDevice(void)
492 {
493     if (AUDIO.System.isReady)
494     {
495         // Unload dummy audio buffers pool
496         // WARNING: They can be pointing to already unloaded data
497         for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
498         {
499             //UnloadAudioBuffer(AUDIO.MultiChannel.pool[i]);
500             if (AUDIO.MultiChannel.pool[i] != NULL)
501             {
502                 ma_data_converter_uninit(&AUDIO.MultiChannel.pool[i]->converter);
503                 UntrackAudioBuffer(AUDIO.MultiChannel.pool[i]);
504                 //RL_FREE(buffer->data);    // Already unloaded by UnloadSound()
505                 RL_FREE(AUDIO.MultiChannel.pool[i]);
506             }
507         }
508
509         ma_mutex_uninit(&AUDIO.System.lock);
510         ma_device_uninit(&AUDIO.System.device);
511         ma_context_uninit(&AUDIO.System.context);
512
513         AUDIO.System.isReady = false;
514
515         TRACELOG(LOG_INFO, "AUDIO: Device closed successfully");
516     }
517     else TRACELOG(LOG_WARNING, "AUDIO: Device could not be closed, not currently initialized");
518 }
519
520 // Check if device has been initialized successfully
521 bool IsAudioDeviceReady(void)
522 {
523     return AUDIO.System.isReady;
524 }
525
526 // Set master volume (listener)
527 void SetMasterVolume(float volume)
528 {
529     ma_device_set_master_volume(&AUDIO.System.device, volume);
530 }
531
532 //----------------------------------------------------------------------------------
533 // Module Functions Definition - Audio Buffer management
534 //----------------------------------------------------------------------------------
535
536 // Initialize a new audio buffer (filled with silence)
537 AudioBuffer *LoadAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 sizeInFrames, int usage)
538 {
539     AudioBuffer *audioBuffer = (AudioBuffer *)RL_CALLOC(1, sizeof(AudioBuffer));
540
541     if (audioBuffer == NULL)
542     {
543         TRACELOG(LOG_WARNING, "AUDIO: Failed to allocate memory for buffer");
544         return NULL;
545     }
546
547     if (sizeInFrames > 0) audioBuffer->data = RL_CALLOC(sizeInFrames*channels*ma_get_bytes_per_sample(format), 1);
548
549     // Audio data runs through a format converter
550     ma_data_converter_config converterConfig = ma_data_converter_config_init(format, AUDIO_DEVICE_FORMAT, channels, AUDIO_DEVICE_CHANNELS, sampleRate, AUDIO.System.device.sampleRate);
551     converterConfig.resampling.allowDynamicSampleRate = true;        // Required for pitch shifting
552
553     ma_result result = ma_data_converter_init(&converterConfig, &audioBuffer->converter);
554
555     if (result != MA_SUCCESS)
556     {
557         TRACELOG(LOG_WARNING, "AUDIO: Failed to create data conversion pipeline");
558         RL_FREE(audioBuffer);
559         return NULL;
560     }
561
562     // Init audio buffer values
563     audioBuffer->volume = 1.0f;
564     audioBuffer->pitch = 1.0f;
565     audioBuffer->playing = false;
566     audioBuffer->paused = false;
567     audioBuffer->looping = false;
568     audioBuffer->usage = usage;
569     audioBuffer->frameCursorPos = 0;
570     audioBuffer->sizeInFrames = sizeInFrames;
571
572     // Buffers should be marked as processed by default so that a call to
573     // UpdateAudioStream() immediately after initialization works correctly
574     audioBuffer->isSubBufferProcessed[0] = true;
575     audioBuffer->isSubBufferProcessed[1] = true;
576
577     // Track audio buffer to linked list next position
578     TrackAudioBuffer(audioBuffer);
579
580     return audioBuffer;
581 }
582
583 // Delete an audio buffer
584 void UnloadAudioBuffer(AudioBuffer *buffer)
585 {
586     if (buffer != NULL)
587     {
588         ma_data_converter_uninit(&buffer->converter);
589         UntrackAudioBuffer(buffer);
590         RL_FREE(buffer->data);
591         RL_FREE(buffer);
592     }
593 }
594
595 // Check if an audio buffer is playing
596 bool IsAudioBufferPlaying(AudioBuffer *buffer)
597 {
598     bool result = false;
599
600     if (buffer != NULL) result = (buffer->playing && !buffer->paused);
601
602     return result;
603 }
604
605 // Play an audio buffer
606 // NOTE: Buffer is restarted to the start.
607 // Use PauseAudioBuffer() and ResumeAudioBuffer() if the playback position should be maintained.
608 void PlayAudioBuffer(AudioBuffer *buffer)
609 {
610     if (buffer != NULL)
611     {
612         buffer->playing = true;
613         buffer->paused = false;
614         buffer->frameCursorPos = 0;
615     }
616 }
617
618 // Stop an audio buffer
619 void StopAudioBuffer(AudioBuffer *buffer)
620 {
621     if (buffer != NULL)
622     {
623         if (IsAudioBufferPlaying(buffer))
624         {
625             buffer->playing = false;
626             buffer->paused = false;
627             buffer->frameCursorPos = 0;
628             buffer->totalFramesProcessed = 0;
629             buffer->isSubBufferProcessed[0] = true;
630             buffer->isSubBufferProcessed[1] = true;
631         }
632     }
633 }
634
635 // Pause an audio buffer
636 void PauseAudioBuffer(AudioBuffer *buffer)
637 {
638     if (buffer != NULL) buffer->paused = true;
639 }
640
641 // Resume an audio buffer
642 void ResumeAudioBuffer(AudioBuffer *buffer)
643 {
644     if (buffer != NULL) buffer->paused = false;
645 }
646
647 // Set volume for an audio buffer
648 void SetAudioBufferVolume(AudioBuffer *buffer, float volume)
649 {
650     if (buffer != NULL) buffer->volume = volume;
651 }
652
653 // Set pitch for an audio buffer
654 void SetAudioBufferPitch(AudioBuffer *buffer, float pitch)
655 {
656     if ((buffer != NULL) && (pitch > 0.0f))
657     {
658         // Pitching is just an adjustment of the sample rate.
659         // Note that this changes the duration of the sound:
660         //  - higher pitches will make the sound faster
661         //  - lower pitches make it slower
662         ma_uint32 outputSampleRate = (ma_uint32)((float)buffer->converter.config.sampleRateOut/pitch);
663         ma_data_converter_set_rate(&buffer->converter, buffer->converter.config.sampleRateIn, outputSampleRate);
664
665         buffer->pitch = pitch;
666     }
667 }
668
669 // Track audio buffer to linked list next position
670 void TrackAudioBuffer(AudioBuffer *buffer)
671 {
672     ma_mutex_lock(&AUDIO.System.lock);
673     {
674         if (AUDIO.Buffer.first == NULL) AUDIO.Buffer.first = buffer;
675         else
676         {
677             AUDIO.Buffer.last->next = buffer;
678             buffer->prev = AUDIO.Buffer.last;
679         }
680
681         AUDIO.Buffer.last = buffer;
682     }
683     ma_mutex_unlock(&AUDIO.System.lock);
684 }
685
686 // Untrack audio buffer from linked list
687 void UntrackAudioBuffer(AudioBuffer *buffer)
688 {
689     ma_mutex_lock(&AUDIO.System.lock);
690     {
691         if (buffer->prev == NULL) AUDIO.Buffer.first = buffer->next;
692         else buffer->prev->next = buffer->next;
693
694         if (buffer->next == NULL) AUDIO.Buffer.last = buffer->prev;
695         else buffer->next->prev = buffer->prev;
696
697         buffer->prev = NULL;
698         buffer->next = NULL;
699     }
700     ma_mutex_unlock(&AUDIO.System.lock);
701 }
702
703 //----------------------------------------------------------------------------------
704 // Module Functions Definition - Sounds loading and playing (.WAV)
705 //----------------------------------------------------------------------------------
706
707 // Load wave data from file
708 Wave LoadWave(const char *fileName)
709 {
710     Wave wave = { 0 };
711
712     // Loading file to memory
713     unsigned int fileSize = 0;
714     unsigned char *fileData = LoadFileData(fileName, &fileSize);
715
716     if (fileData != NULL)
717     {
718         // Loading wave from memory data
719         wave = LoadWaveFromMemory(GetFileExtension(fileName), fileData, fileSize);
720
721         RL_FREE(fileData);
722     }
723
724     return wave;
725 }
726
727 // Load wave from memory buffer, fileType refers to extension: i.e. ".wav"
728 Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int dataSize)
729 {
730     Wave wave = { 0 };
731
732     char fileExtLower[16] = { 0 };
733     strcpy(fileExtLower, TextToLower(fileType));
734
735     if (false) { }
736 #if defined(SUPPORT_FILEFORMAT_WAV)
737     else if (TextIsEqual(fileExtLower, ".wav")) wave = LoadWAV(fileData, dataSize);
738 #endif
739 #if defined(SUPPORT_FILEFORMAT_OGG)
740     else if (TextIsEqual(fileExtLower, ".ogg")) wave = LoadOGG(fileData, dataSize);
741 #endif
742 #if defined(SUPPORT_FILEFORMAT_FLAC)
743     else if (TextIsEqual(fileExtLower, ".flac")) wave = LoadFLAC(fileData, dataSize);
744 #endif
745 #if defined(SUPPORT_FILEFORMAT_MP3)
746     else if (TextIsEqual(fileExtLower, ".mp3")) wave = LoadMP3(fileData, dataSize);
747 #endif
748     else TRACELOG(LOG_WARNING, "WAVE: File format not supported");
749
750     return wave;
751 }
752
753 // Load sound from file
754 // NOTE: The entire file is loaded to memory to be played (no-streaming)
755 Sound LoadSound(const char *fileName)
756 {
757     Wave wave = LoadWave(fileName);
758
759     Sound sound = LoadSoundFromWave(wave);
760
761     UnloadWave(wave);       // Sound is loaded, we can unload wave
762
763     return sound;
764 }
765
766 // Load sound from wave data
767 // NOTE: Wave data must be unallocated manually
768 Sound LoadSoundFromWave(Wave wave)
769 {
770     Sound sound = { 0 };
771
772     if (wave.data != NULL)
773     {
774         // When using miniaudio we need to do our own mixing.
775         // To simplify this we need convert the format of each sound to be consistent with
776         // the format used to open the playback AUDIO.System.device. We can do this two ways:
777         //
778         //   1) Convert the whole sound in one go at load time (here).
779         //   2) Convert the audio data in chunks at mixing time.
780         //
781         // First option has been selected, format conversion is done on the loading stage.
782         // The downside is that it uses more memory if the original sound is u8 or s16.
783         ma_format formatIn  = ((wave.sampleSize == 8)? ma_format_u8 : ((wave.sampleSize == 16)? ma_format_s16 : ma_format_f32));
784         ma_uint32 frameCountIn = wave.sampleCount/wave.channels;
785
786         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);
787         if (frameCount == 0) TRACELOG(LOG_WARNING, "SOUND: Failed to get frame count for format conversion");
788
789         AudioBuffer *audioBuffer = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, frameCount, AUDIO_BUFFER_USAGE_STATIC);
790         if (audioBuffer == NULL)
791         {
792             TRACELOG(LOG_WARNING, "SOUND: Failed to create buffer");
793             return sound; // early return to avoid dereferencing the audioBuffer null pointer
794         }
795
796         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);
797         if (frameCount == 0) TRACELOG(LOG_WARNING, "SOUND: Failed format conversion");
798
799         sound.sampleCount = frameCount*AUDIO_DEVICE_CHANNELS;
800         sound.stream.sampleRate = AUDIO.System.device.sampleRate;
801         sound.stream.sampleSize = 32;
802         sound.stream.channels = AUDIO_DEVICE_CHANNELS;
803         sound.stream.buffer = audioBuffer;
804     }
805
806     return sound;
807 }
808
809 // Unload wave data
810 void UnloadWave(Wave wave)
811 {
812     if (wave.data != NULL) RL_FREE(wave.data);
813
814     TRACELOG(LOG_INFO, "WAVE: Unloaded wave data from RAM");
815 }
816
817 // Unload sound
818 void UnloadSound(Sound sound)
819 {
820     UnloadAudioBuffer(sound.stream.buffer);
821
822     TRACELOG(LOG_INFO, "WAVE: Unloaded sound data from RAM");
823 }
824
825 // Update sound buffer with new data
826 void UpdateSound(Sound sound, const void *data, int samplesCount)
827 {
828     if (sound.stream.buffer != NULL)
829     {
830         StopAudioBuffer(sound.stream.buffer);
831
832         // TODO: May want to lock/unlock this since this data buffer is read at mixing time
833         memcpy(sound.stream.buffer->data, data, samplesCount*ma_get_bytes_per_frame(sound.stream.buffer->converter.config.formatIn, sound.stream.buffer->converter.config.channelsIn));
834     }
835 }
836
837 // Export wave data to file
838 bool ExportWave(Wave wave, const char *fileName)
839 {
840     bool success = false;
841
842     if (false) { }
843 #if defined(SUPPORT_FILEFORMAT_WAV)
844     else if (IsFileExtension(fileName, ".wav")) success = SaveWAV(wave, fileName);
845 #endif
846     else if (IsFileExtension(fileName, ".raw"))
847     {
848         // Export raw sample data (without header)
849         // NOTE: It's up to the user to track wave parameters
850         success = SaveFileData(fileName, wave.data, wave.sampleCount*wave.sampleSize/8);
851     }
852
853     if (success) TRACELOG(LOG_INFO, "FILEIO: [%s] Wave data exported successfully", fileName);
854     else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export wave data", fileName);
855
856     return success;
857 }
858
859 // Export wave sample data to code (.h)
860 bool ExportWaveAsCode(Wave wave, const char *fileName)
861 {
862     bool success = false;
863
864 #ifndef TEXT_BYTES_PER_LINE
865     #define TEXT_BYTES_PER_LINE     20
866 #endif
867
868     int waveDataSize = wave.sampleCount*wave.channels*wave.sampleSize/8;
869
870     // NOTE: Text data buffer size is estimated considering wave data size in bytes
871     // and requiring 6 char bytes for every byte: "0x00, "
872     char *txtData = (char *)RL_CALLOC(6*waveDataSize + 2000, sizeof(char));
873
874     int bytesCount = 0;
875     bytesCount += sprintf(txtData + bytesCount, "\n//////////////////////////////////////////////////////////////////////////////////\n");
876     bytesCount += sprintf(txtData + bytesCount, "//                                                                              //\n");
877     bytesCount += sprintf(txtData + bytesCount, "// WaveAsCode exporter v1.0 - Wave data exported as an array of bytes           //\n");
878     bytesCount += sprintf(txtData + bytesCount, "//                                                                              //\n");
879     bytesCount += sprintf(txtData + bytesCount, "// more info and bugs-report:  github.com/raysan5/raylib                        //\n");
880     bytesCount += sprintf(txtData + bytesCount, "// feedback and support:       ray[at]raylib.com                                //\n");
881     bytesCount += sprintf(txtData + bytesCount, "//                                                                              //\n");
882     bytesCount += sprintf(txtData + bytesCount, "// Copyright (c) 2018 Ramon Santamaria (@raysan5)                               //\n");
883     bytesCount += sprintf(txtData + bytesCount, "//                                                                              //\n");
884     bytesCount += sprintf(txtData + bytesCount, "//////////////////////////////////////////////////////////////////////////////////\n\n");
885
886     char varFileName[256] = { 0 };
887 #if !defined(RAUDIO_STANDALONE)
888     // Get file name from path and convert variable name to uppercase
889     strcpy(varFileName, GetFileNameWithoutExt(fileName));
890     for (int i = 0; varFileName[i] != '\0'; i++) if (varFileName[i] >= 'a' && varFileName[i] <= 'z') { varFileName[i] = varFileName[i] - 32; }
891 #else
892     strcpy(varFileName, fileName);
893 #endif
894
895     bytesCount += sprintf(txtData + bytesCount, "// Wave data information\n");
896     bytesCount += sprintf(txtData + bytesCount, "#define %s_SAMPLE_COUNT     %u\n", varFileName, wave.sampleCount);
897     bytesCount += sprintf(txtData + bytesCount, "#define %s_SAMPLE_RATE      %u\n", varFileName, wave.sampleRate);
898     bytesCount += sprintf(txtData + bytesCount, "#define %s_SAMPLE_SIZE      %u\n", varFileName, wave.sampleSize);
899     bytesCount += sprintf(txtData + bytesCount, "#define %s_CHANNELS         %u\n\n", varFileName, wave.channels);
900
901     // Write byte data as hexadecimal text
902     bytesCount += sprintf(txtData + bytesCount, "static unsigned char %s_DATA[%i] = { ", varFileName, waveDataSize);
903     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]);
904     bytesCount += sprintf(txtData + bytesCount, "0x%x };\n", ((unsigned char *)wave.data)[waveDataSize - 1]);
905
906     // NOTE: Text data length exported is determined by '\0' (NULL) character
907     success = SaveFileText(fileName, txtData);
908
909     RL_FREE(txtData);
910
911     return success;
912 }
913
914 // Play a sound
915 void PlaySound(Sound sound)
916 {
917     PlayAudioBuffer(sound.stream.buffer);
918 }
919
920 // Play a sound in the multichannel buffer pool
921 void PlaySoundMulti(Sound sound)
922 {
923     int index = -1;
924     unsigned int oldAge = 0;
925     int oldIndex = -1;
926
927     // find the first non playing pool entry
928     for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
929     {
930         if (AUDIO.MultiChannel.channels[i] > oldAge)
931         {
932             oldAge = AUDIO.MultiChannel.channels[i];
933             oldIndex = i;
934         }
935
936         if (!IsAudioBufferPlaying(AUDIO.MultiChannel.pool[i]))
937         {
938             index = i;
939             break;
940         }
941     }
942
943     // If no none playing pool members can be index choose the oldest
944     if (index == -1)
945     {
946         TRACELOG(LOG_WARNING, "SOUND: Buffer pool is already full, count: %i", AUDIO.MultiChannel.poolCounter);
947
948         if (oldIndex == -1)
949         {
950             // Shouldn't be able to get here... but just in case something odd happens!
951             TRACELOG(LOG_WARNING, "SOUND: Buffer pool could not determine oldest buffer not playing sound");
952             return;
953         }
954
955         index = oldIndex;
956
957         // Just in case...
958         StopAudioBuffer(AUDIO.MultiChannel.pool[index]);
959     }
960
961     // Experimentally mutex lock doesn't seem to be needed this makes sense
962     // as pool[index] isn't playing and the only stuff we're copying
963     // shouldn't be changing...
964
965     AUDIO.MultiChannel.channels[index] = AUDIO.MultiChannel.poolCounter;
966     AUDIO.MultiChannel.poolCounter++;
967
968     AUDIO.MultiChannel.pool[index]->volume = sound.stream.buffer->volume;
969     AUDIO.MultiChannel.pool[index]->pitch = sound.stream.buffer->pitch;
970     AUDIO.MultiChannel.pool[index]->looping = sound.stream.buffer->looping;
971     AUDIO.MultiChannel.pool[index]->usage = sound.stream.buffer->usage;
972     AUDIO.MultiChannel.pool[index]->isSubBufferProcessed[0] = false;
973     AUDIO.MultiChannel.pool[index]->isSubBufferProcessed[1] = false;
974     AUDIO.MultiChannel.pool[index]->sizeInFrames = sound.stream.buffer->sizeInFrames;
975     AUDIO.MultiChannel.pool[index]->data = sound.stream.buffer->data;
976
977     PlayAudioBuffer(AUDIO.MultiChannel.pool[index]);
978 }
979
980 // Stop any sound played with PlaySoundMulti()
981 void StopSoundMulti(void)
982 {
983     for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++) StopAudioBuffer(AUDIO.MultiChannel.pool[i]);
984 }
985
986 // Get number of sounds playing in the multichannel buffer pool
987 int GetSoundsPlaying(void)
988 {
989     int counter = 0;
990
991     for (int i = 0; i < MAX_AUDIO_BUFFER_POOL_CHANNELS; i++)
992     {
993         if (IsAudioBufferPlaying(AUDIO.MultiChannel.pool[i])) counter++;
994     }
995
996     return counter;
997 }
998
999 // Pause a sound
1000 void PauseSound(Sound sound)
1001 {
1002     PauseAudioBuffer(sound.stream.buffer);
1003 }
1004
1005 // Resume a paused sound
1006 void ResumeSound(Sound sound)
1007 {
1008     ResumeAudioBuffer(sound.stream.buffer);
1009 }
1010
1011 // Stop reproducing a sound
1012 void StopSound(Sound sound)
1013 {
1014     StopAudioBuffer(sound.stream.buffer);
1015 }
1016
1017 // Check if a sound is playing
1018 bool IsSoundPlaying(Sound sound)
1019 {
1020     return IsAudioBufferPlaying(sound.stream.buffer);
1021 }
1022
1023 // Set volume for a sound
1024 void SetSoundVolume(Sound sound, float volume)
1025 {
1026     SetAudioBufferVolume(sound.stream.buffer, volume);
1027 }
1028
1029 // Set pitch for a sound
1030 void SetSoundPitch(Sound sound, float pitch)
1031 {
1032     SetAudioBufferPitch(sound.stream.buffer, pitch);
1033 }
1034
1035 // Convert wave data to desired format
1036 void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels)
1037 {
1038     ma_format formatIn = ((wave->sampleSize == 8)? ma_format_u8 : ((wave->sampleSize == 16)? ma_format_s16 : ma_format_f32));
1039     ma_format formatOut = ((sampleSize == 8)? ma_format_u8 : ((sampleSize == 16)? ma_format_s16 : ma_format_f32));
1040
1041     ma_uint32 frameCountIn = wave->sampleCount/wave->channels;
1042
1043     ma_uint32 frameCount = (ma_uint32)ma_convert_frames(NULL, 0, formatOut, channels, sampleRate, NULL, frameCountIn, formatIn, wave->channels, wave->sampleRate);
1044     if (frameCount == 0)
1045     {
1046         TRACELOG(LOG_WARNING, "WAVE: Failed to get frame count for format conversion");
1047         return;
1048     }
1049
1050     void *data = RL_MALLOC(frameCount*channels*(sampleSize/8));
1051
1052     frameCount = (ma_uint32)ma_convert_frames(data, frameCount, formatOut, channels, sampleRate, wave->data, frameCountIn, formatIn, wave->channels, wave->sampleRate);
1053     if (frameCount == 0)
1054     {
1055         TRACELOG(LOG_WARNING, "WAVE: Failed format conversion");
1056         return;
1057     }
1058
1059     wave->sampleCount = frameCount*channels;
1060     wave->sampleSize = sampleSize;
1061     wave->sampleRate = sampleRate;
1062     wave->channels = channels;
1063     RL_FREE(wave->data);
1064     wave->data = data;
1065 }
1066
1067 // Copy a wave to a new wave
1068 Wave WaveCopy(Wave wave)
1069 {
1070     Wave newWave = { 0 };
1071
1072     newWave.data = RL_MALLOC(wave.sampleCount*wave.sampleSize/8);
1073
1074     if (newWave.data != NULL)
1075     {
1076         // NOTE: Size must be provided in bytes
1077         memcpy(newWave.data, wave.data, wave.sampleCount*wave.sampleSize/8);
1078
1079         newWave.sampleCount = wave.sampleCount;
1080         newWave.sampleRate = wave.sampleRate;
1081         newWave.sampleSize = wave.sampleSize;
1082         newWave.channels = wave.channels;
1083     }
1084
1085     return newWave;
1086 }
1087
1088 // Crop a wave to defined samples range
1089 // NOTE: Security check in case of out-of-range
1090 void WaveCrop(Wave *wave, int initSample, int finalSample)
1091 {
1092     if ((initSample >= 0) && (initSample < finalSample) &&
1093         (finalSample > 0) && ((unsigned int)finalSample < wave->sampleCount))
1094     {
1095         int sampleCount = finalSample - initSample;
1096
1097         void *data = RL_MALLOC(sampleCount*wave->sampleSize/8);
1098
1099         memcpy(data, (unsigned char *)wave->data + (initSample*wave->channels*wave->sampleSize/8), sampleCount*wave->sampleSize/8);
1100
1101         RL_FREE(wave->data);
1102         wave->data = data;
1103     }
1104     else TRACELOG(LOG_WARNING, "WAVE: Crop range out of bounds");
1105 }
1106
1107 // Load samples data from wave as a floats array
1108 // NOTE 1: Returned sample values are normalized to range [-1..1]
1109 // NOTE 2: Sample data allocated should be freed with UnloadWaveSamples()
1110 float *LoadWaveSamples(Wave wave)
1111 {
1112     float *samples = (float *)RL_MALLOC(wave.sampleCount*sizeof(float));
1113
1114     // NOTE: sampleCount is the total number of interlaced samples (including channels)
1115
1116     for (unsigned int i = 0; i < wave.sampleCount; i++)
1117     {
1118         if (wave.sampleSize == 8) samples[i] = (float)(((unsigned char *)wave.data)[i] - 127)/256.0f;
1119         else if (wave.sampleSize == 16) samples[i] = (float)(((short *)wave.data)[i])/32767.0f;
1120         else if (wave.sampleSize == 32) samples[i] = ((float *)wave.data)[i];
1121     }
1122
1123     return samples;
1124 }
1125
1126 // Unload samples data loaded with LoadWaveSamples()
1127 void UnloadWaveSamples(float *samples)
1128 {
1129     RL_FREE(samples);
1130 }
1131
1132 //----------------------------------------------------------------------------------
1133 // Module Functions Definition - Music loading and stream playing (.OGG)
1134 //----------------------------------------------------------------------------------
1135
1136 // Load music stream from file
1137 Music LoadMusicStream(const char *fileName)
1138 {
1139     Music music = { 0 };
1140     bool musicLoaded = false;
1141
1142     if (false) { }
1143 #if defined(SUPPORT_FILEFORMAT_WAV)
1144     else if (IsFileExtension(fileName, ".wav"))
1145     {
1146         drwav *ctxWav = RL_CALLOC(1, sizeof(drwav));
1147         bool success = drwav_init_file(ctxWav, fileName, NULL);
1148
1149         music.ctxType = MUSIC_AUDIO_WAV;
1150         music.ctxData = ctxWav;
1151
1152         if (success)
1153         {
1154             int sampleSize = ctxWav->bitsPerSample;
1155             if (ctxWav->bitsPerSample == 24) sampleSize = 16;   // Forcing conversion to s16 on UpdateMusicStream()
1156
1157             music.stream = InitAudioStream(ctxWav->sampleRate, sampleSize, ctxWav->channels);
1158             music.sampleCount = (unsigned int)ctxWav->totalPCMFrameCount*ctxWav->channels;
1159             music.looping = true;   // Looping enabled by default
1160             musicLoaded = true;
1161         }
1162     }
1163 #endif
1164 #if defined(SUPPORT_FILEFORMAT_OGG)
1165     else if (IsFileExtension(fileName, ".ogg"))
1166     {
1167         // Open ogg audio stream
1168         music.ctxType = MUSIC_AUDIO_OGG;
1169         music.ctxData = stb_vorbis_open_filename(fileName, NULL, NULL);
1170
1171         if (music.ctxData != NULL)
1172         {
1173             stb_vorbis_info info = stb_vorbis_get_info((stb_vorbis *)music.ctxData);  // Get Ogg file info
1174
1175             // OGG bit rate defaults to 16 bit, it's enough for compressed format
1176             music.stream = InitAudioStream(info.sample_rate, 16, info.channels);
1177
1178             // WARNING: It seems this function returns length in frames, not samples, so we multiply by channels
1179             music.sampleCount = (unsigned int)stb_vorbis_stream_length_in_samples((stb_vorbis *)music.ctxData)*info.channels;
1180             music.looping = true;   // Looping enabled by default
1181             musicLoaded = true;
1182         }
1183     }
1184 #endif
1185 #if defined(SUPPORT_FILEFORMAT_FLAC)
1186     else if (IsFileExtension(fileName, ".flac"))
1187     {
1188         music.ctxType = MUSIC_AUDIO_FLAC;
1189         music.ctxData = drflac_open_file(fileName, NULL);
1190
1191         if (music.ctxData != NULL)
1192         {
1193             drflac *ctxFlac = (drflac *)music.ctxData;
1194
1195             music.stream = InitAudioStream(ctxFlac->sampleRate, ctxFlac->bitsPerSample, ctxFlac->channels);
1196             music.sampleCount = (unsigned int)ctxFlac->totalPCMFrameCount*ctxFlac->channels;
1197             music.looping = true;   // Looping enabled by default
1198             musicLoaded = true;
1199         }
1200     }
1201 #endif
1202 #if defined(SUPPORT_FILEFORMAT_MP3)
1203     else if (IsFileExtension(fileName, ".mp3"))
1204     {
1205         drmp3 *ctxMp3 = RL_CALLOC(1, sizeof(drmp3));
1206         int result = drmp3_init_file(ctxMp3, fileName, NULL);
1207
1208         music.ctxType = MUSIC_AUDIO_MP3;
1209         music.ctxData = ctxMp3;
1210
1211         if (result > 0)
1212         {
1213             music.stream = InitAudioStream(ctxMp3->sampleRate, 32, ctxMp3->channels);
1214             music.sampleCount = (unsigned int)drmp3_get_pcm_frame_count(ctxMp3)*ctxMp3->channels;
1215             music.looping = true;   // Looping enabled by default
1216             musicLoaded = true;
1217         }
1218     }
1219 #endif
1220 #if defined(SUPPORT_FILEFORMAT_XM)
1221     else if (IsFileExtension(fileName, ".xm"))
1222     {
1223         jar_xm_context_t *ctxXm = NULL;
1224         int result = jar_xm_create_context_from_file(&ctxXm, AUDIO.System.device.sampleRate, fileName);
1225
1226         music.ctxType = MUSIC_MODULE_XM;
1227         music.ctxData = ctxXm;
1228
1229         if (result == 0)    // XM AUDIO.System.context created successfully
1230         {
1231             jar_xm_set_max_loop_count(ctxXm, 0);    // Set infinite number of loops
1232
1233             unsigned int bits = 32;
1234             if (AUDIO_DEVICE_FORMAT == ma_format_s16)
1235                 bits = 16;
1236             else if (AUDIO_DEVICE_FORMAT == ma_format_u8)
1237                 bits = 8;
1238
1239             // NOTE: Only stereo is supported for XM
1240             music.stream = InitAudioStream(AUDIO.System.device.sampleRate, bits, AUDIO_DEVICE_CHANNELS);
1241             music.sampleCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm)*2;    // 2 channels
1242             music.looping = true;   // Looping enabled by default
1243             jar_xm_reset(ctxXm);   // make sure we start at the beginning of the song
1244             musicLoaded = true;
1245         }
1246     }
1247 #endif
1248 #if defined(SUPPORT_FILEFORMAT_MOD)
1249     else if (IsFileExtension(fileName, ".mod"))
1250     {
1251         jar_mod_context_t *ctxMod = RL_CALLOC(1, sizeof(jar_mod_context_t));
1252         jar_mod_init(ctxMod);
1253         int result = jar_mod_load_file(ctxMod, fileName);
1254
1255         music.ctxType = MUSIC_MODULE_MOD;
1256         music.ctxData = ctxMod;
1257
1258         if (result > 0)
1259         {
1260             // NOTE: Only stereo is supported for MOD
1261             music.stream = InitAudioStream(AUDIO.System.device.sampleRate, 16, AUDIO_DEVICE_CHANNELS);
1262             music.sampleCount = (unsigned int)jar_mod_max_samples(ctxMod)*2;    // 2 channels
1263             music.looping = true;   // Looping enabled by default
1264             musicLoaded = true;
1265         }
1266     }
1267 #endif
1268     else TRACELOG(LOG_WARNING, "STREAM: [%s] Fileformat not supported", fileName);
1269
1270     if (!musicLoaded)
1271     {
1272         if (false) { }
1273     #if defined(SUPPORT_FILEFORMAT_WAV)
1274         else if (music.ctxType == MUSIC_AUDIO_WAV) drwav_uninit((drwav *)music.ctxData);
1275     #endif
1276     #if defined(SUPPORT_FILEFORMAT_OGG)
1277         else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData);
1278     #endif
1279     #if defined(SUPPORT_FILEFORMAT_FLAC)
1280         else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData, NULL);
1281     #endif
1282     #if defined(SUPPORT_FILEFORMAT_MP3)
1283         else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); }
1284     #endif
1285     #if defined(SUPPORT_FILEFORMAT_XM)
1286         else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData);
1287     #endif
1288     #if defined(SUPPORT_FILEFORMAT_MOD)
1289         else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); }
1290     #endif
1291
1292         music.ctxData = NULL;
1293         TRACELOG(LOG_WARNING, "FILEIO: [%s] Music file could not be opened", fileName);
1294     }
1295     else
1296     {
1297         // Show some music stream info
1298         TRACELOG(LOG_INFO, "FILEIO: [%s] Music file successfully loaded:", fileName);
1299         TRACELOG(LOG_INFO, "    > Total samples: %i", music.sampleCount);
1300         TRACELOG(LOG_INFO, "    > Sample rate:   %i Hz", music.stream.sampleRate);
1301         TRACELOG(LOG_INFO, "    > Sample size:   %i bits", music.stream.sampleSize);
1302         TRACELOG(LOG_INFO, "    > Channels:      %i (%s)", music.stream.channels, (music.stream.channels == 1)? "Mono" : (music.stream.channels == 2)? "Stereo" : "Multi");
1303     }
1304
1305     return music;
1306 }
1307
1308 // extension including period ".mod"
1309 Music LoadMusicStreamFromMemory(const char *fileType, unsigned char* data, int dataSize)
1310 {
1311     Music music = { 0 };
1312     bool musicLoaded = false;
1313
1314     char fileExtLower[16] = { 0 };
1315     strcpy(fileExtLower, TextToLower(fileType));
1316
1317     if (false) { }
1318 #if defined(SUPPORT_FILEFORMAT_WAV)
1319     else if (TextIsEqual(fileExtLower, ".wav"))
1320     {
1321         drwav *ctxWav = RL_CALLOC(1, sizeof(drwav));
1322
1323         bool success = drwav_init_memory(ctxWav, (const void*)data, dataSize, NULL);
1324
1325         music.ctxType = MUSIC_AUDIO_WAV;
1326         music.ctxData = ctxWav;
1327
1328         if (success)
1329         {
1330             int sampleSize = ctxWav->bitsPerSample;
1331             if (ctxWav->bitsPerSample == 24) sampleSize = 16;   // Forcing conversion to s16 on UpdateMusicStream()
1332
1333             music.stream = InitAudioStream(ctxWav->sampleRate, sampleSize, ctxWav->channels);
1334             music.sampleCount = (unsigned int)ctxWav->totalPCMFrameCount*ctxWav->channels;
1335             music.looping = true;   // Looping enabled by default
1336             musicLoaded = true;
1337         }
1338     }
1339 #endif
1340 #if defined(SUPPORT_FILEFORMAT_FLAC)
1341     else if (TextIsEqual(fileExtLower, ".flac"))
1342     {
1343         music.ctxType = MUSIC_AUDIO_FLAC;
1344         music.ctxData = drflac_open_memory((const void*)data, dataSize, NULL);
1345
1346         if (music.ctxData != NULL)
1347         {
1348             drflac *ctxFlac = (drflac *)music.ctxData;
1349
1350             music.stream = InitAudioStream(ctxFlac->sampleRate, ctxFlac->bitsPerSample, ctxFlac->channels);
1351             music.sampleCount = (unsigned int)ctxFlac->totalPCMFrameCount*ctxFlac->channels;
1352             music.looping = true;   // Looping enabled by default
1353             musicLoaded = true;
1354         }
1355     }
1356 #endif
1357 #if defined(SUPPORT_FILEFORMAT_MP3)
1358     else if (TextIsEqual(fileExtLower, ".mp3"))
1359     {
1360         drmp3 *ctxMp3 = RL_CALLOC(1, sizeof(drmp3));
1361         int success = drmp3_init_memory(ctxMp3, (const void*)data, dataSize, NULL);
1362
1363         music.ctxType = MUSIC_AUDIO_MP3;
1364         music.ctxData = ctxMp3;
1365
1366         if (success)
1367         {
1368             music.stream = InitAudioStream(ctxMp3->sampleRate, 32, ctxMp3->channels);
1369             music.sampleCount = (unsigned int)drmp3_get_pcm_frame_count(ctxMp3)*ctxMp3->channels;
1370             music.looping = true;   // Looping enabled by default
1371             musicLoaded = true;
1372         }
1373     }
1374 #endif
1375 #if defined(SUPPORT_FILEFORMAT_OGG)
1376     else if (TextIsEqual(fileExtLower, ".ogg"))
1377     {
1378         // Open ogg audio stream
1379         music.ctxType = MUSIC_AUDIO_OGG;
1380         //music.ctxData = stb_vorbis_open_filename(fileName, NULL, NULL);
1381         music.ctxData = stb_vorbis_open_memory((const unsigned char*)data, dataSize, NULL, NULL);
1382
1383         if (music.ctxData != NULL)
1384         {
1385             stb_vorbis_info info = stb_vorbis_get_info((stb_vorbis *)music.ctxData);  // Get Ogg file info
1386
1387             // OGG bit rate defaults to 16 bit, it's enough for compressed format
1388             music.stream = InitAudioStream(info.sample_rate, 16, info.channels);
1389
1390             // WARNING: It seems this function returns length in frames, not samples, so we multiply by channels
1391             music.sampleCount = (unsigned int)stb_vorbis_stream_length_in_samples((stb_vorbis *)music.ctxData)*info.channels;
1392             music.looping = true;   // Looping enabled by default
1393             musicLoaded = true;
1394         }
1395     }
1396 #endif
1397 #if defined(SUPPORT_FILEFORMAT_XM)
1398     else if (TextIsEqual(fileExtLower, ".xm"))
1399     {
1400         jar_xm_context_t *ctxXm = NULL;
1401         int result = jar_xm_create_context_safe(&ctxXm, (const char*)data, dataSize, AUDIO.System.device.sampleRate);
1402         if (result == 0)    // XM AUDIO.System.context created successfully
1403         {
1404             music.ctxType = MUSIC_MODULE_XM;
1405             jar_xm_set_max_loop_count(ctxXm, 0);    // Set infinite number of loops
1406
1407             unsigned int bits = 32;
1408             if (AUDIO_DEVICE_FORMAT == ma_format_s16)
1409                 bits = 16;
1410             else if (AUDIO_DEVICE_FORMAT == ma_format_u8)
1411                 bits = 8;
1412
1413             // NOTE: Only stereo is supported for XM
1414             music.stream = InitAudioStream(AUDIO.System.device.sampleRate, bits, 2);
1415             music.sampleCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm)*2;    // 2 channels
1416             music.looping = true;   // Looping enabled by default
1417             jar_xm_reset(ctxXm);   // make sure we start at the beginning of the song
1418
1419             music.ctxData = ctxXm;
1420             musicLoaded = true;
1421         }
1422     }
1423 #endif
1424 #if defined(SUPPORT_FILEFORMAT_MOD)
1425     else if (TextIsEqual(fileExtLower, ".mod"))
1426     {
1427         jar_mod_context_t *ctxMod = RL_MALLOC(sizeof(jar_mod_context_t));
1428         int result = 0;
1429
1430         jar_mod_init(ctxMod);
1431
1432         // copy data to allocated memory for default UnloadMusicStream
1433         unsigned char *newData = RL_MALLOC(dataSize);
1434         int it = dataSize/sizeof(unsigned char);
1435         for (int i = 0; i < it; i++){
1436             newData[i] = data[i];
1437         }
1438
1439         // Memory loaded version for jar_mod_load_file()
1440         if (dataSize && dataSize < 32*1024*1024)
1441         {
1442             ctxMod->modfilesize = dataSize;
1443             ctxMod->modfile = newData;
1444             if (jar_mod_load(ctxMod, (void *)ctxMod->modfile, dataSize)) result = dataSize;
1445         }
1446
1447         if (result > 0)
1448         {
1449             music.ctxType = MUSIC_MODULE_MOD;
1450
1451             // NOTE: Only stereo is supported for MOD
1452             music.stream = InitAudioStream(AUDIO.System.device.sampleRate, 16, 2);
1453             music.sampleCount = (unsigned int)jar_mod_max_samples(ctxMod)*2;    // 2 channels
1454             music.looping = true;   // Looping enabled by default
1455             musicLoaded = true;
1456
1457             music.ctxData = ctxMod;
1458             musicLoaded = true;
1459         }
1460     }
1461 #endif
1462     else TRACELOG(LOG_WARNING, "STREAM: [%s] Fileformat not supported", fileType);
1463
1464     if (!musicLoaded)
1465     {
1466         if (false) { }
1467     #if defined(SUPPORT_FILEFORMAT_WAV)
1468         else if (music.ctxType == MUSIC_AUDIO_WAV) drwav_uninit((drwav *)music.ctxData);
1469     #endif
1470     #if defined(SUPPORT_FILEFORMAT_FLAC)
1471         else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData, NULL);
1472     #endif
1473     #if defined(SUPPORT_FILEFORMAT_MP3)
1474         else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); }
1475     #endif
1476     #if defined(SUPPORT_FILEFORMAT_OGG)
1477         else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData);
1478     #endif
1479     #if defined(SUPPORT_FILEFORMAT_XM)
1480         else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData);
1481     #endif
1482     #if defined(SUPPORT_FILEFORMAT_MOD)
1483         else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); }
1484     #endif
1485
1486         music.ctxData = NULL;
1487         TRACELOG(LOG_WARNING, "FILEIO: [%s] Music memory could not be opened", fileType);
1488     }
1489     else
1490     {
1491         // Show some music stream info
1492         TRACELOG(LOG_INFO, "FILEIO: [%s] Music memory successfully loaded:", fileType);
1493         TRACELOG(LOG_INFO, "    > Total samples: %i", music.sampleCount);
1494         TRACELOG(LOG_INFO, "    > Sample rate:   %i Hz", music.stream.sampleRate);
1495         TRACELOG(LOG_INFO, "    > Sample size:   %i bits", music.stream.sampleSize);
1496         TRACELOG(LOG_INFO, "    > Channels:      %i (%s)", music.stream.channels, (music.stream.channels == 1)? "Mono" : (music.stream.channels == 2)? "Stereo" : "Multi");
1497     }
1498
1499     return music;
1500 }
1501
1502 // Unload music stream
1503 void UnloadMusicStream(Music music)
1504 {
1505     CloseAudioStream(music.stream);
1506
1507     if (music.ctxData != NULL)
1508     {
1509         if (false) { }
1510 #if defined(SUPPORT_FILEFORMAT_WAV)
1511         else if (music.ctxType == MUSIC_AUDIO_WAV) drwav_uninit((drwav *)music.ctxData);
1512 #endif
1513 #if defined(SUPPORT_FILEFORMAT_OGG)
1514         else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData);
1515 #endif
1516 #if defined(SUPPORT_FILEFORMAT_FLAC)
1517         else if (music.ctxType == MUSIC_AUDIO_FLAC) drflac_free((drflac *)music.ctxData, NULL);
1518 #endif
1519 #if defined(SUPPORT_FILEFORMAT_MP3)
1520     else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); }
1521 #endif
1522 #if defined(SUPPORT_FILEFORMAT_XM)
1523         else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData);
1524 #endif
1525 #if defined(SUPPORT_FILEFORMAT_MOD)
1526         else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); }
1527 #endif
1528     }
1529 }
1530
1531 // Start music playing (open stream)
1532 void PlayMusicStream(Music music)
1533 {
1534     if (music.stream.buffer != NULL)
1535     {
1536         // For music streams, we need to make sure we maintain the frame cursor position
1537         // This is a hack for this section of code in UpdateMusicStream()
1538         // NOTE: In case window is minimized, music stream is stopped, just make sure to
1539         // play again on window restore: if (IsMusicPlaying(music)) PlayMusicStream(music);
1540         ma_uint32 frameCursorPos = music.stream.buffer->frameCursorPos;
1541         PlayAudioStream(music.stream);  // WARNING: This resets the cursor position.
1542         music.stream.buffer->frameCursorPos = frameCursorPos;
1543     }
1544 }
1545
1546 // Pause music playing
1547 void PauseMusicStream(Music music)
1548 {
1549     PauseAudioStream(music.stream);
1550 }
1551
1552 // Resume music playing
1553 void ResumeMusicStream(Music music)
1554 {
1555     ResumeAudioStream(music.stream);
1556 }
1557
1558 // Stop music playing (close stream)
1559 void StopMusicStream(Music music)
1560 {
1561     StopAudioStream(music.stream);
1562
1563     switch (music.ctxType)
1564     {
1565 #if defined(SUPPORT_FILEFORMAT_WAV)
1566         case MUSIC_AUDIO_WAV: drwav_seek_to_pcm_frame((drwav *)music.ctxData, 0); break;
1567 #endif
1568 #if defined(SUPPORT_FILEFORMAT_OGG)
1569         case MUSIC_AUDIO_OGG: stb_vorbis_seek_start((stb_vorbis *)music.ctxData); break;
1570 #endif
1571 #if defined(SUPPORT_FILEFORMAT_FLAC)
1572         case MUSIC_AUDIO_FLAC: drflac_seek_to_pcm_frame((drflac *)music.ctxData, 0); break;
1573 #endif
1574 #if defined(SUPPORT_FILEFORMAT_MP3)
1575         case MUSIC_AUDIO_MP3: drmp3_seek_to_pcm_frame((drmp3 *)music.ctxData, 0); break;
1576 #endif
1577 #if defined(SUPPORT_FILEFORMAT_XM)
1578         case MUSIC_MODULE_XM: jar_xm_reset((jar_xm_context_t *)music.ctxData); break;
1579 #endif
1580 #if defined(SUPPORT_FILEFORMAT_MOD)
1581         case MUSIC_MODULE_MOD: jar_mod_seek_start((jar_mod_context_t *)music.ctxData); break;
1582 #endif
1583         default: break;
1584     }
1585 }
1586
1587 // Update (re-fill) music buffers if data already processed
1588 void UpdateMusicStream(Music music)
1589 {
1590     if (music.stream.buffer == NULL)
1591         return;
1592
1593     if (music.ctxType == MUSIC_MODULE_XM)
1594         jar_xm_set_max_loop_count(music.ctxData, music.looping ? 0 : 1);
1595
1596     bool streamEnding = false;
1597
1598     unsigned int subBufferSizeInFrames = music.stream.buffer->sizeInFrames/2;
1599
1600     // NOTE: Using dynamic allocation because it could require more than 16KB
1601     void *pcm = RL_CALLOC(subBufferSizeInFrames*music.stream.channels*music.stream.sampleSize/8, 1);
1602
1603     int samplesCount = 0;    // Total size of data streamed in L+R samples for xm floats, individual L or R for ogg shorts
1604
1605     // TODO: Get the sampleLeft using totalFramesProcessed... but first, get total frames processed correctly...
1606     //ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(music.stream.buffer->dsp.formatConverterIn.config.formatIn)*music.stream.buffer->dsp.formatConverterIn.config.channels;
1607     int sampleLeft = music.sampleCount - (music.stream.buffer->totalFramesProcessed*music.stream.channels);
1608
1609     if (music.ctxType == MUSIC_MODULE_XM && music.looping) sampleLeft = subBufferSizeInFrames*4;
1610
1611     while (IsAudioStreamProcessed(music.stream))
1612     {
1613         if ((sampleLeft/music.stream.channels) >= subBufferSizeInFrames) samplesCount = subBufferSizeInFrames*music.stream.channels;
1614         else samplesCount = sampleLeft;
1615
1616         switch (music.ctxType)
1617         {
1618         #if defined(SUPPORT_FILEFORMAT_WAV)
1619             case MUSIC_AUDIO_WAV:
1620             {
1621                 // NOTE: Returns the number of samples to process (not required)
1622                 if (music.stream.sampleSize == 16) drwav_read_pcm_frames_s16((drwav *)music.ctxData, samplesCount/music.stream.channels, (short *)pcm);
1623                 else if (music.stream.sampleSize == 32) drwav_read_pcm_frames_f32((drwav *)music.ctxData, samplesCount/music.stream.channels, (float *)pcm);
1624
1625             } break;
1626         #endif
1627         #if defined(SUPPORT_FILEFORMAT_OGG)
1628             case MUSIC_AUDIO_OGG:
1629             {
1630                 // NOTE: Returns the number of samples to process (be careful! we ask for number of shorts!)
1631                 stb_vorbis_get_samples_short_interleaved((stb_vorbis *)music.ctxData, music.stream.channels, (short *)pcm, samplesCount);
1632
1633             } break;
1634         #endif
1635         #if defined(SUPPORT_FILEFORMAT_FLAC)
1636             case MUSIC_AUDIO_FLAC:
1637             {
1638                 // NOTE: Returns the number of samples to process (not required)
1639                 drflac_read_pcm_frames_s16((drflac *)music.ctxData, samplesCount, (short *)pcm);
1640
1641             } break;
1642         #endif
1643         #if defined(SUPPORT_FILEFORMAT_MP3)
1644             case MUSIC_AUDIO_MP3:
1645             {
1646                 // NOTE: samplesCount, actually refers to framesCount and returns the number of frames processed
1647                 drmp3_read_pcm_frames_f32((drmp3 *)music.ctxData, samplesCount/music.stream.channels, (float *)pcm);
1648
1649             } break;
1650         #endif
1651         #if defined(SUPPORT_FILEFORMAT_XM)
1652             case MUSIC_MODULE_XM:
1653             {
1654                 switch (AUDIO_DEVICE_FORMAT)
1655                 {
1656                 case ma_format_f32:
1657                     // NOTE: Internally this function considers 2 channels generation, so samplesCount/2
1658                     jar_xm_generate_samples((jar_xm_context_t*)music.ctxData, (float*)pcm, samplesCount / 2);
1659                     break;
1660
1661                 case ma_format_s16:
1662                     // NOTE: Internally this function considers 2 channels generation, so samplesCount/2
1663                     jar_xm_generate_samples_16bit((jar_xm_context_t*)music.ctxData, (short*)pcm, samplesCount / 2);
1664                     break;
1665
1666                 case ma_format_u8:
1667                     // NOTE: Internally this function considers 2 channels generation, so samplesCount/2
1668                     jar_xm_generate_samples_8bit((jar_xm_context_t*)music.ctxData, (char*)pcm, samplesCount / 2);
1669                     break;
1670                 }
1671
1672             } break;
1673         #endif
1674         #if defined(SUPPORT_FILEFORMAT_MOD)
1675             case MUSIC_MODULE_MOD:
1676             {
1677                 // NOTE: 3rd parameter (nbsample) specify the number of stereo 16bits samples you want, so sampleCount/2
1678                 jar_mod_fillbuffer((jar_mod_context_t *)music.ctxData, (short *)pcm, samplesCount/2, 0);
1679             } break;
1680         #endif
1681             default: break;
1682         }
1683
1684         UpdateAudioStream(music.stream, pcm, samplesCount);
1685
1686         if ((music.ctxType == MUSIC_MODULE_XM) || music.ctxType == MUSIC_MODULE_MOD)
1687         {
1688             if (samplesCount > 1) sampleLeft -= samplesCount/2;
1689             else sampleLeft -= samplesCount;
1690         }
1691         else sampleLeft -= samplesCount;
1692
1693         if (sampleLeft <= 0)
1694         {
1695             streamEnding = true;
1696             break;
1697         }
1698     }
1699
1700     // Free allocated pcm data
1701     RL_FREE(pcm);
1702
1703     // Reset audio stream for looping
1704     if (streamEnding)
1705     {
1706         StopMusicStream(music);                     // Stop music (and reset)
1707         if (music.looping) PlayMusicStream(music);  // Play again
1708     }
1709     else
1710     {
1711         // NOTE: In case window is minimized, music stream is stopped,
1712         // just make sure to play again on window restore
1713         if (IsMusicPlaying(music)) PlayMusicStream(music);
1714     }
1715 }
1716
1717 // Check if any music is playing
1718 bool IsMusicPlaying(Music music)
1719 {
1720     return IsAudioStreamPlaying(music.stream);
1721 }
1722
1723 // Set volume for music
1724 void SetMusicVolume(Music music, float volume)
1725 {
1726     SetAudioStreamVolume(music.stream, volume);
1727 }
1728
1729 // Set pitch for music
1730 void SetMusicPitch(Music music, float pitch)
1731 {
1732     SetAudioBufferPitch(music.stream.buffer, pitch);
1733 }
1734
1735 // Get music time length (in seconds)
1736 float GetMusicTimeLength(Music music)
1737 {
1738     float totalSeconds = 0.0f;
1739
1740     totalSeconds = (float)music.sampleCount/(music.stream.sampleRate*music.stream.channels);
1741
1742     return totalSeconds;
1743 }
1744
1745 // Get current music time played (in seconds)
1746 float GetMusicTimePlayed(Music music)
1747 {
1748 #if defined(SUPPORT_FILEFORMAT_XM)
1749     if (music.ctxType == MUSIC_MODULE_XM)
1750     {
1751         uint64_t samples = 0;
1752         jar_xm_get_position(music.ctxData, NULL, NULL, NULL, &samples);
1753         samples = samples % (music.sampleCount);
1754
1755         return (float)(samples)/(music.stream.sampleRate*music.stream.channels);
1756     }
1757 #endif
1758     float secondsPlayed = 0.0f;
1759     if (music.stream.buffer != NULL)
1760     {
1761         //ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(music.stream.buffer->dsp.formatConverterIn.config.formatIn)*music.stream.buffer->dsp.formatConverterIn.config.channels;
1762         unsigned int samplesPlayed = music.stream.buffer->totalFramesProcessed*music.stream.channels;
1763         secondsPlayed = (float)samplesPlayed/(music.stream.sampleRate*music.stream.channels);
1764     }
1765
1766     return secondsPlayed;
1767 }
1768
1769 // Init audio stream (to stream audio pcm data)
1770 AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels)
1771 {
1772     AudioStream stream = { 0 };
1773
1774     stream.sampleRate = sampleRate;
1775     stream.sampleSize = sampleSize;
1776     stream.channels = channels;
1777
1778     ma_format formatIn = ((stream.sampleSize == 8)? ma_format_u8 : ((stream.sampleSize == 16)? ma_format_s16 : ma_format_f32));
1779
1780     // The size of a streaming buffer must be at least double the size of a period
1781     unsigned int periodSize = AUDIO.System.device.playback.internalPeriodSizeInFrames;
1782     unsigned int subBufferSize = GetAudioStreamBufferSizeDefault();
1783
1784     if (subBufferSize < periodSize) subBufferSize = periodSize;
1785
1786     // Create a double audio buffer of defined size
1787     stream.buffer = LoadAudioBuffer(formatIn, stream.channels, stream.sampleRate, subBufferSize*2, AUDIO_BUFFER_USAGE_STREAM);
1788
1789     if (stream.buffer != NULL)
1790     {
1791         stream.buffer->looping = true;    // Always loop for streaming buffers
1792         TRACELOG(LOG_INFO, "STREAM: Initialized successfully (%i Hz, %i bit, %s)", stream.sampleRate, stream.sampleSize, (stream.channels == 1)? "Mono" : "Stereo");
1793     }
1794     else TRACELOG(LOG_WARNING, "STREAM: Failed to load audio buffer, stream could not be created");
1795
1796     return stream;
1797 }
1798
1799 // Close audio stream and free memory
1800 void CloseAudioStream(AudioStream stream)
1801 {
1802     UnloadAudioBuffer(stream.buffer);
1803
1804     TRACELOG(LOG_INFO, "STREAM: Unloaded audio stream data from RAM");
1805 }
1806
1807 // Update audio stream buffers with data
1808 // NOTE 1: Only updates one buffer of the stream source: unqueue -> update -> queue
1809 // NOTE 2: To unqueue a buffer it needs to be processed: IsAudioStreamProcessed()
1810 void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount)
1811 {
1812     if (stream.buffer != NULL)
1813     {
1814         if (stream.buffer->isSubBufferProcessed[0] || stream.buffer->isSubBufferProcessed[1])
1815         {
1816             ma_uint32 subBufferToUpdate = 0;
1817
1818             if (stream.buffer->isSubBufferProcessed[0] && stream.buffer->isSubBufferProcessed[1])
1819             {
1820                 // Both buffers are available for updating.
1821                 // Update the first one and make sure the cursor is moved back to the front.
1822                 subBufferToUpdate = 0;
1823                 stream.buffer->frameCursorPos = 0;
1824             }
1825             else
1826             {
1827                 // Just update whichever sub-buffer is processed.
1828                 subBufferToUpdate = (stream.buffer->isSubBufferProcessed[0])? 0 : 1;
1829             }
1830
1831             ma_uint32 subBufferSizeInFrames = stream.buffer->sizeInFrames/2;
1832             unsigned char *subBuffer = stream.buffer->data + ((subBufferSizeInFrames*stream.channels*(stream.sampleSize/8))*subBufferToUpdate);
1833
1834             // TODO: Get total frames processed on this buffer... DOES NOT WORK.
1835             stream.buffer->totalFramesProcessed += subBufferSizeInFrames;
1836
1837             // Does this API expect a whole buffer to be updated in one go?
1838             // Assuming so, but if not will need to change this logic.
1839             if (subBufferSizeInFrames >= (ma_uint32)samplesCount/stream.channels)
1840             {
1841                 ma_uint32 framesToWrite = subBufferSizeInFrames;
1842
1843                 if (framesToWrite > ((ma_uint32)samplesCount/stream.channels)) framesToWrite = (ma_uint32)samplesCount/stream.channels;
1844
1845                 ma_uint32 bytesToWrite = framesToWrite*stream.channels*(stream.sampleSize/8);
1846                 memcpy(subBuffer, data, bytesToWrite);
1847
1848                 // Any leftover frames should be filled with zeros.
1849                 ma_uint32 leftoverFrameCount = subBufferSizeInFrames - framesToWrite;
1850
1851                 if (leftoverFrameCount > 0) memset(subBuffer + bytesToWrite, 0, leftoverFrameCount*stream.channels*(stream.sampleSize/8));
1852
1853                 stream.buffer->isSubBufferProcessed[subBufferToUpdate] = false;
1854             }
1855             else TRACELOG(LOG_WARNING, "STREAM: Attempting to write too many frames to buffer");
1856         }
1857         else TRACELOG(LOG_WARNING, "STREAM: Buffer not available for updating");
1858     }
1859 }
1860
1861 // Check if any audio stream buffers requires refill
1862 bool IsAudioStreamProcessed(AudioStream stream)
1863 {
1864     if (stream.buffer == NULL) return false;
1865
1866     return (stream.buffer->isSubBufferProcessed[0] || stream.buffer->isSubBufferProcessed[1]);
1867 }
1868
1869 // Play audio stream
1870 void PlayAudioStream(AudioStream stream)
1871 {
1872     PlayAudioBuffer(stream.buffer);
1873 }
1874
1875 // Play audio stream
1876 void PauseAudioStream(AudioStream stream)
1877 {
1878     PauseAudioBuffer(stream.buffer);
1879 }
1880
1881 // Resume audio stream playing
1882 void ResumeAudioStream(AudioStream stream)
1883 {
1884     ResumeAudioBuffer(stream.buffer);
1885 }
1886
1887 // Check if audio stream is playing.
1888 bool IsAudioStreamPlaying(AudioStream stream)
1889 {
1890     return IsAudioBufferPlaying(stream.buffer);
1891 }
1892
1893 // Stop audio stream
1894 void StopAudioStream(AudioStream stream)
1895 {
1896     StopAudioBuffer(stream.buffer);
1897 }
1898
1899 // Set volume for audio stream (1.0 is max level)
1900 void SetAudioStreamVolume(AudioStream stream, float volume)
1901 {
1902     SetAudioBufferVolume(stream.buffer, volume);
1903 }
1904
1905 // Set pitch for audio stream (1.0 is base level)
1906 void SetAudioStreamPitch(AudioStream stream, float pitch)
1907 {
1908     SetAudioBufferPitch(stream.buffer, pitch);
1909 }
1910
1911 // Default size for new audio streams
1912 void SetAudioStreamBufferSizeDefault(int size)
1913 {
1914     AUDIO.Buffer.defaultSize = size;
1915 }
1916
1917 int GetAudioStreamBufferSizeDefault()
1918 {
1919     // if the buffer is not set, compute one that would give us a buffer good enough for a decent frame rate
1920     if (AUDIO.Buffer.defaultSize == 0)
1921         AUDIO.Buffer.defaultSize = AUDIO.System.device.sampleRate/30;
1922
1923     return AUDIO.Buffer.defaultSize;
1924 }
1925
1926 //----------------------------------------------------------------------------------
1927 // Module specific Functions Definition
1928 //----------------------------------------------------------------------------------
1929
1930 // Log callback function
1931 static void OnLog(ma_context *pContext, ma_device *pDevice, ma_uint32 logLevel, const char *message)
1932 {
1933     (void)pContext;
1934     (void)pDevice;
1935
1936     TRACELOG(LOG_WARNING, "miniaudio: %s", message);   // All log messages from miniaudio are errors
1937 }
1938
1939 // Reads audio data from an AudioBuffer object in internal format.
1940 static ma_uint32 ReadAudioBufferFramesInInternalFormat(AudioBuffer *audioBuffer, void *framesOut, ma_uint32 frameCount)
1941 {
1942     ma_uint32 subBufferSizeInFrames = (audioBuffer->sizeInFrames > 1)? audioBuffer->sizeInFrames/2 : audioBuffer->sizeInFrames;
1943     ma_uint32 currentSubBufferIndex = audioBuffer->frameCursorPos/subBufferSizeInFrames;
1944
1945     if (currentSubBufferIndex > 1) return 0;
1946
1947     // Another thread can update the processed state of buffers so
1948     // we just take a copy here to try and avoid potential synchronization problems
1949     bool isSubBufferProcessed[2];
1950     isSubBufferProcessed[0] = audioBuffer->isSubBufferProcessed[0];
1951     isSubBufferProcessed[1] = audioBuffer->isSubBufferProcessed[1];
1952
1953     ma_uint32 frameSizeInBytes = ma_get_bytes_per_frame(audioBuffer->converter.config.formatIn, audioBuffer->converter.config.channelsIn);
1954
1955     // Fill out every frame until we find a buffer that's marked as processed. Then fill the remainder with 0
1956     ma_uint32 framesRead = 0;
1957     while (1)
1958     {
1959         // We break from this loop differently depending on the buffer's usage
1960         //  - For static buffers, we simply fill as much data as we can
1961         //  - For streaming buffers we only fill the halves of the buffer that are processed
1962         //    Unprocessed halves must keep their audio data in-tact
1963         if (audioBuffer->usage == AUDIO_BUFFER_USAGE_STATIC)
1964         {
1965             if (framesRead >= frameCount) break;
1966         }
1967         else
1968         {
1969             if (isSubBufferProcessed[currentSubBufferIndex]) break;
1970         }
1971
1972         ma_uint32 totalFramesRemaining = (frameCount - framesRead);
1973         if (totalFramesRemaining == 0) break;
1974
1975         ma_uint32 framesRemainingInOutputBuffer;
1976         if (audioBuffer->usage == AUDIO_BUFFER_USAGE_STATIC)
1977         {
1978             framesRemainingInOutputBuffer = audioBuffer->sizeInFrames - audioBuffer->frameCursorPos;
1979         }
1980         else
1981         {
1982             ma_uint32 firstFrameIndexOfThisSubBuffer = subBufferSizeInFrames*currentSubBufferIndex;
1983             framesRemainingInOutputBuffer = subBufferSizeInFrames - (audioBuffer->frameCursorPos - firstFrameIndexOfThisSubBuffer);
1984         }
1985
1986         ma_uint32 framesToRead = totalFramesRemaining;
1987         if (framesToRead > framesRemainingInOutputBuffer) framesToRead = framesRemainingInOutputBuffer;
1988
1989         memcpy((unsigned char *)framesOut + (framesRead*frameSizeInBytes), audioBuffer->data + (audioBuffer->frameCursorPos*frameSizeInBytes), framesToRead*frameSizeInBytes);
1990         audioBuffer->frameCursorPos = (audioBuffer->frameCursorPos + framesToRead)%audioBuffer->sizeInFrames;
1991         framesRead += framesToRead;
1992
1993         // If we've read to the end of the buffer, mark it as processed
1994         if (framesToRead == framesRemainingInOutputBuffer)
1995         {
1996             audioBuffer->isSubBufferProcessed[currentSubBufferIndex] = true;
1997             isSubBufferProcessed[currentSubBufferIndex] = true;
1998
1999             currentSubBufferIndex = (currentSubBufferIndex + 1)%2;
2000
2001             // We need to break from this loop if we're not looping
2002             if (!audioBuffer->looping)
2003             {
2004                 StopAudioBuffer(audioBuffer);
2005                 break;
2006             }
2007         }
2008     }
2009
2010     // Zero-fill excess
2011     ma_uint32 totalFramesRemaining = (frameCount - framesRead);
2012     if (totalFramesRemaining > 0)
2013     {
2014         memset((unsigned char *)framesOut + (framesRead*frameSizeInBytes), 0, totalFramesRemaining*frameSizeInBytes);
2015
2016         // For static buffers we can fill the remaining frames with silence for safety, but we don't want
2017         // to report those frames as "read". The reason for this is that the caller uses the return value
2018         // to know whether or not a non-looping sound has finished playback.
2019         if (audioBuffer->usage != AUDIO_BUFFER_USAGE_STATIC) framesRead += totalFramesRemaining;
2020     }
2021
2022     return framesRead;
2023 }
2024
2025 // Reads audio data from an AudioBuffer object in device format. Returned data will be in a format appropriate for mixing.
2026 static ma_uint32 ReadAudioBufferFramesInMixingFormat(AudioBuffer *audioBuffer, float *framesOut, ma_uint32 frameCount)
2027 {
2028     // What's going on here is that we're continuously converting data from the AudioBuffer's internal format to the mixing format, which
2029     // should be defined by the output format of the data converter. We do this until frameCount frames have been output. The important
2030     // detail to remember here is that we never, ever attempt to read more input data than is required for the specified number of output
2031     // frames. This can be achieved with ma_data_converter_get_required_input_frame_count().
2032     ma_uint8 inputBuffer[4096];
2033     ma_uint32 inputBufferFrameCap = sizeof(inputBuffer)/ma_get_bytes_per_frame(audioBuffer->converter.config.formatIn, audioBuffer->converter.config.channelsIn);
2034
2035     ma_uint32 totalOutputFramesProcessed = 0;
2036     while (totalOutputFramesProcessed < frameCount)
2037     {
2038         ma_uint64 outputFramesToProcessThisIteration = frameCount - totalOutputFramesProcessed;
2039
2040         ma_uint64 inputFramesToProcessThisIteration = ma_data_converter_get_required_input_frame_count(&audioBuffer->converter, outputFramesToProcessThisIteration);
2041         if (inputFramesToProcessThisIteration > inputBufferFrameCap)
2042         {
2043             inputFramesToProcessThisIteration = inputBufferFrameCap;
2044         }
2045
2046         float *runningFramesOut = framesOut + (totalOutputFramesProcessed*audioBuffer->converter.config.channelsOut);
2047
2048         /* At this point we can convert the data to our mixing format. */
2049         ma_uint64 inputFramesProcessedThisIteration = ReadAudioBufferFramesInInternalFormat(audioBuffer, inputBuffer, (ma_uint32)inputFramesToProcessThisIteration);    /* Safe cast. */
2050         ma_uint64 outputFramesProcessedThisIteration = outputFramesToProcessThisIteration;
2051         ma_data_converter_process_pcm_frames(&audioBuffer->converter, inputBuffer, &inputFramesProcessedThisIteration, runningFramesOut, &outputFramesProcessedThisIteration);
2052
2053         totalOutputFramesProcessed += (ma_uint32)outputFramesProcessedThisIteration; /* Safe cast. */
2054
2055         if (inputFramesProcessedThisIteration < inputFramesToProcessThisIteration)
2056         {
2057             break;  /* Ran out of input data. */
2058         }
2059
2060         /* This should never be hit, but will add it here for safety. Ensures we get out of the loop when no input nor output frames are processed. */
2061         if (inputFramesProcessedThisIteration == 0 && outputFramesProcessedThisIteration == 0)
2062         {
2063             break;
2064         }
2065     }
2066
2067     return totalOutputFramesProcessed;
2068 }
2069
2070
2071 // Sending audio data to device callback function
2072 // NOTE: All the mixing takes place here
2073 static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const void *pFramesInput, ma_uint32 frameCount)
2074 {
2075     (void)pDevice;
2076
2077     // Mixing is basically just an accumulation, we need to initialize the output buffer to 0
2078     memset(pFramesOut, 0, frameCount*pDevice->playback.channels*ma_get_bytes_per_sample(pDevice->playback.format));
2079
2080     // Using a mutex here for thread-safety which makes things not real-time
2081     // This is unlikely to be necessary for this project, but may want to consider how you might want to avoid this
2082     ma_mutex_lock(&AUDIO.System.lock);
2083     {
2084         for (AudioBuffer *audioBuffer = AUDIO.Buffer.first; audioBuffer != NULL; audioBuffer = audioBuffer->next)
2085         {
2086             // Ignore stopped or paused sounds
2087             if (!audioBuffer->playing || audioBuffer->paused) continue;
2088
2089             ma_uint32 framesRead = 0;
2090
2091             while (1)
2092             {
2093                 if (framesRead >= frameCount) break;
2094
2095                 // Just read as much data as we can from the stream
2096                 ma_uint32 framesToRead = (frameCount - framesRead);
2097
2098                 while (framesToRead > 0)
2099                 {
2100                     float tempBuffer[1024]; // 512 frames for stereo
2101
2102                     ma_uint32 framesToReadRightNow = framesToRead;
2103                     if (framesToReadRightNow > sizeof(tempBuffer)/sizeof(tempBuffer[0])/AUDIO_DEVICE_CHANNELS)
2104                     {
2105                         framesToReadRightNow = sizeof(tempBuffer)/sizeof(tempBuffer[0])/AUDIO_DEVICE_CHANNELS;
2106                     }
2107
2108                     ma_uint32 framesJustRead = ReadAudioBufferFramesInMixingFormat(audioBuffer, tempBuffer, framesToReadRightNow);
2109                     if (framesJustRead > 0)
2110                     {
2111                         float *framesOut = (float *)pFramesOut + (framesRead*AUDIO.System.device.playback.channels);
2112                         float *framesIn  = tempBuffer;
2113
2114                         MixAudioFrames(framesOut, framesIn, framesJustRead, audioBuffer->volume);
2115
2116                         framesToRead -= framesJustRead;
2117                         framesRead += framesJustRead;
2118                     }
2119
2120                     if (!audioBuffer->playing)
2121                     {
2122                         framesRead = frameCount;
2123                         break;
2124                     }
2125
2126                     // If we weren't able to read all the frames we requested, break
2127                     if (framesJustRead < framesToReadRightNow)
2128                     {
2129                         if (!audioBuffer->looping)
2130                         {
2131                             StopAudioBuffer(audioBuffer);
2132                             break;
2133                         }
2134                         else
2135                         {
2136                             // Should never get here, but just for safety,
2137                             // move the cursor position back to the start and continue the loop
2138                             audioBuffer->frameCursorPos = 0;
2139                             continue;
2140                         }
2141                     }
2142                 }
2143
2144                 // If for some reason we weren't able to read every frame we'll need to break from the loop
2145                 // Not doing this could theoretically put us into an infinite loop
2146                 if (framesToRead > 0) break;
2147             }
2148         }
2149     }
2150
2151     ma_mutex_unlock(&AUDIO.System.lock);
2152 }
2153
2154 // This is the main mixing function. Mixing is pretty simple in this project - it's just an accumulation.
2155 // NOTE: framesOut is both an input and an output. It will be initially filled with zeros outside of this function.
2156 static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 frameCount, float localVolume)
2157 {
2158     for (ma_uint32 iFrame = 0; iFrame < frameCount; ++iFrame)
2159     {
2160         for (ma_uint32 iChannel = 0; iChannel < AUDIO.System.device.playback.channels; ++iChannel)
2161         {
2162             float *frameOut = framesOut + (iFrame*AUDIO.System.device.playback.channels);
2163             const float *frameIn  = framesIn  + (iFrame*AUDIO.System.device.playback.channels);
2164
2165             frameOut[iChannel] += (frameIn[iChannel]*localVolume);
2166         }
2167     }
2168 }
2169
2170 #if defined(SUPPORT_FILEFORMAT_WAV)
2171 // Load WAV file data into Wave structure
2172 // NOTE: Using dr_wav library
2173 static Wave LoadWAV(const unsigned char *fileData, unsigned int fileSize)
2174 {
2175     Wave wave = { 0 };
2176     drwav wav = { 0 };
2177
2178     bool success = drwav_init_memory(&wav, fileData, fileSize, NULL);
2179
2180     if (success)
2181     {
2182         wave.sampleCount = (unsigned int)wav.totalPCMFrameCount*wav.channels;
2183         wave.sampleRate = wav.sampleRate;
2184         wave.sampleSize = 16;   // NOTE: We are forcing conversion to 16bit
2185         wave.channels = wav.channels;
2186         wave.data = (short *)RL_MALLOC(wave.sampleCount*sizeof(short));
2187         drwav_read_pcm_frames_s16(&wav, wav.totalPCMFrameCount, wave.data);
2188     }
2189     else TRACELOG(LOG_WARNING, "WAVE: Failed to load WAV data");
2190
2191     drwav_uninit(&wav);
2192
2193     return wave;
2194 }
2195
2196 // Save wave data as WAV file
2197 // NOTE: Using dr_wav library
2198 static int SaveWAV(Wave wave, const char *fileName)
2199 {
2200     int success = false;
2201
2202     drwav wav = { 0 };
2203     drwav_data_format format = { 0 };
2204     format.container = drwav_container_riff;
2205     format.format = DR_WAVE_FORMAT_PCM;
2206     format.channels = wave.channels;
2207     format.sampleRate = wave.sampleRate;
2208     format.bitsPerSample = wave.sampleSize;
2209
2210     void *fileData = NULL;
2211     size_t fileDataSize = 0;
2212     success = drwav_init_memory_write(&wav, &fileData, &fileDataSize, &format, NULL);
2213     if (success) success = (int)drwav_write_pcm_frames(&wav, wave.sampleCount/wave.channels, wave.data);
2214     drwav_result result = drwav_uninit(&wav);
2215
2216     if (result == DRWAV_SUCCESS) success = SaveFileData(fileName, (unsigned char *)fileData, (unsigned int)fileDataSize);
2217
2218     drwav_free(fileData, NULL);
2219
2220     return success;
2221 }
2222 #endif
2223
2224 #if defined(SUPPORT_FILEFORMAT_OGG)
2225 // Load OGG file data into Wave structure
2226 // NOTE: Using stb_vorbis library
2227 static Wave LoadOGG(const unsigned char *fileData, unsigned int fileSize)
2228 {
2229     Wave wave = { 0 };
2230
2231     stb_vorbis *oggData = stb_vorbis_open_memory((unsigned char *)fileData, fileSize, NULL, NULL);
2232
2233     if (oggData != NULL)
2234     {
2235         stb_vorbis_info info = stb_vorbis_get_info(oggData);
2236
2237         wave.sampleRate = info.sample_rate;
2238         wave.sampleSize = 16;                   // 16 bit per sample (short)
2239         wave.channels = info.channels;
2240         wave.sampleCount = (unsigned int)stb_vorbis_stream_length_in_samples(oggData)*info.channels;  // Independent by channel
2241
2242         float totalSeconds = stb_vorbis_stream_length_in_seconds(oggData);
2243         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);
2244
2245         wave.data = (short *)RL_MALLOC(wave.sampleCount*sizeof(short));
2246
2247         // NOTE: Returns the number of samples to process (be careful! we ask for number of shorts!)
2248         stb_vorbis_get_samples_short_interleaved(oggData, info.channels, (short *)wave.data, wave.sampleCount);
2249         TRACELOG(LOG_INFO, "WAVE: OGG data loaded successfully (%i Hz, %i bit, %s)", wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
2250
2251         stb_vorbis_close(oggData);
2252     }
2253     else TRACELOG(LOG_WARNING, "WAVE: Failed to load OGG data");
2254
2255     return wave;
2256 }
2257 #endif
2258
2259 #if defined(SUPPORT_FILEFORMAT_FLAC)
2260 // Load FLAC file data into Wave structure
2261 // NOTE: Using dr_flac library
2262 static Wave LoadFLAC(const unsigned char *fileData, unsigned int fileSize)
2263 {
2264     Wave wave = { 0 };
2265
2266     // Decode the entire FLAC file in one go
2267     unsigned long long int totalFrameCount = 0;
2268     wave.data = drflac_open_memory_and_read_pcm_frames_s16(fileData, fileSize, &wave.channels, &wave.sampleRate, &totalFrameCount, NULL);
2269
2270     if (wave.data != NULL)
2271     {
2272         wave.sampleCount = (unsigned int)totalFrameCount*wave.channels;
2273         wave.sampleSize = 16;
2274
2275         TRACELOG(LOG_INFO, "WAVE: FLAC data loaded successfully (%i Hz, %i bit, %s)", wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
2276     }
2277     else TRACELOG(LOG_WARNING, "WAVE: Failed to load FLAC data");
2278
2279     return wave;
2280 }
2281 #endif
2282
2283 #if defined(SUPPORT_FILEFORMAT_MP3)
2284 // Load MP3 file data into Wave structure
2285 // NOTE: Using dr_mp3 library
2286 static Wave LoadMP3(const unsigned char *fileData, unsigned int fileSize)
2287 {
2288     Wave wave = { 0 };
2289     drmp3_config config = { 0 };
2290
2291     // Decode the entire MP3 file in one go
2292     unsigned long long int totalFrameCount = 0;
2293     wave.data = drmp3_open_memory_and_read_pcm_frames_f32(fileData, fileSize, &config, &totalFrameCount, NULL);
2294
2295     if (wave.data != NULL)
2296     {
2297         wave.channels = config.channels;
2298         wave.sampleRate = config.sampleRate;
2299         wave.sampleCount = (int)totalFrameCount*wave.channels;
2300         wave.sampleSize = 32;
2301
2302         // NOTE: Only support up to 2 channels (mono, stereo)
2303         // TODO: Really?
2304         if (wave.channels > 2) TRACELOG(LOG_WARNING, "WAVE: MP3 channels number (%i) not supported", wave.channels);
2305
2306         TRACELOG(LOG_INFO, "WAVE: MP3 file loaded successfully (%i Hz, %i bit, %s)", wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo");
2307     }
2308     else TRACELOG(LOG_WARNING, "WAVE: Failed to load MP3 data");
2309
2310     return wave;
2311 }
2312 #endif
2313
2314 // Some required functions for audio standalone module version
2315 #if defined(RAUDIO_STANDALONE)
2316 // Check file extension
2317 static bool IsFileExtension(const char *fileName, const char *ext)
2318 {
2319     bool result = false;
2320     const char *fileExt;
2321
2322     if ((fileExt = strrchr(fileName, '.')) != NULL)
2323     {
2324         if (strcmp(fileExt, ext) == 0) result = true;
2325     }
2326
2327     return result;
2328 }
2329
2330 // Load data from file into a buffer
2331 static unsigned char *LoadFileData(const char *fileName, unsigned int *bytesRead)
2332 {
2333     unsigned char *data = NULL;
2334     *bytesRead = 0;
2335
2336     if (fileName != NULL)
2337     {
2338         FILE *file = fopen(fileName, "rb");
2339
2340         if (file != NULL)
2341         {
2342             // WARNING: On binary streams SEEK_END could not be found,
2343             // using fseek() and ftell() could not work in some (rare) cases
2344             fseek(file, 0, SEEK_END);
2345             int size = ftell(file);
2346             fseek(file, 0, SEEK_SET);
2347
2348             if (size > 0)
2349             {
2350                 data = (unsigned char *)RL_MALLOC(size*sizeof(unsigned char));
2351
2352                 // NOTE: fread() returns number of read elements instead of bytes, so we read [1 byte, size elements]
2353                 unsigned int count = (unsigned int)fread(data, sizeof(unsigned char), size, file);
2354                 *bytesRead = count;
2355
2356                 if (count != size) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially loaded", fileName);
2357                 else TRACELOG(LOG_INFO, "FILEIO: [%s] File loaded successfully", fileName);
2358             }
2359             else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to read file", fileName);
2360
2361             fclose(file);
2362         }
2363         else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName);
2364     }
2365     else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
2366
2367     return data;
2368 }
2369
2370 // Save data to file from buffer
2371 static bool SaveFileData(const char *fileName, void *data, unsigned int bytesToWrite)
2372 {
2373     if (fileName != NULL)
2374     {
2375         FILE *file = fopen(fileName, "wb");
2376
2377         if (file != NULL)
2378         {
2379             unsigned int count = (unsigned int)fwrite(data, sizeof(unsigned char), bytesToWrite, file);
2380
2381             if (count == 0) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to write file", fileName);
2382             else if (count != bytesToWrite) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially written", fileName);
2383             else TRACELOG(LOG_INFO, "FILEIO: [%s] File saved successfully", fileName);
2384
2385             fclose(file);
2386         }
2387         else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName);
2388     }
2389     else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
2390 }
2391
2392 // Save text data to file (write), string must be '\0' terminated
2393 static bool SaveFileText(const char *fileName, char *text)
2394 {
2395     if (fileName != NULL)
2396     {
2397         FILE *file = fopen(fileName, "wt");
2398
2399         if (file != NULL)
2400         {
2401             int count = fprintf(file, "%s", text);
2402
2403             if (count == 0) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to write text file", fileName);
2404             else TRACELOG(LOG_INFO, "FILEIO: [%s] Text file saved successfully", fileName);
2405
2406             fclose(file);
2407         }
2408         else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open text file", fileName);
2409     }
2410     else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
2411 }
2412 #endif
2413
2414 #undef AudioBuffer