master
ブランチ master
Tetris / deps / raylib / src / raudio.c
111.2 KB、2956行 生 Blame 履歴
1/**********************************************************************************************
2*
3* raudio v1.1 - 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* #define SUPPORT_MODULE_RAUDIO 1
15* raudio module is included in the build
16*
17* #define RAUDIO_STANDALONE
18* Define to use the module as standalone library (independently of raylib)
19* Required types and functions are defined in the same module
20*
21* #define SUPPORT_FILEFORMAT_WAV 1
22* #define SUPPORT_FILEFORMAT_OGG 1
23* #define SUPPORT_FILEFORMAT_MP3 1
24* #define SUPPORT_FILEFORMAT_QOA 1
25* #define SUPPORT_FILEFORMAT_FLAC 0
26* #define SUPPORT_FILEFORMAT_XM 1
27* #define SUPPORT_FILEFORMAT_MOD 1
28* Selected desired fileformats to be supported for loading. Some of those formats are
29* supported by default, to remove support, #define as 0 in this module or your build system
30*
31* DEPENDENCIES:
32* miniaudio.h - Audio device management lib (https://github.com/mackron/miniaudio)
33* stb_vorbis.h - Ogg audio files loading (http://www.nothings.org/stb_vorbis/)
34* dr_wav.h - WAV audio files loading (http://github.com/mackron/dr_libs)
35* dr_mp3.h - MP3 audio file loading (https://github.com/mackron/dr_libs)
36* dr_flac.h - FLAC audio file loading (https://github.com/mackron/dr_libs)
37* jar_xm.h - XM module file loading
38* jar_mod.h - MOD audio file loading
39*
40* CONTRIBUTORS:
41* David Reid (github: @mackron) (Nov. 2017):
42* - Complete port to miniaudio library
43*
44* Joshua Reisenauer (github: @kd7tck) (2015):
45* - XM audio module support (jar_xm)
46* - MOD audio module support (jar_mod)
47* - Mixing channels support
48* - Raw audio context support
49*
50*
51* LICENSE: zlib/libpng
52*
53* Copyright (c) 2013-2026 Ramon Santamaria (@raysan5)
54*
55* This software is provided "as-is", without any express or implied warranty. In no event
56* will the authors be held liable for any damages arising from the use of this software.
57*
58* Permission is granted to anyone to use this software for any purpose, including commercial
59* applications, and to alter it and redistribute it freely, subject to the following restrictions:
60*
61* 1. The origin of this software must not be misrepresented; you must not claim that you
62* wrote the original software. If you use this software in a product, an acknowledgment
63* in the product documentation would be appreciated but is not required.
64*
65* 2. Altered source versions must be plainly marked as such, and must not be misrepresented
66* as being the original software.
67*
68* 3. This notice may not be removed or altered from any source distribution.
69*
70**********************************************************************************************/
71
72#if defined(RAUDIO_STANDALONE)
73 #include "raudio.h"
74#else
75 #include "raylib.h" // Declares module functions
76
77 #include "config.h" // Defines module configuration flags
78#endif
79
80#if SUPPORT_MODULE_RAUDIO || defined(RAUDIO_STANDALONE)
81
82#if defined(_WIN32)
83// To avoid conflicting windows.h symbols with raylib, some flags are defined
84// WARNING: Those flags avoid inclusion of some Win32 headers that could be required
85// by user at some point and won't be included...
86//-------------------------------------------------------------------------------------
87
88// If defined, the following flags inhibit definition of the indicated items
89#define NOGDICAPMASKS // CC_*, LC_*, PC_*, CP_*, TC_*, RC_
90#define NOVIRTUALKEYCODES // VK_*
91#define NOWINMESSAGES // WM_*, EM_*, LB_*, CB_*
92#define NOWINSTYLES // WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_*
93#define NOSYSMETRICS // SM_*
94#define NOMENUS // MF_*
95#define NOICONS // IDI_*
96#define NOKEYSTATES // MK_*
97#define NOSYSCOMMANDS // SC_*
98#define NORASTEROPS // Binary and Tertiary raster ops
99#define NOSHOWWINDOW // SW_*
100#define OEMRESOURCE // OEM Resource values
101#define NOATOM // Atom Manager routines
102#define NOCLIPBOARD // Clipboard routines
103#define NOCOLOR // Screen colors
104#define NOCTLMGR // Control and Dialog routines
105#define NODRAWTEXT // DrawText() and DT_*
106#define NOGDI // All GDI defines and routines
107#define NOKERNEL // All KERNEL defines and routines
108#define NOUSER // All USER defines and routines
109//#define NONLS // All NLS defines and routines
110#define NOMB // MB_* and MessageBox()
111#define NOMEMMGR // GMEM_*, LMEM_*, GHND, LHND, associated routines
112#define NOMETAFILE // typedef METAFILEPICT
113#define NOMINMAX // Macros min(a,b) and max(a,b)
114#define NOMSG // typedef MSG and associated routines
115#define NOOPENFILE // OpenFile(), OemToAnsi, AnsiToOem, and OF_*
116#define NOSCROLL // SB_* and scrolling routines
117#define NOSERVICE // All Service Controller routines, SERVICE_ equates, etc.
118#define NOSOUND // Sound driver routines
119#define NOTEXTMETRIC // typedef TEXTMETRIC and associated routines
120#define NOWH // SetWindowsHook and WH_*
121#define NOWINOFFSETS // GWL_*, GCL_*, associated routines
122#define NOCOMM // COMM driver routines
123#define NOKANJI // Kanji support stuff
124#define NOHELP // Help engine interface
125#define NOPROFILER // Profiler interface
126#define NODEFERWINDOWPOS // DeferWindowPos routines
127#define NOMCX // Modem Configuration Extensions
128
129// Type required before windows.h inclusion
130typedef struct tagMSG *LPMSG;
131
132#include <windows.h> // Windows functionality (miniaudio)
133
134// Type required by some unused function...
135typedef struct tagBITMAPINFOHEADER {
136 DWORD biSize;
137 LONG biWidth;
138 LONG biHeight;
139 WORD biPlanes;
140 WORD biBitCount;
141 DWORD biCompression;
142 DWORD biSizeImage;
143 LONG biXPelsPerMeter;
144 LONG biYPelsPerMeter;
145 DWORD biClrUsed;
146 DWORD biClrImportant;
147} BITMAPINFOHEADER, *PBITMAPINFOHEADER;
148
149#include <objbase.h> // Component Object Model (COM) header
150#include <mmreg.h> // Windows Multimedia, defines some WAVE structs
151#include <mmsystem.h> // Windows Multimedia, used by Windows GDI, defines DIBINDEX macro
152
153// Some required types defined for MSVC/TinyC compiler
154#if defined(_MSC_VER) || defined(__TINYC__)
155 #include "propidl.h"
156#endif
157#endif
158
159#define MA_MALLOC RL_MALLOC
160#define MA_FREE RL_FREE
161
162#define MA_NO_JACK
163#define MA_NO_WAV
164#define MA_NO_FLAC
165#define MA_NO_MP3
166#define MA_NO_RESOURCE_MANAGER
167#define MA_NO_NODE_GRAPH
168#define MA_NO_ENGINE
169#define MA_NO_GENERATION
170
171// Threading model: Default: [0] COINIT_MULTITHREADED: COM calls objects on any thread (free threading)
172#define MA_COINIT_VALUE 2 // [2] COINIT_APARTMENTTHREADED: Each object has its own thread (apartment model)
173
174#define MINIAUDIO_IMPLEMENTATION
175//#define MA_DEBUG_OUTPUT
176#include "external/miniaudio.h" // Audio device initialization and management
177#undef PlaySound // Win32 API: windows.h > mmsystem.h defines PlaySound macro
178
179#include <stdlib.h> // Required for: malloc(), free()
180#include <stdio.h> // Required for: FILE, fopen(), fclose(), fread()
181#include <string.h> // Required for: strcmp() [Used in IsFileExtension(), LoadWaveFromMemory(), LoadMusicStreamFromMemory()]
182
183#if defined(RAUDIO_STANDALONE)
184 #ifndef TRACELOG
185 #define TRACELOG(level, ...) printf(__VA_ARGS__)
186 #endif
187
188 // Allow custom memory allocators
189 #ifndef RL_MALLOC
190 #define RL_MALLOC(sz) malloc(sz)
191 #endif
192 #ifndef RL_CALLOC
193 #define RL_CALLOC(n,sz) calloc(n,sz)
194 #endif
195 #ifndef RL_REALLOC
196 #define RL_REALLOC(ptr,sz) realloc(ptr,sz)
197 #endif
198 #ifndef RL_FREE
199 #define RL_FREE(ptr) free(ptr)
200 #endif
201#endif
202
203#if SUPPORT_FILEFORMAT_WAV
204 #define DRWAV_MALLOC RL_MALLOC
205 #define DRWAV_REALLOC RL_REALLOC
206 #define DRWAV_FREE RL_FREE
207
208 #define DR_WAV_IMPLEMENTATION
209 #include "external/dr_wav.h" // WAV loading functions
210#endif
211
212#if SUPPORT_FILEFORMAT_OGG
213 // TODO: Remap stb_vorbis malloc()/free() calls to RL_MALLOC/RL_FREE
214 #include "external/stb_vorbis.c" // OGG loading functions
215#endif
216
217#if SUPPORT_FILEFORMAT_MP3
218 #define DRMP3_MALLOC RL_MALLOC
219 #define DRMP3_REALLOC RL_REALLOC
220 #define DRMP3_FREE RL_FREE
221
222 #define DR_MP3_IMPLEMENTATION
223 #include "external/dr_mp3.h" // MP3 loading functions
224#endif
225
226#if SUPPORT_FILEFORMAT_QOA
227 #define QOA_MALLOC RL_MALLOC
228 #define QOA_FREE RL_FREE
229
230 #if defined(_MSC_VER) // Disable some MSVC warning
231 #pragma warning(push)
232 #pragma warning(disable : 4018)
233 #pragma warning(disable : 4267)
234 #pragma warning(disable : 4244)
235 #endif
236
237 #define QOA_IMPLEMENTATION
238 #include "external/qoa.h" // QOA loading and saving functions
239 #include "external/qoaplay.c" // QOA stream playing helper functions
240
241 #if defined(_MSC_VER)
242 #pragma warning(pop) // Disable MSVC warning suppression
243 #endif
244#endif
245
246#if SUPPORT_FILEFORMAT_FLAC
247 #define DRFLAC_MALLOC RL_MALLOC
248 #define DRFLAC_REALLOC RL_REALLOC
249 #define DRFLAC_FREE RL_FREE
250
251 #define DR_FLAC_IMPLEMENTATION
252 #define DR_FLAC_NO_WIN32_IO
253 #include "external/dr_flac.h" // FLAC loading functions
254#endif
255
256#if SUPPORT_FILEFORMAT_XM
257 #define JARXM_MALLOC RL_MALLOC
258 #define JARXM_FREE RL_FREE
259
260 #if defined(_MSC_VER) // Disable some MSVC warning
261 #pragma warning(push)
262 #pragma warning(disable : 4244)
263 #endif
264
265 #define JAR_XM_IMPLEMENTATION
266 #include "external/jar_xm.h" // XM loading functions
267
268 #if defined(_MSC_VER)
269 #pragma warning(pop) // Disable MSVC warning suppression
270 #endif
271#endif
272
273#if SUPPORT_FILEFORMAT_MOD
274 #define JARMOD_MALLOC RL_MALLOC
275 #define JARMOD_FREE RL_FREE
276
277 #define JAR_MOD_IMPLEMENTATION
278 #include "external/jar_mod.h" // MOD loading functions
279#endif
280
281//----------------------------------------------------------------------------------
282// Defines and Macros
283//----------------------------------------------------------------------------------
284#ifndef AUDIO_DEVICE_FORMAT
285 #define AUDIO_DEVICE_FORMAT ma_format_f32 // Device output format (float-32bit)
286#endif
287#ifndef AUDIO_DEVICE_CHANNELS
288 #define AUDIO_DEVICE_CHANNELS 2 // Device output channels: stereo
289#endif
290#ifndef AUDIO_DEVICE_SAMPLE_RATE
291 #define AUDIO_DEVICE_SAMPLE_RATE 0 // Device output sample rate
292#endif
293#ifndef AUDIO_DEVICE_PERIOD_SIZE_IN_FRAMES
294 #define AUDIO_DEVICE_PERIOD_SIZE_IN_FRAMES 0 // Device latency. 0 defaults to 10ms
295#endif
296
297#ifndef MAX_AUDIO_BUFFER_POOL_CHANNELS
298 #define MAX_AUDIO_BUFFER_POOL_CHANNELS 16 // Audio pool channels
299#endif
300
301#ifndef AUDIO_BUFFER_RESIDUAL_CAPACITY
302 #define AUDIO_BUFFER_RESIDUAL_CAPACITY 8 // In PCM frames, for resampling and pitch shifting
303#endif
304
305//----------------------------------------------------------------------------------
306// Types and Structures Definition
307//----------------------------------------------------------------------------------
308#if defined(RAUDIO_STANDALONE)
309// Trace log level
310// NOTE: Organized by priority level
311typedef enum {
312 LOG_ALL = 0, // Display all logs
313 LOG_TRACE, // Trace logging, intended for internal use only
314 LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds
315 LOG_INFO, // Info logging, used for program execution info
316 LOG_WARNING, // Warning logging, used on recoverable failures
317 LOG_ERROR, // Error logging, used on unrecoverable failures
318 LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE)
319 LOG_NONE // Disable logging
320} TraceLogLevel;
321#endif
322
323// Music context type
324// NOTE: Depends on data structure provided by the library
325// in charge of reading the different file types
326typedef enum {
327 MUSIC_AUDIO_NONE = 0, // No audio context loaded
328 MUSIC_AUDIO_WAV, // WAV audio context
329 MUSIC_AUDIO_OGG, // OGG audio context
330 MUSIC_AUDIO_FLAC, // FLAC audio context
331 MUSIC_AUDIO_MP3, // MP3 audio context
332 MUSIC_AUDIO_QOA, // QOA audio context
333 MUSIC_MODULE_XM, // XM module audio context
334 MUSIC_MODULE_MOD // MOD module audio context
335} MusicContextType;
336
337// NOTE: Different logic is used when feeding data to the playback device
338// depending on whether data is streamed (Music vs Sound)
339typedef enum {
340 AUDIO_BUFFER_USAGE_STATIC = 0,
341 AUDIO_BUFFER_USAGE_STREAM
342} AudioBufferUsage;
343
344// Audio buffer struct
345struct rAudioBuffer {
346 ma_data_converter converter; // Audio data converter
347 unsigned char* converterResidual; // Cached residual input frames for use by the converter
348 unsigned int converterResidualCount; // The number of valid frames sitting in converterResidual
349
350 AudioCallback callback; // Audio buffer callback for buffer filling on audio threads
351 rAudioProcessor *processor; // Audio processor
352
353 float volume; // Audio buffer volume
354 float pitch; // Audio buffer pitch
355 float pan; // Audio buffer pan (-1.0f to 1.0f)
356
357 bool playing; // Audio buffer state: AUDIO_PLAYING
358 bool paused; // Audio buffer state: AUDIO_PAUSED
359 bool looping; // Audio buffer looping, default to true for AudioStreams
360 int usage; // Audio buffer usage mode: STATIC or STREAM
361
362 bool isSubBufferProcessed[2]; // SubBuffer processed (virtual double buffer)
363 unsigned int sizeInFrames; // Total buffer size in frames
364 unsigned int frameCursorPos; // Frame cursor position
365 unsigned int framesProcessed; // Total frames processed in this buffer (required for play timing)
366
367 unsigned char *data; // Data buffer, on music stream keeps filling
368
369 rAudioBuffer *next; // Next audio buffer on the list
370 rAudioBuffer *prev; // Previous audio buffer on the list
371};
372
373// Audio processor struct
374// NOTE: Useful to apply effects to an AudioBuffer
375struct rAudioProcessor {
376 AudioCallback process; // Processor callback function
377 rAudioProcessor *next; // Next audio processor on the list
378 rAudioProcessor *prev; // Previous audio processor on the list
379};
380
381#define AudioBuffer rAudioBuffer // HACK: To avoid CoreAudio (macOS) symbol collision
382
383// Audio data context
384typedef struct AudioData {
385 struct {
386 ma_context context; // miniaudio context data
387 ma_device device; // miniaudio device
388 ma_mutex lock; // miniaudio mutex lock
389 bool isReady; // Check if audio device is ready
390 size_t pcmBufferSize; // Pre-allocated buffer size
391 void *pcmBuffer; // Pre-allocated buffer to read audio data from file/memory
392 } System;
393 struct {
394 AudioBuffer *first; // Pointer to first AudioBuffer in the list
395 AudioBuffer *last; // Pointer to last AudioBuffer in the list
396 int defaultSize; // Default audio buffer size for audio streams
397 } Buffer;
398 rAudioProcessor *mixedProcessor;
399} AudioData;
400
401//----------------------------------------------------------------------------------
402// Global Variables Definition
403//----------------------------------------------------------------------------------
404static AudioData AUDIO = { // Global AUDIO context
405
406 // NOTE: Music buffer size is defined by number of samples, independent of sample size and channels number
407 // After some math, considering a sampleRate of 48000, a buffer refill rate of 1/60 seconds and a
408 // standard double-buffering system, a 4096 samples buffer has been chosen, it should be enough
409 // In case of music-stalls, increase this number
410 .Buffer.defaultSize = 0,
411 .mixedProcessor = NULL
412};
413
414//----------------------------------------------------------------------------------
415// Module Internal Functions Declaration
416//----------------------------------------------------------------------------------
417static void OnLog(void *pUserData, ma_uint32 level, const char *pMessage);
418
419// Reads audio data from an AudioBuffer object in internal/device formats
420static ma_uint32 ReadAudioBufferFramesInInternalFormat(AudioBuffer *audioBuffer, void *framesOut, ma_uint32 frameCount);
421static ma_uint32 ReadAudioBufferFramesInMixingFormat(AudioBuffer *audioBuffer, float *framesOut, ma_uint32 frameCount);
422
423static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const void *pFramesInput, ma_uint32 frameCount);
424static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 frameCount, AudioBuffer *buffer);
425
426static bool IsAudioBufferPlayingInLockedState(AudioBuffer *buffer);
427static void StopAudioBufferInLockedState(AudioBuffer *buffer);
428static void UpdateAudioStreamInLockedState(AudioStream stream, const void *data, int frameCount);
429
430#if defined(RAUDIO_STANDALONE)
431static bool IsFileExtension(const char *fileName, const char *ext); // Check file extension
432static const char *GetFileExtension(const char *fileName); // Get pointer to extension for a filename string (includes the dot: .png)
433static const char *GetFileName(const char *filePath); // Get pointer to filename for a path string
434static const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (uses static string)
435
436static unsigned char *LoadFileData(const char *fileName, int *dataSize); // Load file data as byte array (read)
437static bool SaveFileData(const char *fileName, void *data, int dataSize); // Save data to file from byte array (write)
438static bool SaveFileText(const char *fileName, char *text); // Save text data to file (write), string must be '\0' terminated
439#endif
440
441//----------------------------------------------------------------------------------
442// AudioBuffer management functions declaration
443// NOTE: Those functions are not exposed by raylib... for the moment
444//----------------------------------------------------------------------------------
445AudioBuffer *LoadAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 sizeInFrames, int usage);
446void UnloadAudioBuffer(AudioBuffer *buffer);
447
448bool IsAudioBufferPlaying(AudioBuffer *buffer);
449void PlayAudioBuffer(AudioBuffer *buffer);
450void StopAudioBuffer(AudioBuffer *buffer);
451void PauseAudioBuffer(AudioBuffer *buffer);
452void ResumeAudioBuffer(AudioBuffer *buffer);
453void SetAudioBufferVolume(AudioBuffer *buffer, float volume);
454void SetAudioBufferPitch(AudioBuffer *buffer, float pitch);
455void SetAudioBufferPan(AudioBuffer *buffer, float pan);
456void TrackAudioBuffer(AudioBuffer *buffer);
457void UntrackAudioBuffer(AudioBuffer *buffer);
458
459//----------------------------------------------------------------------------------
460// Module Functions Definition - Audio Device initialization and Closing
461//----------------------------------------------------------------------------------
462
463// Initialize audio device
464void InitAudioDevice(void)
465{
466 // Init audio context
467 ma_context_config ctxConfig = ma_context_config_init();
468 ma_log_callback_init(OnLog, NULL);
469
470 ma_result result = ma_context_init(NULL, 0, &ctxConfig, &AUDIO.System.context);
471 if (result != MA_SUCCESS)
472 {
473 TRACELOG(LOG_WARNING, "AUDIO: Failed to initialize context");
474 return;
475 }
476
477 // Init audio device
478 // NOTE: Using the default device. Format is floating point because it simplifies mixing
479 ma_device_config config = ma_device_config_init(ma_device_type_playback);
480 config.playback.pDeviceID = NULL; // NULL for the default playback AUDIO.System.device
481 config.playback.format = AUDIO_DEVICE_FORMAT;
482 config.playback.channels = AUDIO_DEVICE_CHANNELS;
483 config.sampleRate = AUDIO_DEVICE_SAMPLE_RATE;
484 config.periodSizeInFrames = AUDIO_DEVICE_PERIOD_SIZE_IN_FRAMES;
485 config.dataCallback = OnSendAudioDataToDevice;
486 config.pUserData = NULL;
487 config.noPreSilencedOutputBuffer = true; // raylib pre-silences the output buffer manually
488 config.noFixedSizedCallback = true; // raylib does not require fixed sized callback guarantees. This bypasses an internal intermediary buffer
489
490 result = ma_device_init(&AUDIO.System.context, &config, &AUDIO.System.device);
491 if (result != MA_SUCCESS)
492 {
493 TRACELOG(LOG_WARNING, "AUDIO: Failed to initialize playback device");
494 ma_context_uninit(&AUDIO.System.context);
495 return;
496 }
497
498 // Mixing happens on a separate thread which means synchronization is needed
499 // A mutex is used here to make things simple, but may want to look at something
500 // a bit smarter later on to keep everything real-time, if that's necessary
501 if (ma_mutex_init(&AUDIO.System.lock) != MA_SUCCESS)
502 {
503 TRACELOG(LOG_WARNING, "AUDIO: Failed to create mutex for mixing");
504 ma_device_uninit(&AUDIO.System.device);
505 ma_context_uninit(&AUDIO.System.context);
506 return;
507 }
508
509 // Keep the device running the whole time. May want to consider doing something a bit smarter and only have the device running
510 // while there's at least one sound being played
511 result = ma_device_start(&AUDIO.System.device);
512 if (result != MA_SUCCESS)
513 {
514 TRACELOG(LOG_WARNING, "AUDIO: Failed to start playback device");
515 ma_device_uninit(&AUDIO.System.device);
516 ma_context_uninit(&AUDIO.System.context);
517 return;
518 }
519
520 TRACELOG(LOG_INFO, "AUDIO: Device initialized successfully");
521 TRACELOG(LOG_INFO, " > Backend: miniaudio | %s", ma_get_backend_name(AUDIO.System.context.backend));
522 TRACELOG(LOG_INFO, " > Format: %s -> %s", ma_get_format_name(AUDIO.System.device.playback.format), ma_get_format_name(AUDIO.System.device.playback.internalFormat));
523 TRACELOG(LOG_INFO, " > Channels: %d -> %d", AUDIO.System.device.playback.channels, AUDIO.System.device.playback.internalChannels);
524 TRACELOG(LOG_INFO, " > Sample rate: %d -> %d", AUDIO.System.device.sampleRate, AUDIO.System.device.playback.internalSampleRate);
525 TRACELOG(LOG_INFO, " > Periods size: %d", AUDIO.System.device.playback.internalPeriodSizeInFrames*AUDIO.System.device.playback.internalPeriods);
526
527 AUDIO.System.isReady = true;
528}
529
530// Close the audio device for all contexts
531void CloseAudioDevice(void)
532{
533 if (AUDIO.System.isReady)
534 {
535 ma_mutex_uninit(&AUDIO.System.lock);
536 ma_device_uninit(&AUDIO.System.device);
537 ma_context_uninit(&AUDIO.System.context);
538
539 AUDIO.System.isReady = false;
540 RL_FREE(AUDIO.System.pcmBuffer);
541 AUDIO.System.pcmBuffer = NULL;
542 AUDIO.System.pcmBufferSize = 0;
543
544 TRACELOG(LOG_INFO, "AUDIO: Device closed successfully");
545 }
546 else TRACELOG(LOG_WARNING, "AUDIO: Device could not be closed, not currently initialized");
547}
548
549// Check if device has been initialized successfully
550bool IsAudioDeviceReady(void)
551{
552 return AUDIO.System.isReady;
553}
554
555// Set master volume (listener)
556void SetMasterVolume(float volume)
557{
558 ma_device_set_master_volume(&AUDIO.System.device, volume);
559}
560
561// Get master volume (listener)
562float GetMasterVolume(void)
563{
564 float volume = 0.0f;
565 ma_device_get_master_volume(&AUDIO.System.device, &volume);
566 return volume;
567}
568
569//----------------------------------------------------------------------------------
570// Module Functions Definition - Audio Buffer management
571//----------------------------------------------------------------------------------
572
573// Initialize a new audio buffer (filled with silence)
574AudioBuffer *LoadAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 sizeInFrames, int usage)
575{
576 AudioBuffer *audioBuffer = (AudioBuffer *)RL_CALLOC(1, sizeof(AudioBuffer));
577
578 if (audioBuffer == NULL)
579 {
580 TRACELOG(LOG_WARNING, "AUDIO: Failed to allocate memory for buffer");
581 return NULL;
582 }
583
584 if (sizeInFrames > 0) audioBuffer->data = (unsigned char *)RL_CALLOC(sizeInFrames*channels*ma_get_bytes_per_sample(format), 1);
585
586 // Audio data runs through a format converter
587 ma_data_converter_config converterConfig = ma_data_converter_config_init(format, AUDIO_DEVICE_FORMAT, channels, AUDIO_DEVICE_CHANNELS, sampleRate, AUDIO.System.device.sampleRate);
588 converterConfig.allowDynamicSampleRate = true;
589
590 ma_result result = ma_data_converter_init(&converterConfig, NULL, &audioBuffer->converter);
591
592 if (result != MA_SUCCESS)
593 {
594 TRACELOG(LOG_WARNING, "AUDIO: Failed to create data conversion pipeline");
595 RL_FREE(audioBuffer);
596 return NULL;
597 }
598
599 // A cache for use by the converter is necessary when resampling because
600 // when generating output frames a different number of input frames will
601 // be consumed. Any residual input frames need to be kept track of to
602 // ensure there are no discontinuities. Since raylib supports pitch
603 // shifting, which is done through resampling, a cache will always be
604 // required. This will be kept relatively small to avoid too much wastage
605 audioBuffer->converterResidualCount = 0;
606 audioBuffer->converterResidual = (unsigned char*)RL_CALLOC(AUDIO_BUFFER_RESIDUAL_CAPACITY*ma_get_bytes_per_frame(format, channels), 1);
607
608 // Init audio buffer values
609 audioBuffer->volume = 1.0f;
610 audioBuffer->pitch = 1.0f;
611 audioBuffer->pan = 0.0f; // Center
612
613 audioBuffer->callback = NULL;
614 audioBuffer->processor = NULL;
615
616 audioBuffer->playing = false;
617 audioBuffer->paused = false;
618 audioBuffer->looping = false;
619
620 audioBuffer->usage = usage;
621 audioBuffer->frameCursorPos = 0;
622 audioBuffer->framesProcessed = 0;
623 audioBuffer->sizeInFrames = sizeInFrames;
624
625 // Buffers should be marked as processed by default so that a call to
626 // UpdateAudioStream() immediately after initialization works correctly
627 audioBuffer->isSubBufferProcessed[0] = true;
628 audioBuffer->isSubBufferProcessed[1] = true;
629
630 // Track audio buffer to linked list next position
631 TrackAudioBuffer(audioBuffer);
632
633 return audioBuffer;
634}
635
636// Delete an audio buffer
637void UnloadAudioBuffer(AudioBuffer *buffer)
638{
639 if (buffer != NULL)
640 {
641 UntrackAudioBuffer(buffer);
642 ma_data_converter_uninit(&buffer->converter, NULL);
643 RL_FREE(buffer->converterResidual);
644 RL_FREE(buffer->data);
645 RL_FREE(buffer);
646 }
647}
648
649// Check if an audio buffer is playing from a program state without lock
650bool IsAudioBufferPlaying(AudioBuffer *buffer)
651{
652 bool result = false;
653 ma_mutex_lock(&AUDIO.System.lock);
654 result = IsAudioBufferPlayingInLockedState(buffer);
655 ma_mutex_unlock(&AUDIO.System.lock);
656 return result;
657}
658
659// Play an audio buffer
660// NOTE: Buffer is restarted to the start
661// Use PauseAudioBuffer() and ResumeAudioBuffer() if the playback position should be maintained
662void PlayAudioBuffer(AudioBuffer *buffer)
663{
664 if (buffer != NULL)
665 {
666 ma_mutex_lock(&AUDIO.System.lock);
667 buffer->playing = true;
668 buffer->paused = false;
669 buffer->frameCursorPos = 0;
670 buffer->framesProcessed = 0;
671 buffer->isSubBufferProcessed[0] = true;
672 buffer->isSubBufferProcessed[1] = true;
673 ma_mutex_unlock(&AUDIO.System.lock);
674 }
675}
676
677// Stop an audio buffer from a program state without lock
678void StopAudioBuffer(AudioBuffer *buffer)
679{
680 ma_mutex_lock(&AUDIO.System.lock);
681 StopAudioBufferInLockedState(buffer);
682 ma_mutex_unlock(&AUDIO.System.lock);
683}
684
685// Pause an audio buffer
686void PauseAudioBuffer(AudioBuffer *buffer)
687{
688 if (buffer != NULL)
689 {
690 ma_mutex_lock(&AUDIO.System.lock);
691 buffer->paused = true;
692 ma_mutex_unlock(&AUDIO.System.lock);
693 }
694}
695
696// Resume an audio buffer
697void ResumeAudioBuffer(AudioBuffer *buffer)
698{
699 if (buffer != NULL)
700 {
701 ma_mutex_lock(&AUDIO.System.lock);
702 buffer->paused = false;
703 ma_mutex_unlock(&AUDIO.System.lock);
704 }
705}
706
707// Set volume for an audio buffer
708void SetAudioBufferVolume(AudioBuffer *buffer, float volume)
709{
710 if (buffer != NULL)
711 {
712 ma_mutex_lock(&AUDIO.System.lock);
713 buffer->volume = volume;
714 ma_mutex_unlock(&AUDIO.System.lock);
715 }
716}
717
718// Set pitch for an audio buffer
719void SetAudioBufferPitch(AudioBuffer *buffer, float pitch)
720{
721 if ((buffer != NULL) && (pitch > 0.0f))
722 {
723 ma_mutex_lock(&AUDIO.System.lock);
724 // Pitching is an adjustment of the sample rate
725 // Note that this changes the duration of the sound:
726 // - higher pitches will make the sound faster
727 // - lower pitches make it slower
728 ma_uint32 outputSampleRate = (ma_uint32)((float)AUDIO.System.device.sampleRate/pitch);
729 ma_data_converter_set_rate(&buffer->converter, buffer->converter.sampleRateIn, outputSampleRate);
730
731 buffer->pitch = pitch;
732 ma_mutex_unlock(&AUDIO.System.lock);
733 }
734}
735
736// Set pan for an audio buffer
737void SetAudioBufferPan(AudioBuffer *buffer, float pan)
738{
739 if (pan < -1.0f) pan = -1.0f;
740 else if (pan > 1.0f) pan = 1.0f;
741
742 if (buffer != NULL)
743 {
744 ma_mutex_lock(&AUDIO.System.lock);
745 buffer->pan = pan;
746 ma_mutex_unlock(&AUDIO.System.lock);
747 }
748}
749
750// Track audio buffer to linked list next position
751void TrackAudioBuffer(AudioBuffer *buffer)
752{
753 ma_mutex_lock(&AUDIO.System.lock);
754 {
755 if (AUDIO.Buffer.first == NULL) AUDIO.Buffer.first = buffer;
756 else
757 {
758 AUDIO.Buffer.last->next = buffer;
759 buffer->prev = AUDIO.Buffer.last;
760 }
761
762 AUDIO.Buffer.last = buffer;
763 }
764 ma_mutex_unlock(&AUDIO.System.lock);
765}
766
767// Untrack audio buffer from linked list
768void UntrackAudioBuffer(AudioBuffer *buffer)
769{
770 ma_mutex_lock(&AUDIO.System.lock);
771 {
772 if (buffer->prev == NULL) AUDIO.Buffer.first = buffer->next;
773 else buffer->prev->next = buffer->next;
774
775 if (buffer->next == NULL) AUDIO.Buffer.last = buffer->prev;
776 else buffer->next->prev = buffer->prev;
777
778 buffer->prev = NULL;
779 buffer->next = NULL;
780 }
781 ma_mutex_unlock(&AUDIO.System.lock);
782}
783
784//----------------------------------------------------------------------------------
785// Module Functions Definition - Sounds loading and playing (.WAV)
786//----------------------------------------------------------------------------------
787
788// Load wave data from file
789Wave LoadWave(const char *fileName)
790{
791 Wave wave = { 0 };
792
793 // Loading file to memory
794 int dataSize = 0;
795 unsigned char *fileData = LoadFileData(fileName, &dataSize);
796
797 // Loading wave from memory data
798 if (fileData != NULL) wave = LoadWaveFromMemory(GetFileExtension(fileName), fileData, dataSize);
799
800 UnloadFileData(fileData);
801
802 return wave;
803}
804
805// Load wave from memory buffer, fileType refers to extension: i.e. ".wav"
806// WARNING: File extension must be provided in lower-case
807Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int dataSize)
808{
809 Wave wave = { 0 };
810
811 if (false) { }
812#if SUPPORT_FILEFORMAT_WAV
813 else if ((strcmp(fileType, ".wav") == 0) || (strcmp(fileType, ".WAV") == 0))
814 {
815 drwav wav = { 0 };
816 bool success = drwav_init_memory(&wav, fileData, dataSize, NULL);
817
818 if (success)
819 {
820 wave.frameCount = (unsigned int)wav.totalPCMFrameCount;
821 wave.sampleRate = wav.sampleRate;
822 wave.sampleSize = 16;
823 wave.channels = wav.channels;
824 wave.data = (short *)RL_MALLOC((size_t)wave.frameCount*wave.channels*sizeof(short));
825
826 // NOTE: Forcing conversion to 16bit sample size on reading
827 drwav_read_pcm_frames_s16(&wav, wave.frameCount, (drwav_int16 *)wave.data);
828 }
829 else TRACELOG(LOG_WARNING, "WAVE: Failed to load WAV data");
830
831 drwav_uninit(&wav);
832 }
833#endif
834#if SUPPORT_FILEFORMAT_OGG
835 else if ((strcmp(fileType, ".ogg") == 0) || (strcmp(fileType, ".OGG") == 0))
836 {
837 stb_vorbis *oggData = stb_vorbis_open_memory((unsigned char *)fileData, dataSize, NULL, NULL);
838
839 if (oggData != NULL)
840 {
841 stb_vorbis_info info = stb_vorbis_get_info(oggData);
842
843 wave.sampleRate = info.sample_rate;
844 wave.sampleSize = 16; // By default, ogg data is 16 bit per sample (short)
845 wave.channels = info.channels;
846 wave.frameCount = (unsigned int)stb_vorbis_stream_length_in_samples(oggData); // NOTE: It returns frames!
847 wave.data = (short *)RL_MALLOC(wave.frameCount*wave.channels*sizeof(short));
848
849 // NOTE: Get the number of samples to process (be careful! asking for number of shorts, not bytes!)
850 stb_vorbis_get_samples_short_interleaved(oggData, info.channels, (short *)wave.data, wave.frameCount*wave.channels);
851 stb_vorbis_close(oggData);
852 }
853 else TRACELOG(LOG_WARNING, "WAVE: Failed to load OGG data");
854 }
855#endif
856#if SUPPORT_FILEFORMAT_MP3
857 else if ((strcmp(fileType, ".mp3") == 0) || (strcmp(fileType, ".MP3") == 0))
858 {
859 drmp3_config config = { 0 };
860 unsigned long long int totalFrameCount = 0;
861
862 // NOTE: Forcing conversion to 32bit float sample size on reading
863 wave.data = drmp3_open_memory_and_read_pcm_frames_f32(fileData, dataSize, &config, &totalFrameCount, NULL);
864 wave.sampleSize = 32;
865
866 if (wave.data != NULL)
867 {
868 wave.channels = config.channels;
869 wave.sampleRate = config.sampleRate;
870 wave.frameCount = (int)totalFrameCount;
871 }
872 else TRACELOG(LOG_WARNING, "WAVE: Failed to load MP3 data");
873
874 }
875#endif
876#if SUPPORT_FILEFORMAT_QOA
877 else if ((strcmp(fileType, ".qoa") == 0) || (strcmp(fileType, ".QOA") == 0))
878 {
879 qoa_desc qoa = { 0 };
880
881 // NOTE: Returned sample data is always 16 bit?
882 wave.data = qoa_decode(fileData, dataSize, &qoa);
883 wave.sampleSize = 16;
884
885 if (wave.data != NULL)
886 {
887 wave.channels = qoa.channels;
888 wave.sampleRate = qoa.samplerate;
889 wave.frameCount = qoa.samples;
890 }
891 else TRACELOG(LOG_WARNING, "WAVE: Failed to load QOA data");
892
893 }
894#endif
895#if SUPPORT_FILEFORMAT_FLAC
896 else if ((strcmp(fileType, ".flac") == 0) || (strcmp(fileType, ".FLAC") == 0))
897 {
898 unsigned long long int totalFrameCount = 0;
899
900 // NOTE: Forcing conversion to 16bit sample size on reading
901 wave.data = drflac_open_memory_and_read_pcm_frames_s16(fileData, dataSize, &wave.channels, &wave.sampleRate, &totalFrameCount, NULL);
902 wave.sampleSize = 16;
903
904 if (wave.data != NULL) wave.frameCount = (unsigned int)totalFrameCount;
905 else TRACELOG(LOG_WARNING, "WAVE: Failed to load FLAC data");
906 }
907#endif
908 else TRACELOG(LOG_WARNING, "WAVE: Data format not supported");
909
910 TRACELOG(LOG_INFO, "WAVE: Data loaded successfully (%i Hz, %i bit, %i channels)", wave.sampleRate, wave.sampleSize, wave.channels);
911
912 return wave;
913}
914
915// Checks if wave data is valid (data loaded and parameters)
916bool IsWaveValid(Wave wave)
917{
918 bool result = false;
919
920 if ((wave.data != NULL) && // Validate wave data available
921 (wave.frameCount > 0) && // Validate frame count
922 (wave.sampleRate > 0) && // Validate sample rate is supported
923 (wave.sampleSize > 0) && // Validate sample size is supported
924 (wave.channels > 0)) result = true; // Validate number of channels supported
925
926 return result;
927}
928
929// Load sound from file
930// NOTE: The entire file is loaded to memory to be played (no-streaming)
931Sound LoadSound(const char *fileName)
932{
933 Wave wave = LoadWave(fileName);
934
935 Sound sound = LoadSoundFromWave(wave);
936
937 UnloadWave(wave); // Sound is loaded, wave can be unloaded
938
939 return sound;
940}
941
942// Load sound from wave data
943// NOTE: Wave data must be unallocated manually
944Sound LoadSoundFromWave(Wave wave)
945{
946 Sound sound = { 0 };
947
948 if (wave.data != NULL)
949 {
950 // When using miniaudio mixing needs to b done manually
951 // To simplify this, the format of each sound needs to be converted to be consistent with
952 // the format used to open the playback AUDIO.System.device. It can be done in two ways:
953 //
954 // 1) Convert the whole sound in one go at load time (here)
955 // 2) Convert the audio data in chunks at mixing time
956 //
957 // First option has been selected, format conversion is done on the loading stage
958 // The downside is that it uses more memory if the original sound is u8 or s16
959 ma_format formatIn = ((wave.sampleSize == 8)? ma_format_u8 : ((wave.sampleSize == 16)? ma_format_s16 : ma_format_f32));
960 ma_uint32 frameCountIn = wave.frameCount;
961
962 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);
963 if (frameCount == 0) TRACELOG(LOG_WARNING, "SOUND: Failed to get frame count for format conversion");
964
965 AudioBuffer *audioBuffer = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, frameCount, AUDIO_BUFFER_USAGE_STATIC);
966 if (audioBuffer != NULL)
967 {
968 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);
969 if (frameCount == 0) TRACELOG(LOG_WARNING, "SOUND: Failed format conversion");
970
971 sound.frameCount = frameCount;
972 sound.stream.sampleRate = AUDIO.System.device.sampleRate;
973 sound.stream.sampleSize = 32;
974 sound.stream.channels = AUDIO_DEVICE_CHANNELS;
975 sound.stream.buffer = audioBuffer;
976 }
977 else TRACELOG(LOG_WARNING, "SOUND: Failed to create buffer");
978 }
979
980 return sound;
981}
982
983// Clone sound from existing sound data, clone does not own wave data
984// NOTE: Wave data must be unallocated manually and will be shared across all clones
985Sound LoadSoundAlias(Sound source)
986{
987 Sound sound = { 0 };
988
989 if (source.stream.buffer->data != NULL)
990 {
991 AudioBuffer *audioBuffer = LoadAudioBuffer(AUDIO_DEVICE_FORMAT, AUDIO_DEVICE_CHANNELS, AUDIO.System.device.sampleRate, 0, AUDIO_BUFFER_USAGE_STATIC);
992
993 if (audioBuffer != NULL)
994 {
995 audioBuffer->sizeInFrames = source.stream.buffer->sizeInFrames;
996 audioBuffer->data = source.stream.buffer->data;
997
998 // Initalize the buffer as if it was new
999 audioBuffer->volume = 1.0f;
1000 audioBuffer->pitch = 1.0f;
1001 audioBuffer->pan = 0.0f; // Center
1002
1003 sound.frameCount = source.frameCount;
1004 sound.stream.sampleRate = AUDIO.System.device.sampleRate;
1005 sound.stream.sampleSize = 32;
1006 sound.stream.channels = AUDIO_DEVICE_CHANNELS;
1007 sound.stream.buffer = audioBuffer;
1008 }
1009 else TRACELOG(LOG_WARNING, "SOUND: Failed to create buffer");
1010 }
1011
1012 return sound;
1013}
1014
1015// Checks if a sound is valid (data loaded and buffers initialized)
1016bool IsSoundValid(Sound sound)
1017{
1018 bool result = false;
1019
1020 if ((sound.frameCount > 0) && // Validate frame count
1021 (sound.stream.buffer != NULL) && // Validate stream buffer
1022 (sound.stream.sampleRate > 0) && // Validate sample rate is supported
1023 (sound.stream.sampleSize > 0) && // Validate sample size is supported
1024 (sound.stream.channels > 0)) result = true; // Validate number of channels supported
1025
1026 return result;
1027}
1028
1029// Unload wave data
1030void UnloadWave(Wave wave)
1031{
1032 RL_FREE(wave.data);
1033 //TRACELOG(LOG_INFO, "WAVE: Unloaded wave data from RAM");
1034}
1035
1036// Unload sound
1037void UnloadSound(Sound sound)
1038{
1039 UnloadAudioBuffer(sound.stream.buffer);
1040 //TRACELOG(LOG_INFO, "SOUND: Unloaded sound data from RAM");
1041}
1042
1043void UnloadSoundAlias(Sound alias)
1044{
1045 // Untrack and unload the sound buffer, not the sample data, it is shared with the source for the alias
1046 if (alias.stream.buffer != NULL)
1047 {
1048 UntrackAudioBuffer(alias.stream.buffer);
1049 ma_data_converter_uninit(&alias.stream.buffer->converter, NULL);
1050 RL_FREE(alias.stream.buffer);
1051 }
1052}
1053
1054// Update sound buffer with new data
1055// PARAMS: [data], format must match sound.stream.sampleSize, default 32 bit float - stereo
1056// PARAMS: [frameCount] must not exceed sound.frameCount
1057void UpdateSound(Sound sound, const void *data, int frameCount)
1058{
1059 if (sound.stream.buffer != NULL)
1060 {
1061 StopAudioBuffer(sound.stream.buffer);
1062
1063 memcpy(sound.stream.buffer->data, data, frameCount*ma_get_bytes_per_frame(sound.stream.buffer->converter.formatIn, sound.stream.buffer->converter.channelsIn));
1064 }
1065}
1066
1067// Export wave data to file
1068bool ExportWave(Wave wave, const char *fileName)
1069{
1070 bool result = false;
1071
1072 if (false) { }
1073#if SUPPORT_FILEFORMAT_WAV
1074 else if (IsFileExtension(fileName, ".wav"))
1075 {
1076 drwav wav = { 0 };
1077 drwav_data_format format = { 0 };
1078 format.container = drwav_container_riff;
1079 if (wave.sampleSize == 32) format.format = DR_WAVE_FORMAT_IEEE_FLOAT;
1080 else format.format = DR_WAVE_FORMAT_PCM;
1081 format.channels = wave.channels;
1082 format.sampleRate = wave.sampleRate;
1083 format.bitsPerSample = wave.sampleSize;
1084
1085 void *fileData = NULL;
1086 size_t fileDataSize = 0;
1087 result = drwav_init_memory_write(&wav, &fileData, &fileDataSize, &format, NULL);
1088 if (result) result = (int)drwav_write_pcm_frames(&wav, wave.frameCount, wave.data);
1089 drwav_result result = drwav_uninit(&wav);
1090
1091 if (result == DRWAV_SUCCESS) result = SaveFileData(fileName, (unsigned char *)fileData, (unsigned int)fileDataSize);
1092
1093 drwav_free(fileData, NULL);
1094 }
1095#endif
1096#if SUPPORT_FILEFORMAT_QOA
1097 else if (IsFileExtension(fileName, ".qoa"))
1098 {
1099 if (wave.sampleSize == 16)
1100 {
1101 qoa_desc qoa = { 0 };
1102 qoa.channels = wave.channels;
1103 qoa.samplerate = wave.sampleRate;
1104 qoa.samples = wave.frameCount;
1105
1106 int bytesWritten = qoa_write(fileName, (const short *)wave.data, &qoa);
1107 if (bytesWritten > 0) result = true;
1108 }
1109 else TRACELOG(LOG_WARNING, "AUDIO: Wave data must be 16 bit per sample for QOA format export");
1110 }
1111#endif
1112 else if (IsFileExtension(fileName, ".raw"))
1113 {
1114 // Export raw sample data (without header)
1115 // NOTE: It's up to the user to track wave parameters
1116 result = SaveFileData(fileName, wave.data, wave.frameCount*wave.channels*wave.sampleSize/8);
1117 }
1118
1119 if (result) TRACELOG(LOG_INFO, "FILEIO: [%s] Wave data exported successfully", fileName);
1120 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export wave data", fileName);
1121
1122 return result;
1123}
1124
1125// Export wave sample data to code (.h)
1126bool ExportWaveAsCode(Wave wave, const char *fileName)
1127{
1128 bool result = false;
1129
1130#ifndef TEXT_BYTES_PER_LINE
1131 #define TEXT_BYTES_PER_LINE 20
1132#endif
1133
1134 int waveDataSize = wave.frameCount*wave.channels*wave.sampleSize/8;
1135
1136 // NOTE: Text data buffer size is estimated considering wave data size in bytes
1137 // and requiring 12 char bytes for every byte; the actual size varies, but
1138 // the longest possible char being appended is "%.4ff,\n ", which is 12 bytes
1139 char *txtData = (char *)RL_CALLOC(waveDataSize*12 + 2000, sizeof(char));
1140
1141 int byteCount = 0;
1142 byteCount += sprintf(txtData + byteCount, "\n//////////////////////////////////////////////////////////////////////////////////\n");
1143 byteCount += sprintf(txtData + byteCount, "// //\n");
1144 byteCount += sprintf(txtData + byteCount, "// WaveAsCode exporter v1.1 - Wave data exported as an array of bytes //\n");
1145 byteCount += sprintf(txtData + byteCount, "// //\n");
1146 byteCount += sprintf(txtData + byteCount, "// more info and bugs-report: github.com/raysan5/raylib //\n");
1147 byteCount += sprintf(txtData + byteCount, "// feedback and support: ray[at]raylib.com //\n");
1148 byteCount += sprintf(txtData + byteCount, "// //\n");
1149 byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2018-2026 Ramon Santamaria (@raysan5) //\n");
1150 byteCount += sprintf(txtData + byteCount, "// //\n");
1151 byteCount += sprintf(txtData + byteCount, "//////////////////////////////////////////////////////////////////////////////////\n\n");
1152
1153 // Get file name from path and convert variable name to uppercase
1154 char varFileName[256] = { 0 };
1155 strncpy(varFileName, GetFileNameWithoutExt(fileName), 256 - 1);
1156 for (int i = 0; varFileName[i] != '\0'; i++) if (varFileName[i] >= 'a' && varFileName[i] <= 'z') { varFileName[i] = varFileName[i] - 32; }
1157
1158 // Add wave information
1159 byteCount += sprintf(txtData + byteCount, "// Wave data information\n");
1160 byteCount += sprintf(txtData + byteCount, "#define %s_FRAME_COUNT %u\n", varFileName, wave.frameCount);
1161 byteCount += sprintf(txtData + byteCount, "#define %s_SAMPLE_RATE %u\n", varFileName, wave.sampleRate);
1162 byteCount += sprintf(txtData + byteCount, "#define %s_SAMPLE_SIZE %u\n", varFileName, wave.sampleSize);
1163 byteCount += sprintf(txtData + byteCount, "#define %s_CHANNELS %u\n\n", varFileName, wave.channels);
1164
1165 // Write wave data as an array of values
1166 // Wave data is exported as byte array for 8/16bit and float array for 32bit float data
1167 // NOTE: Frame data exported is channel-interlaced: frame01[sampleChannel1, sampleChannel2, ...], frame02[], frame03[]
1168 if (wave.sampleSize == 32)
1169 {
1170 byteCount += sprintf(txtData + byteCount, "static float %s_DATA[%i] = {\n", varFileName, waveDataSize/4);
1171 for (int i = 1; i < waveDataSize/4; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "%.4ff,\n " : "%.4ff, "), ((float *)wave.data)[i - 1]);
1172 byteCount += sprintf(txtData + byteCount, "%.4ff };\n", ((float *)wave.data)[waveDataSize/4 - 1]);
1173 }
1174 else
1175 {
1176 byteCount += sprintf(txtData + byteCount, "static unsigned char %s_DATA[%i] = { ", varFileName, waveDataSize);
1177 for (int i = 1; i < waveDataSize; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "0x%x,\n " : "0x%x, "), ((unsigned char *)wave.data)[i - 1]);
1178 byteCount += sprintf(txtData + byteCount, "0x%x };\n", ((unsigned char *)wave.data)[waveDataSize - 1]);
1179 }
1180
1181 // NOTE: Text data length exported is determined by '\0' (NULL) character
1182 result = SaveFileText(fileName, txtData);
1183
1184 RL_FREE(txtData);
1185
1186 if (result != 0) TRACELOG(LOG_INFO, "FILEIO: [%s] Wave as code exported successfully", fileName);
1187 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export wave as code", fileName);
1188
1189 return result;
1190}
1191
1192// Play a sound
1193void PlaySound(Sound sound)
1194{
1195 PlayAudioBuffer(sound.stream.buffer);
1196}
1197
1198// Pause a sound
1199void PauseSound(Sound sound)
1200{
1201 PauseAudioBuffer(sound.stream.buffer);
1202}
1203
1204// Resume a paused sound
1205void ResumeSound(Sound sound)
1206{
1207 ResumeAudioBuffer(sound.stream.buffer);
1208}
1209
1210// Stop reproducing a sound
1211void StopSound(Sound sound)
1212{
1213 StopAudioBuffer(sound.stream.buffer);
1214}
1215
1216// Check if a sound is playing
1217bool IsSoundPlaying(Sound sound)
1218{
1219 bool result = false;
1220
1221 if (IsAudioBufferPlaying(sound.stream.buffer)) result = true;
1222
1223 return result;
1224}
1225
1226// Set volume for a sound
1227void SetSoundVolume(Sound sound, float volume)
1228{
1229 SetAudioBufferVolume(sound.stream.buffer, volume);
1230}
1231
1232// Set pitch for a sound
1233void SetSoundPitch(Sound sound, float pitch)
1234{
1235 SetAudioBufferPitch(sound.stream.buffer, pitch);
1236}
1237
1238// Set pan for a sound
1239void SetSoundPan(Sound sound, float pan)
1240{
1241 SetAudioBufferPan(sound.stream.buffer, pan);
1242}
1243
1244// Convert wave data to desired format
1245void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels)
1246{
1247 ma_format formatIn = ((wave->sampleSize == 8)? ma_format_u8 : ((wave->sampleSize == 16)? ma_format_s16 : ma_format_f32));
1248 ma_format formatOut = ((sampleSize == 8)? ma_format_u8 : ((sampleSize == 16)? ma_format_s16 : ma_format_f32));
1249
1250 ma_uint32 frameCountIn = wave->frameCount;
1251 ma_uint32 frameCount = (ma_uint32)ma_convert_frames(NULL, 0, formatOut, channels, sampleRate, NULL, frameCountIn, formatIn, wave->channels, wave->sampleRate);
1252
1253 if (frameCount == 0)
1254 {
1255 TRACELOG(LOG_WARNING, "WAVE: Failed to get frame count for format conversion");
1256 return;
1257 }
1258
1259 void *data = RL_MALLOC(frameCount*channels*(sampleSize/8));
1260
1261 frameCount = (ma_uint32)ma_convert_frames(data, frameCount, formatOut, channels, sampleRate, wave->data, frameCountIn, formatIn, wave->channels, wave->sampleRate);
1262 if (frameCount == 0)
1263 {
1264 RL_FREE(data);
1265 TRACELOG(LOG_WARNING, "WAVE: Failed format conversion");
1266 return;
1267 }
1268
1269 wave->frameCount = frameCount;
1270 wave->sampleSize = sampleSize;
1271 wave->sampleRate = sampleRate;
1272 wave->channels = channels;
1273
1274 RL_FREE(wave->data);
1275 wave->data = data;
1276}
1277
1278// Copy a wave to a new wave
1279Wave WaveCopy(Wave wave)
1280{
1281 Wave newWave = { 0 };
1282
1283 newWave.data = RL_MALLOC(wave.frameCount*wave.channels*wave.sampleSize/8);
1284
1285 if (newWave.data != NULL)
1286 {
1287 // NOTE: Size must be provided in bytes
1288 memcpy(newWave.data, wave.data, wave.frameCount*wave.channels*wave.sampleSize/8);
1289
1290 newWave.frameCount = wave.frameCount;
1291 newWave.sampleRate = wave.sampleRate;
1292 newWave.sampleSize = wave.sampleSize;
1293 newWave.channels = wave.channels;
1294 }
1295
1296 return newWave;
1297}
1298
1299// Crop a wave to defined frames range
1300// NOTE: Security check in case of out-of-range
1301void WaveCrop(Wave *wave, int initFrame, int finalFrame)
1302{
1303 if ((initFrame >= 0) && (initFrame < finalFrame) && ((unsigned int)finalFrame <= wave->frameCount))
1304 {
1305 int frameCount = finalFrame - initFrame;
1306
1307 void *data = RL_MALLOC(frameCount*wave->channels*wave->sampleSize/8);
1308
1309 memcpy(data, (unsigned char *)wave->data + (initFrame*wave->channels*wave->sampleSize/8), frameCount*wave->channels*wave->sampleSize/8);
1310
1311 RL_FREE(wave->data);
1312 wave->data = data;
1313 wave->frameCount = (unsigned int)frameCount;
1314 }
1315 else TRACELOG(LOG_WARNING, "WAVE: Crop range out of bounds");
1316}
1317
1318// Load samples data from wave as a floats array
1319// NOTE 1: Returned sample values are normalized to range [-1..1]
1320// NOTE 2: Sample data allocated should be freed with UnloadWaveSamples()
1321float *LoadWaveSamples(Wave wave)
1322{
1323 float *samples = (float *)RL_MALLOC(wave.frameCount*wave.channels*sizeof(float));
1324
1325 // NOTE: sampleCount is the total number of interlaced samples (including channels)
1326
1327 for (unsigned int i = 0; i < wave.frameCount*wave.channels; i++)
1328 {
1329 if (wave.sampleSize == 8) samples[i] = (float)(((unsigned char *)wave.data)[i] - 128)/128.0f;
1330 else if (wave.sampleSize == 16) samples[i] = (float)(((short *)wave.data)[i])/32768.0f;
1331 else if (wave.sampleSize == 32) samples[i] = ((float *)wave.data)[i];
1332 }
1333
1334 return samples;
1335}
1336
1337// Unload samples data loaded with LoadWaveSamples()
1338void UnloadWaveSamples(float *samples)
1339{
1340 RL_FREE(samples);
1341}
1342
1343//----------------------------------------------------------------------------------
1344// Module Functions Definition - Music loading and stream playing
1345//----------------------------------------------------------------------------------
1346
1347// Load music stream from file
1348Music LoadMusicStream(const char *fileName)
1349{
1350 Music music = { 0 };
1351 bool musicLoaded = false;
1352
1353 if (false) { }
1354#if SUPPORT_FILEFORMAT_WAV
1355 else if (IsFileExtension(fileName, ".wav"))
1356 {
1357 drwav *ctxWav = (drwav *)RL_CALLOC(1, sizeof(drwav));
1358 bool success = drwav_init_file(ctxWav, fileName, NULL);
1359
1360 if (success)
1361 {
1362 music.ctxType = MUSIC_AUDIO_WAV;
1363 music.ctxData = ctxWav;
1364 int sampleSize = ctxWav->bitsPerSample;
1365 if (ctxWav->bitsPerSample == 24) sampleSize = 16; // Forcing conversion to s16 on UpdateMusicStream()
1366
1367 music.stream = LoadAudioStream(ctxWav->sampleRate, sampleSize, ctxWav->channels);
1368 music.frameCount = (unsigned int)ctxWav->totalPCMFrameCount;
1369 music.looping = true; // Looping enabled by default
1370 musicLoaded = true;
1371 }
1372 else
1373 {
1374 RL_FREE(ctxWav);
1375 }
1376 }
1377#endif
1378#if SUPPORT_FILEFORMAT_OGG
1379 else if (IsFileExtension(fileName, ".ogg"))
1380 {
1381 // Open ogg audio stream
1382 stb_vorbis *ctxOgg = stb_vorbis_open_filename(fileName, NULL, NULL);
1383
1384 if (ctxOgg != NULL)
1385 {
1386 music.ctxType = MUSIC_AUDIO_OGG;
1387 music.ctxData = ctxOgg;
1388 stb_vorbis_info info = stb_vorbis_get_info((stb_vorbis *)music.ctxData); // Get Ogg file info
1389
1390 // OGG bit rate defaults to 16 bit, it's enough for compressed format
1391 music.stream = LoadAudioStream(info.sample_rate, 16, info.channels);
1392
1393 // WARNING: It seems this function returns length in frames, not samples, so multiply by channels
1394 music.frameCount = (unsigned int)stb_vorbis_stream_length_in_samples((stb_vorbis *)music.ctxData);
1395 music.looping = true; // Looping enabled by default
1396 musicLoaded = true;
1397 }
1398 else
1399 {
1400 stb_vorbis_close(ctxOgg);
1401 }
1402 }
1403#endif
1404#if SUPPORT_FILEFORMAT_MP3
1405 else if (IsFileExtension(fileName, ".mp3"))
1406 {
1407 drmp3 *ctxMp3 = (drmp3 *)RL_CALLOC(1, sizeof(drmp3));
1408 int result = drmp3_init_file(ctxMp3, fileName, NULL);
1409
1410 if (result > 0)
1411 {
1412 music.ctxType = MUSIC_AUDIO_MP3;
1413 music.ctxData = ctxMp3;
1414 music.stream = LoadAudioStream(ctxMp3->sampleRate, 32, ctxMp3->channels);
1415 music.frameCount = (unsigned int)drmp3_get_pcm_frame_count(ctxMp3);
1416 music.looping = true; // Looping enabled by default
1417 musicLoaded = true;
1418 }
1419 else
1420 {
1421 RL_FREE(ctxMp3);
1422 }
1423 }
1424#endif
1425#if SUPPORT_FILEFORMAT_QOA
1426 else if (IsFileExtension(fileName, ".qoa"))
1427 {
1428 qoaplay_desc *ctxQoa = qoaplay_open(fileName);
1429
1430 if (ctxQoa != NULL)
1431 {
1432 music.ctxType = MUSIC_AUDIO_QOA;
1433 music.ctxData = ctxQoa;
1434 // NOTE: Loading samples as 32bit float normalized data, so,
1435 // configure the output audio stream to also use float 32bit
1436 music.stream = LoadAudioStream(ctxQoa->info.samplerate, 32, ctxQoa->info.channels);
1437 music.frameCount = ctxQoa->info.samples;
1438 music.looping = true; // Looping enabled by default
1439 musicLoaded = true;
1440 }
1441 else{} //No uninit required
1442 }
1443#endif
1444#if SUPPORT_FILEFORMAT_FLAC
1445 else if (IsFileExtension(fileName, ".flac"))
1446 {
1447 drflac *ctxFlac = drflac_open_file(fileName, NULL);
1448
1449 if (ctxFlac != NULL)
1450 {
1451 music.ctxType = MUSIC_AUDIO_FLAC;
1452 music.ctxData = ctxFlac;
1453 int sampleSize = ctxFlac->bitsPerSample;
1454 if (ctxFlac->bitsPerSample == 24) sampleSize = 16; // Forcing conversion to s16 on UpdateMusicStream()
1455 music.stream = LoadAudioStream(ctxFlac->sampleRate, sampleSize, ctxFlac->channels);
1456 music.frameCount = (unsigned int)ctxFlac->totalPCMFrameCount;
1457 music.looping = true; // Looping enabled by default
1458 musicLoaded = true;
1459 }
1460 else
1461 {
1462 drflac_free(ctxFlac, NULL);
1463 }
1464 }
1465#endif
1466#if SUPPORT_FILEFORMAT_XM
1467 else if (IsFileExtension(fileName, ".xm"))
1468 {
1469 jar_xm_context_t *ctxXm = NULL;
1470 int result = jar_xm_create_context_from_file(&ctxXm, AUDIO.System.device.sampleRate, fileName);
1471
1472 if (result == 0) // XM AUDIO.System.context created successfully
1473 {
1474 music.ctxType = MUSIC_MODULE_XM;
1475 music.ctxData = ctxXm;
1476 jar_xm_set_max_loop_count(ctxXm, 0); // Set infinite number of loops
1477
1478 unsigned int bits = 32;
1479 if (AUDIO_DEVICE_FORMAT == ma_format_s16) bits = 16;
1480 else if (AUDIO_DEVICE_FORMAT == ma_format_u8) bits = 8;
1481
1482 // NOTE: Only stereo is supported for XM
1483 music.stream = LoadAudioStream(AUDIO.System.device.sampleRate, bits, AUDIO_DEVICE_CHANNELS);
1484 music.frameCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm); // NOTE: Always 2 channels (stereo)
1485 music.looping = true; // Looping enabled by default
1486 jar_xm_reset(ctxXm); // Make sure to start at the beginning of the song
1487 musicLoaded = true;
1488 }
1489 else
1490 {
1491 jar_xm_free_context(ctxXm);
1492 }
1493 }
1494#endif
1495#if SUPPORT_FILEFORMAT_MOD
1496 else if (IsFileExtension(fileName, ".mod"))
1497 {
1498 jar_mod_context_t *ctxMod = (jar_mod_context_t *)RL_CALLOC(1, sizeof(jar_mod_context_t));
1499 jar_mod_init(ctxMod);
1500 int result = jar_mod_load_file(ctxMod, fileName);
1501
1502 if (result > 0)
1503 {
1504 music.ctxType = MUSIC_MODULE_MOD;
1505 music.ctxData = ctxMod;
1506 // NOTE: Only stereo is supported for MOD
1507 music.stream = LoadAudioStream(AUDIO.System.device.sampleRate, 16, AUDIO_DEVICE_CHANNELS);
1508 music.frameCount = (unsigned int)jar_mod_max_samples(ctxMod); // NOTE: Always 2 channels (stereo)
1509 music.looping = true; // Looping enabled by default
1510 musicLoaded = true;
1511 }
1512 else
1513 {
1514 jar_mod_unload(ctxMod);
1515 RL_FREE(ctxMod);
1516 }
1517 }
1518#endif
1519 else TRACELOG(LOG_WARNING, "STREAM: [%s] File format not supported", fileName);
1520
1521 if (!musicLoaded)
1522 {
1523 TRACELOG(LOG_WARNING, "FILEIO: [%s] Music file could not be opened", fileName);
1524 }
1525 else
1526 {
1527 // Show some music stream info
1528 TRACELOG(LOG_INFO, "FILEIO: [%s] Music file loaded successfully", fileName);
1529 TRACELOG(LOG_INFO, " > Sample rate: %i Hz", music.stream.sampleRate);
1530 TRACELOG(LOG_INFO, " > Sample size: %i bits", music.stream.sampleSize);
1531 TRACELOG(LOG_INFO, " > Channels: %i (%s)", music.stream.channels, (music.stream.channels == 1)? "Mono" : (music.stream.channels == 2)? "Stereo" : "Multi");
1532 TRACELOG(LOG_INFO, " > Total frames: %i", music.frameCount);
1533 }
1534
1535 return music;
1536}
1537
1538// Load music stream from memory buffer, fileType refers to extension: i.e. ".wav"
1539// WARNING: File extension must be provided in lower-case
1540Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, int dataSize)
1541{
1542 Music music = { 0 };
1543 bool musicLoaded = false;
1544
1545 if (false) { }
1546#if SUPPORT_FILEFORMAT_WAV
1547 else if ((strcmp(fileType, ".wav") == 0) || (strcmp(fileType, ".WAV") == 0))
1548 {
1549 drwav *ctxWav = (drwav *)RL_CALLOC(1, sizeof(drwav));
1550
1551 bool success = drwav_init_memory(ctxWav, (const void *)data, dataSize, NULL);
1552
1553 if (success)
1554 {
1555 music.ctxType = MUSIC_AUDIO_WAV;
1556 music.ctxData = ctxWav;
1557 int sampleSize = ctxWav->bitsPerSample;
1558 if (ctxWav->bitsPerSample == 24) sampleSize = 16; // Forcing conversion to s16 on UpdateMusicStream()
1559
1560 music.stream = LoadAudioStream(ctxWav->sampleRate, sampleSize, ctxWav->channels);
1561 music.frameCount = (unsigned int)ctxWav->totalPCMFrameCount;
1562 music.looping = true; // Looping enabled by default
1563 musicLoaded = true;
1564 }
1565 else
1566 {
1567 drwav_uninit(ctxWav);
1568 RL_FREE(ctxWav);
1569 }
1570 }
1571#endif
1572#if SUPPORT_FILEFORMAT_OGG
1573 else if ((strcmp(fileType, ".ogg") == 0) || (strcmp(fileType, ".OGG") == 0))
1574 {
1575 // Open ogg audio stream
1576 stb_vorbis *ctxOgg = stb_vorbis_open_memory((const unsigned char *)data, dataSize, NULL, NULL);
1577
1578 if (ctxOgg != NULL)
1579 {
1580 music.ctxType = MUSIC_AUDIO_OGG;
1581 music.ctxData = ctxOgg;
1582 stb_vorbis_info info = stb_vorbis_get_info((stb_vorbis *)music.ctxData); // Get Ogg file info
1583
1584 // OGG bit rate defaults to 16 bit, it's enough for compressed format
1585 music.stream = LoadAudioStream(info.sample_rate, 16, info.channels);
1586
1587 // WARNING: It seems this function returns length in frames, not samples, so multiply by channels
1588 music.frameCount = (unsigned int)stb_vorbis_stream_length_in_samples((stb_vorbis *)music.ctxData);
1589 music.looping = true; // Looping enabled by default
1590 musicLoaded = true;
1591 }
1592 else
1593 {
1594 stb_vorbis_close(ctxOgg);
1595 }
1596 }
1597#endif
1598#if SUPPORT_FILEFORMAT_MP3
1599 else if ((strcmp(fileType, ".mp3") == 0) || (strcmp(fileType, ".MP3") == 0))
1600 {
1601 drmp3 *ctxMp3 = (drmp3 *)RL_CALLOC(1, sizeof(drmp3));
1602 int success = drmp3_init_memory(ctxMp3, (const void *)data, dataSize, NULL);
1603
1604 if (success)
1605 {
1606 music.ctxType = MUSIC_AUDIO_MP3;
1607 music.ctxData = ctxMp3;
1608 music.stream = LoadAudioStream(ctxMp3->sampleRate, 32, ctxMp3->channels);
1609 music.frameCount = (unsigned int)drmp3_get_pcm_frame_count(ctxMp3);
1610 music.looping = true; // Looping enabled by default
1611 musicLoaded = true;
1612 }
1613 else
1614 {
1615 drmp3_uninit(ctxMp3);
1616 RL_FREE(ctxMp3);
1617 }
1618 }
1619#endif
1620#if SUPPORT_FILEFORMAT_QOA
1621 else if ((strcmp(fileType, ".qoa") == 0) || (strcmp(fileType, ".QOA") == 0))
1622 {
1623 qoaplay_desc *ctxQoa = NULL;
1624 if ((data != NULL) && (dataSize > 0))
1625 {
1626 ctxQoa = qoaplay_open_memory(data, dataSize);
1627 }
1628
1629 if (ctxQoa != NULL)
1630 {
1631 music.ctxType = MUSIC_AUDIO_QOA;
1632 music.ctxData = ctxQoa;
1633
1634 // NOTE: Loading samples are 32bit float normalized data, so,
1635 // configure the output audio stream to also use float 32bit
1636 music.stream = LoadAudioStream(ctxQoa->info.samplerate, 32, ctxQoa->info.channels);
1637 music.frameCount = ctxQoa->info.samples;
1638 music.looping = true; // Looping enabled by default
1639 musicLoaded = true;
1640 }
1641 else{} //No uninit required
1642 }
1643#endif
1644#if SUPPORT_FILEFORMAT_FLAC
1645 else if ((strcmp(fileType, ".flac") == 0) || (strcmp(fileType, ".FLAC") == 0))
1646 {
1647 drflac *ctxFlac = drflac_open_memory((const void *)data, dataSize, NULL);
1648
1649 if (ctxFlac != NULL)
1650 {
1651 music.ctxType = MUSIC_AUDIO_FLAC;
1652 music.ctxData = ctxFlac;
1653 int sampleSize = ctxFlac->bitsPerSample;
1654 if (ctxFlac->bitsPerSample == 24) sampleSize = 16; // Forcing conversion to s16 on UpdateMusicStream()
1655 music.stream = LoadAudioStream(ctxFlac->sampleRate, sampleSize, ctxFlac->channels);
1656 music.frameCount = (unsigned int)ctxFlac->totalPCMFrameCount;
1657 music.looping = true; // Looping enabled by default
1658 musicLoaded = true;
1659 }
1660 else
1661 {
1662 drflac_free(ctxFlac, NULL);
1663 }
1664 }
1665#endif
1666#if SUPPORT_FILEFORMAT_XM
1667 else if ((strcmp(fileType, ".xm") == 0) || (strcmp(fileType, ".XM") == 0))
1668 {
1669 jar_xm_context_t *ctxXm = NULL;
1670 int result = jar_xm_create_context_safe(&ctxXm, (const char *)data, dataSize, AUDIO.System.device.sampleRate);
1671 if (result == 0) // XM AUDIO.System.context created successfully
1672 {
1673 music.ctxType = MUSIC_MODULE_XM;
1674 music.ctxData = ctxXm;
1675 jar_xm_set_max_loop_count(ctxXm, 0); // Set infinite number of loops
1676
1677 unsigned int bits = 32;
1678 if (AUDIO_DEVICE_FORMAT == ma_format_s16) bits = 16;
1679 else if (AUDIO_DEVICE_FORMAT == ma_format_u8) bits = 8;
1680
1681 // NOTE: Only stereo is supported for XM
1682 music.stream = LoadAudioStream(AUDIO.System.device.sampleRate, bits, 2);
1683 music.frameCount = (unsigned int)jar_xm_get_remaining_samples(ctxXm); // NOTE: Always 2 channels (stereo)
1684 music.looping = true; // Looping enabled by default
1685 jar_xm_reset(ctxXm); // Make sure to start at the beginning of the song
1686
1687 musicLoaded = true;
1688 }
1689 else
1690 {
1691 jar_xm_free_context(ctxXm);
1692 }
1693 }
1694#endif
1695#if SUPPORT_FILEFORMAT_MOD
1696 else if ((strcmp(fileType, ".mod") == 0) || (strcmp(fileType, ".MOD") == 0))
1697 {
1698 jar_mod_context_t *ctxMod = (jar_mod_context_t *)RL_MALLOC(sizeof(jar_mod_context_t));
1699 int result = 0;
1700
1701 jar_mod_init(ctxMod);
1702
1703 // Copy data to allocated memory for default UnloadMusicStream
1704 unsigned char *newData = (unsigned char *)RL_MALLOC(dataSize);
1705 for (int i = 0; i < dataSize; i++) newData[i] = data[i];
1706
1707 // Memory loaded version for jar_mod_load_file()
1708 if (dataSize && (dataSize < 32*1024*1024))
1709 {
1710 ctxMod->modfilesize = dataSize;
1711 ctxMod->modfile = newData;
1712 if (jar_mod_load(ctxMod, (void *)ctxMod->modfile, dataSize)) result = dataSize;
1713 }
1714
1715 if (result > 0)
1716 {
1717 music.ctxType = MUSIC_MODULE_MOD;
1718 music.ctxData = ctxMod;
1719
1720 // NOTE: Only stereo is supported for MOD
1721 music.stream = LoadAudioStream(AUDIO.System.device.sampleRate, 16, 2);
1722 music.frameCount = (unsigned int)jar_mod_max_samples(ctxMod); // NOTE: Always 2 channels (stereo)
1723 music.looping = true; // Looping enabled by default
1724 musicLoaded = true;
1725 }
1726 else
1727 {
1728 jar_mod_unload(ctxMod);
1729 RL_FREE(ctxMod);
1730 }
1731 }
1732#endif
1733 else TRACELOG(LOG_WARNING, "STREAM: Data format not supported");
1734
1735 if (!musicLoaded)
1736 {
1737 TRACELOG(LOG_WARNING, "FILEIO: Music data could not be loaded");
1738 }
1739 else
1740 {
1741 // Show some music stream info
1742 TRACELOG(LOG_INFO, "FILEIO: Music data loaded successfully");
1743 TRACELOG(LOG_INFO, " > Sample rate: %i Hz", music.stream.sampleRate);
1744 TRACELOG(LOG_INFO, " > Sample size: %i bits", music.stream.sampleSize);
1745 TRACELOG(LOG_INFO, " > Channels: %i (%s)", music.stream.channels, (music.stream.channels == 1)? "Mono" : (music.stream.channels == 2)? "Stereo" : "Multi");
1746 TRACELOG(LOG_INFO, " > Total frames: %i", music.frameCount);
1747 }
1748
1749 return music;
1750}
1751
1752// Checks if a music stream is valid (context and buffers initialized)
1753bool IsMusicValid(Music music)
1754{
1755 return ((music.ctxData != NULL) && // Validate context loaded
1756 (music.frameCount > 0) && // Validate audio frame count
1757 (music.stream.sampleRate > 0) && // Validate sample rate is supported
1758 (music.stream.sampleSize > 0) && // Validate sample size is supported
1759 (music.stream.channels > 0)); // Validate number of channels supported
1760}
1761
1762// Unload music stream
1763void UnloadMusicStream(Music music)
1764{
1765 if (IsMusicStreamPlaying(music)) StopMusicStream(music);
1766
1767 UnloadAudioStream(music.stream);
1768
1769 if (music.ctxData != NULL)
1770 {
1771 if (false) { }
1772#if SUPPORT_FILEFORMAT_WAV
1773 else if (music.ctxType == MUSIC_AUDIO_WAV) drwav_uninit((drwav *)music.ctxData);
1774#endif
1775#if SUPPORT_FILEFORMAT_OGG
1776 else if (music.ctxType == MUSIC_AUDIO_OGG) stb_vorbis_close((stb_vorbis *)music.ctxData);
1777#endif
1778#if SUPPORT_FILEFORMAT_MP3
1779 else if (music.ctxType == MUSIC_AUDIO_MP3) { drmp3_uninit((drmp3 *)music.ctxData); RL_FREE(music.ctxData); }
1780#endif
1781#if SUPPORT_FILEFORMAT_QOA
1782 else if (music.ctxType == MUSIC_AUDIO_QOA) qoaplay_close((qoaplay_desc *)music.ctxData);
1783#endif
1784#if SUPPORT_FILEFORMAT_FLAC
1785 else if (music.ctxType == MUSIC_AUDIO_FLAC) { drflac_close((drflac *)music.ctxData); drflac_free((drflac *)music.ctxData, NULL); }
1786#endif
1787#if SUPPORT_FILEFORMAT_XM
1788 else if (music.ctxType == MUSIC_MODULE_XM) jar_xm_free_context((jar_xm_context_t *)music.ctxData);
1789#endif
1790#if SUPPORT_FILEFORMAT_MOD
1791 else if (music.ctxType == MUSIC_MODULE_MOD) { jar_mod_unload((jar_mod_context_t *)music.ctxData); RL_FREE(music.ctxData); }
1792#endif
1793 }
1794}
1795
1796// Start music playing (open stream) from beginning
1797void PlayMusicStream(Music music)
1798{
1799 PlayAudioStream(music.stream);
1800}
1801
1802// Pause music playing
1803void PauseMusicStream(Music music)
1804{
1805 PauseAudioStream(music.stream);
1806}
1807
1808// Resume music playing
1809void ResumeMusicStream(Music music)
1810{
1811 ResumeAudioStream(music.stream);
1812}
1813
1814// Stop music playing (close stream)
1815void StopMusicStream(Music music)
1816{
1817 StopAudioStream(music.stream);
1818
1819 switch (music.ctxType)
1820 {
1821#if SUPPORT_FILEFORMAT_WAV
1822 case MUSIC_AUDIO_WAV: drwav_seek_to_first_pcm_frame((drwav *)music.ctxData); break;
1823#endif
1824#if SUPPORT_FILEFORMAT_OGG
1825 case MUSIC_AUDIO_OGG: stb_vorbis_seek_start((stb_vorbis *)music.ctxData); break;
1826#endif
1827#if SUPPORT_FILEFORMAT_MP3
1828 case MUSIC_AUDIO_MP3: drmp3_seek_to_start_of_stream((drmp3 *)music.ctxData); break;
1829#endif
1830#if SUPPORT_FILEFORMAT_QOA
1831 case MUSIC_AUDIO_QOA: qoaplay_rewind((qoaplay_desc *)music.ctxData); break;
1832#endif
1833#if SUPPORT_FILEFORMAT_FLAC
1834 case MUSIC_AUDIO_FLAC: drflac__seek_to_first_frame((drflac *)music.ctxData); break;
1835#endif
1836#if SUPPORT_FILEFORMAT_XM
1837 case MUSIC_MODULE_XM: jar_xm_reset((jar_xm_context_t *)music.ctxData); break;
1838#endif
1839#if SUPPORT_FILEFORMAT_MOD
1840 case MUSIC_MODULE_MOD: jar_mod_seek_start((jar_mod_context_t *)music.ctxData); break;
1841#endif
1842 default: break;
1843 }
1844}
1845
1846// Seek music to a certain position (in seconds)
1847void SeekMusicStream(Music music, float position)
1848{
1849 // Seeking is not supported in module formats
1850 if ((music.ctxType == MUSIC_MODULE_XM) || (music.ctxType == MUSIC_MODULE_MOD)) return;
1851
1852 unsigned int positionInFrames = (unsigned int)(position*music.stream.sampleRate);
1853
1854 switch (music.ctxType)
1855 {
1856#if SUPPORT_FILEFORMAT_WAV
1857 case MUSIC_AUDIO_WAV: drwav_seek_to_pcm_frame((drwav *)music.ctxData, positionInFrames); break;
1858#endif
1859#if SUPPORT_FILEFORMAT_OGG
1860 case MUSIC_AUDIO_OGG: stb_vorbis_seek_frame((stb_vorbis *)music.ctxData, positionInFrames); break;
1861#endif
1862#if SUPPORT_FILEFORMAT_MP3
1863 case MUSIC_AUDIO_MP3: drmp3_seek_to_pcm_frame((drmp3 *)music.ctxData, positionInFrames); break;
1864#endif
1865#if SUPPORT_FILEFORMAT_QOA
1866 case MUSIC_AUDIO_QOA:
1867 {
1868 int qoaFrame = positionInFrames/QOA_FRAME_LEN;
1869 qoaplay_seek_frame((qoaplay_desc *)music.ctxData, qoaFrame); // Seeks to QOA frame, not PCM frame
1870
1871 // Compute QOA frame number and update positionInFrames
1872 positionInFrames = ((qoaplay_desc *)music.ctxData)->sample_position;
1873 } break;
1874#endif
1875#if SUPPORT_FILEFORMAT_FLAC
1876 case MUSIC_AUDIO_FLAC: drflac_seek_to_pcm_frame((drflac *)music.ctxData, positionInFrames); break;
1877#endif
1878 default: break;
1879 }
1880
1881 ma_mutex_lock(&AUDIO.System.lock);
1882 music.stream.buffer->framesProcessed = positionInFrames;
1883 music.stream.buffer->isSubBufferProcessed[0] = true;
1884 music.stream.buffer->isSubBufferProcessed[1] = true;
1885 ma_mutex_unlock(&AUDIO.System.lock);
1886}
1887
1888// Update (re-fill) music buffers if data already processed
1889void UpdateMusicStream(Music music)
1890{
1891 if (music.stream.buffer == NULL) return;
1892 if (!music.stream.buffer->playing) return;
1893
1894 ma_mutex_lock(&AUDIO.System.lock);
1895
1896 unsigned int subBufferSizeInFrames = music.stream.buffer->sizeInFrames/2;
1897
1898 // On first call of this function, lazily pre-allocated a temp buffer to read audio files/memory data in
1899 int frameSize = music.stream.channels*music.stream.sampleSize/8;
1900 unsigned int pcmSize = subBufferSizeInFrames*frameSize;
1901
1902 if (AUDIO.System.pcmBufferSize < pcmSize)
1903 {
1904 RL_FREE(AUDIO.System.pcmBuffer);
1905 AUDIO.System.pcmBuffer = RL_CALLOC(1, pcmSize);
1906 AUDIO.System.pcmBufferSize = pcmSize;
1907 }
1908
1909 // Check both sub-buffers to check if they require refilling
1910 for (int i = 0; i < 2; i++)
1911 {
1912 unsigned int framesLeft = music.frameCount - music.stream.buffer->framesProcessed; // Frames left to be processed
1913 unsigned int framesToStream = 0; // Total frames to be streamed
1914
1915 if ((framesLeft >= subBufferSizeInFrames) || music.looping) framesToStream = subBufferSizeInFrames;
1916 else framesToStream = framesLeft;
1917
1918 if (framesToStream == 0)
1919 {
1920 // Check if both buffers have been processed
1921 if (music.stream.buffer->isSubBufferProcessed[0] && music.stream.buffer->isSubBufferProcessed[1])
1922 {
1923 ma_mutex_unlock(&AUDIO.System.lock);
1924 StopMusicStream(music);
1925 return;
1926 }
1927
1928 ma_mutex_unlock(&AUDIO.System.lock);
1929 return;
1930 }
1931
1932 if (!music.stream.buffer->isSubBufferProcessed[i]) continue; // No refilling required, move to next sub-buffer
1933
1934 int frameCountStillNeeded = framesToStream;
1935 int frameCountReadTotal = 0;
1936
1937 switch (music.ctxType)
1938 {
1939 #if SUPPORT_FILEFORMAT_WAV
1940 case MUSIC_AUDIO_WAV:
1941 {
1942 if (music.stream.sampleSize == 16)
1943 {
1944 while (true)
1945 {
1946 int frameCountRead = (int)drwav_read_pcm_frames_s16((drwav *)music.ctxData, frameCountStillNeeded, (short *)((char *)AUDIO.System.pcmBuffer + frameCountReadTotal*frameSize));
1947 frameCountReadTotal += frameCountRead;
1948 frameCountStillNeeded -= frameCountRead;
1949 if (frameCountStillNeeded == 0) break;
1950 else drwav_seek_to_first_pcm_frame((drwav *)music.ctxData);
1951 }
1952 }
1953 else if (music.stream.sampleSize == 32)
1954 {
1955 while (true)
1956 {
1957 int frameCountRead = (int)drwav_read_pcm_frames_f32((drwav *)music.ctxData, frameCountStillNeeded, (float *)((char *)AUDIO.System.pcmBuffer + frameCountReadTotal*frameSize));
1958 frameCountReadTotal += frameCountRead;
1959 frameCountStillNeeded -= frameCountRead;
1960 if (frameCountStillNeeded == 0) break;
1961 else drwav_seek_to_first_pcm_frame((drwav *)music.ctxData);
1962 }
1963 }
1964 } break;
1965 #endif
1966 #if SUPPORT_FILEFORMAT_OGG
1967 case MUSIC_AUDIO_OGG:
1968 {
1969 while (true)
1970 {
1971 int frameCountRead = stb_vorbis_get_samples_short_interleaved((stb_vorbis *)music.ctxData, music.stream.channels, (short *)((char *)AUDIO.System.pcmBuffer + frameCountReadTotal*frameSize), frameCountStillNeeded*music.stream.channels);
1972 frameCountReadTotal += frameCountRead;
1973 frameCountStillNeeded -= frameCountRead;
1974 if (frameCountStillNeeded == 0) break;
1975 else stb_vorbis_seek_start((stb_vorbis *)music.ctxData);
1976 }
1977 } break;
1978 #endif
1979 #if SUPPORT_FILEFORMAT_MP3
1980 case MUSIC_AUDIO_MP3:
1981 {
1982 while (true)
1983 {
1984 int frameCountRead = (int)drmp3_read_pcm_frames_f32((drmp3 *)music.ctxData, frameCountStillNeeded, (float *)((char *)AUDIO.System.pcmBuffer + frameCountReadTotal*frameSize));
1985 frameCountReadTotal += frameCountRead;
1986 frameCountStillNeeded -= frameCountRead;
1987 if (frameCountStillNeeded == 0) break;
1988 else drmp3_seek_to_start_of_stream((drmp3 *)music.ctxData);
1989 }
1990 } break;
1991 #endif
1992 #if SUPPORT_FILEFORMAT_QOA
1993 case MUSIC_AUDIO_QOA:
1994 {
1995 unsigned int frameCountRead = qoaplay_decode((qoaplay_desc *)music.ctxData, (float *)AUDIO.System.pcmBuffer, framesToStream);
1996 frameCountReadTotal += frameCountRead;
1997 /*
1998 while (true)
1999 {
2000 int frameCountRead = (int)qoaplay_decode((qoaplay_desc *)music.ctxData, (float *)((char *)AUDIO.System.pcmBuffer + frameCountReadTotal*frameSize), frameCountStillNeeded);
2001 frameCountReadTotal += frameCountRead;
2002 frameCountStillNeeded -= frameCountRead;
2003 if (frameCountStillNeeded == 0) break;
2004 else qoaplay_rewind((qoaplay_desc *)music.ctxData);
2005 }
2006 */
2007 } break;
2008 #endif
2009 #if SUPPORT_FILEFORMAT_FLAC
2010 case MUSIC_AUDIO_FLAC:
2011 {
2012 while (true)
2013 {
2014 int frameCountRead = (int)drflac_read_pcm_frames_s16((drflac *)music.ctxData, frameCountStillNeeded, (short *)((char *)AUDIO.System.pcmBuffer + frameCountReadTotal*frameSize));
2015 frameCountReadTotal += frameCountRead;
2016 frameCountStillNeeded -= frameCountRead;
2017 if (frameCountStillNeeded == 0) break;
2018 else drflac__seek_to_first_frame((drflac *)music.ctxData);
2019 }
2020 } break;
2021 #endif
2022 #if SUPPORT_FILEFORMAT_XM
2023 case MUSIC_MODULE_XM:
2024 {
2025 // NOTE: Internally considering 2 channels generation, so sampleCount/2
2026 if (AUDIO_DEVICE_FORMAT == ma_format_f32) jar_xm_generate_samples((jar_xm_context_t *)music.ctxData, (float *)AUDIO.System.pcmBuffer, framesToStream);
2027 else if (AUDIO_DEVICE_FORMAT == ma_format_s16) jar_xm_generate_samples_16bit((jar_xm_context_t *)music.ctxData, (short *)AUDIO.System.pcmBuffer, framesToStream);
2028 else if (AUDIO_DEVICE_FORMAT == ma_format_u8) jar_xm_generate_samples_8bit((jar_xm_context_t *)music.ctxData, (char *)AUDIO.System.pcmBuffer, framesToStream);
2029 //jar_xm_reset((jar_xm_context_t *)music.ctxData);
2030
2031 } break;
2032 #endif
2033 #if SUPPORT_FILEFORMAT_MOD
2034 case MUSIC_MODULE_MOD:
2035 {
2036 // NOTE: 3rd parameter (nbsample) specify the number of stereo 16bits samples desired, so sampleCount/2
2037 jar_mod_fillbuffer((jar_mod_context_t *)music.ctxData, (short *)AUDIO.System.pcmBuffer, framesToStream, 0);
2038 //jar_mod_seek_start((jar_mod_context_t *)music.ctxData);
2039
2040 } break;
2041 #endif
2042 default: break;
2043 }
2044
2045 UpdateAudioStreamInLockedState(music.stream, AUDIO.System.pcmBuffer, framesToStream);
2046 }
2047
2048 ma_mutex_unlock(&AUDIO.System.lock);
2049}
2050
2051// Check if any music is playing
2052bool IsMusicStreamPlaying(Music music)
2053{
2054 return IsAudioStreamPlaying(music.stream);
2055}
2056
2057// Set volume for music
2058void SetMusicVolume(Music music, float volume)
2059{
2060 SetAudioStreamVolume(music.stream, volume);
2061}
2062
2063// Set pitch for music
2064void SetMusicPitch(Music music, float pitch)
2065{
2066 SetAudioBufferPitch(music.stream.buffer, pitch);
2067}
2068
2069// Set pan for a music
2070void SetMusicPan(Music music, float pan)
2071{
2072 SetAudioBufferPan(music.stream.buffer, pan);
2073}
2074
2075// Get music time length (in seconds)
2076float GetMusicTimeLength(Music music)
2077{
2078 float totalSeconds = 0.0f;
2079
2080 totalSeconds = (float)music.frameCount/music.stream.sampleRate;
2081
2082 return totalSeconds;
2083}
2084
2085// Get current music time played (in seconds)
2086float GetMusicTimePlayed(Music music)
2087{
2088 float secondsPlayed = 0.0f;
2089 if (music.stream.buffer != NULL)
2090 {
2091#if SUPPORT_FILEFORMAT_XM
2092 if (music.ctxType == MUSIC_MODULE_XM)
2093 {
2094 uint64_t framesPlayed = 0;
2095
2096 jar_xm_get_position((jar_xm_context_t *)music.ctxData, NULL, NULL, NULL, &framesPlayed);
2097 secondsPlayed = (float)framesPlayed/music.stream.sampleRate;
2098 }
2099 else
2100#endif
2101 {
2102 ma_mutex_lock(&AUDIO.System.lock);
2103 //ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(music.stream.buffer->dsp.formatConverterIn.config.formatIn)*music.stream.buffer->dsp.formatConverterIn.config.channels;
2104 int framesProcessed = (int)music.stream.buffer->framesProcessed;
2105 int subBufferSize = (int)music.stream.buffer->sizeInFrames/2;
2106 int framesInFirstBuffer = music.stream.buffer->isSubBufferProcessed[0]? 0 : subBufferSize;
2107 int framesInSecondBuffer = music.stream.buffer->isSubBufferProcessed[1]? 0 : subBufferSize;
2108 int framesInBuffers = framesInFirstBuffer + framesInSecondBuffer;
2109 if (((unsigned int)framesInBuffers > music.frameCount) && !music.looping) framesInBuffers = music.frameCount;
2110 int framesSentToMix = music.stream.buffer->frameCursorPos%subBufferSize;
2111 int framesPlayed = (framesProcessed - framesInBuffers + framesSentToMix)%(int)music.frameCount;
2112 if (framesPlayed < 0) framesPlayed += music.frameCount;
2113 secondsPlayed = (float)framesPlayed/music.stream.sampleRate;
2114 ma_mutex_unlock(&AUDIO.System.lock);
2115 }
2116 }
2117
2118 return secondsPlayed;
2119}
2120
2121// Load audio stream (to stream audio pcm data)
2122AudioStream LoadAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels)
2123{
2124 AudioStream stream = { 0 };
2125
2126 stream.sampleRate = sampleRate;
2127 stream.sampleSize = sampleSize;
2128 stream.channels = channels;
2129
2130 ma_format formatIn = ((stream.sampleSize == 8)? ma_format_u8 : ((stream.sampleSize == 16)? ma_format_s16 : ma_format_f32));
2131
2132 // The size of a streaming buffer must be at least double the size of a period
2133 unsigned int periodSize = AUDIO.System.device.playback.internalPeriodSizeInFrames;
2134
2135 // If the buffer is not set, compute one that would give us a buffer good enough for a decent frame rate at the device bit size/rate
2136 int deviceBitsPerSample = AUDIO.System.device.playback.format;
2137 if (deviceBitsPerSample > 4) deviceBitsPerSample = 4;
2138 deviceBitsPerSample *= AUDIO.System.device.playback.channels;
2139
2140 unsigned int subBufferSize = (AUDIO.Buffer.defaultSize == 0)? (AUDIO.System.device.sampleRate/30*deviceBitsPerSample) : AUDIO.Buffer.defaultSize;
2141
2142 if (subBufferSize < periodSize) subBufferSize = periodSize;
2143
2144 // Create a double audio buffer of defined size
2145 stream.buffer = LoadAudioBuffer(formatIn, stream.channels, stream.sampleRate, subBufferSize*2, AUDIO_BUFFER_USAGE_STREAM);
2146
2147 if (stream.buffer != NULL)
2148 {
2149 stream.buffer->looping = true; // Always loop for streaming buffers
2150 TRACELOG(LOG_INFO, "STREAM: Initialized successfully (%i Hz, %i bit, %s)", stream.sampleRate, stream.sampleSize, (stream.channels == 1)? "Mono" : "Stereo");
2151 }
2152 else TRACELOG(LOG_WARNING, "STREAM: Failed to load audio buffer, stream could not be created");
2153
2154 return stream;
2155}
2156
2157// Checks if an audio stream is valid (buffers initialized)
2158bool IsAudioStreamValid(AudioStream stream)
2159{
2160 return ((stream.buffer != NULL) && // Validate stream buffer
2161 (stream.sampleRate > 0) && // Validate sample rate is supported
2162 (stream.sampleSize > 0) && // Validate sample size is supported
2163 (stream.channels > 0)); // Validate number of channels supported
2164}
2165
2166// Unload audio stream and free memory
2167void UnloadAudioStream(AudioStream stream)
2168{
2169 UnloadAudioBuffer(stream.buffer);
2170
2171 TRACELOG(LOG_INFO, "STREAM: Unloaded audio stream data from RAM");
2172}
2173
2174// Update audio stream buffers with data
2175// NOTE 1: Only updates one buffer of the stream source: dequeue -> update -> queue
2176// NOTE 2: To dequeue a buffer it needs to be processed: IsAudioStreamProcessed()
2177void UpdateAudioStream(AudioStream stream, const void *data, int frameCount)
2178{
2179 ma_mutex_lock(&AUDIO.System.lock);
2180 UpdateAudioStreamInLockedState(stream, data, frameCount);
2181 ma_mutex_unlock(&AUDIO.System.lock);
2182}
2183
2184// Check if any audio stream buffers requires refill
2185bool IsAudioStreamProcessed(AudioStream stream)
2186{
2187 bool result = false;
2188
2189 if (stream.buffer != NULL)
2190 {
2191 ma_mutex_lock(&AUDIO.System.lock);
2192 result = stream.buffer->isSubBufferProcessed[0] || stream.buffer->isSubBufferProcessed[1];
2193 ma_mutex_unlock(&AUDIO.System.lock);
2194 }
2195
2196 return result;
2197}
2198
2199// Play audio stream
2200void PlayAudioStream(AudioStream stream)
2201{
2202 PlayAudioBuffer(stream.buffer);
2203}
2204
2205// Play audio stream
2206void PauseAudioStream(AudioStream stream)
2207{
2208 PauseAudioBuffer(stream.buffer);
2209}
2210
2211// Resume audio stream playing
2212void ResumeAudioStream(AudioStream stream)
2213{
2214 ResumeAudioBuffer(stream.buffer);
2215}
2216
2217// Check if audio stream is playing
2218bool IsAudioStreamPlaying(AudioStream stream)
2219{
2220 return IsAudioBufferPlaying(stream.buffer);
2221}
2222
2223// Stop audio stream
2224void StopAudioStream(AudioStream stream)
2225{
2226 StopAudioBuffer(stream.buffer);
2227}
2228
2229// Set volume for audio stream (1.0 is max level)
2230void SetAudioStreamVolume(AudioStream stream, float volume)
2231{
2232 SetAudioBufferVolume(stream.buffer, volume);
2233}
2234
2235// Set pitch for audio stream (1.0 is base level)
2236void SetAudioStreamPitch(AudioStream stream, float pitch)
2237{
2238 SetAudioBufferPitch(stream.buffer, pitch);
2239}
2240
2241// Set pan for audio stream
2242void SetAudioStreamPan(AudioStream stream, float pan)
2243{
2244 SetAudioBufferPan(stream.buffer, pan);
2245}
2246
2247// Default size for new audio streams
2248void SetAudioStreamBufferSizeDefault(int size)
2249{
2250 AUDIO.Buffer.defaultSize = size;
2251}
2252
2253// Audio thread callback to request new data
2254void SetAudioStreamCallback(AudioStream stream, AudioCallback callback)
2255{
2256 if (stream.buffer != NULL)
2257 {
2258 ma_mutex_lock(&AUDIO.System.lock);
2259 stream.buffer->callback = callback;
2260 ma_mutex_unlock(&AUDIO.System.lock);
2261 }
2262}
2263
2264// Add processor to audio stream. Contrary to buffers, the order of processors is important
2265// The new processor must be added at the end. As there aren't supposed to be a lot of processors attached to
2266// a given stream, iterate through the list to find the end. That way there is no need to keep a pointer to the last element
2267void AttachAudioStreamProcessor(AudioStream stream, AudioCallback process)
2268{
2269 ma_mutex_lock(&AUDIO.System.lock);
2270
2271 rAudioProcessor *processor = (rAudioProcessor *)RL_CALLOC(1, sizeof(rAudioProcessor));
2272 processor->process = process;
2273
2274 rAudioProcessor *last = stream.buffer->processor;
2275
2276 while (last && last->next)
2277 {
2278 last = last->next;
2279 }
2280 if (last)
2281 {
2282 processor->prev = last;
2283 last->next = processor;
2284 }
2285 else stream.buffer->processor = processor;
2286
2287 ma_mutex_unlock(&AUDIO.System.lock);
2288}
2289
2290// Remove processor from audio stream
2291void DetachAudioStreamProcessor(AudioStream stream, AudioCallback process)
2292{
2293 ma_mutex_lock(&AUDIO.System.lock);
2294
2295 rAudioProcessor *processor = stream.buffer->processor;
2296
2297 while (processor)
2298 {
2299 rAudioProcessor *next = processor->next;
2300 rAudioProcessor *prev = processor->prev;
2301
2302 if (processor->process == process)
2303 {
2304 if (stream.buffer->processor == processor) stream.buffer->processor = next;
2305 if (prev) prev->next = next;
2306 if (next) next->prev = prev;
2307
2308 RL_FREE(processor);
2309 }
2310
2311 processor = next;
2312 }
2313
2314 ma_mutex_unlock(&AUDIO.System.lock);
2315}
2316
2317// Add processor to audio pipeline. Order of processors is important
2318// Works the same way as {Attach,Detach}AudioStreamProcessor() functions, except
2319// these two work on the already mixed output before sending it to the sound hardware
2320void AttachAudioMixedProcessor(AudioCallback process)
2321{
2322 ma_mutex_lock(&AUDIO.System.lock);
2323
2324 rAudioProcessor *processor = (rAudioProcessor *)RL_CALLOC(1, sizeof(rAudioProcessor));
2325 processor->process = process;
2326
2327 rAudioProcessor *last = AUDIO.mixedProcessor;
2328
2329 while (last && last->next)
2330 {
2331 last = last->next;
2332 }
2333 if (last)
2334 {
2335 processor->prev = last;
2336 last->next = processor;
2337 }
2338 else AUDIO.mixedProcessor = processor;
2339
2340 ma_mutex_unlock(&AUDIO.System.lock);
2341}
2342
2343// Remove processor from audio pipeline
2344void DetachAudioMixedProcessor(AudioCallback process)
2345{
2346 ma_mutex_lock(&AUDIO.System.lock);
2347
2348 rAudioProcessor *processor = AUDIO.mixedProcessor;
2349
2350 while (processor)
2351 {
2352 rAudioProcessor *next = processor->next;
2353 rAudioProcessor *prev = processor->prev;
2354
2355 if (processor->process == process)
2356 {
2357 if (AUDIO.mixedProcessor == processor) AUDIO.mixedProcessor = next;
2358 if (prev) prev->next = next;
2359 if (next) next->prev = prev;
2360
2361 RL_FREE(processor);
2362 }
2363
2364 processor = next;
2365 }
2366
2367 ma_mutex_unlock(&AUDIO.System.lock);
2368}
2369
2370//----------------------------------------------------------------------------------
2371// Module Internal Functions Definition
2372//----------------------------------------------------------------------------------
2373// Log callback function
2374static void OnLog(void *pUserData, ma_uint32 level, const char *pMessage)
2375{
2376 TRACELOG(LOG_WARNING, "miniaudio: %s", pMessage); // All log messages from miniaudio are errors
2377}
2378
2379// Reads audio data from an AudioBuffer object in internal format
2380static ma_uint32 ReadAudioBufferFramesInInternalFormat(AudioBuffer *audioBuffer, void *framesOut, ma_uint32 frameCount)
2381{
2382 // Don't read anything if the sound is not playing
2383 if (!audioBuffer->playing) return 0;
2384
2385 // Using audio buffer callback
2386 if (audioBuffer->callback)
2387 {
2388 audioBuffer->callback(framesOut, frameCount);
2389 audioBuffer->framesProcessed += frameCount;
2390
2391 return frameCount;
2392 }
2393
2394 ma_uint32 subBufferSizeInFrames = (audioBuffer->sizeInFrames > 1)? audioBuffer->sizeInFrames/2 : audioBuffer->sizeInFrames;
2395 ma_uint32 currentSubBufferIndex = audioBuffer->frameCursorPos/subBufferSizeInFrames;
2396
2397 if (currentSubBufferIndex > 1) return 0;
2398
2399 // Another thread can update the processed state of buffers, so
2400 // take a copy here to try and avoid potential synchronization problems
2401 bool isSubBufferProcessed[2] = { 0 };
2402 isSubBufferProcessed[0] = audioBuffer->isSubBufferProcessed[0];
2403 isSubBufferProcessed[1] = audioBuffer->isSubBufferProcessed[1];
2404
2405 ma_uint32 frameSizeInBytes = ma_get_bytes_per_frame(audioBuffer->converter.formatIn, audioBuffer->converter.channelsIn);
2406
2407 // Fill out every frame until a buffer that's marked as processed is found, then fill the remainder with 0
2408 ma_uint32 framesRead = 0;
2409 while (1)
2410 {
2411 // Break from this loop differently depending on the buffer's usage
2412 // - For static buffers, simply fill as much data as possible
2413 // - For streaming buffers, only fill half of the buffer that are processed
2414 // Unprocessed halves must keep their audio data in-tact
2415 if (audioBuffer->usage == AUDIO_BUFFER_USAGE_STATIC)
2416 {
2417 if (framesRead >= frameCount) break;
2418 }
2419 else
2420 {
2421 if (isSubBufferProcessed[currentSubBufferIndex]) break;
2422 }
2423
2424 ma_uint32 totalFramesRemaining = (frameCount - framesRead);
2425 if (totalFramesRemaining == 0) break;
2426
2427 ma_uint32 framesRemainingInOutputBuffer;
2428 if (audioBuffer->usage == AUDIO_BUFFER_USAGE_STATIC)
2429 {
2430 framesRemainingInOutputBuffer = audioBuffer->sizeInFrames - audioBuffer->frameCursorPos;
2431 }
2432 else
2433 {
2434 ma_uint32 firstFrameIndexOfThisSubBuffer = subBufferSizeInFrames*currentSubBufferIndex;
2435 framesRemainingInOutputBuffer = subBufferSizeInFrames - (audioBuffer->frameCursorPos - firstFrameIndexOfThisSubBuffer);
2436 }
2437
2438 ma_uint32 framesToRead = totalFramesRemaining;
2439 if (framesToRead > framesRemainingInOutputBuffer) framesToRead = framesRemainingInOutputBuffer;
2440
2441 memcpy((unsigned char *)framesOut + (framesRead*frameSizeInBytes), audioBuffer->data + (audioBuffer->frameCursorPos*frameSizeInBytes), framesToRead*frameSizeInBytes);
2442 audioBuffer->frameCursorPos = (audioBuffer->frameCursorPos + framesToRead)%audioBuffer->sizeInFrames;
2443 framesRead += framesToRead;
2444
2445 // If the end of the buffer is read, mark it as processed
2446 if (framesToRead == framesRemainingInOutputBuffer)
2447 {
2448 audioBuffer->isSubBufferProcessed[currentSubBufferIndex] = true;
2449 isSubBufferProcessed[currentSubBufferIndex] = true;
2450
2451 currentSubBufferIndex = (currentSubBufferIndex + 1)%2;
2452
2453 // Break from this loop if looping not enabled
2454 if (!audioBuffer->looping)
2455 {
2456 StopAudioBufferInLockedState(audioBuffer);
2457 break;
2458 }
2459 }
2460 }
2461
2462 // Zero-fill excess
2463 ma_uint32 totalFramesRemaining = (frameCount - framesRead);
2464 if (totalFramesRemaining > 0)
2465 {
2466 memset((unsigned char *)framesOut + (framesRead*frameSizeInBytes), 0, totalFramesRemaining*frameSizeInBytes);
2467
2468 // For static buffers, fill the remaining frames with silence for safety, but don't report those
2469 // frames as "read"; The reason for this is that the caller uses the return value
2470 // to know whether a non-looping sound has finished playback
2471 if (audioBuffer->usage != AUDIO_BUFFER_USAGE_STATIC) framesRead += totalFramesRemaining;
2472 }
2473
2474 return framesRead;
2475}
2476
2477// Reads audio data from an AudioBuffer object in device format, returned data will be in a format appropriate for mixing
2478static ma_uint32 ReadAudioBufferFramesInMixingFormat(AudioBuffer *audioBuffer, float *framesOut, ma_uint32 frameCount)
2479{
2480 // NOTE: Continuously converting data from the AudioBuffer's internal format to the mixing format,
2481 // which should be defined by the output format of the data converter
2482 // This is done until frameCount frames have been output
2483 ma_uint32 bpf = ma_get_bytes_per_frame(audioBuffer->converter.formatIn, audioBuffer->converter.channelsIn);
2484 ma_uint8 inputBuffer[4096] = { 0 };
2485 ma_uint32 inputBufferFrameCap = sizeof(inputBuffer)/bpf;
2486
2487 ma_uint32 totalOutputFramesProcessed = 0;
2488 while (totalOutputFramesProcessed < frameCount)
2489 {
2490 float *runningFramesOut = framesOut + (totalOutputFramesProcessed*audioBuffer->converter.channelsOut);
2491 ma_uint64 outputFramesToProcessThisIteration = frameCount - totalOutputFramesProcessed;
2492 //ma_uint64 inputFramesToProcessThisIteration = 0;
2493
2494 // Process any residual input frames from the previous read first
2495 if (audioBuffer->converterResidualCount > 0)
2496 {
2497 ma_uint64 inputFramesProcessedThisIteration = audioBuffer->converterResidualCount;
2498 ma_uint64 outputFramesProcessedThisIteration = outputFramesToProcessThisIteration;
2499 ma_data_converter_process_pcm_frames(&audioBuffer->converter, audioBuffer->converterResidual, &inputFramesProcessedThisIteration, runningFramesOut, &outputFramesProcessedThisIteration);
2500
2501 // Make sure the data in the cache is consumed, this can be optimized to use a cursor instead of a memmove()
2502 memmove(audioBuffer->converterResidual, audioBuffer->converterResidual + inputFramesProcessedThisIteration*bpf, (size_t)(AUDIO_BUFFER_RESIDUAL_CAPACITY - inputFramesProcessedThisIteration)*bpf);
2503 audioBuffer->converterResidualCount -= (ma_uint32)inputFramesProcessedThisIteration; // Safe cast
2504
2505 totalOutputFramesProcessed += (ma_uint32)outputFramesProcessedThisIteration; // Safe cast
2506 }
2507 else
2508 {
2509 // Getting here means there are no residual frames from the previous read
2510 // Fresh data can now be pulled from the AudioBuffer and processed
2511 //
2512 // A best guess needs to be used made to determine how many input frames to pull from the buffer
2513 // There are three possible outcomes: 1) exact; 2) underestimated; 3) overestimated
2514 //
2515 // When the guess is exactly correct or underestimated there is nothing special to handle,
2516 // it'll be handled naturally by the loop
2517 //
2518 // When the guess is overestimated, that's when it gets more complicated
2519 // In this case, any overflow needs to be stored in a buffer for later processing by the next read
2520 ma_uint32 estimatedInputFrameCount = (ma_uint32)(((float)audioBuffer->converter.resampler.sampleRateIn / audioBuffer->converter.resampler.sampleRateOut)*outputFramesToProcessThisIteration);
2521 if (estimatedInputFrameCount == 0) estimatedInputFrameCount = 1; // Make sure at least one input frame is read
2522 if (estimatedInputFrameCount > inputBufferFrameCap) estimatedInputFrameCount = inputBufferFrameCap;
2523
2524 ma_uint32 inputFramesInInternalFormatCount = ReadAudioBufferFramesInInternalFormat(audioBuffer, inputBuffer, estimatedInputFrameCount);
2525
2526 ma_uint64 inputFramesProcessedThisIteration = inputFramesInInternalFormatCount;
2527 ma_uint64 outputFramesProcessedThisIteration = outputFramesToProcessThisIteration;
2528 ma_data_converter_process_pcm_frames(&audioBuffer->converter, inputBuffer, &inputFramesProcessedThisIteration, runningFramesOut, &outputFramesProcessedThisIteration);
2529
2530 totalOutputFramesProcessed += (ma_uint32)outputFramesProcessedThisIteration;
2531
2532 if (inputFramesInInternalFormatCount > inputFramesProcessedThisIteration)
2533 {
2534 // Getting here means the estimated input frame count was overestimated
2535 // The residual needs be stored for later use
2536 ma_uint64 residualFrameCount = inputFramesInInternalFormatCount - inputFramesProcessedThisIteration;
2537
2538 // A safety check to make sure the capacity of the residual cache is not exceeded
2539 if (residualFrameCount > AUDIO_BUFFER_RESIDUAL_CAPACITY)
2540 {
2541 residualFrameCount = AUDIO_BUFFER_RESIDUAL_CAPACITY;
2542 }
2543
2544 memcpy(audioBuffer->converterResidual, inputBuffer + inputFramesProcessedThisIteration*bpf, (size_t)(residualFrameCount*bpf));
2545 audioBuffer->converterResidualCount = (unsigned int)residualFrameCount;
2546 }
2547
2548 if (inputFramesInInternalFormatCount < estimatedInputFrameCount) break; // Reached the end of the sound
2549 }
2550 }
2551
2552 return totalOutputFramesProcessed;
2553}
2554
2555// Sending audio data to device callback function
2556// This function will be called when miniaudio needs more data
2557// NOTE: All the mixing takes place here
2558static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const void *pFramesInput, ma_uint32 frameCount)
2559{
2560 (void)pDevice;
2561
2562 // Mixing is basically an accumulation, need to initialize the output buffer to 0
2563 memset(pFramesOut, 0, frameCount*pDevice->playback.channels*ma_get_bytes_per_sample(pDevice->playback.format));
2564
2565 // Using a mutex here for thread-safety which makes things not real-time
2566 // This is unlikely to be necessary for this project, but it can be reconsidered
2567 ma_mutex_lock(&AUDIO.System.lock);
2568 {
2569 for (AudioBuffer *audioBuffer = AUDIO.Buffer.first; audioBuffer != NULL; audioBuffer = audioBuffer->next)
2570 {
2571 // Ignore stopped or paused sounds
2572 if (!audioBuffer->playing || audioBuffer->paused) continue;
2573
2574 ma_uint32 framesRead = 0;
2575
2576 while (1)
2577 {
2578 if (framesRead >= frameCount) break;
2579
2580 // Read as much data as possible from the stream
2581 ma_uint32 framesToRead = (frameCount - framesRead);
2582
2583 while (framesToRead > 0)
2584 {
2585 float tempBuffer[1024] = { 0 }; // Frames for stereo
2586
2587 ma_uint32 framesToReadRightNow = framesToRead;
2588 if (framesToReadRightNow > sizeof(tempBuffer)/sizeof(tempBuffer[0])/AUDIO_DEVICE_CHANNELS)
2589 {
2590 framesToReadRightNow = sizeof(tempBuffer)/sizeof(tempBuffer[0])/AUDIO_DEVICE_CHANNELS;
2591 }
2592
2593 ma_uint32 framesJustRead = ReadAudioBufferFramesInMixingFormat(audioBuffer, tempBuffer, framesToReadRightNow);
2594 if (framesJustRead > 0)
2595 {
2596 float *framesOut = (float *)pFramesOut + (framesRead*AUDIO.System.device.playback.channels);
2597 float *framesIn = tempBuffer;
2598
2599 // Apply processors chain if defined
2600 rAudioProcessor *processor = audioBuffer->processor;
2601 while (processor)
2602 {
2603 processor->process(framesIn, framesJustRead);
2604 processor = processor->next;
2605 }
2606
2607 MixAudioFrames(framesOut, framesIn, framesJustRead, audioBuffer);
2608
2609 framesToRead -= framesJustRead;
2610 framesRead += framesJustRead;
2611 }
2612
2613 if (!audioBuffer->playing)
2614 {
2615 framesRead = frameCount;
2616 break;
2617 }
2618
2619 // If all the frames requested can't be read, break
2620 if (framesJustRead < framesToReadRightNow)
2621 {
2622 if (!audioBuffer->looping)
2623 {
2624 StopAudioBufferInLockedState(audioBuffer);
2625 break;
2626 }
2627 else
2628 {
2629 // Should never get here, but for safety,
2630 // move the cursor position back to the start and continue the loop
2631 audioBuffer->frameCursorPos = 0;
2632 continue;
2633 }
2634 }
2635 }
2636
2637 // If for some reason is not possible to read every frame, the loop needs to be broken
2638 // Not doing this could theoretically eend up into an infinite loop
2639 if (framesToRead > 0) break;
2640 }
2641 }
2642 }
2643
2644 rAudioProcessor *processor = AUDIO.mixedProcessor;
2645 while (processor)
2646 {
2647 processor->process(pFramesOut, frameCount);
2648 processor = processor->next;
2649 }
2650
2651 ma_mutex_unlock(&AUDIO.System.lock);
2652}
2653
2654// Main mixing function, pretty simple in this project, only an accumulation
2655// NOTE: framesOut is both an input and an output, it is initially filled with zeros outside of this function
2656static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 frameCount, AudioBuffer *buffer)
2657{
2658 const float localVolume = buffer->volume;
2659 const ma_uint32 channels = AUDIO.System.device.playback.channels;
2660
2661 if (channels == 2) // Consider panning
2662 {
2663 const float right = (buffer->pan + 1.0f)/2.0f; // Normalize: [-1..1] -> [0..1]
2664 const float left = 1.0f - right;
2665
2666 // Fast sine approximation in [0..1] for pan law: y = 0.5f*x*(3 - x*x);
2667 const float levels[2] = { localVolume*0.5f*left*(3.0f - left*left), localVolume*0.5f*right*(3.0f - right*right) };
2668
2669 float *frameOut = framesOut;
2670 const float *frameIn = framesIn;
2671
2672 for (ma_uint32 frame = 0; frame < frameCount; frame++)
2673 {
2674 frameOut[0] += (frameIn[0]*levels[0]);
2675 frameOut[1] += (frameIn[1]*levels[1]);
2676
2677 frameOut += 2;
2678 frameIn += 2;
2679 }
2680 }
2681 else // Do not consider panning
2682 {
2683 for (ma_uint32 frame = 0; frame < frameCount; frame++)
2684 {
2685 for (ma_uint32 c = 0; c < channels; c++)
2686 {
2687 float *frameOut = framesOut + (frame*channels);
2688 const float *frameIn = framesIn + (frame*channels);
2689
2690 // Output accumulates input multiplied by volume to provided output (usually 0)
2691 frameOut[c] += (frameIn[c]*localVolume);
2692 }
2693 }
2694 }
2695}
2696
2697// Check if an audio buffer is playing, assuming the audio system mutex has been locked
2698static bool IsAudioBufferPlayingInLockedState(AudioBuffer *buffer)
2699{
2700 bool result = false;
2701
2702 if (buffer != NULL) result = (buffer->playing && !buffer->paused);
2703
2704 return result;
2705}
2706
2707// Stop an audio buffer, assuming the audio system mutex has been locked
2708static void StopAudioBufferInLockedState(AudioBuffer *buffer)
2709{
2710 if (buffer != NULL)
2711 {
2712 if (IsAudioBufferPlayingInLockedState(buffer))
2713 {
2714 buffer->playing = false;
2715 buffer->paused = false;
2716 buffer->frameCursorPos = 0;
2717 buffer->framesProcessed = 0;
2718 buffer->isSubBufferProcessed[0] = true;
2719 buffer->isSubBufferProcessed[1] = true;
2720 }
2721 }
2722}
2723
2724// Update audio stream, assuming the audio system mutex has been locked
2725static void UpdateAudioStreamInLockedState(AudioStream stream, const void *data, int frameCount)
2726{
2727 if (stream.buffer != NULL)
2728 {
2729 if (stream.buffer->isSubBufferProcessed[0] || stream.buffer->isSubBufferProcessed[1])
2730 {
2731 ma_uint32 subBufferToUpdate = 0;
2732
2733 if (stream.buffer->isSubBufferProcessed[0] && stream.buffer->isSubBufferProcessed[1])
2734 {
2735 // Both buffers are available for updating
2736 // Update the first one and make sure the cursor is moved back to the front
2737 subBufferToUpdate = 0;
2738 stream.buffer->frameCursorPos = 0;
2739 }
2740 else
2741 {
2742 // Update whichever sub-buffer is processed
2743 subBufferToUpdate = (stream.buffer->isSubBufferProcessed[0])? 0 : 1;
2744 }
2745
2746 ma_uint32 subBufferSizeInFrames = stream.buffer->sizeInFrames/2;
2747 unsigned char *subBuffer = stream.buffer->data + ((subBufferSizeInFrames*stream.channels*(stream.sampleSize/8))*subBufferToUpdate);
2748
2749 stream.buffer->framesProcessed += frameCount;
2750
2751 // Does this API expect a whole buffer to be updated in one go?
2752 // Assuming so, but if not will need to change this logic
2753 if (subBufferSizeInFrames >= (ma_uint32)frameCount)
2754 {
2755 ma_uint32 framesToWrite = (ma_uint32)frameCount;
2756
2757 ma_uint32 bytesToWrite = framesToWrite*stream.channels*(stream.sampleSize/8);
2758 memcpy(subBuffer, data, bytesToWrite);
2759
2760 // Any leftover frames should be filled with zeros
2761 ma_uint32 leftoverFrameCount = subBufferSizeInFrames - framesToWrite;
2762
2763 if (leftoverFrameCount > 0) memset(subBuffer + bytesToWrite, 0, leftoverFrameCount*stream.channels*(stream.sampleSize/8));
2764
2765 stream.buffer->isSubBufferProcessed[subBufferToUpdate] = false;
2766 }
2767 else TRACELOG(LOG_WARNING, "STREAM: Attempting to write too many frames to buffer");
2768 }
2769 else TRACELOG(LOG_WARNING, "STREAM: Buffer not available for updating");
2770 }
2771}
2772
2773// Some required functions for audio standalone module version
2774#if defined(RAUDIO_STANDALONE)
2775// Check file extension
2776static bool IsFileExtension(const char *fileName, const char *ext)
2777{
2778 bool result = false;
2779 const char *fileExt;
2780
2781 if ((fileExt = strrchr(fileName, '.')) != NULL)
2782 {
2783 if (strcmp(fileExt, ext) == 0) result = true;
2784 }
2785
2786 return result;
2787}
2788
2789// Get pointer to extension for a filename string (includes the dot: .png)
2790static const char *GetFileExtension(const char *fileName)
2791{
2792 const char *dot = strrchr(fileName, '.');
2793
2794 if (!dot || dot == fileName) return NULL;
2795
2796 return dot;
2797}
2798
2799// String pointer reverse break: returns right-most occurrence of charset in text
2800static const char *strprbrk(const char *text, const char *charset)
2801{
2802 const char *latestMatch = NULL;
2803
2804 for (; (text != NULL) && (text = strpbrk(text, charset)); latestMatch = text++) { }
2805
2806 return latestMatch;
2807}
2808
2809// Get pointer to filename for a path string
2810static const char *GetFileName(const char *filePath)
2811{
2812 const char *fileName = NULL;
2813 if (filePath != NULL) fileName = strprbrk(filePath, "\\/");
2814
2815 if (!fileName) return filePath;
2816
2817 return fileName + 1;
2818}
2819
2820// Get filename string without extension (uses static string)
2821static const char *GetFileNameWithoutExt(const char *filePath)
2822{
2823 #define MAX_FILENAMEWITHOUTEXT_LENGTH 256
2824
2825 static char fileName[MAX_FILENAMEWITHOUTEXT_LENGTH] = { 0 };
2826 memset(fileName, 0, MAX_FILENAMEWITHOUTEXT_LENGTH);
2827
2828 if (filePath != NULL) strncpy(fileName, GetFileName(filePath), MAX_FILENAMEWITHOUTEXT_LENGTH - 1); // Get filename with extension
2829
2830 int fileNameLength = (int)strlen(fileName); // Get size in bytes
2831
2832 for (int i = 0; (i < fileNameLength) && (i < MAX_FILENAMEWITHOUTEXT_LENGTH); i++)
2833 {
2834 if (fileName[i] == '.')
2835 {
2836 // NOTE: Break on first '.' found
2837 fileName[i] = '\0';
2838 break;
2839 }
2840 }
2841
2842 return fileName;
2843}
2844
2845// Load data from file into a buffer
2846static unsigned char *LoadFileData(const char *fileName, int *dataSize)
2847{
2848 unsigned char *data = NULL;
2849 *dataSize = 0;
2850
2851 if (fileName != NULL)
2852 {
2853 FILE *file = fopen(fileName, "rb");
2854
2855 if (file != NULL)
2856 {
2857 // WARNING: On binary streams SEEK_END could not be found,
2858 // using fseek() and ftell() could not work in some (rare) cases
2859 fseek(file, 0, SEEK_END);
2860 int size = ftell(file);
2861 fseek(file, 0, SEEK_SET);
2862
2863 if (size > 0)
2864 {
2865 data = (unsigned char *)RL_MALLOC(size*sizeof(unsigned char));
2866
2867 // NOTE: fread() returns number of read elements instead of bytes, so reading [1 byte, size elements]
2868 unsigned int count = (unsigned int)fread(data, sizeof(unsigned char), size, file);
2869 *dataSize = count;
2870
2871 if (count != size) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially loaded", fileName);
2872 else TRACELOG(LOG_INFO, "FILEIO: [%s] File loaded successfully", fileName);
2873 }
2874 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to read file", fileName);
2875
2876 fclose(file);
2877 }
2878 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName);
2879 }
2880 else TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
2881
2882 return data;
2883}
2884
2885// Save data to file from buffer
2886static bool SaveFileData(const char *fileName, void *data, int dataSize)
2887{
2888 bool result = true;
2889
2890 if (fileName != NULL)
2891 {
2892 FILE *file = fopen(fileName, "wb");
2893
2894 if (file != NULL)
2895 {
2896 unsigned int count = (unsigned int)fwrite(data, sizeof(unsigned char), dataSize, file);
2897
2898 if (count == 0) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to write file", fileName);
2899 else if (count != dataSize) TRACELOG(LOG_WARNING, "FILEIO: [%s] File partially written", fileName);
2900 else TRACELOG(LOG_INFO, "FILEIO: [%s] File saved successfully", fileName);
2901
2902 fclose(file);
2903 }
2904 else
2905 {
2906 TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open file", fileName);
2907 result = false;
2908 }
2909 }
2910 else
2911 {
2912 TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
2913 result = false;
2914 }
2915
2916 return result;
2917}
2918
2919// Save text data to file (write), string must be '\0' terminated
2920static bool SaveFileText(const char *fileName, char *text)
2921{
2922 bool result = true;
2923
2924 if (fileName != NULL)
2925 {
2926 FILE *file = fopen(fileName, "wt");
2927
2928 if (file != NULL)
2929 {
2930 int count = 0;
2931 if (text != NULL) count = fprintf(file, "%s", text);
2932
2933 if (count == 0) TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to write text file", fileName);
2934 else TRACELOG(LOG_INFO, "FILEIO: [%s] Text file saved successfully", fileName);
2935
2936 fclose(file);
2937 }
2938 else
2939 {
2940 TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to open text file", fileName);
2941 result = false;
2942 }
2943 }
2944 else
2945 {
2946 TRACELOG(LOG_WARNING, "FILEIO: File name provided is not valid");
2947 result = false;
2948 }
2949
2950 return result;
2951}
2952#endif
2953
2954#undef AudioBuffer
2955
2956#endif // SUPPORT_MODULE_RAUDIO