aboutsummaryrefslogtreecommitdiff
path: root/src/cube_generic.h
diff options
context:
space:
mode:
Diffstat (limited to '')
0 files changed, 0 insertions, 0 deletions

Generated with cgit - Back to sebastiano.tronto.net

th: 0.0%;'/>
1 files changed, 92633 insertions, 0 deletions
diff --git a/raylib/src/external/miniaudio.h b/raylib/src/external/miniaudio.h
new file mode 100644
index 0000000..ad11333
--- /dev/null
+++ b/raylib/src/external/miniaudio.h
@@ -0,0 +1,92633 @@
1/*
2Audio playback and capture library. Choice of public domain or MIT-0. See license statements at the end of this file.
3miniaudio - v0.11.21 - 2023-11-15
4
5David Reid - mackron@gmail.com
6
7Website: https://miniaud.io
8Documentation: https://miniaud.io/docs
9GitHub: https://github.com/mackron/miniaudio
10*/
11
12/*
131. Introduction
14===============
15miniaudio is a single file library for audio playback and capture. To use it, do the following in
16one .c file:
17
18 ```c
19 #define MINIAUDIO_IMPLEMENTATION
20 #include "miniaudio.h"
21 ```
22
23You can do `#include "miniaudio.h"` in other parts of the program just like any other header.
24
25miniaudio includes both low level and high level APIs. The low level API is good for those who want
26to do all of their mixing themselves and only require a light weight interface to the underlying
27audio device. The high level API is good for those who have complex mixing and effect requirements.
28
29In miniaudio, objects are transparent structures. Unlike many other libraries, there are no handles
30to opaque objects which means you need to allocate memory for objects yourself. In the examples
31presented in this documentation you will often see objects declared on the stack. You need to be
32careful when translating these examples to your own code so that you don't accidentally declare
33your objects on the stack and then cause them to become invalid once the function returns. In
34addition, you must ensure the memory address of your objects remain the same throughout their
35lifetime. You therefore cannot be making copies of your objects.
36
37A config/init pattern is used throughout the entire library. The idea is that you set up a config
38object and pass that into the initialization routine. The advantage to this system is that the
39config object can be initialized with logical defaults and new properties added to it without
40breaking the API. The config object can be allocated on the stack and does not need to be
41maintained after initialization of the corresponding object.
42
43
441.1. Low Level API
45------------------
46The low level API gives you access to the raw audio data of an audio device. It supports playback,
47capture, full-duplex and loopback (WASAPI only). You can enumerate over devices to determine which
48physical device(s) you want to connect to.
49
50The low level API uses the concept of a "device" as the abstraction for physical devices. The idea
51is that you choose a physical device to emit or capture audio from, and then move data to/from the
52device when miniaudio tells you to. Data is delivered to and from devices asynchronously via a
53callback which you specify when initializing the device.
54
55When initializing the device you first need to configure it. The device configuration allows you to
56specify things like the format of the data delivered via the callback, the size of the internal
57buffer and the ID of the device you want to emit or capture audio from.
58
59Once you have the device configuration set up you can initialize the device. When initializing a
60device you need to allocate memory for the device object beforehand. This gives the application
61complete control over how the memory is allocated. In the example below we initialize a playback
62device on the stack, but you could allocate it on the heap if that suits your situation better.
63
64 ```c
65 void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
66 {
67 // In playback mode copy data to pOutput. In capture mode read data from pInput. In full-duplex mode, both
68 // pOutput and pInput will be valid and you can move data from pInput into pOutput. Never process more than
69 // frameCount frames.
70 }
71
72 int main()
73 {
74 ma_device_config config = ma_device_config_init(ma_device_type_playback);
75 config.playback.format = ma_format_f32; // Set to ma_format_unknown to use the device's native format.
76 config.playback.channels = 2; // Set to 0 to use the device's native channel count.
77 config.sampleRate = 48000; // Set to 0 to use the device's native sample rate.
78 config.dataCallback = data_callback; // This function will be called when miniaudio needs more data.
79 config.pUserData = pMyCustomData; // Can be accessed from the device object (device.pUserData).
80
81 ma_device device;
82 if (ma_device_init(NULL, &config, &device) != MA_SUCCESS) {
83 return -1; // Failed to initialize the device.
84 }
85
86 ma_device_start(&device); // The device is sleeping by default so you'll need to start it manually.
87
88 // Do something here. Probably your program's main loop.
89
90 ma_device_uninit(&device);
91 return 0;
92 }
93 ```
94
95In the example above, `data_callback()` is where audio data is written and read from the device.
96The idea is in playback mode you cause sound to be emitted from the speakers by writing audio data
97to the output buffer (`pOutput` in the example). In capture mode you read data from the input
98buffer (`pInput`) to extract sound captured by the microphone. The `frameCount` parameter tells you
99how many frames can be written to the output buffer and read from the input buffer. A "frame" is
100one sample for each channel. For example, in a stereo stream (2 channels), one frame is 2
101samples: one for the left, one for the right. The channel count is defined by the device config.
102The size in bytes of an individual sample is defined by the sample format which is also specified
103in the device config. Multi-channel audio data is always interleaved, which means the samples for
104each frame are stored next to each other in memory. For example, in a stereo stream the first pair
105of samples will be the left and right samples for the first frame, the second pair of samples will
106be the left and right samples for the second frame, etc.
107
108The configuration of the device is defined by the `ma_device_config` structure. The config object
109is always initialized with `ma_device_config_init()`. It's important to always initialize the
110config with this function as it initializes it with logical defaults and ensures your program
111doesn't break when new members are added to the `ma_device_config` structure. The example above
112uses a fairly simple and standard device configuration. The call to `ma_device_config_init()` takes
113a single parameter, which is whether or not the device is a playback, capture, duplex or loopback
114device (loopback devices are not supported on all backends). The `config.playback.format` member
115sets the sample format which can be one of the following (all formats are native-endian):
116
117 +---------------+----------------------------------------+---------------------------+
118 | Symbol | Description | Range |
119 +---------------+----------------------------------------+---------------------------+
120 | ma_format_f32 | 32-bit floating point | [-1, 1] |
121 | ma_format_s16 | 16-bit signed integer | [-32768, 32767] |
122 | ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] |
123 | ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] |
124 | ma_format_u8 | 8-bit unsigned integer | [0, 255] |
125 +---------------+----------------------------------------+---------------------------+
126
127The `config.playback.channels` member sets the number of channels to use with the device. The
128channel count cannot exceed MA_MAX_CHANNELS. The `config.sampleRate` member sets the sample rate
129(which must be the same for both playback and capture in full-duplex configurations). This is
130usually set to 44100 or 48000, but can be set to anything. It's recommended to keep this between
1318000 and 384000, however.
132
133Note that leaving the format, channel count and/or sample rate at their default values will result
134in the internal device's native configuration being used which is useful if you want to avoid the
135overhead of miniaudio's automatic data conversion.
136
137In addition to the sample format, channel count and sample rate, the data callback and user data
138pointer are also set via the config. The user data pointer is not passed into the callback as a
139parameter, but is instead set to the `pUserData` member of `ma_device` which you can access
140directly since all miniaudio structures are transparent.
141
142Initializing the device is done with `ma_device_init()`. This will return a result code telling you
143what went wrong, if anything. On success it will return `MA_SUCCESS`. After initialization is
144complete the device will be in a stopped state. To start it, use `ma_device_start()`.
145Uninitializing the device will stop it, which is what the example above does, but you can also stop
146the device with `ma_device_stop()`. To resume the device simply call `ma_device_start()` again.
147Note that it's important to never stop or start the device from inside the callback. This will
148result in a deadlock. Instead you set a variable or signal an event indicating that the device
149needs to stop and handle it in a different thread. The following APIs must never be called inside
150the callback:
151
152 ```c
153 ma_device_init()
154 ma_device_init_ex()
155 ma_device_uninit()
156 ma_device_start()
157 ma_device_stop()
158 ```
159
160You must never try uninitializing and reinitializing a device inside the callback. You must also
161never try to stop and start it from inside the callback. There are a few other things you shouldn't
162do in the callback depending on your requirements, however this isn't so much a thread-safety
163thing, but rather a real-time processing thing which is beyond the scope of this introduction.
164
165The example above demonstrates the initialization of a playback device, but it works exactly the
166same for capture. All you need to do is change the device type from `ma_device_type_playback` to
167`ma_device_type_capture` when setting up the config, like so:
168
169 ```c
170 ma_device_config config = ma_device_config_init(ma_device_type_capture);
171 config.capture.format = MY_FORMAT;
172 config.capture.channels = MY_CHANNEL_COUNT;
173 ```
174
175In the data callback you just read from the input buffer (`pInput` in the example above) and leave
176the output buffer alone (it will be set to NULL when the device type is set to
177`ma_device_type_capture`).
178
179These are the available device types and how you should handle the buffers in the callback:
180
181 +-------------------------+--------------------------------------------------------+
182 | Device Type | Callback Behavior |
183 +-------------------------+--------------------------------------------------------+
184 | ma_device_type_playback | Write to output buffer, leave input buffer untouched. |
185 | ma_device_type_capture | Read from input buffer, leave output buffer untouched. |
186 | ma_device_type_duplex | Read from input buffer, write to output buffer. |
187 | ma_device_type_loopback | Read from input buffer, leave output buffer untouched. |
188 +-------------------------+--------------------------------------------------------+
189
190You will notice in the example above that the sample format and channel count is specified
191separately for playback and capture. This is to support different data formats between the playback
192and capture devices in a full-duplex system. An example may be that you want to capture audio data
193as a monaural stream (one channel), but output sound to a stereo speaker system. Note that if you
194use different formats between playback and capture in a full-duplex configuration you will need to
195convert the data yourself. There are functions available to help you do this which will be
196explained later.
197
198The example above did not specify a physical device to connect to which means it will use the
199operating system's default device. If you have multiple physical devices connected and you want to
200use a specific one you will need to specify the device ID in the configuration, like so:
201
202 ```c
203 config.playback.pDeviceID = pMyPlaybackDeviceID; // Only if requesting a playback or duplex device.
204 config.capture.pDeviceID = pMyCaptureDeviceID; // Only if requesting a capture, duplex or loopback device.
205 ```
206
207To retrieve the device ID you will need to perform device enumeration, however this requires the
208use of a new concept called the "context". Conceptually speaking the context sits above the device.
209There is one context to many devices. The purpose of the context is to represent the backend at a
210more global level and to perform operations outside the scope of an individual device. Mainly it is
211used for performing run-time linking against backend libraries, initializing backends and
212enumerating devices. The example below shows how to enumerate devices.
213
214 ```c
215 ma_context context;
216 if (ma_context_init(NULL, 0, NULL, &context) != MA_SUCCESS) {
217 // Error.
218 }
219
220 ma_device_info* pPlaybackInfos;
221 ma_uint32 playbackCount;
222 ma_device_info* pCaptureInfos;
223 ma_uint32 captureCount;
224 if (ma_context_get_devices(&context, &pPlaybackInfos, &playbackCount, &pCaptureInfos, &captureCount) != MA_SUCCESS) {
225 // Error.
226 }
227
228 // Loop over each device info and do something with it. Here we just print the name with their index. You may want
229 // to give the user the opportunity to choose which device they'd prefer.
230 for (ma_uint32 iDevice = 0; iDevice < playbackCount; iDevice += 1) {
231 printf("%d - %s\n", iDevice, pPlaybackInfos[iDevice].name);
232 }
233
234 ma_device_config config = ma_device_config_init(ma_device_type_playback);
235 config.playback.pDeviceID = &pPlaybackInfos[chosenPlaybackDeviceIndex].id;
236 config.playback.format = MY_FORMAT;
237 config.playback.channels = MY_CHANNEL_COUNT;
238 config.sampleRate = MY_SAMPLE_RATE;
239 config.dataCallback = data_callback;
240 config.pUserData = pMyCustomData;
241
242 ma_device device;
243 if (ma_device_init(&context, &config, &device) != MA_SUCCESS) {
244 // Error
245 }
246
247 ...
248
249 ma_device_uninit(&device);
250 ma_context_uninit(&context);
251 ```
252
253The first thing we do in this example is initialize a `ma_context` object with `ma_context_init()`.
254The first parameter is a pointer to a list of `ma_backend` values which are used to override the
255default backend priorities. When this is NULL, as in this example, miniaudio's default priorities
256are used. The second parameter is the number of backends listed in the array pointed to by the
257first parameter. The third parameter is a pointer to a `ma_context_config` object which can be
258NULL, in which case defaults are used. The context configuration is used for setting the logging
259callback, custom memory allocation callbacks, user-defined data and some backend-specific
260configurations.
261
262Once the context has been initialized you can enumerate devices. In the example above we use the
263simpler `ma_context_get_devices()`, however you can also use a callback for handling devices by
264using `ma_context_enumerate_devices()`. When using `ma_context_get_devices()` you provide a pointer
265to a pointer that will, upon output, be set to a pointer to a buffer containing a list of
266`ma_device_info` structures. You also provide a pointer to an unsigned integer that will receive
267the number of items in the returned buffer. Do not free the returned buffers as their memory is
268managed internally by miniaudio.
269
270The `ma_device_info` structure contains an `id` member which is the ID you pass to the device
271config. It also contains the name of the device which is useful for presenting a list of devices
272to the user via the UI.
273
274When creating your own context you will want to pass it to `ma_device_init()` when initializing the
275device. Passing in NULL, like we do in the first example, will result in miniaudio creating the
276context for you, which you don't want to do since you've already created a context. Note that
277internally the context is only tracked by it's pointer which means you must not change the location
278of the `ma_context` object. If this is an issue, consider using `malloc()` to allocate memory for
279the context.
280
281
2821.2. High Level API
283-------------------
284The high level API consists of three main parts:
285
286 * Resource management for loading and streaming sounds.
287 * A node graph for advanced mixing and effect processing.
288 * A high level "engine" that wraps around the resource manager and node graph.
289
290The resource manager (`ma_resource_manager`) is used for loading sounds. It supports loading sounds
291fully into memory and also streaming. It will also deal with reference counting for you which
292avoids the same sound being loaded multiple times.
293
294The node graph is used for mixing and effect processing. The idea is that you connect a number of
295nodes into the graph by connecting each node's outputs to another node's inputs. Each node can
296implement it's own effect. By chaining nodes together, advanced mixing and effect processing can
297be achieved.
298
299The engine encapsulates both the resource manager and the node graph to create a simple, easy to
300use high level API. The resource manager and node graph APIs are covered in more later sections of
301this manual.
302
303The code below shows how you can initialize an engine using it's default configuration.
304
305 ```c
306 ma_result result;
307 ma_engine engine;
308
309 result = ma_engine_init(NULL, &engine);
310 if (result != MA_SUCCESS) {
311 return result; // Failed to initialize the engine.
312 }
313 ```
314
315This creates an engine instance which will initialize a device internally which you can access with
316`ma_engine_get_device()`. It will also initialize a resource manager for you which can be accessed
317with `ma_engine_get_resource_manager()`. The engine itself is a node graph (`ma_node_graph`) which
318means you can pass a pointer to the engine object into any of the `ma_node_graph` APIs (with a
319cast). Alternatively, you can use `ma_engine_get_node_graph()` instead of a cast.
320
321Note that all objects in miniaudio, including the `ma_engine` object in the example above, are
322transparent structures. There are no handles to opaque structures in miniaudio which means you need
323to be mindful of how you declare them. In the example above we are declaring it on the stack, but
324this will result in the struct being invalidated once the function encapsulating it returns. If
325allocating the engine on the heap is more appropriate, you can easily do so with a standard call
326to `malloc()` or whatever heap allocation routine you like:
327
328 ```c
329 ma_engine* pEngine = malloc(sizeof(*pEngine));
330 ```
331
332The `ma_engine` API uses the same config/init pattern used all throughout miniaudio. To configure
333an engine, you can fill out a `ma_engine_config` object and pass it into the first parameter of
334`ma_engine_init()`:
335
336 ```c
337 ma_result result;
338 ma_engine engine;
339 ma_engine_config engineConfig;
340
341 engineConfig = ma_engine_config_init();
342 engineConfig.pResourceManager = &myCustomResourceManager; // <-- Initialized as some earlier stage.
343
344 result = ma_engine_init(&engineConfig, &engine);
345 if (result != MA_SUCCESS) {
346 return result;
347 }
348 ```
349
350This creates an engine instance using a custom config. In this particular example it's showing how
351you can specify a custom resource manager rather than having the engine initialize one internally.
352This is particularly useful if you want to have multiple engine's share the same resource manager.
353
354The engine must be uninitialized with `ma_engine_uninit()` when it's no longer needed.
355
356By default the engine will be started, but nothing will be playing because no sounds have been
357initialized. The easiest but least flexible way of playing a sound is like so:
358
359 ```c
360 ma_engine_play_sound(&engine, "my_sound.wav", NULL);
361 ```
362
363This plays what miniaudio calls an "inline" sound. It plays the sound once, and then puts the
364internal sound up for recycling. The last parameter is used to specify which sound group the sound
365should be associated with which will be explained later. This particular way of playing a sound is
366simple, but lacks flexibility and features. A more flexible way of playing a sound is to first
367initialize a sound:
368
369 ```c
370 ma_result result;
371 ma_sound sound;
372
373 result = ma_sound_init_from_file(&engine, "my_sound.wav", 0, NULL, NULL, &sound);
374 if (result != MA_SUCCESS) {
375 return result;
376 }
377
378 ma_sound_start(&sound);
379 ```
380
381This returns a `ma_sound` object which represents a single instance of the specified sound file. If
382you want to play the same file multiple times simultaneously, you need to create one sound for each
383instance.
384
385Sounds should be uninitialized with `ma_sound_uninit()`.
386
387Sounds are not started by default. Start a sound with `ma_sound_start()` and stop it with
388`ma_sound_stop()`. When a sound is stopped, it is not rewound to the start. Use
389`ma_sound_seek_to_pcm_frame(&sound, 0)` to seek back to the start of a sound. By default, starting
390and stopping sounds happens immediately, but sometimes it might be convenient to schedule the sound
391the be started and/or stopped at a specific time. This can be done with the following functions:
392
393 ```c
394 ma_sound_set_start_time_in_pcm_frames()
395 ma_sound_set_start_time_in_milliseconds()
396 ma_sound_set_stop_time_in_pcm_frames()
397 ma_sound_set_stop_time_in_milliseconds()
398 ```
399
400The start/stop time needs to be specified based on the absolute timer which is controlled by the
401engine. The current global time time in PCM frames can be retrieved with
402`ma_engine_get_time_in_pcm_frames()`. The engine's global time can be changed with
403`ma_engine_set_time_in_pcm_frames()` for synchronization purposes if required. Note that scheduling
404a start time still requires an explicit call to `ma_sound_start()` before anything will play:
405
406 ```c
407 ma_sound_set_start_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 2);
408 ma_sound_start(&sound);
409 ```
410
411The third parameter of `ma_sound_init_from_file()` is a set of flags that control how the sound be
412loaded and a few options on which features should be enabled for that sound. By default, the sound
413is synchronously loaded fully into memory straight from the file system without any kind of
414decoding. If you want to decode the sound before storing it in memory, you need to specify the
415`MA_SOUND_FLAG_DECODE` flag. This is useful if you want to incur the cost of decoding at an earlier
416stage, such as a loading stage. Without this option, decoding will happen dynamically at mixing
417time which might be too expensive on the audio thread.
418
419If you want to load the sound asynchronously, you can specify the `MA_SOUND_FLAG_ASYNC` flag. This
420will result in `ma_sound_init_from_file()` returning quickly, but the sound will not start playing
421until the sound has had some audio decoded.
422
423The fourth parameter is a pointer to sound group. A sound group is used as a mechanism to organise
424sounds into groups which have their own effect processing and volume control. An example is a game
425which might have separate groups for sfx, voice and music. Each of these groups have their own
426independent volume control. Use `ma_sound_group_init()` or `ma_sound_group_init_ex()` to initialize
427a sound group.
428
429Sounds and sound groups are nodes in the engine's node graph and can be plugged into any `ma_node`
430API. This makes it possible to connect sounds and sound groups to effect nodes to produce complex
431effect chains.
432
433A sound can have it's volume changed with `ma_sound_set_volume()`. If you prefer decibel volume
434control you can use `ma_volume_db_to_linear()` to convert from decibel representation to linear.
435
436Panning and pitching is supported with `ma_sound_set_pan()` and `ma_sound_set_pitch()`. If you know
437a sound will never have it's pitch changed with `ma_sound_set_pitch()` or via the doppler effect,
438you can specify the `MA_SOUND_FLAG_NO_PITCH` flag when initializing the sound for an optimization.
439
440By default, sounds and sound groups have spatialization enabled. If you don't ever want to
441spatialize your sounds, initialize the sound with the `MA_SOUND_FLAG_NO_SPATIALIZATION` flag. The
442spatialization model is fairly simple and is roughly on feature parity with OpenAL. HRTF and
443environmental occlusion are not currently supported, but planned for the future. The supported
444features include:
445
446 * Sound and listener positioning and orientation with cones
447 * Attenuation models: none, inverse, linear and exponential
448 * Doppler effect
449
450Sounds can be faded in and out with `ma_sound_set_fade_in_pcm_frames()`.
451
452To check if a sound is currently playing, you can use `ma_sound_is_playing()`. To check if a sound
453is at the end, use `ma_sound_at_end()`. Looping of a sound can be controlled with
454`ma_sound_set_looping()`. Use `ma_sound_is_looping()` to check whether or not the sound is looping.
455
456
457
4582. Building
459===========
460miniaudio should work cleanly out of the box without the need to download or install any
461dependencies. See below for platform-specific details.
462
463Note that GCC and Clang require `-msse2`, `-mavx2`, etc. for SIMD optimizations.
464
465If you get errors about undefined references to `__sync_val_compare_and_swap_8`, `__atomic_load_8`,
466etc. you need to link with `-latomic`.
467
468
4692.1. Windows
470------------
471The Windows build should compile cleanly on all popular compilers without the need to configure any
472include paths nor link to any libraries.
473
474The UWP build may require linking to mmdevapi.lib if you get errors about an unresolved external
475symbol for `ActivateAudioInterfaceAsync()`.
476
477
4782.2. macOS and iOS
479------------------
480The macOS build should compile cleanly without the need to download any dependencies nor link to
481any libraries or frameworks. The iOS build needs to be compiled as Objective-C and will need to
482link the relevant frameworks but should compile cleanly out of the box with Xcode. Compiling
483through the command line requires linking to `-lpthread` and `-lm`.
484
485Due to the way miniaudio links to frameworks at runtime, your application may not pass Apple's
486notarization process. To fix this there are two options. The first is to use the
487`MA_NO_RUNTIME_LINKING` option, like so:
488
489 ```c
490 #ifdef __APPLE__
491 #define MA_NO_RUNTIME_LINKING
492 #endif
493 #define MINIAUDIO_IMPLEMENTATION
494 #include "miniaudio.h"
495 ```
496
497This will require linking with `-framework CoreFoundation -framework CoreAudio -framework AudioToolbox`.
498If you get errors about AudioToolbox, try with `-framework AudioUnit` instead. You may get this when
499using older versions of iOS. Alternatively, if you would rather keep using runtime linking you can
500add the following to your entitlements.xcent file:
501
502 ```
503 <key>com.apple.security.cs.allow-dyld-environment-variables</key>
504 <true/>
505 <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
506 <true/>
507 ```
508
509See this discussion for more info: https://github.com/mackron/miniaudio/issues/203.
510
511
5122.3. Linux
513----------
514The Linux build only requires linking to `-ldl`, `-lpthread` and `-lm`. You do not need any
515development packages. You may need to link with `-latomic` if you're compiling for 32-bit ARM.
516
517
5182.4. BSD
519--------
520The BSD build only requires linking to `-lpthread` and `-lm`. NetBSD uses audio(4), OpenBSD uses
521sndio and FreeBSD uses OSS. You may need to link with `-latomic` if you're compiling for 32-bit
522ARM.
523
524
5252.5. Android
526------------
527AAudio is the highest priority backend on Android. This should work out of the box without needing
528any kind of compiler configuration. Support for AAudio starts with Android 8 which means older
529versions will fall back to OpenSL|ES which requires API level 16+.
530
531There have been reports that the OpenSL|ES backend fails to initialize on some Android based
532devices due to `dlopen()` failing to open "libOpenSLES.so". If this happens on your platform
533you'll need to disable run-time linking with `MA_NO_RUNTIME_LINKING` and link with -lOpenSLES.
534
535
5362.6. Emscripten
537---------------
538The Emscripten build emits Web Audio JavaScript directly and should compile cleanly out of the box.
539You cannot use `-std=c*` compiler flags, nor `-ansi`.
540
541You can enable the use of AudioWorkets by defining `MA_ENABLE_AUDIO_WORKLETS` and then compiling
542with the following options:
543
544 -sAUDIO_WORKLET=1 -sWASM_WORKERS=1 -sASYNCIFY
545
546An example for compiling with AudioWorklet support might look like this:
547
548 emcc program.c -o bin/program.html -DMA_ENABLE_AUDIO_WORKLETS -sAUDIO_WORKLET=1 -sWASM_WORKERS=1 -sASYNCIFY
549
550To run locally, you'll need to use emrun:
551
552 emrun bin/program.html
553
554
555
5562.7. Build Options
557------------------
558`#define` these options before including miniaudio.h.
559
560 +----------------------------------+--------------------------------------------------------------------+
561 | Option | Description |
562 +----------------------------------+--------------------------------------------------------------------+
563 | MA_NO_WASAPI | Disables the WASAPI backend. |
564 +----------------------------------+--------------------------------------------------------------------+
565 | MA_NO_DSOUND | Disables the DirectSound backend. |
566 +----------------------------------+--------------------------------------------------------------------+
567 | MA_NO_WINMM | Disables the WinMM backend. |
568 +----------------------------------+--------------------------------------------------------------------+
569 | MA_NO_ALSA | Disables the ALSA backend. |
570 +----------------------------------+--------------------------------------------------------------------+
571 | MA_NO_PULSEAUDIO | Disables the PulseAudio backend. |
572 +----------------------------------+--------------------------------------------------------------------+
573 | MA_NO_JACK | Disables the JACK backend. |
574 +----------------------------------+--------------------------------------------------------------------+
575 | MA_NO_COREAUDIO | Disables the Core Audio backend. |
576 +----------------------------------+--------------------------------------------------------------------+
577 | MA_NO_SNDIO | Disables the sndio backend. |
578 +----------------------------------+--------------------------------------------------------------------+
579 | MA_NO_AUDIO4 | Disables the audio(4) backend. |
580 +----------------------------------+--------------------------------------------------------------------+
581 | MA_NO_OSS | Disables the OSS backend. |
582 +----------------------------------+--------------------------------------------------------------------+
583 | MA_NO_AAUDIO | Disables the AAudio backend. |
584 +----------------------------------+--------------------------------------------------------------------+
585 | MA_NO_OPENSL | Disables the OpenSL|ES backend. |
586 +----------------------------------+--------------------------------------------------------------------+
587 | MA_NO_WEBAUDIO | Disables the Web Audio backend. |
588 +----------------------------------+--------------------------------------------------------------------+
589 | MA_NO_NULL | Disables the null backend. |
590 +----------------------------------+--------------------------------------------------------------------+
591 | MA_ENABLE_ONLY_SPECIFIC_BACKENDS | Disables all backends by default and requires `MA_ENABLE_*` to |
592 | | enable specific backends. |
593 +----------------------------------+--------------------------------------------------------------------+
594 | MA_ENABLE_WASAPI | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
595 | | enable the WASAPI backend. |
596 +----------------------------------+--------------------------------------------------------------------+
597 | MA_ENABLE_DSOUND | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
598 | | enable the DirectSound backend. |
599 +----------------------------------+--------------------------------------------------------------------+
600 | MA_ENABLE_WINMM | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
601 | | enable the WinMM backend. |
602 +----------------------------------+--------------------------------------------------------------------+
603 | MA_ENABLE_ALSA | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
604 | | enable the ALSA backend. |
605 +----------------------------------+--------------------------------------------------------------------+
606 | MA_ENABLE_PULSEAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
607 | | enable the PulseAudio backend. |
608 +----------------------------------+--------------------------------------------------------------------+
609 | MA_ENABLE_JACK | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
610 | | enable the JACK backend. |
611 +----------------------------------+--------------------------------------------------------------------+
612 | MA_ENABLE_COREAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
613 | | enable the Core Audio backend. |
614 +----------------------------------+--------------------------------------------------------------------+
615 | MA_ENABLE_SNDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
616 | | enable the sndio backend. |
617 +----------------------------------+--------------------------------------------------------------------+
618 | MA_ENABLE_AUDIO4 | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
619 | | enable the audio(4) backend. |
620 +----------------------------------+--------------------------------------------------------------------+
621 | MA_ENABLE_OSS | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
622 | | enable the OSS backend. |
623 +----------------------------------+--------------------------------------------------------------------+
624 | MA_ENABLE_AAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
625 | | enable the AAudio backend. |
626 +----------------------------------+--------------------------------------------------------------------+
627 | MA_ENABLE_OPENSL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
628 | | enable the OpenSL|ES backend. |
629 +----------------------------------+--------------------------------------------------------------------+
630 | MA_ENABLE_WEBAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
631 | | enable the Web Audio backend. |
632 +----------------------------------+--------------------------------------------------------------------+
633 | MA_ENABLE_NULL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
634 | | enable the null backend. |
635 +----------------------------------+--------------------------------------------------------------------+
636 | MA_NO_DECODING | Disables decoding APIs. |
637 +----------------------------------+--------------------------------------------------------------------+
638 | MA_NO_ENCODING | Disables encoding APIs. |
639 +----------------------------------+--------------------------------------------------------------------+
640 | MA_NO_WAV | Disables the built-in WAV decoder and encoder. |
641 +----------------------------------+--------------------------------------------------------------------+
642 | MA_NO_FLAC | Disables the built-in FLAC decoder. |
643 +----------------------------------+--------------------------------------------------------------------+
644 | MA_NO_MP3 | Disables the built-in MP3 decoder. |
645 +----------------------------------+--------------------------------------------------------------------+
646 | MA_NO_DEVICE_IO | Disables playback and recording. This will disable `ma_context` |
647 | | and `ma_device` APIs. This is useful if you only want to use |
648 | | miniaudio's data conversion and/or decoding APIs. |
649 +----------------------------------+--------------------------------------------------------------------+
650 | MA_NO_RESOURCE_MANAGER | Disables the resource manager. When using the engine this will |
651 | | also disable the following functions: |
652 | | |
653 | | ``` |
654 | | ma_sound_init_from_file() |
655 | | ma_sound_init_from_file_w() |
656 | | ma_sound_init_copy() |
657 | | ma_engine_play_sound_ex() |
658 | | ma_engine_play_sound() |
659 | | ``` |
660 | | |
661 | | The only way to initialize a `ma_sound` object is to initialize it |
662 | | from a data source. |
663 +----------------------------------+--------------------------------------------------------------------+
664 | MA_NO_NODE_GRAPH | Disables the node graph API. This will also disable the engine API |
665 | | because it depends on the node graph. |
666 +----------------------------------+--------------------------------------------------------------------+
667 | MA_NO_ENGINE | Disables the engine API. |
668 +----------------------------------+--------------------------------------------------------------------+
669 | MA_NO_THREADING | Disables the `ma_thread`, `ma_mutex`, `ma_semaphore` and |
670 | | `ma_event` APIs. This option is useful if you only need to use |
671 | | miniaudio for data conversion, decoding and/or encoding. Some |
672 | | families of APIs require threading which means the following |
673 | | options must also be set: |
674 | | |
675 | | ``` |
676 | | MA_NO_DEVICE_IO |
677 | | ``` |
678 +----------------------------------+--------------------------------------------------------------------+
679 | MA_NO_GENERATION | Disables generation APIs such a `ma_waveform` and `ma_noise`. |
680 +----------------------------------+--------------------------------------------------------------------+
681 | MA_NO_SSE2 | Disables SSE2 optimizations. |
682 +----------------------------------+--------------------------------------------------------------------+
683 | MA_NO_AVX2 | Disables AVX2 optimizations. |
684 +----------------------------------+--------------------------------------------------------------------+
685 | MA_NO_NEON | Disables NEON optimizations. |
686 +----------------------------------+--------------------------------------------------------------------+
687 | MA_NO_RUNTIME_LINKING | Disables runtime linking. This is useful for passing Apple's |
688 | | notarization process. When enabling this, you may need to avoid |
689 | | using `-std=c89` or `-std=c99` on Linux builds or else you may end |
690 | | up with compilation errors due to conflicts with `timespec` and |
691 | | `timeval` data types. |
692 | | |
693 | | You may need to enable this if your target platform does not allow |
694 | | runtime linking via `dlopen()`. |
695 +----------------------------------+--------------------------------------------------------------------+
696 | MA_DEBUG_OUTPUT | Enable `printf()` output of debug logs (`MA_LOG_LEVEL_DEBUG`). |
697 +----------------------------------+--------------------------------------------------------------------+
698 | MA_COINIT_VALUE | Windows only. The value to pass to internal calls to |
699 | | `CoInitializeEx()`. Defaults to `COINIT_MULTITHREADED`. |
700 +----------------------------------+--------------------------------------------------------------------+
701 | MA_API | Controls how public APIs should be decorated. Default is `extern`. |
702 +----------------------------------+--------------------------------------------------------------------+
703
704
7053. Definitions
706==============
707This section defines common terms used throughout miniaudio. Unfortunately there is often ambiguity
708in the use of terms throughout the audio space, so this section is intended to clarify how miniaudio
709uses each term.
710
7113.1. Sample
712-----------
713A sample is a single unit of audio data. If the sample format is f32, then one sample is one 32-bit
714floating point number.
715
7163.2. Frame / PCM Frame
717----------------------
718A frame is a group of samples equal to the number of channels. For a stereo stream a frame is 2
719samples, a mono frame is 1 sample, a 5.1 surround sound frame is 6 samples, etc. The terms "frame"
720and "PCM frame" are the same thing in miniaudio. Note that this is different to a compressed frame.
721If ever miniaudio needs to refer to a compressed frame, such as a FLAC frame, it will always
722clarify what it's referring to with something like "FLAC frame".
723
7243.3. Channel
725------------
726A stream of monaural audio that is emitted from an individual speaker in a speaker system, or
727received from an individual microphone in a microphone system. A stereo stream has two channels (a
728left channel, and a right channel), a 5.1 surround sound system has 6 channels, etc. Some audio
729systems refer to a channel as a complex audio stream that's mixed with other channels to produce
730the final mix - this is completely different to miniaudio's use of the term "channel" and should
731not be confused.
732
7333.4. Sample Rate
734----------------
735The sample rate in miniaudio is always expressed in Hz, such as 44100, 48000, etc. It's the number
736of PCM frames that are processed per second.
737
7383.5. Formats
739------------
740Throughout miniaudio you will see references to different sample formats:
741
742 +---------------+----------------------------------------+---------------------------+
743 | Symbol | Description | Range |
744 +---------------+----------------------------------------+---------------------------+
745 | ma_format_f32 | 32-bit floating point | [-1, 1] |
746 | ma_format_s16 | 16-bit signed integer | [-32768, 32767] |
747 | ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] |
748 | ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] |
749 | ma_format_u8 | 8-bit unsigned integer | [0, 255] |
750 +---------------+----------------------------------------+---------------------------+
751
752All formats are native-endian.
753
754
755
7564. Data Sources
757===============
758The data source abstraction in miniaudio is used for retrieving audio data from some source. A few
759examples include `ma_decoder`, `ma_noise` and `ma_waveform`. You will need to be familiar with data
760sources in order to make sense of some of the higher level concepts in miniaudio.
761
762The `ma_data_source` API is a generic interface for reading from a data source. Any object that
763implements the data source interface can be plugged into any `ma_data_source` function.
764
765To read data from a data source:
766
767 ```c
768 ma_result result;
769 ma_uint64 framesRead;
770
771 result = ma_data_source_read_pcm_frames(pDataSource, pFramesOut, frameCount, &framesRead);
772 if (result != MA_SUCCESS) {
773 return result; // Failed to read data from the data source.
774 }
775 ```
776
777If you don't need the number of frames that were successfully read you can pass in `NULL` to the
778`pFramesRead` parameter. If this returns a value less than the number of frames requested it means
779the end of the file has been reached. `MA_AT_END` will be returned only when the number of frames
780read is 0.
781
782When calling any data source function, with the exception of `ma_data_source_init()` and
783`ma_data_source_uninit()`, you can pass in any object that implements a data source. For example,
784you could plug in a decoder like so:
785
786 ```c
787 ma_result result;
788 ma_uint64 framesRead;
789 ma_decoder decoder; // <-- This would be initialized with `ma_decoder_init_*()`.
790
791 result = ma_data_source_read_pcm_frames(&decoder, pFramesOut, frameCount, &framesRead);
792 if (result != MA_SUCCESS) {
793 return result; // Failed to read data from the decoder.
794 }
795 ```
796
797If you want to seek forward you can pass in `NULL` to the `pFramesOut` parameter. Alternatively you
798can use `ma_data_source_seek_pcm_frames()`.
799
800To seek to a specific PCM frame:
801
802 ```c
803 result = ma_data_source_seek_to_pcm_frame(pDataSource, frameIndex);
804 if (result != MA_SUCCESS) {
805 return result; // Failed to seek to PCM frame.
806 }
807 ```
808
809You can retrieve the total length of a data source in PCM frames, but note that some data sources
810may not have the notion of a length, such as noise and waveforms, and others may just not have a
811way of determining the length such as some decoders. To retrieve the length:
812
813 ```c
814 ma_uint64 length;
815
816 result = ma_data_source_get_length_in_pcm_frames(pDataSource, &length);
817 if (result != MA_SUCCESS) {
818 return result; // Failed to retrieve the length.
819 }
820 ```
821
822Care should be taken when retrieving the length of a data source where the underlying decoder is
823pulling data from a data stream with an undefined length, such as internet radio or some kind of
824broadcast. If you do this, `ma_data_source_get_length_in_pcm_frames()` may never return.
825
826The current position of the cursor in PCM frames can also be retrieved:
827
828 ```c
829 ma_uint64 cursor;
830
831 result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &cursor);
832 if (result != MA_SUCCESS) {
833 return result; // Failed to retrieve the cursor.
834 }
835 ```
836
837You will often need to know the data format that will be returned after reading. This can be
838retrieved like so:
839
840 ```c
841 ma_format format;
842 ma_uint32 channels;
843 ma_uint32 sampleRate;
844 ma_channel channelMap[MA_MAX_CHANNELS];
845
846 result = ma_data_source_get_data_format(pDataSource, &format, &channels, &sampleRate, channelMap, MA_MAX_CHANNELS);
847 if (result != MA_SUCCESS) {
848 return result; // Failed to retrieve data format.
849 }
850 ```
851
852If you do not need a specific data format property, just pass in NULL to the respective parameter.
853
854There may be cases where you want to implement something like a sound bank where you only want to
855read data within a certain range of the underlying data. To do this you can use a range:
856
857 ```c
858 result = ma_data_source_set_range_in_pcm_frames(pDataSource, rangeBegInFrames, rangeEndInFrames);
859 if (result != MA_SUCCESS) {
860 return result; // Failed to set the range.
861 }
862 ```
863
864This is useful if you have a sound bank where many sounds are stored in the same file and you want
865the data source to only play one of those sub-sounds. Note that once the range is set, everything
866that takes a position, such as cursors and loop points, should always be relatvie to the start of
867the range. When the range is set, any previously defined loop point will be reset.
868
869Custom loop points can also be used with data sources. By default, data sources will loop after
870they reach the end of the data source, but if you need to loop at a specific location, you can do
871the following:
872
873 ```c
874 result = ma_data_set_loop_point_in_pcm_frames(pDataSource, loopBegInFrames, loopEndInFrames);
875 if (result != MA_SUCCESS) {
876 return result; // Failed to set the loop point.
877 }
878 ```
879
880The loop point is relative to the current range.
881
882It's sometimes useful to chain data sources together so that a seamless transition can be achieved.
883To do this, you can use chaining:
884
885 ```c
886 ma_decoder decoder1;
887 ma_decoder decoder2;
888
889 // ... initialize decoders with ma_decoder_init_*() ...
890
891 result = ma_data_source_set_next(&decoder1, &decoder2);
892 if (result != MA_SUCCESS) {
893 return result; // Failed to set the next data source.
894 }
895
896 result = ma_data_source_read_pcm_frames(&decoder1, pFramesOut, frameCount, pFramesRead);
897 if (result != MA_SUCCESS) {
898 return result; // Failed to read from the decoder.
899 }
900 ```
901
902In the example above we're using decoders. When reading from a chain, you always want to read from
903the top level data source in the chain. In the example above, `decoder1` is the top level data
904source in the chain. When `decoder1` reaches the end, `decoder2` will start seamlessly without any
905gaps.
906
907Note that when looping is enabled, only the current data source will be looped. You can loop the
908entire chain by linking in a loop like so:
909
910 ```c
911 ma_data_source_set_next(&decoder1, &decoder2); // decoder1 -> decoder2
912 ma_data_source_set_next(&decoder2, &decoder1); // decoder2 -> decoder1 (loop back to the start).
913 ```
914
915Note that setting up chaining is not thread safe, so care needs to be taken if you're dynamically
916changing links while the audio thread is in the middle of reading.
917
918Do not use `ma_decoder_seek_to_pcm_frame()` as a means to reuse a data source to play multiple
919instances of the same sound simultaneously. This can be extremely inefficient depending on the type
920of data source and can result in glitching due to subtle changes to the state of internal filters.
921Instead, initialize multiple data sources for each instance.
922
923
9244.1. Custom Data Sources
925------------------------
926You can implement a custom data source by implementing the functions in `ma_data_source_vtable`.
927Your custom object must have `ma_data_source_base` as it's first member:
928
929 ```c
930 struct my_data_source
931 {
932 ma_data_source_base base;
933 ...
934 };
935 ```
936
937In your initialization routine, you need to call `ma_data_source_init()` in order to set up the
938base object (`ma_data_source_base`):
939
940 ```c
941 static ma_result my_data_source_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
942 {
943 // Read data here. Output in the same format returned by my_data_source_get_data_format().
944 }
945
946 static ma_result my_data_source_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
947 {
948 // Seek to a specific PCM frame here. Return MA_NOT_IMPLEMENTED if seeking is not supported.
949 }
950
951 static ma_result my_data_source_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
952 {
953 // Return the format of the data here.
954 }
955
956 static ma_result my_data_source_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
957 {
958 // Retrieve the current position of the cursor here. Return MA_NOT_IMPLEMENTED and set *pCursor to 0 if there is no notion of a cursor.
959 }
960
961 static ma_result my_data_source_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
962 {
963 // Retrieve the length in PCM frames here. Return MA_NOT_IMPLEMENTED and set *pLength to 0 if there is no notion of a length or if the length is unknown.
964 }
965
966 static ma_data_source_vtable g_my_data_source_vtable =
967 {
968 my_data_source_read,
969 my_data_source_seek,
970 my_data_source_get_data_format,
971 my_data_source_get_cursor,
972 my_data_source_get_length
973 };
974
975 ma_result my_data_source_init(my_data_source* pMyDataSource)
976 {
977 ma_result result;
978 ma_data_source_config baseConfig;
979
980 baseConfig = ma_data_source_config_init();
981 baseConfig.vtable = &g_my_data_source_vtable;
982
983 result = ma_data_source_init(&baseConfig, &pMyDataSource->base);
984 if (result != MA_SUCCESS) {
985 return result;
986 }
987
988 // ... do the initialization of your custom data source here ...
989
990 return MA_SUCCESS;
991 }
992
993 void my_data_source_uninit(my_data_source* pMyDataSource)
994 {
995 // ... do the uninitialization of your custom data source here ...
996
997 // You must uninitialize the base data source.
998 ma_data_source_uninit(&pMyDataSource->base);
999 }
1000 ```
1001
1002Note that `ma_data_source_init()` and `ma_data_source_uninit()` are never called directly outside
1003of the custom data source. It's up to the custom data source itself to call these within their own
1004init/uninit functions.
1005
1006
1007
10085. Engine
1009=========
1010The `ma_engine` API is a high level API for managing and mixing sounds and effect processing. The
1011`ma_engine` object encapsulates a resource manager and a node graph, both of which will be
1012explained in more detail later.
1013
1014Sounds are called `ma_sound` and are created from an engine. Sounds can be associated with a mixing
1015group called `ma_sound_group` which are also created from the engine. Both `ma_sound` and
1016`ma_sound_group` objects are nodes within the engine's node graph.
1017
1018When the engine is initialized, it will normally create a device internally. If you would rather
1019manage the device yourself, you can do so and just pass a pointer to it via the engine config when
1020you initialize the engine. You can also just use the engine without a device, which again can be
1021configured via the engine config.
1022
1023The most basic way to initialize the engine is with a default config, like so:
1024
1025 ```c
1026 ma_result result;
1027 ma_engine engine;
1028
1029 result = ma_engine_init(NULL, &engine);
1030 if (result != MA_SUCCESS) {
1031 return result; // Failed to initialize the engine.
1032 }
1033 ```
1034
1035This will result in the engine initializing a playback device using the operating system's default
1036device. This will be sufficient for many use cases, but if you need more flexibility you'll want to
1037configure the engine with an engine config:
1038
1039 ```c
1040 ma_result result;
1041 ma_engine engine;
1042 ma_engine_config engineConfig;
1043
1044 engineConfig = ma_engine_config_init();
1045 engineConfig.pDevice = &myDevice;
1046
1047 result = ma_engine_init(&engineConfig, &engine);
1048 if (result != MA_SUCCESS) {
1049 return result; // Failed to initialize the engine.
1050 }
1051 ```
1052
1053In the example above we're passing in a pre-initialized device. Since the caller is the one in
1054control of the device's data callback, it's their responsibility to manually call
1055`ma_engine_read_pcm_frames()` from inside their data callback:
1056
1057 ```c
1058 void playback_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
1059 {
1060 ma_engine_read_pcm_frames(&g_Engine, pOutput, frameCount, NULL);
1061 }
1062 ```
1063
1064You can also use the engine independent of a device entirely:
1065
1066 ```c
1067 ma_result result;
1068 ma_engine engine;
1069 ma_engine_config engineConfig;
1070
1071 engineConfig = ma_engine_config_init();
1072 engineConfig.noDevice = MA_TRUE;
1073 engineConfig.channels = 2; // Must be set when not using a device.
1074 engineConfig.sampleRate = 48000; // Must be set when not using a device.
1075
1076 result = ma_engine_init(&engineConfig, &engine);
1077 if (result != MA_SUCCESS) {
1078 return result; // Failed to initialize the engine.
1079 }
1080 ```
1081
1082Note that when you're not using a device, you must set the channel count and sample rate in the
1083config or else miniaudio won't know what to use (miniaudio will use the device to determine this
1084normally). When not using a device, you need to use `ma_engine_read_pcm_frames()` to process audio
1085data from the engine. This kind of setup is useful if you want to do something like offline
1086processing or want to use a different audio system for playback such as SDL.
1087
1088When a sound is loaded it goes through a resource manager. By default the engine will initialize a
1089resource manager internally, but you can also specify a pre-initialized resource manager:
1090
1091 ```c
1092 ma_result result;
1093 ma_engine engine1;
1094 ma_engine engine2;
1095 ma_engine_config engineConfig;
1096
1097 engineConfig = ma_engine_config_init();
1098 engineConfig.pResourceManager = &myResourceManager;
1099
1100 ma_engine_init(&engineConfig, &engine1);
1101 ma_engine_init(&engineConfig, &engine2);
1102 ```
1103
1104In this example we are initializing two engines, both of which are sharing the same resource
1105manager. This is especially useful for saving memory when loading the same file across multiple
1106engines. If you were not to use a shared resource manager, each engine instance would use their own
1107which would result in any sounds that are used between both engine's being loaded twice. By using
1108a shared resource manager, it would only be loaded once. Using multiple engine's is useful when you
1109need to output to multiple playback devices, such as in a local multiplayer game where each player
1110is using their own set of headphones.
1111
1112By default an engine will be in a started state. To make it so the engine is not automatically
1113started you can configure it as such:
1114
1115 ```c
1116 engineConfig.noAutoStart = MA_TRUE;
1117
1118 // The engine will need to be started manually.
1119 ma_engine_start(&engine);
1120
1121 // Later on the engine can be stopped with ma_engine_stop().
1122 ma_engine_stop(&engine);
1123 ```
1124
1125The concept of starting or stopping an engine is only relevant when using the engine with a
1126device. Attempting to start or stop an engine that is not associated with a device will result in
1127`MA_INVALID_OPERATION`.
1128
1129The master volume of the engine can be controlled with `ma_engine_set_volume()` which takes a
1130linear scale, with 0 resulting in silence and anything above 1 resulting in amplification. If you
1131prefer decibel based volume control, use `ma_volume_db_to_linear()` to convert from dB to linear.
1132
1133When a sound is spatialized, it is done so relative to a listener. An engine can be configured to
1134have multiple listeners which can be configured via the config:
1135
1136 ```c
1137 engineConfig.listenerCount = 2;
1138 ```
1139
1140The maximum number of listeners is restricted to `MA_ENGINE_MAX_LISTENERS`. By default, when a
1141sound is spatialized, it will be done so relative to the closest listener. You can also pin a sound
1142to a specific listener which will be explained later. Listener's have a position, direction, cone,
1143and velocity (for doppler effect). A listener is referenced by an index, the meaning of which is up
1144to the caller (the index is 0 based and cannot go beyond the listener count, minus 1). The
1145position, direction and velocity are all specified in absolute terms:
1146
1147 ```c
1148 ma_engine_listener_set_position(&engine, listenerIndex, worldPosX, worldPosY, worldPosZ);
1149 ```
1150
1151The direction of the listener represents it's forward vector. The listener's up vector can also be
1152specified and defaults to +1 on the Y axis.
1153
1154 ```c
1155 ma_engine_listener_set_direction(&engine, listenerIndex, forwardX, forwardY, forwardZ);
1156 ma_engine_listener_set_world_up(&engine, listenerIndex, 0, 1, 0);
1157 ```
1158
1159The engine supports directional attenuation. The listener can have a cone the controls how sound is
1160attenuated based on the listener's direction. When a sound is between the inner and outer cones, it
1161will be attenuated between 1 and the cone's outer gain:
1162
1163 ```c
1164 ma_engine_listener_set_cone(&engine, listenerIndex, innerAngleInRadians, outerAngleInRadians, outerGain);
1165 ```
1166
1167When a sound is inside the inner code, no directional attenuation is applied. When the sound is
1168outside of the outer cone, the attenuation will be set to `outerGain` in the example above. When
1169the sound is in between the inner and outer cones, the attenuation will be interpolated between 1
1170and the outer gain.
1171
1172The engine's coordinate system follows the OpenGL coordinate system where positive X points right,
1173positive Y points up and negative Z points forward.
1174
1175The simplest and least flexible way to play a sound is like so:
1176
1177 ```c
1178 ma_engine_play_sound(&engine, "my_sound.wav", pGroup);
1179 ```
1180
1181This is a "fire and forget" style of function. The engine will manage the `ma_sound` object
1182internally. When the sound finishes playing, it'll be put up for recycling. For more flexibility
1183you'll want to initialize a sound object:
1184
1185 ```c
1186 ma_sound sound;
1187
1188 result = ma_sound_init_from_file(&engine, "my_sound.wav", flags, pGroup, NULL, &sound);
1189 if (result != MA_SUCCESS) {
1190 return result; // Failed to load sound.
1191 }
1192 ```
1193
1194Sounds need to be uninitialized with `ma_sound_uninit()`.
1195
1196The example above loads a sound from a file. If the resource manager has been disabled you will not
1197be able to use this function and instead you'll need to initialize a sound directly from a data
1198source:
1199
1200 ```c
1201 ma_sound sound;
1202
1203 result = ma_sound_init_from_data_source(&engine, &dataSource, flags, pGroup, &sound);
1204 if (result != MA_SUCCESS) {
1205 return result;
1206 }
1207 ```
1208
1209Each `ma_sound` object represents a single instance of the sound. If you want to play the same
1210sound multiple times at the same time, you need to initialize a separate `ma_sound` object.
1211
1212For the most flexibility when initializing sounds, use `ma_sound_init_ex()`. This uses miniaudio's
1213standard config/init pattern:
1214
1215 ```c
1216 ma_sound sound;
1217 ma_sound_config soundConfig;
1218
1219 soundConfig = ma_sound_config_init();
1220 soundConfig.pFilePath = NULL; // Set this to load from a file path.
1221 soundConfig.pDataSource = NULL; // Set this to initialize from an existing data source.
1222 soundConfig.pInitialAttachment = &someNodeInTheNodeGraph;
1223 soundConfig.initialAttachmentInputBusIndex = 0;
1224 soundConfig.channelsIn = 1;
1225 soundConfig.channelsOut = 0; // Set to 0 to use the engine's native channel count.
1226
1227 result = ma_sound_init_ex(&soundConfig, &sound);
1228 if (result != MA_SUCCESS) {
1229 return result;
1230 }
1231 ```
1232
1233In the example above, the sound is being initialized without a file nor a data source. This is
1234valid, in which case the sound acts as a node in the middle of the node graph. This means you can
1235connect other sounds to this sound and allow it to act like a sound group. Indeed, this is exactly
1236what a `ma_sound_group` is.
1237
1238When loading a sound, you specify a set of flags that control how the sound is loaded and what
1239features are enabled for that sound. When no flags are set, the sound will be fully loaded into
1240memory in exactly the same format as how it's stored on the file system. The resource manager will
1241allocate a block of memory and then load the file directly into it. When reading audio data, it
1242will be decoded dynamically on the fly. In order to save processing time on the audio thread, it
1243might be beneficial to pre-decode the sound. You can do this with the `MA_SOUND_FLAG_DECODE` flag:
1244
1245 ```c
1246 ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_DECODE, pGroup, NULL, &sound);
1247 ```
1248
1249By default, sounds will be loaded synchronously, meaning `ma_sound_init_*()` will not return until
1250the sound has been fully loaded. If this is prohibitive you can instead load sounds asynchronously
1251by specifying the `MA_SOUND_FLAG_ASYNC` flag:
1252
1253 ```c
1254 ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_DECODE | MA_SOUND_FLAG_ASYNC, pGroup, NULL, &sound);
1255 ```
1256
1257This will result in `ma_sound_init_*()` returning quickly, but the sound won't yet have been fully
1258loaded. When you start the sound, it won't output anything until some sound is available. The sound
1259will start outputting audio before the sound has been fully decoded when the `MA_SOUND_FLAG_DECODE`
1260is specified.
1261
1262If you need to wait for an asynchronously loaded sound to be fully loaded, you can use a fence. A
1263fence in miniaudio is a simple synchronization mechanism which simply blocks until it's internal
1264counter hit's zero. You can specify a fence like so:
1265
1266 ```c
1267 ma_result result;
1268 ma_fence fence;
1269 ma_sound sounds[4];
1270
1271 result = ma_fence_init(&fence);
1272 if (result != MA_SUCCESS) {
1273 return result;
1274 }
1275
1276 // Load some sounds asynchronously.
1277 for (int iSound = 0; iSound < 4; iSound += 1) {
1278 ma_sound_init_from_file(&engine, mySoundFilesPaths[iSound], MA_SOUND_FLAG_DECODE | MA_SOUND_FLAG_ASYNC, pGroup, &fence, &sounds[iSound]);
1279 }
1280
1281 // ... do some other stuff here in the mean time ...
1282
1283 // Wait for all sounds to finish loading.
1284 ma_fence_wait(&fence);
1285 ```
1286
1287If loading the entire sound into memory is prohibitive, you can also configure the engine to stream
1288the audio data:
1289
1290 ```c
1291 ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_STREAM, pGroup, NULL, &sound);
1292 ```
1293
1294When streaming sounds, 2 seconds worth of audio data is stored in memory. Although it should work
1295fine, it's inefficient to use streaming for short sounds. Streaming is useful for things like music
1296tracks in games.
1297
1298When loading a sound from a file path, the engine will reference count the file to prevent it from
1299being loaded if it's already in memory. When you uninitialize a sound, the reference count will be
1300decremented, and if it hits zero, the sound will be unloaded from memory. This reference counting
1301system is not used for streams. The engine will use a 64-bit hash of the file name when comparing
1302file paths which means there's a small chance you might encounter a name collision. If this is an
1303issue, you'll need to use a different name for one of the colliding file paths, or just not load
1304from files and instead load from a data source.
1305
1306You can use `ma_sound_init_copy()` to initialize a copy of another sound. Note, however, that this
1307only works for sounds that were initialized with `ma_sound_init_from_file()` and without the
1308`MA_SOUND_FLAG_STREAM` flag.
1309
1310When you initialize a sound, if you specify a sound group the sound will be attached to that group
1311automatically. If you set it to NULL, it will be automatically attached to the engine's endpoint.
1312If you would instead rather leave the sound unattached by default, you can can specify the
1313`MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT` flag. This is useful if you want to set up a complex node
1314graph.
1315
1316Sounds are not started by default. To start a sound, use `ma_sound_start()`. Stop a sound with
1317`ma_sound_stop()`.
1318
1319Sounds can have their volume controlled with `ma_sound_set_volume()` in the same way as the
1320engine's master volume.
1321
1322Sounds support stereo panning and pitching. Set the pan with `ma_sound_set_pan()`. Setting the pan
1323to 0 will result in an unpanned sound. Setting it to -1 will shift everything to the left, whereas
1324+1 will shift it to the right. The pitch can be controlled with `ma_sound_set_pitch()`. A larger
1325value will result in a higher pitch. The pitch must be greater than 0.
1326
1327The engine supports 3D spatialization of sounds. By default sounds will have spatialization
1328enabled, but if a sound does not need to be spatialized it's best to disable it. There are two ways
1329to disable spatialization of a sound:
1330
1331 ```c
1332 // Disable spatialization at initialization time via a flag:
1333 ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_NO_SPATIALIZATION, NULL, NULL, &sound);
1334
1335 // Dynamically disable or enable spatialization post-initialization:
1336 ma_sound_set_spatialization_enabled(&sound, isSpatializationEnabled);
1337 ```
1338
1339By default sounds will be spatialized based on the closest listener. If a sound should always be
1340spatialized relative to a specific listener it can be pinned to one:
1341
1342 ```c
1343 ma_sound_set_pinned_listener_index(&sound, listenerIndex);
1344 ```
1345
1346Like listeners, sounds have a position. By default, the position of a sound is in absolute space,
1347but it can be changed to be relative to a listener:
1348
1349 ```c
1350 ma_sound_set_positioning(&sound, ma_positioning_relative);
1351 ```
1352
1353Note that relative positioning of a sound only makes sense if there is either only one listener, or
1354the sound is pinned to a specific listener. To set the position of a sound:
1355
1356 ```c
1357 ma_sound_set_position(&sound, posX, posY, posZ);
1358 ```
1359
1360The direction works the same way as a listener and represents the sound's forward direction:
1361
1362 ```c
1363 ma_sound_set_direction(&sound, forwardX, forwardY, forwardZ);
1364 ```
1365
1366Sound's also have a cone for controlling directional attenuation. This works exactly the same as
1367listeners:
1368
1369 ```c
1370 ma_sound_set_cone(&sound, innerAngleInRadians, outerAngleInRadians, outerGain);
1371 ```
1372
1373The velocity of a sound is used for doppler effect and can be set as such:
1374
1375 ```c
1376 ma_sound_set_velocity(&sound, velocityX, velocityY, velocityZ);
1377 ```
1378
1379The engine supports different attenuation models which can be configured on a per-sound basis. By
1380default the attenuation model is set to `ma_attenuation_model_inverse` which is the equivalent to
1381OpenAL's `AL_INVERSE_DISTANCE_CLAMPED`. Configure the attenuation model like so:
1382
1383 ```c
1384 ma_sound_set_attenuation_model(&sound, ma_attenuation_model_inverse);
1385 ```
1386
1387The supported attenuation models include the following:
1388
1389 +----------------------------------+----------------------------------------------+
1390 | ma_attenuation_model_none | No distance attenuation. |
1391 +----------------------------------+----------------------------------------------+
1392 | ma_attenuation_model_inverse | Equivalent to `AL_INVERSE_DISTANCE_CLAMPED`. |
1393 +----------------------------------+----------------------------------------------+
1394 | ma_attenuation_model_linear | Linear attenuation. |
1395 +----------------------------------+----------------------------------------------+
1396 | ma_attenuation_model_exponential | Exponential attenuation. |
1397 +----------------------------------+----------------------------------------------+
1398
1399To control how quickly a sound rolls off as it moves away from the listener, you need to configure
1400the rolloff:
1401
1402 ```c
1403 ma_sound_set_rolloff(&sound, rolloff);
1404 ```
1405
1406You can control the minimum and maximum gain to apply from spatialization:
1407
1408 ```c
1409 ma_sound_set_min_gain(&sound, minGain);
1410 ma_sound_set_max_gain(&sound, maxGain);
1411 ```
1412
1413Likewise, in the calculation of attenuation, you can control the minimum and maximum distances for
1414the attenuation calculation. This is useful if you want to ensure sounds don't drop below a certain
1415volume after the listener moves further away and to have sounds play a maximum volume when the
1416listener is within a certain distance:
1417
1418 ```c
1419 ma_sound_set_min_distance(&sound, minDistance);
1420 ma_sound_set_max_distance(&sound, maxDistance);
1421 ```
1422
1423The engine's spatialization system supports doppler effect. The doppler factor can be configure on
1424a per-sound basis like so:
1425
1426 ```c
1427 ma_sound_set_doppler_factor(&sound, dopplerFactor);
1428 ```
1429
1430You can fade sounds in and out with `ma_sound_set_fade_in_pcm_frames()` and
1431`ma_sound_set_fade_in_milliseconds()`. Set the volume to -1 to use the current volume as the
1432starting volume:
1433
1434 ```c
1435 // Fade in over 1 second.
1436 ma_sound_set_fade_in_milliseconds(&sound, 0, 1, 1000);
1437
1438 // ... sometime later ...
1439
1440 // Fade out over 1 second, starting from the current volume.
1441 ma_sound_set_fade_in_milliseconds(&sound, -1, 0, 1000);
1442 ```
1443
1444By default sounds will start immediately, but sometimes for timing and synchronization purposes it
1445can be useful to schedule a sound to start or stop:
1446
1447 ```c
1448 // Start the sound in 1 second from now.
1449 ma_sound_set_start_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 1));
1450
1451 // Stop the sound in 2 seconds from now.
1452 ma_sound_set_stop_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 2));
1453 ```
1454
1455Note that scheduling a start time still requires an explicit call to `ma_sound_start()` before
1456anything will play.
1457
1458The time is specified in global time which is controlled by the engine. You can get the engine's
1459current time with `ma_engine_get_time_in_pcm_frames()`. The engine's global time is incremented
1460automatically as audio data is read, but it can be reset with `ma_engine_set_time_in_pcm_frames()`
1461in case it needs to be resynchronized for some reason.
1462
1463To determine whether or not a sound is currently playing, use `ma_sound_is_playing()`. This will
1464take the scheduled start and stop times into account.
1465
1466Whether or not a sound should loop can be controlled with `ma_sound_set_looping()`. Sounds will not
1467be looping by default. Use `ma_sound_is_looping()` to determine whether or not a sound is looping.
1468
1469Use `ma_sound_at_end()` to determine whether or not a sound is currently at the end. For a looping
1470sound this should never return true. Alternatively, you can configure a callback that will be fired
1471when the sound reaches the end. Note that the callback is fired from the audio thread which means
1472you cannot be uninitializing sound from the callback. To set the callback you can use
1473`ma_sound_set_end_callback()`. Alternatively, if you're using `ma_sound_init_ex()`, you can pass it
1474into the config like so:
1475
1476 ```c
1477 soundConfig.endCallback = my_end_callback;
1478 soundConfig.pEndCallbackUserData = pMyEndCallbackUserData;
1479 ```
1480
1481The end callback is declared like so:
1482
1483 ```c
1484 void my_end_callback(void* pUserData, ma_sound* pSound)
1485 {
1486 ...
1487 }
1488 ```
1489
1490Internally a sound wraps around a data source. Some APIs exist to control the underlying data
1491source, mainly for convenience:
1492
1493 ```c
1494 ma_sound_seek_to_pcm_frame(&sound, frameIndex);
1495 ma_sound_get_data_format(&sound, &format, &channels, &sampleRate, pChannelMap, channelMapCapacity);
1496 ma_sound_get_cursor_in_pcm_frames(&sound, &cursor);
1497 ma_sound_get_length_in_pcm_frames(&sound, &length);
1498 ```
1499
1500Sound groups have the same API as sounds, only they are called `ma_sound_group`, and since they do
1501not have any notion of a data source, anything relating to a data source is unavailable.
1502
1503Internally, sound data is loaded via the `ma_decoder` API which means by default it only supports
1504file formats that have built-in support in miniaudio. You can extend this to support any kind of
1505file format through the use of custom decoders. To do this you'll need to use a self-managed
1506resource manager and configure it appropriately. See the "Resource Management" section below for
1507details on how to set this up.
1508
1509
15106. Resource Management
1511======================
1512Many programs will want to manage sound resources for things such as reference counting and
1513streaming. This is supported by miniaudio via the `ma_resource_manager` API.
1514
1515The resource manager is mainly responsible for the following:
1516
1517 * Loading of sound files into memory with reference counting.
1518 * Streaming of sound data.
1519
1520When loading a sound file, the resource manager will give you back a `ma_data_source` compatible
1521object called `ma_resource_manager_data_source`. This object can be passed into any
1522`ma_data_source` API which is how you can read and seek audio data. When loading a sound file, you
1523specify whether or not you want the sound to be fully loaded into memory (and optionally
1524pre-decoded) or streamed. When loading into memory, you can also specify whether or not you want
1525the data to be loaded asynchronously.
1526
1527The example below is how you can initialize a resource manager using it's default configuration:
1528
1529 ```c
1530 ma_resource_manager_config config;
1531 ma_resource_manager resourceManager;
1532
1533 config = ma_resource_manager_config_init();
1534 result = ma_resource_manager_init(&config, &resourceManager);
1535 if (result != MA_SUCCESS) {
1536 ma_device_uninit(&device);
1537 printf("Failed to initialize the resource manager.");
1538 return -1;
1539 }
1540 ```
1541
1542You can configure the format, channels and sample rate of the decoded audio data. By default it
1543will use the file's native data format, but you can configure it to use a consistent format. This
1544is useful for offloading the cost of data conversion to load time rather than dynamically
1545converting at mixing time. To do this, you configure the decoded format, channels and sample rate
1546like the code below:
1547
1548 ```c
1549 config = ma_resource_manager_config_init();
1550 config.decodedFormat = device.playback.format;
1551 config.decodedChannels = device.playback.channels;
1552 config.decodedSampleRate = device.sampleRate;
1553 ```
1554
1555In the code above, the resource manager will be configured so that any decoded audio data will be
1556pre-converted at load time to the device's native data format. If instead you used defaults and
1557the data format of the file did not match the device's data format, you would need to convert the
1558data at mixing time which may be prohibitive in high-performance and large scale scenarios like
1559games.
1560
1561Internally the resource manager uses the `ma_decoder` API to load sounds. This means by default it
1562only supports decoders that are built into miniaudio. It's possible to support additional encoding
1563formats through the use of custom decoders. To do so, pass in your `ma_decoding_backend_vtable`
1564vtables into the resource manager config:
1565
1566 ```c
1567 ma_decoding_backend_vtable* pCustomBackendVTables[] =
1568 {
1569 &g_ma_decoding_backend_vtable_libvorbis,
1570 &g_ma_decoding_backend_vtable_libopus
1571 };
1572
1573 ...
1574
1575 resourceManagerConfig.ppCustomDecodingBackendVTables = pCustomBackendVTables;
1576 resourceManagerConfig.customDecodingBackendCount = sizeof(pCustomBackendVTables) / sizeof(pCustomBackendVTables[0]);
1577 resourceManagerConfig.pCustomDecodingBackendUserData = NULL;
1578 ```
1579
1580This system can allow you to support any kind of file format. See the "Decoding" section for
1581details on how to implement custom decoders. The miniaudio repository includes examples for Opus
1582via libopus and libopusfile and Vorbis via libvorbis and libvorbisfile.
1583
1584Asynchronicity is achieved via a job system. When an operation needs to be performed, such as the
1585decoding of a page, a job will be posted to a queue which will then be processed by a job thread.
1586By default there will be only one job thread running, but this can be configured, like so:
1587
1588 ```c
1589 config = ma_resource_manager_config_init();
1590 config.jobThreadCount = MY_JOB_THREAD_COUNT;
1591 ```
1592
1593By default job threads are managed internally by the resource manager, however you can also self
1594manage your job threads if, for example, you want to integrate the job processing into your
1595existing job infrastructure, or if you simply don't like the way the resource manager does it. To
1596do this, just set the job thread count to 0 and process jobs manually. To process jobs, you first
1597need to retrieve a job using `ma_resource_manager_next_job()` and then process it using
1598`ma_job_process()`:
1599
1600 ```c
1601 config = ma_resource_manager_config_init();
1602 config.jobThreadCount = 0; // Don't manage any job threads internally.
1603 config.flags = MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING; // Optional. Makes `ma_resource_manager_next_job()` non-blocking.
1604
1605 // ... Initialize your custom job threads ...
1606
1607 void my_custom_job_thread(...)
1608 {
1609 for (;;) {
1610 ma_job job;
1611 ma_result result = ma_resource_manager_next_job(pMyResourceManager, &job);
1612 if (result != MA_SUCCESS) {
1613 if (result == MA_NO_DATA_AVAILABLE) {
1614 // No jobs are available. Keep going. Will only get this if the resource manager was initialized
1615 // with MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING.
1616 continue;
1617 } else if (result == MA_CANCELLED) {
1618 // MA_JOB_TYPE_QUIT was posted. Exit.
1619 break;
1620 } else {
1621 // Some other error occurred.
1622 break;
1623 }
1624 }
1625
1626 ma_job_process(&job);
1627 }
1628 }
1629 ```
1630
1631In the example above, the `MA_JOB_TYPE_QUIT` event is the used as the termination
1632indicator, but you can use whatever you would like to terminate the thread. The call to
1633`ma_resource_manager_next_job()` is blocking by default, but can be configured to be non-blocking
1634by initializing the resource manager with the `MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING` configuration
1635flag. Note that the `MA_JOB_TYPE_QUIT` will never be removed from the job queue. This
1636is to give every thread the opportunity to catch the event and terminate naturally.
1637
1638When loading a file, it's sometimes convenient to be able to customize how files are opened and
1639read instead of using standard `fopen()`, `fclose()`, etc. which is what miniaudio will use by
1640default. This can be done by setting `pVFS` member of the resource manager's config:
1641
1642 ```c
1643 // Initialize your custom VFS object. See documentation for VFS for information on how to do this.
1644 my_custom_vfs vfs = my_custom_vfs_init();
1645
1646 config = ma_resource_manager_config_init();
1647 config.pVFS = &vfs;
1648 ```
1649
1650This is particularly useful in programs like games where you want to read straight from an archive
1651rather than the normal file system. If you do not specify a custom VFS, the resource manager will
1652use the operating system's normal file operations.
1653
1654To load a sound file and create a data source, call `ma_resource_manager_data_source_init()`. When
1655loading a sound you need to specify the file path and options for how the sounds should be loaded.
1656By default a sound will be loaded synchronously. The returned data source is owned by the caller
1657which means the caller is responsible for the allocation and freeing of the data source. Below is
1658an example for initializing a data source:
1659
1660 ```c
1661 ma_resource_manager_data_source dataSource;
1662 ma_result result = ma_resource_manager_data_source_init(pResourceManager, pFilePath, flags, &dataSource);
1663 if (result != MA_SUCCESS) {
1664 // Error.
1665 }
1666
1667 // ...
1668
1669 // A ma_resource_manager_data_source object is compatible with the `ma_data_source` API. To read data, just call
1670 // the `ma_data_source_read_pcm_frames()` like you would with any normal data source.
1671 result = ma_data_source_read_pcm_frames(&dataSource, pDecodedData, frameCount, &framesRead);
1672 if (result != MA_SUCCESS) {
1673 // Failed to read PCM frames.
1674 }
1675
1676 // ...
1677
1678 ma_resource_manager_data_source_uninit(&dataSource);
1679 ```
1680
1681The `flags` parameter specifies how you want to perform loading of the sound file. It can be a
1682combination of the following flags:
1683
1684 ```
1685 MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM
1686 MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE
1687 MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC
1688 MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT
1689 ```
1690
1691When no flags are specified (set to 0), the sound will be fully loaded into memory, but not
1692decoded, meaning the raw file data will be stored in memory, and then dynamically decoded when
1693`ma_data_source_read_pcm_frames()` is called. To instead decode the audio data before storing it in
1694memory, use the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` flag. By default, the sound file will
1695be loaded synchronously, meaning `ma_resource_manager_data_source_init()` will only return after
1696the entire file has been loaded. This is good for simplicity, but can be prohibitively slow. You
1697can instead load the sound asynchronously using the `MA_RESOURCE_MANAGER_DATA_SOURCE_ASYNC` flag.
1698This will result in `ma_resource_manager_data_source_init()` returning quickly, but no data will be
1699returned by `ma_data_source_read_pcm_frames()` until some data is available. When no data is
1700available because the asynchronous decoding hasn't caught up, `MA_BUSY` will be returned by
1701`ma_data_source_read_pcm_frames()`.
1702
1703For large sounds, it's often prohibitive to store the entire file in memory. To mitigate this, you
1704can instead stream audio data which you can do by specifying the
1705`MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag. When streaming, data will be decoded in 1
1706second pages. When a new page needs to be decoded, a job will be posted to the job queue and then
1707subsequently processed in a job thread.
1708
1709For in-memory sounds, reference counting is used to ensure the data is loaded only once. This means
1710multiple calls to `ma_resource_manager_data_source_init()` with the same file path will result in
1711the file data only being loaded once. Each call to `ma_resource_manager_data_source_init()` must be
1712matched up with a call to `ma_resource_manager_data_source_uninit()`. Sometimes it can be useful
1713for a program to register self-managed raw audio data and associate it with a file path. Use the
1714`ma_resource_manager_register_*()` and `ma_resource_manager_unregister_*()` APIs to do this.
1715`ma_resource_manager_register_decoded_data()` is used to associate a pointer to raw, self-managed
1716decoded audio data in the specified data format with the specified name. Likewise,
1717`ma_resource_manager_register_encoded_data()` is used to associate a pointer to raw self-managed
1718encoded audio data (the raw file data) with the specified name. Note that these names need not be
1719actual file paths. When `ma_resource_manager_data_source_init()` is called (without the
1720`MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag), the resource manager will look for these
1721explicitly registered data buffers and, if found, will use it as the backing data for the data
1722source. Note that the resource manager does *not* make a copy of this data so it is up to the
1723caller to ensure the pointer stays valid for it's lifetime. Use
1724`ma_resource_manager_unregister_data()` to unregister the self-managed data. You can also use
1725`ma_resource_manager_register_file()` and `ma_resource_manager_unregister_file()` to register and
1726unregister a file. It does not make sense to use the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM`
1727flag with a self-managed data pointer.
1728
1729
17306.1. Asynchronous Loading and Synchronization
1731---------------------------------------------
1732When loading asynchronously, it can be useful to poll whether or not loading has finished. Use
1733`ma_resource_manager_data_source_result()` to determine this. For in-memory sounds, this will
1734return `MA_SUCCESS` when the file has been *entirely* decoded. If the sound is still being decoded,
1735`MA_BUSY` will be returned. Otherwise, some other error code will be returned if the sound failed
1736to load. For streaming data sources, `MA_SUCCESS` will be returned when the first page has been
1737decoded and the sound is ready to be played. If the first page is still being decoded, `MA_BUSY`
1738will be returned. Otherwise, some other error code will be returned if the sound failed to load.
1739
1740In addition to polling, you can also use a simple synchronization object called a "fence" to wait
1741for asynchronously loaded sounds to finish. This is called `ma_fence`. The advantage to using a
1742fence is that it can be used to wait for a group of sounds to finish loading rather than waiting
1743for sounds on an individual basis. There are two stages to loading a sound:
1744
1745 * Initialization of the internal decoder; and
1746 * Completion of decoding of the file (the file is fully decoded)
1747
1748You can specify separate fences for each of the different stages. Waiting for the initialization
1749of the internal decoder is important for when you need to know the sample format, channels and
1750sample rate of the file.
1751
1752The example below shows how you could use a fence when loading a number of sounds:
1753
1754 ```c
1755 // This fence will be released when all sounds are finished loading entirely.
1756 ma_fence fence;
1757 ma_fence_init(&fence);
1758
1759 // This will be passed into the initialization routine for each sound.
1760 ma_resource_manager_pipeline_notifications notifications = ma_resource_manager_pipeline_notifications_init();
1761 notifications.done.pFence = &fence;
1762
1763 // Now load a bunch of sounds:
1764 for (iSound = 0; iSound < soundCount; iSound += 1) {
1765 ma_resource_manager_data_source_init(pResourceManager, pSoundFilePaths[iSound], flags, &notifications, &pSoundSources[iSound]);
1766 }
1767
1768 // ... DO SOMETHING ELSE WHILE SOUNDS ARE LOADING ...
1769
1770 // Wait for loading of sounds to finish.
1771 ma_fence_wait(&fence);
1772 ```
1773
1774In the example above we used a fence for waiting until the entire file has been fully decoded. If
1775you only need to wait for the initialization of the internal decoder to complete, you can use the
1776`init` member of the `ma_resource_manager_pipeline_notifications` object:
1777
1778 ```c
1779 notifications.init.pFence = &fence;
1780 ```
1781
1782If a fence is not appropriate for your situation, you can instead use a callback that is fired on
1783an individual sound basis. This is done in a very similar way to fences:
1784
1785 ```c
1786 typedef struct
1787 {
1788 ma_async_notification_callbacks cb;
1789 void* pMyData;
1790 } my_notification;
1791
1792 void my_notification_callback(ma_async_notification* pNotification)
1793 {
1794 my_notification* pMyNotification = (my_notification*)pNotification;
1795
1796 // Do something in response to the sound finishing loading.
1797 }
1798
1799 ...
1800
1801 my_notification myCallback;
1802 myCallback.cb.onSignal = my_notification_callback;
1803 myCallback.pMyData = pMyData;
1804
1805 ma_resource_manager_pipeline_notifications notifications = ma_resource_manager_pipeline_notifications_init();
1806 notifications.done.pNotification = &myCallback;
1807
1808 ma_resource_manager_data_source_init(pResourceManager, "my_sound.wav", flags, &notifications, &mySound);
1809 ```
1810
1811In the example above we just extend the `ma_async_notification_callbacks` object and pass an
1812instantiation into the `ma_resource_manager_pipeline_notifications` in the same way as we did with
1813the fence, only we set `pNotification` instead of `pFence`. You can set both of these at the same
1814time and they should both work as expected. If using the `pNotification` system, you need to ensure
1815your `ma_async_notification_callbacks` object stays valid.
1816
1817
1818
18196.2. Resource Manager Implementation Details
1820--------------------------------------------
1821Resources are managed in two main ways:
1822
1823 * By storing the entire sound inside an in-memory buffer (referred to as a data buffer)
1824 * By streaming audio data on the fly (referred to as a data stream)
1825
1826A resource managed data source (`ma_resource_manager_data_source`) encapsulates a data buffer or
1827data stream, depending on whether or not the data source was initialized with the
1828`MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag. If so, it will make use of a
1829`ma_resource_manager_data_stream` object. Otherwise it will use a `ma_resource_manager_data_buffer`
1830object. Both of these objects are data sources which means they can be used with any
1831`ma_data_source_*()` API.
1832
1833Another major feature of the resource manager is the ability to asynchronously decode audio files.
1834This relieves the audio thread of time-consuming decoding which can negatively affect scalability
1835due to the audio thread needing to complete it's work extremely quickly to avoid glitching.
1836Asynchronous decoding is achieved through a job system. There is a central multi-producer,
1837multi-consumer, fixed-capacity job queue. When some asynchronous work needs to be done, a job is
1838posted to the queue which is then read by a job thread. The number of job threads can be
1839configured for improved scalability, and job threads can all run in parallel without needing to
1840worry about the order of execution (how this is achieved is explained below).
1841
1842When a sound is being loaded asynchronously, playback can begin before the sound has been fully
1843decoded. This enables the application to start playback of the sound quickly, while at the same
1844time allowing to resource manager to keep loading in the background. Since there may be less
1845threads than the number of sounds being loaded at a given time, a simple scheduling system is used
1846to keep decoding time balanced and fair. The resource manager solves this by splitting decoding
1847into chunks called pages. By default, each page is 1 second long. When a page has been decoded, a
1848new job will be posted to start decoding the next page. By dividing up decoding into pages, an
1849individual sound shouldn't ever delay every other sound from having their first page decoded. Of
1850course, when loading many sounds at the same time, there will always be an amount of time required
1851to process jobs in the queue so in heavy load situations there will still be some delay. To
1852determine if a data source is ready to have some frames read, use
1853`ma_resource_manager_data_source_get_available_frames()`. This will return the number of frames
1854available starting from the current position.
1855
1856
18576.2.1. Job Queue
1858----------------
1859The resource manager uses a job queue which is multi-producer, multi-consumer, and fixed-capacity.
1860This job queue is not currently lock-free, and instead uses a spinlock to achieve thread-safety.
1861Only a fixed number of jobs can be allocated and inserted into the queue which is done through a
1862lock-free data structure for allocating an index into a fixed sized array, with reference counting
1863for mitigation of the ABA problem. The reference count is 32-bit.
1864
1865For many types of jobs it's important that they execute in a specific order. In these cases, jobs
1866are executed serially. For the resource manager, serial execution of jobs is only required on a
1867per-object basis (per data buffer or per data stream). Each of these objects stores an execution
1868counter. When a job is posted it is associated with an execution counter. When the job is
1869processed, it checks if the execution counter of the job equals the execution counter of the
1870owning object and if so, processes the job. If the counters are not equal, the job will be posted
1871back onto the job queue for later processing. When the job finishes processing the execution order
1872of the main object is incremented. This system means the no matter how many job threads are
1873executing, decoding of an individual sound will always get processed serially. The advantage to
1874having multiple threads comes into play when loading multiple sounds at the same time.
1875
1876The resource manager's job queue is not 100% lock-free and will use a spinlock to achieve
1877thread-safety for a very small section of code. This is only relevant when the resource manager
1878uses more than one job thread. If only using a single job thread, which is the default, the
1879lock should never actually wait in practice. The amount of time spent locking should be quite
1880short, but it's something to be aware of for those who have pedantic lock-free requirements and
1881need to use more than one job thread. There are plans to remove this lock in a future version.
1882
1883In addition, posting a job will release a semaphore, which on Win32 is implemented with
1884`ReleaseSemaphore` and on POSIX platforms via a condition variable:
1885
1886 ```c
1887 pthread_mutex_lock(&pSemaphore->lock);
1888 {
1889 pSemaphore->value += 1;
1890 pthread_cond_signal(&pSemaphore->cond);
1891 }
1892 pthread_mutex_unlock(&pSemaphore->lock);
1893 ```
1894
1895Again, this is relevant for those with strict lock-free requirements in the audio thread. To avoid
1896this, you can use non-blocking mode (via the `MA_JOB_QUEUE_FLAG_NON_BLOCKING`
1897flag) and implement your own job processing routine (see the "Resource Manager" section above for
1898details on how to do this).
1899
1900
1901
19026.2.2. Data Buffers
1903-------------------
1904When the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag is excluded at initialization time, the
1905resource manager will try to load the data into an in-memory data buffer. Before doing so, however,
1906it will first check if the specified file is already loaded. If so, it will increment a reference
1907counter and just use the already loaded data. This saves both time and memory. When the data buffer
1908is uninitialized, the reference counter will be decremented. If the counter hits zero, the file
1909will be unloaded. This is a detail to keep in mind because it could result in excessive loading and
1910unloading of a sound. For example, the following sequence will result in a file be loaded twice,
1911once after the other:
1912
1913 ```c
1914 ma_resource_manager_data_source_init(pResourceManager, "my_file", ..., &myDataBuffer0); // Refcount = 1. Initial load.
1915 ma_resource_manager_data_source_uninit(&myDataBuffer0); // Refcount = 0. Unloaded.
1916
1917 ma_resource_manager_data_source_init(pResourceManager, "my_file", ..., &myDataBuffer1); // Refcount = 1. Reloaded because previous uninit() unloaded it.
1918 ma_resource_manager_data_source_uninit(&myDataBuffer1); // Refcount = 0. Unloaded.
1919 ```
1920
1921A binary search tree (BST) is used for storing data buffers as it has good balance between
1922efficiency and simplicity. The key of the BST is a 64-bit hash of the file path that was passed
1923into `ma_resource_manager_data_source_init()`. The advantage of using a hash is that it saves
1924memory over storing the entire path, has faster comparisons, and results in a mostly balanced BST
1925due to the random nature of the hash. The disadvantages are that file names are case-sensitive and
1926there's a small chance of name collisions. If case-sensitivity is an issue, you should normalize
1927your file names to upper- or lower-case before initializing your data sources. If name collisions
1928become an issue, you'll need to change the name of one of the colliding names or just not use the
1929resource manager.
1930
1931When a sound file has not already been loaded and the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC`
1932flag is excluded, the file will be decoded synchronously by the calling thread. There are two
1933options for controlling how the audio is stored in the data buffer - encoded or decoded. When the
1934`MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` option is excluded, the raw file data will be stored
1935in memory. Otherwise the sound will be decoded before storing it in memory. Synchronous loading is
1936a very simple and standard process of simply adding an item to the BST, allocating a block of
1937memory and then decoding (if `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` is specified).
1938
1939When the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` flag is specified, loading of the data buffer
1940is done asynchronously. In this case, a job is posted to the queue to start loading and then the
1941function immediately returns, setting an internal result code to `MA_BUSY`. This result code is
1942returned when the program calls `ma_resource_manager_data_source_result()`. When decoding has fully
1943completed `MA_SUCCESS` will be returned. This can be used to know if loading has fully completed.
1944
1945When loading asynchronously, a single job is posted to the queue of the type
1946`MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE`. This involves making a copy of the file path and
1947associating it with job. When the job is processed by the job thread, it will first load the file
1948using the VFS associated with the resource manager. When using a custom VFS, it's important that it
1949be completely thread-safe because it will be used from one or more job threads at the same time.
1950Individual files should only ever be accessed by one thread at a time, however. After opening the
1951file via the VFS, the job will determine whether or not the file is being decoded. If not, it
1952simply allocates a block of memory and loads the raw file contents into it and returns. On the
1953other hand, when the file is being decoded, it will first allocate a decoder on the heap and
1954initialize it. Then it will check if the length of the file is known. If so it will allocate a
1955block of memory to store the decoded output and initialize it to silence. If the size is unknown,
1956it will allocate room for one page. After memory has been allocated, the first page will be
1957decoded. If the sound is shorter than a page, the result code will be set to `MA_SUCCESS` and the
1958completion event will be signalled and loading is now complete. If, however, there is more to
1959decode, a job with the code `MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE` is posted. This job
1960will decode the next page and perform the same process if it reaches the end. If there is more to
1961decode, the job will post another `MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE` job which will
1962keep on happening until the sound has been fully decoded. For sounds of an unknown length, each
1963page will be linked together as a linked list. Internally this is implemented via the
1964`ma_paged_audio_buffer` object.
1965
1966
19676.2.3. Data Streams
1968-------------------
1969Data streams only ever store two pages worth of data for each instance. They are most useful for
1970large sounds like music tracks in games that would consume too much memory if fully decoded in
1971memory. After every frame from a page has been read, a job will be posted to load the next page
1972which is done from the VFS.
1973
1974For data streams, the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` flag will determine whether or
1975not initialization of the data source waits until the two pages have been decoded. When unset,
1976`ma_resource_manager_data_source_init()` will wait until the two pages have been loaded, otherwise
1977it will return immediately.
1978
1979When frames are read from a data stream using `ma_resource_manager_data_source_read_pcm_frames()`,
1980`MA_BUSY` will be returned if there are no frames available. If there are some frames available,
1981but less than the number requested, `MA_SUCCESS` will be returned, but the actual number of frames
1982read will be less than the number requested. Due to the asynchronous nature of data streams,
1983seeking is also asynchronous. If the data stream is in the middle of a seek, `MA_BUSY` will be
1984returned when trying to read frames.
1985
1986When `ma_resource_manager_data_source_read_pcm_frames()` results in a page getting fully consumed
1987a job is posted to load the next page. This will be posted from the same thread that called
1988`ma_resource_manager_data_source_read_pcm_frames()`.
1989
1990Data streams are uninitialized by posting a job to the queue, but the function won't return until
1991that job has been processed. The reason for this is that the caller owns the data stream object and
1992therefore miniaudio needs to ensure everything completes before handing back control to the caller.
1993Also, if the data stream is uninitialized while pages are in the middle of decoding, they must
1994complete before destroying any underlying object and the job system handles this cleanly.
1995
1996Note that when a new page needs to be loaded, a job will be posted to the resource manager's job
1997thread from the audio thread. You must keep in mind the details mentioned in the "Job Queue"
1998section above regarding locking when posting an event if you require a strictly lock-free audio
1999thread.
2000
2001
2002
20037. Node Graph
2004=============
2005miniaudio's routing infrastructure follows a node graph paradigm. The idea is that you create a
2006node whose outputs are attached to inputs of another node, thereby creating a graph. There are
2007different types of nodes, with each node in the graph processing input data to produce output,
2008which is then fed through the chain. Each node in the graph can apply their own custom effects. At
2009the start of the graph will usually be one or more data source nodes which have no inputs and
2010instead pull their data from a data source. At the end of the graph is an endpoint which represents
2011the end of the chain and is where the final output is ultimately extracted from.
2012
2013Each node has a number of input buses and a number of output buses. An output bus from a node is
2014attached to an input bus of another. Multiple nodes can connect their output buses to another
2015node's input bus, in which case their outputs will be mixed before processing by the node. Below is
2016a diagram that illustrates a hypothetical node graph setup:
2017
2018 ```
2019 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Data flows left to right >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
2020
2021 +---------------+ +-----------------+
2022 | Data Source 1 =----+ +----------+ +----= Low Pass Filter =----+
2023 +---------------+ | | =----+ +-----------------+ | +----------+
2024 +----= Splitter | +----= ENDPOINT |
2025 +---------------+ | | =----+ +-----------------+ | +----------+
2026 | Data Source 2 =----+ +----------+ +----= Echo / Delay =----+
2027 +---------------+ +-----------------+
2028 ```
2029
2030In the above graph, it starts with two data sources whose outputs are attached to the input of a
2031splitter node. It's at this point that the two data sources are mixed. After mixing, the splitter
2032performs it's processing routine and produces two outputs which is simply a duplication of the
2033input stream. One output is attached to a low pass filter, whereas the other output is attached to
2034a echo/delay. The outputs of the the low pass filter and the echo are attached to the endpoint, and
2035since they're both connected to the same input bus, they'll be mixed.
2036
2037Each input bus must be configured to accept the same number of channels, but the number of channels
2038used by input buses can be different to the number of channels for output buses in which case
2039miniaudio will automatically convert the input data to the output channel count before processing.
2040The number of channels of an output bus of one node must match the channel count of the input bus
2041it's attached to. The channel counts cannot be changed after the node has been initialized. If you
2042attempt to attach an output bus to an input bus with a different channel count, attachment will
2043fail.
2044
2045To use a node graph, you first need to initialize a `ma_node_graph` object. This is essentially a
2046container around the entire graph. The `ma_node_graph` object is required for some thread-safety
2047issues which will be explained later. A `ma_node_graph` object is initialized using miniaudio's
2048standard config/init system:
2049
2050 ```c
2051 ma_node_graph_config nodeGraphConfig = ma_node_graph_config_init(myChannelCount);
2052
2053 result = ma_node_graph_init(&nodeGraphConfig, NULL, &nodeGraph); // Second parameter is a pointer to allocation callbacks.
2054 if (result != MA_SUCCESS) {
2055 // Failed to initialize node graph.
2056 }
2057 ```
2058
2059When you initialize the node graph, you're specifying the channel count of the endpoint. The
2060endpoint is a special node which has one input bus and one output bus, both of which have the
2061same channel count, which is specified in the config. Any nodes that connect directly to the
2062endpoint must be configured such that their output buses have the same channel count. When you read
2063audio data from the node graph, it'll have the channel count you specified in the config. To read
2064data from the graph:
2065
2066 ```c
2067 ma_uint32 framesRead;
2068 result = ma_node_graph_read_pcm_frames(&nodeGraph, pFramesOut, frameCount, &framesRead);
2069 if (result != MA_SUCCESS) {
2070 // Failed to read data from the node graph.
2071 }
2072 ```
2073
2074When you read audio data, miniaudio starts at the node graph's endpoint node which then pulls in
2075data from it's input attachments, which in turn recursively pull in data from their inputs, and so
2076on. At the start of the graph there will be some kind of data source node which will have zero
2077inputs and will instead read directly from a data source. The base nodes don't literally need to
2078read from a `ma_data_source` object, but they will always have some kind of underlying object that
2079sources some kind of audio. The `ma_data_source_node` node can be used to read from a
2080`ma_data_source`. Data is always in floating-point format and in the number of channels you
2081specified when the graph was initialized. The sample rate is defined by the underlying data sources.
2082It's up to you to ensure they use a consistent and appropriate sample rate.
2083
2084The `ma_node` API is designed to allow custom nodes to be implemented with relative ease, but
2085miniaudio includes a few stock nodes for common functionality. This is how you would initialize a
2086node which reads directly from a data source (`ma_data_source_node`) which is an example of one
2087of the stock nodes that comes with miniaudio:
2088
2089 ```c
2090 ma_data_source_node_config config = ma_data_source_node_config_init(pMyDataSource);
2091
2092 ma_data_source_node dataSourceNode;
2093 result = ma_data_source_node_init(&nodeGraph, &config, NULL, &dataSourceNode);
2094 if (result != MA_SUCCESS) {
2095 // Failed to create data source node.
2096 }
2097 ```
2098
2099The data source node will use the output channel count to determine the channel count of the output
2100bus. There will be 1 output bus and 0 input buses (data will be drawn directly from the data
2101source). The data source must output to floating-point (`ma_format_f32`) or else an error will be
2102returned from `ma_data_source_node_init()`.
2103
2104By default the node will not be attached to the graph. To do so, use `ma_node_attach_output_bus()`:
2105
2106 ```c
2107 result = ma_node_attach_output_bus(&dataSourceNode, 0, ma_node_graph_get_endpoint(&nodeGraph), 0);
2108 if (result != MA_SUCCESS) {
2109 // Failed to attach node.
2110 }
2111 ```
2112
2113The code above connects the data source node directly to the endpoint. Since the data source node
2114has only a single output bus, the index will always be 0. Likewise, the endpoint only has a single
2115input bus which means the input bus index will also always be 0.
2116
2117To detach a specific output bus, use `ma_node_detach_output_bus()`. To detach all output buses, use
2118`ma_node_detach_all_output_buses()`. If you want to just move the output bus from one attachment to
2119another, you do not need to detach first. You can just call `ma_node_attach_output_bus()` and it'll
2120deal with it for you.
2121
2122Less frequently you may want to create a specialized node. This will be a node where you implement
2123your own processing callback to apply a custom effect of some kind. This is similar to initializing
2124one of the stock node types, only this time you need to specify a pointer to a vtable containing a
2125pointer to the processing function and the number of input and output buses. Example:
2126
2127 ```c
2128 static void my_custom_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
2129 {
2130 // Do some processing of ppFramesIn (one stream of audio data per input bus)
2131 const float* pFramesIn_0 = ppFramesIn[0]; // Input bus @ index 0.
2132 const float* pFramesIn_1 = ppFramesIn[1]; // Input bus @ index 1.
2133 float* pFramesOut_0 = ppFramesOut[0]; // Output bus @ index 0.
2134
2135 // Do some processing. On input, `pFrameCountIn` will be the number of input frames in each
2136 // buffer in `ppFramesIn` and `pFrameCountOut` will be the capacity of each of the buffers
2137 // in `ppFramesOut`. On output, `pFrameCountIn` should be set to the number of input frames
2138 // your node consumed and `pFrameCountOut` should be set the number of output frames that
2139 // were produced.
2140 //
2141 // You should process as many frames as you can. If your effect consumes input frames at the
2142 // same rate as output frames (always the case, unless you're doing resampling), you need
2143 // only look at `ppFramesOut` and process that exact number of frames. If you're doing
2144 // resampling, you'll need to be sure to set both `pFrameCountIn` and `pFrameCountOut`
2145 // properly.
2146 }
2147
2148 static ma_node_vtable my_custom_node_vtable =
2149 {
2150 my_custom_node_process_pcm_frames, // The function that will be called to process your custom node. This is where you'd implement your effect processing.
2151 NULL, // Optional. A callback for calculating the number of input frames that are required to process a specified number of output frames.
2152 2, // 2 input buses.
2153 1, // 1 output bus.
2154 0 // Default flags.
2155 };
2156
2157 ...
2158
2159 // Each bus needs to have a channel count specified. To do this you need to specify the channel
2160 // counts in an array and then pass that into the node config.
2161 ma_uint32 inputChannels[2]; // Equal in size to the number of input channels specified in the vtable.
2162 ma_uint32 outputChannels[1]; // Equal in size to the number of output channels specified in the vtable.
2163
2164 inputChannels[0] = channelsIn;
2165 inputChannels[1] = channelsIn;
2166 outputChannels[0] = channelsOut;
2167
2168 ma_node_config nodeConfig = ma_node_config_init();
2169 nodeConfig.vtable = &my_custom_node_vtable;
2170 nodeConfig.pInputChannels = inputChannels;
2171 nodeConfig.pOutputChannels = outputChannels;
2172
2173 ma_node_base node;
2174 result = ma_node_init(&nodeGraph, &nodeConfig, NULL, &node);
2175 if (result != MA_SUCCESS) {
2176 // Failed to initialize node.
2177 }
2178 ```
2179
2180When initializing a custom node, as in the code above, you'll normally just place your vtable in
2181static space. The number of input and output buses are specified as part of the vtable. If you need
2182a variable number of buses on a per-node bases, the vtable should have the relevant bus count set
2183to `MA_NODE_BUS_COUNT_UNKNOWN`. In this case, the bus count should be set in the node config:
2184
2185 ```c
2186 static ma_node_vtable my_custom_node_vtable =
2187 {
2188 my_custom_node_process_pcm_frames, // The function that will be called process your custom node. This is where you'd implement your effect processing.
2189 NULL, // Optional. A callback for calculating the number of input frames that are required to process a specified number of output frames.
2190 MA_NODE_BUS_COUNT_UNKNOWN, // The number of input buses is determined on a per-node basis.
2191 1, // 1 output bus.
2192 0 // Default flags.
2193 };
2194
2195 ...
2196
2197 ma_node_config nodeConfig = ma_node_config_init();
2198 nodeConfig.vtable = &my_custom_node_vtable;
2199 nodeConfig.inputBusCount = myBusCount; // <-- Since the vtable specifies MA_NODE_BUS_COUNT_UNKNOWN, the input bus count should be set here.
2200 nodeConfig.pInputChannels = inputChannels; // <-- Make sure there are nodeConfig.inputBusCount elements in this array.
2201 nodeConfig.pOutputChannels = outputChannels; // <-- The vtable specifies 1 output bus, so there must be 1 element in this array.
2202 ```
2203
2204In the above example it's important to never set the `inputBusCount` and `outputBusCount` members
2205to anything other than their defaults if the vtable specifies an explicit count. They can only be
2206set if the vtable specifies MA_NODE_BUS_COUNT_UNKNOWN in the relevant bus count.
2207
2208Most often you'll want to create a structure to encapsulate your node with some extra data. You
2209need to make sure the `ma_node_base` object is your first member of the structure:
2210
2211 ```c
2212 typedef struct
2213 {
2214 ma_node_base base; // <-- Make sure this is always the first member.
2215 float someCustomData;
2216 } my_custom_node;
2217 ```
2218
2219By doing this, your object will be compatible with all `ma_node` APIs and you can attach it to the
2220graph just like any other node.
2221
2222In the custom processing callback (`my_custom_node_process_pcm_frames()` in the example above), the
2223number of channels for each bus is what was specified by the config when the node was initialized
2224with `ma_node_init()`. In addition, all attachments to each of the input buses will have been
2225pre-mixed by miniaudio. The config allows you to specify different channel counts for each
2226individual input and output bus. It's up to the effect to handle it appropriate, and if it can't,
2227return an error in it's initialization routine.
2228
2229Custom nodes can be assigned some flags to describe their behaviour. These are set via the vtable
2230and include the following:
2231
2232 +-----------------------------------------+---------------------------------------------------+
2233 | Flag Name | Description |
2234 +-----------------------------------------+---------------------------------------------------+
2235 | MA_NODE_FLAG_PASSTHROUGH | Useful for nodes that do not do any kind of audio |
2236 | | processing, but are instead used for tracking |
2237 | | time, handling events, etc. Also used by the |
2238 | | internal endpoint node. It reads directly from |
2239 | | the input bus to the output bus. Nodes with this |
2240 | | flag must have exactly 1 input bus and 1 output |
2241 | | bus, and both buses must have the same channel |
2242 | | counts. |
2243 +-----------------------------------------+---------------------------------------------------+
2244 | MA_NODE_FLAG_CONTINUOUS_PROCESSING | Causes the processing callback to be called even |
2245 | | when no data is available to be read from input |
2246 | | attachments. When a node has at least one input |
2247 | | bus, but there are no inputs attached or the |
2248 | | inputs do not deliver any data, the node's |
2249 | | processing callback will not get fired. This flag |
2250 | | will make it so the callback is always fired |
2251 | | regardless of whether or not any input data is |
2252 | | received. This is useful for effects like |
2253 | | echos where there will be a tail of audio data |
2254 | | that still needs to be processed even when the |
2255 | | original data sources have reached their ends. It |
2256 | | may also be useful for nodes that must always |
2257 | | have their processing callback fired when there |
2258 | | are no inputs attached. |
2259 +-----------------------------------------+---------------------------------------------------+
2260 | MA_NODE_FLAG_ALLOW_NULL_INPUT | Used in conjunction with |
2261 | | `MA_NODE_FLAG_CONTINUOUS_PROCESSING`. When this |
2262 | | is set, the `ppFramesIn` parameter of the |
2263 | | processing callback will be set to NULL when |
2264 | | there are no input frames are available. When |
2265 | | this is unset, silence will be posted to the |
2266 | | processing callback. |
2267 +-----------------------------------------+---------------------------------------------------+
2268 | MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES | Used to tell miniaudio that input and output |
2269 | | frames are processed at different rates. You |
2270 | | should set this for any nodes that perform |
2271 | | resampling. |
2272 +-----------------------------------------+---------------------------------------------------+
2273 | MA_NODE_FLAG_SILENT_OUTPUT | Used to tell miniaudio that a node produces only |
2274 | | silent output. This is useful for nodes where you |
2275 | | don't want the output to contribute to the final |
2276 | | mix. An example might be if you want split your |
2277 | | stream and have one branch be output to a file. |
2278 | | When using this flag, you should avoid writing to |
2279 | | the output buffer of the node's processing |
2280 | | callback because miniaudio will ignore it anyway. |
2281 +-----------------------------------------+---------------------------------------------------+
2282
2283
2284If you need to make a copy of an audio stream for effect processing you can use a splitter node
2285called `ma_splitter_node`. This takes has 1 input bus and splits the stream into 2 output buses.
2286You can use it like this:
2287
2288 ```c
2289 ma_splitter_node_config splitterNodeConfig = ma_splitter_node_config_init(channels);
2290
2291 ma_splitter_node splitterNode;
2292 result = ma_splitter_node_init(&nodeGraph, &splitterNodeConfig, NULL, &splitterNode);
2293 if (result != MA_SUCCESS) {
2294 // Failed to create node.
2295 }
2296
2297 // Attach your output buses to two different input buses (can be on two different nodes).
2298 ma_node_attach_output_bus(&splitterNode, 0, ma_node_graph_get_endpoint(&nodeGraph), 0); // Attach directly to the endpoint.
2299 ma_node_attach_output_bus(&splitterNode, 1, &myEffectNode, 0); // Attach to input bus 0 of some effect node.
2300 ```
2301
2302The volume of an output bus can be configured on a per-bus basis:
2303
2304 ```c
2305 ma_node_set_output_bus_volume(&splitterNode, 0, 0.5f);
2306 ma_node_set_output_bus_volume(&splitterNode, 1, 0.5f);
2307 ```
2308
2309In the code above we're using the splitter node from before and changing the volume of each of the
2310copied streams.
2311
2312You can start and stop a node with the following:
2313
2314 ```c
2315 ma_node_set_state(&splitterNode, ma_node_state_started); // The default state.
2316 ma_node_set_state(&splitterNode, ma_node_state_stopped);
2317 ```
2318
2319By default the node is in a started state, but since it won't be connected to anything won't
2320actually be invoked by the node graph until it's connected. When you stop a node, data will not be
2321read from any of it's input connections. You can use this property to stop a group of sounds
2322atomically.
2323
2324You can configure the initial state of a node in it's config:
2325
2326 ```c
2327 nodeConfig.initialState = ma_node_state_stopped;
2328 ```
2329
2330Note that for the stock specialized nodes, all of their configs will have a `nodeConfig` member
2331which is the config to use with the base node. This is where the initial state can be configured
2332for specialized nodes:
2333
2334 ```c
2335 dataSourceNodeConfig.nodeConfig.initialState = ma_node_state_stopped;
2336 ```
2337
2338When using a specialized node like `ma_data_source_node` or `ma_splitter_node`, be sure to not
2339modify the `vtable` member of the `nodeConfig` object.
2340
2341
23427.1. Timing
2343-----------
2344The node graph supports starting and stopping nodes at scheduled times. This is especially useful
2345for data source nodes where you want to get the node set up, but only start playback at a specific
2346time. There are two clocks: local and global.
2347
2348A local clock is per-node, whereas the global clock is per graph. Scheduling starts and stops can
2349only be done based on the global clock because the local clock will not be running while the node
2350is stopped. The global clocks advances whenever `ma_node_graph_read_pcm_frames()` is called. On the
2351other hand, the local clock only advances when the node's processing callback is fired, and is
2352advanced based on the output frame count.
2353
2354To retrieve the global time, use `ma_node_graph_get_time()`. The global time can be set with
2355`ma_node_graph_set_time()` which might be useful if you want to do seeking on a global timeline.
2356Getting and setting the local time is similar. Use `ma_node_get_time()` to retrieve the local time,
2357and `ma_node_set_time()` to set the local time. The global and local times will be advanced by the
2358audio thread, so care should be taken to avoid data races. Ideally you should avoid calling these
2359outside of the node processing callbacks which are always run on the audio thread.
2360
2361There is basic support for scheduling the starting and stopping of nodes. You can only schedule one
2362start and one stop at a time. This is mainly intended for putting nodes into a started or stopped
2363state in a frame-exact manner. Without this mechanism, starting and stopping of a node is limited
2364to the resolution of a call to `ma_node_graph_read_pcm_frames()` which would typically be in blocks
2365of several milliseconds. The following APIs can be used for scheduling node states:
2366
2367 ```c
2368 ma_node_set_state_time()
2369 ma_node_get_state_time()
2370 ```
2371
2372The time is absolute and must be based on the global clock. An example is below:
2373
2374 ```c
2375 ma_node_set_state_time(&myNode, ma_node_state_started, sampleRate*1); // Delay starting to 1 second.
2376 ma_node_set_state_time(&myNode, ma_node_state_stopped, sampleRate*5); // Delay stopping to 5 seconds.
2377 ```
2378
2379An example for changing the state using a relative time.
2380
2381 ```c
2382 ma_node_set_state_time(&myNode, ma_node_state_started, sampleRate*1 + ma_node_graph_get_time(&myNodeGraph));
2383 ma_node_set_state_time(&myNode, ma_node_state_stopped, sampleRate*5 + ma_node_graph_get_time(&myNodeGraph));
2384 ```
2385
2386Note that due to the nature of multi-threading the times may not be 100% exact. If this is an
2387issue, consider scheduling state changes from within a processing callback. An idea might be to
2388have some kind of passthrough trigger node that is used specifically for tracking time and handling
2389events.
2390
2391
2392
23937.2. Thread Safety and Locking
2394------------------------------
2395When processing audio, it's ideal not to have any kind of locking in the audio thread. Since it's
2396expected that `ma_node_graph_read_pcm_frames()` would be run on the audio thread, it does so
2397without the use of any locks. This section discusses the implementation used by miniaudio and goes
2398over some of the compromises employed by miniaudio to achieve this goal. Note that the current
2399implementation may not be ideal - feedback and critiques are most welcome.
2400
2401The node graph API is not *entirely* lock-free. Only `ma_node_graph_read_pcm_frames()` is expected
2402to be lock-free. Attachment, detachment and uninitialization of nodes use locks to simplify the
2403implementation, but are crafted in a way such that such locking is not required when reading audio
2404data from the graph. Locking in these areas are achieved by means of spinlocks.
2405
2406The main complication with keeping `ma_node_graph_read_pcm_frames()` lock-free stems from the fact
2407that a node can be uninitialized, and it's memory potentially freed, while in the middle of being
2408processed on the audio thread. There are times when the audio thread will be referencing a node,
2409which means the uninitialization process of a node needs to make sure it delays returning until the
2410audio thread is finished so that control is not handed back to the caller thereby giving them a
2411chance to free the node's memory.
2412
2413When the audio thread is processing a node, it does so by reading from each of the output buses of
2414the node. In order for a node to process data for one of it's output buses, it needs to read from
2415each of it's input buses, and so on an so forth. It follows that once all output buses of a node
2416are detached, the node as a whole will be disconnected and no further processing will occur unless
2417it's output buses are reattached, which won't be happening when the node is being uninitialized.
2418By having `ma_node_detach_output_bus()` wait until the audio thread is finished with it, we can
2419simplify a few things, at the expense of making `ma_node_detach_output_bus()` a bit slower. By
2420doing this, the implementation of `ma_node_uninit()` becomes trivial - just detach all output
2421nodes, followed by each of the attachments to each of it's input nodes, and then do any final clean
2422up.
2423
2424With the above design, the worst-case scenario is `ma_node_detach_output_bus()` taking as long as
2425it takes to process the output bus being detached. This will happen if it's called at just the
2426wrong moment where the audio thread has just iterated it and has just started processing. The
2427caller of `ma_node_detach_output_bus()` will stall until the audio thread is finished, which
2428includes the cost of recursively processing it's inputs. This is the biggest compromise made with
2429the approach taken by miniaudio for it's lock-free processing system. The cost of detaching nodes
2430earlier in the pipeline (data sources, for example) will be cheaper than the cost of detaching
2431higher level nodes, such as some kind of final post-processing endpoint. If you need to do mass
2432detachments, detach starting from the lowest level nodes and work your way towards the final
2433endpoint node (but don't try detaching the node graph's endpoint). If the audio thread is not
2434running, detachment will be fast and detachment in any order will be the same. The reason nodes
2435need to wait for their input attachments to complete is due to the potential for desyncs between
2436data sources. If the node was to terminate processing mid way through processing it's inputs,
2437there's a chance that some of the underlying data sources will have been read, but then others not.
2438That will then result in a potential desynchronization when detaching and reattaching higher-level
2439nodes. A possible solution to this is to have an option when detaching to terminate processing
2440before processing all input attachments which should be fairly simple.
2441
2442Another compromise, albeit less significant, is locking when attaching and detaching nodes. This
2443locking is achieved by means of a spinlock in order to reduce memory overhead. A lock is present
2444for each input bus and output bus. When an output bus is connected to an input bus, both the output
2445bus and input bus is locked. This locking is specifically for attaching and detaching across
2446different threads and does not affect `ma_node_graph_read_pcm_frames()` in any way. The locking and
2447unlocking is mostly self-explanatory, but a slightly less intuitive aspect comes into it when
2448considering that iterating over attachments must not break as a result of attaching or detaching a
2449node while iteration is occurring.
2450
2451Attaching and detaching are both quite simple. When an output bus of a node is attached to an input
2452bus of another node, it's added to a linked list. Basically, an input bus is a linked list, where
2453each item in the list is and output bus. We have some intentional (and convenient) restrictions on
2454what can done with the linked list in order to simplify the implementation. First of all, whenever
2455something needs to iterate over the list, it must do so in a forward direction. Backwards iteration
2456is not supported. Also, items can only be added to the start of the list.
2457
2458The linked list is a doubly-linked list where each item in the list (an output bus) holds a pointer
2459to the next item in the list, and another to the previous item. A pointer to the previous item is
2460only required for fast detachment of the node - it is never used in iteration. This is an
2461important property because it means from the perspective of iteration, attaching and detaching of
2462an item can be done with a single atomic assignment. This is exploited by both the attachment and
2463detachment process. When attaching the node, the first thing that is done is the setting of the
2464local "next" and "previous" pointers of the node. After that, the item is "attached" to the list
2465by simply performing an atomic exchange with the head pointer. After that, the node is "attached"
2466to the list from the perspective of iteration. Even though the "previous" pointer of the next item
2467hasn't yet been set, from the perspective of iteration it's been attached because iteration will
2468only be happening in a forward direction which means the "previous" pointer won't actually ever get
2469used. The same general process applies to detachment. See `ma_node_attach_output_bus()` and
2470`ma_node_detach_output_bus()` for the implementation of this mechanism.
2471
2472
2473
24748. Decoding
2475===========
2476The `ma_decoder` API is used for reading audio files. Decoders are completely decoupled from
2477devices and can be used independently. Built-in support is included for the following formats:
2478
2479 +---------+
2480 | Format |
2481 +---------+
2482 | WAV |
2483 | MP3 |
2484 | FLAC |
2485 +---------+
2486
2487You can disable the built-in decoders by specifying one or more of the following options before the
2488miniaudio implementation:
2489
2490 ```c
2491 #define MA_NO_WAV
2492 #define MA_NO_MP3
2493 #define MA_NO_FLAC
2494 ```
2495
2496miniaudio supports the ability to plug in custom decoders. See the section below for details on how
2497to use custom decoders.
2498
2499A decoder can be initialized from a file with `ma_decoder_init_file()`, a block of memory with
2500`ma_decoder_init_memory()`, or from data delivered via callbacks with `ma_decoder_init()`. Here is
2501an example for loading a decoder from a file:
2502
2503 ```c
2504 ma_decoder decoder;
2505 ma_result result = ma_decoder_init_file("MySong.mp3", NULL, &decoder);
2506 if (result != MA_SUCCESS) {
2507 return false; // An error occurred.
2508 }
2509
2510 ...
2511
2512 ma_decoder_uninit(&decoder);
2513 ```
2514
2515When initializing a decoder, you can optionally pass in a pointer to a `ma_decoder_config` object
2516(the `NULL` argument in the example above) which allows you to configure the output format, channel
2517count, sample rate and channel map:
2518
2519 ```c
2520 ma_decoder_config config = ma_decoder_config_init(ma_format_f32, 2, 48000);
2521 ```
2522
2523When passing in `NULL` for decoder config in `ma_decoder_init*()`, the output format will be the
2524same as that defined by the decoding backend.
2525
2526Data is read from the decoder as PCM frames. This will output the number of PCM frames actually
2527read. If this is less than the requested number of PCM frames it means you've reached the end. The
2528return value will be `MA_AT_END` if no samples have been read and the end has been reached.
2529
2530 ```c
2531 ma_result result = ma_decoder_read_pcm_frames(pDecoder, pFrames, framesToRead, &framesRead);
2532 if (framesRead < framesToRead) {
2533 // Reached the end.
2534 }
2535 ```
2536
2537You can also seek to a specific frame like so:
2538
2539 ```c
2540 ma_result result = ma_decoder_seek_to_pcm_frame(pDecoder, targetFrame);
2541 if (result != MA_SUCCESS) {
2542 return false; // An error occurred.
2543 }
2544 ```
2545
2546If you want to loop back to the start, you can simply seek back to the first PCM frame:
2547
2548 ```c
2549 ma_decoder_seek_to_pcm_frame(pDecoder, 0);
2550 ```
2551
2552When loading a decoder, miniaudio uses a trial and error technique to find the appropriate decoding
2553backend. This can be unnecessarily inefficient if the type is already known. In this case you can
2554use `encodingFormat` variable in the device config to specify a specific encoding format you want
2555to decode:
2556
2557 ```c
2558 decoderConfig.encodingFormat = ma_encoding_format_wav;
2559 ```
2560
2561See the `ma_encoding_format` enum for possible encoding formats.
2562
2563The `ma_decoder_init_file()` API will try using the file extension to determine which decoding
2564backend to prefer.
2565
2566
25678.1. Custom Decoders
2568--------------------
2569It's possible to implement a custom decoder and plug it into miniaudio. This is extremely useful
2570when you want to use the `ma_decoder` API, but need to support an encoding format that's not one of
2571the stock formats supported by miniaudio. This can be put to particularly good use when using the
2572`ma_engine` and/or `ma_resource_manager` APIs because they use `ma_decoder` internally. If, for
2573example, you wanted to support Opus, you can do so with a custom decoder (there if a reference
2574Opus decoder in the "extras" folder of the miniaudio repository which uses libopus + libopusfile).
2575
2576A custom decoder must implement a data source. A vtable called `ma_decoding_backend_vtable` needs
2577to be implemented which is then passed into the decoder config:
2578
2579 ```c
2580 ma_decoding_backend_vtable* pCustomBackendVTables[] =
2581 {
2582 &g_ma_decoding_backend_vtable_libvorbis,
2583 &g_ma_decoding_backend_vtable_libopus
2584 };
2585
2586 ...
2587
2588 decoderConfig = ma_decoder_config_init_default();
2589 decoderConfig.pCustomBackendUserData = NULL;
2590 decoderConfig.ppCustomBackendVTables = pCustomBackendVTables;
2591 decoderConfig.customBackendCount = sizeof(pCustomBackendVTables) / sizeof(pCustomBackendVTables[0]);
2592 ```
2593
2594The `ma_decoding_backend_vtable` vtable has the following functions:
2595
2596 ```
2597 onInit
2598 onInitFile
2599 onInitFileW
2600 onInitMemory
2601 onUninit
2602 ```
2603
2604There are only two functions that must be implemented - `onInit` and `onUninit`. The other
2605functions can be implemented for a small optimization for loading from a file path or memory. If
2606these are not specified, miniaudio will deal with it for you via a generic implementation.
2607
2608When you initialize a custom data source (by implementing the `onInit` function in the vtable) you
2609will need to output a pointer to a `ma_data_source` which implements your custom decoder. See the
2610section about data sources for details on how to implement this. Alternatively, see the
2611"custom_decoders" example in the miniaudio repository.
2612
2613The `onInit` function takes a pointer to some callbacks for the purpose of reading raw audio data
2614from some arbitrary source. You'll use these functions to read from the raw data and perform the
2615decoding. When you call them, you will pass in the `pReadSeekTellUserData` pointer to the relevant
2616parameter.
2617
2618The `pConfig` parameter in `onInit` can be used to configure the backend if appropriate. It's only
2619used as a hint and can be ignored. However, if any of the properties are relevant to your decoder,
2620an optimal implementation will handle the relevant properties appropriately.
2621
2622If memory allocation is required, it should be done so via the specified allocation callbacks if
2623possible (the `pAllocationCallbacks` parameter).
2624
2625If an error occurs when initializing the decoder, you should leave `ppBackend` unset, or set to
2626NULL, and make sure everything is cleaned up appropriately and an appropriate result code returned.
2627When multiple custom backends are specified, miniaudio will cycle through the vtables in the order
2628they're listed in the array that's passed into the decoder config so it's important that your
2629initialization routine is clean.
2630
2631When a decoder is uninitialized, the `onUninit` callback will be fired which will give you an
2632opportunity to clean up and internal data.
2633
2634
2635
26369. Encoding
2637===========
2638The `ma_encoding` API is used for writing audio files. The only supported output format is WAV.
2639This can be disabled by specifying the following option before the implementation of miniaudio:
2640
2641 ```c
2642 #define MA_NO_WAV
2643 ```
2644
2645An encoder can be initialized to write to a file with `ma_encoder_init_file()` or from data
2646delivered via callbacks with `ma_encoder_init()`. Below is an example for initializing an encoder
2647to output to a file.
2648
2649 ```c
2650 ma_encoder_config config = ma_encoder_config_init(ma_encoding_format_wav, FORMAT, CHANNELS, SAMPLE_RATE);
2651 ma_encoder encoder;
2652 ma_result result = ma_encoder_init_file("my_file.wav", &config, &encoder);
2653 if (result != MA_SUCCESS) {
2654 // Error
2655 }
2656
2657 ...
2658
2659 ma_encoder_uninit(&encoder);
2660 ```
2661
2662When initializing an encoder you must specify a config which is initialized with
2663`ma_encoder_config_init()`. Here you must specify the file type, the output sample format, output
2664channel count and output sample rate. The following file types are supported:
2665
2666 +------------------------+-------------+
2667 | Enum | Description |
2668 +------------------------+-------------+
2669 | ma_encoding_format_wav | WAV |
2670 +------------------------+-------------+
2671
2672If the format, channel count or sample rate is not supported by the output file type an error will
2673be returned. The encoder will not perform data conversion so you will need to convert it before
2674outputting any audio data. To output audio data, use `ma_encoder_write_pcm_frames()`, like in the
2675example below:
2676
2677 ```c
2678 ma_uint64 framesWritten;
2679 result = ma_encoder_write_pcm_frames(&encoder, pPCMFramesToWrite, framesToWrite, &framesWritten);
2680 if (result != MA_SUCCESS) {
2681 ... handle error ...
2682 }
2683 ```
2684
2685The `framesWritten` variable will contain the number of PCM frames that were actually written. This
2686is optionally and you can pass in `NULL` if you need this.
2687
2688Encoders must be uninitialized with `ma_encoder_uninit()`.
2689
2690
2691
269210. Data Conversion
2693===================
2694A data conversion API is included with miniaudio which supports the majority of data conversion
2695requirements. This supports conversion between sample formats, channel counts (with channel
2696mapping) and sample rates.
2697
2698
269910.1. Sample Format Conversion
2700------------------------------
2701Conversion between sample formats is achieved with the `ma_pcm_*_to_*()`, `ma_pcm_convert()` and
2702`ma_convert_pcm_frames_format()` APIs. Use `ma_pcm_*_to_*()` to convert between two specific
2703formats. Use `ma_pcm_convert()` to convert based on a `ma_format` variable. Use
2704`ma_convert_pcm_frames_format()` to convert PCM frames where you want to specify the frame count
2705and channel count as a variable instead of the total sample count.
2706
2707
270810.1.1. Dithering
2709-----------------
2710Dithering can be set using the ditherMode parameter.
2711
2712The different dithering modes include the following, in order of efficiency:
2713
2714 +-----------+--------------------------+
2715 | Type | Enum Token |
2716 +-----------+--------------------------+
2717 | None | ma_dither_mode_none |
2718 | Rectangle | ma_dither_mode_rectangle |
2719 | Triangle | ma_dither_mode_triangle |
2720 +-----------+--------------------------+
2721
2722Note that even if the dither mode is set to something other than `ma_dither_mode_none`, it will be
2723ignored for conversions where dithering is not needed. Dithering is available for the following
2724conversions:
2725
2726 ```
2727 s16 -> u8
2728 s24 -> u8
2729 s32 -> u8
2730 f32 -> u8
2731 s24 -> s16
2732 s32 -> s16
2733 f32 -> s16
2734 ```
2735
2736Note that it is not an error to pass something other than ma_dither_mode_none for conversions where
2737dither is not used. It will just be ignored.
2738
2739
2740
274110.2. Channel Conversion
2742------------------------
2743Channel conversion is used for channel rearrangement and conversion from one channel count to
2744another. The `ma_channel_converter` API is used for channel conversion. Below is an example of
2745initializing a simple channel converter which converts from mono to stereo.
2746
2747 ```c
2748 ma_channel_converter_config config = ma_channel_converter_config_init(
2749 ma_format, // Sample format
2750 1, // Input channels
2751 NULL, // Input channel map
2752 2, // Output channels
2753 NULL, // Output channel map
2754 ma_channel_mix_mode_default); // The mixing algorithm to use when combining channels.
2755
2756 result = ma_channel_converter_init(&config, NULL, &converter);
2757 if (result != MA_SUCCESS) {
2758 // Error.
2759 }
2760 ```
2761
2762To perform the conversion simply call `ma_channel_converter_process_pcm_frames()` like so:
2763
2764 ```c
2765 ma_result result = ma_channel_converter_process_pcm_frames(&converter, pFramesOut, pFramesIn, frameCount);
2766 if (result != MA_SUCCESS) {
2767 // Error.
2768 }
2769 ```
2770
2771It is up to the caller to ensure the output buffer is large enough to accommodate the new PCM
2772frames.
2773
2774Input and output PCM frames are always interleaved. Deinterleaved layouts are not supported.
2775
2776
277710.2.1. Channel Mapping
2778-----------------------
2779In addition to converting from one channel count to another, like the example above, the channel
2780converter can also be used to rearrange channels. When initializing the channel converter, you can
2781optionally pass in channel maps for both the input and output frames. If the channel counts are the
2782same, and each channel map contains the same channel positions with the exception that they're in
2783a different order, a simple shuffling of the channels will be performed. If, however, there is not
2784a 1:1 mapping of channel positions, or the channel counts differ, the input channels will be mixed
2785based on a mixing mode which is specified when initializing the `ma_channel_converter_config`
2786object.
2787
2788When converting from mono to multi-channel, the mono channel is simply copied to each output
2789channel. When going the other way around, the audio of each output channel is simply averaged and
2790copied to the mono channel.
2791
2792In more complicated cases blending is used. The `ma_channel_mix_mode_simple` mode will drop excess
2793channels and silence extra channels. For example, converting from 4 to 2 channels, the 3rd and 4th
2794channels will be dropped, whereas converting from 2 to 4 channels will put silence into the 3rd and
27954th channels.
2796
2797The `ma_channel_mix_mode_rectangle` mode uses spacial locality based on a rectangle to compute a
2798simple distribution between input and output. Imagine sitting in the middle of a room, with
2799speakers on the walls representing channel positions. The `MA_CHANNEL_FRONT_LEFT` position can be
2800thought of as being in the corner of the front and left walls.
2801
2802Finally, the `ma_channel_mix_mode_custom_weights` mode can be used to use custom user-defined
2803weights. Custom weights can be passed in as the last parameter of
2804`ma_channel_converter_config_init()`.
2805
2806Predefined channel maps can be retrieved with `ma_channel_map_init_standard()`. This takes a
2807`ma_standard_channel_map` enum as it's first parameter, which can be one of the following:
2808
2809 +-----------------------------------+-----------------------------------------------------------+
2810 | Name | Description |
2811 +-----------------------------------+-----------------------------------------------------------+
2812 | ma_standard_channel_map_default | Default channel map used by miniaudio. See below. |
2813 | ma_standard_channel_map_microsoft | Channel map used by Microsoft's bitfield channel maps. |
2814 | ma_standard_channel_map_alsa | Default ALSA channel map. |
2815 | ma_standard_channel_map_rfc3551 | RFC 3551. Based on AIFF. |
2816 | ma_standard_channel_map_flac | FLAC channel map. |
2817 | ma_standard_channel_map_vorbis | Vorbis channel map. |
2818 | ma_standard_channel_map_sound4 | FreeBSD's sound(4). |
2819 | ma_standard_channel_map_sndio | sndio channel map. http://www.sndio.org/tips.html. |
2820 | ma_standard_channel_map_webaudio | https://webaudio.github.io/web-audio-api/#ChannelOrdering |
2821 +-----------------------------------+-----------------------------------------------------------+
2822
2823Below are the channel maps used by default in miniaudio (`ma_standard_channel_map_default`):
2824
2825 +---------------+---------------------------------+
2826 | Channel Count | Mapping |
2827 +---------------+---------------------------------+
2828 | 1 (Mono) | 0: MA_CHANNEL_MONO |
2829 +---------------+---------------------------------+
2830 | 2 (Stereo) | 0: MA_CHANNEL_FRONT_LEFT <br> |
2831 | | 1: MA_CHANNEL_FRONT_RIGHT |
2832 +---------------+---------------------------------+
2833 | 3 | 0: MA_CHANNEL_FRONT_LEFT <br> |
2834 | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
2835 | | 2: MA_CHANNEL_FRONT_CENTER |
2836 +---------------+---------------------------------+
2837 | 4 (Surround) | 0: MA_CHANNEL_FRONT_LEFT <br> |
2838 | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
2839 | | 2: MA_CHANNEL_FRONT_CENTER <br> |
2840 | | 3: MA_CHANNEL_BACK_CENTER |
2841 +---------------+---------------------------------+
2842 | 5 | 0: MA_CHANNEL_FRONT_LEFT <br> |
2843 | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
2844 | | 2: MA_CHANNEL_FRONT_CENTER <br> |
2845 | | 3: MA_CHANNEL_BACK_LEFT <br> |
2846 | | 4: MA_CHANNEL_BACK_RIGHT |
2847 +---------------+---------------------------------+
2848 | 6 (5.1) | 0: MA_CHANNEL_FRONT_LEFT <br> |
2849 | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
2850 | | 2: MA_CHANNEL_FRONT_CENTER <br> |
2851 | | 3: MA_CHANNEL_LFE <br> |
2852 | | 4: MA_CHANNEL_SIDE_LEFT <br> |
2853 | | 5: MA_CHANNEL_SIDE_RIGHT |
2854 +---------------+---------------------------------+
2855 | 7 | 0: MA_CHANNEL_FRONT_LEFT <br> |
2856 | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
2857 | | 2: MA_CHANNEL_FRONT_CENTER <br> |
2858 | | 3: MA_CHANNEL_LFE <br> |
2859 | | 4: MA_CHANNEL_BACK_CENTER <br> |
2860 | | 4: MA_CHANNEL_SIDE_LEFT <br> |
2861 | | 5: MA_CHANNEL_SIDE_RIGHT |
2862 +---------------+---------------------------------+
2863 | 8 (7.1) | 0: MA_CHANNEL_FRONT_LEFT <br> |
2864 | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
2865 | | 2: MA_CHANNEL_FRONT_CENTER <br> |
2866 | | 3: MA_CHANNEL_LFE <br> |
2867 | | 4: MA_CHANNEL_BACK_LEFT <br> |
2868 | | 5: MA_CHANNEL_BACK_RIGHT <br> |
2869 | | 6: MA_CHANNEL_SIDE_LEFT <br> |
2870 | | 7: MA_CHANNEL_SIDE_RIGHT |
2871 +---------------+---------------------------------+
2872 | Other | All channels set to 0. This |
2873 | | is equivalent to the same |
2874 | | mapping as the device. |
2875 +---------------+---------------------------------+
2876
2877
2878
287910.3. Resampling
2880----------------
2881Resampling is achieved with the `ma_resampler` object. To create a resampler object, do something
2882like the following:
2883
2884 ```c
2885 ma_resampler_config config = ma_resampler_config_init(
2886 ma_format_s16,
2887 channels,
2888 sampleRateIn,
2889 sampleRateOut,
2890 ma_resample_algorithm_linear);
2891
2892 ma_resampler resampler;
2893 ma_result result = ma_resampler_init(&config, &resampler);
2894 if (result != MA_SUCCESS) {
2895 // An error occurred...
2896 }
2897 ```
2898
2899Do the following to uninitialize the resampler:
2900
2901 ```c
2902 ma_resampler_uninit(&resampler);
2903 ```
2904
2905The following example shows how data can be processed
2906
2907 ```c
2908 ma_uint64 frameCountIn = 1000;
2909 ma_uint64 frameCountOut = 2000;
2910 ma_result result = ma_resampler_process_pcm_frames(&resampler, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut);
2911 if (result != MA_SUCCESS) {
2912 // An error occurred...
2913 }
2914
2915 // At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the
2916 // number of output frames written.
2917 ```
2918
2919To initialize the resampler you first need to set up a config (`ma_resampler_config`) with
2920`ma_resampler_config_init()`. You need to specify the sample format you want to use, the number of
2921channels, the input and output sample rate, and the algorithm.
2922
2923The sample format can be either `ma_format_s16` or `ma_format_f32`. If you need a different format
2924you will need to perform pre- and post-conversions yourself where necessary. Note that the format
2925is the same for both input and output. The format cannot be changed after initialization.
2926
2927The resampler supports multiple channels and is always interleaved (both input and output). The
2928channel count cannot be changed after initialization.
2929
2930The sample rates can be anything other than zero, and are always specified in hertz. They should be
2931set to something like 44100, etc. The sample rate is the only configuration property that can be
2932changed after initialization.
2933
2934The miniaudio resampler has built-in support for the following algorithms:
2935
2936 +-----------+------------------------------+
2937 | Algorithm | Enum Token |
2938 +-----------+------------------------------+
2939 | Linear | ma_resample_algorithm_linear |
2940 | Custom | ma_resample_algorithm_custom |
2941 +-----------+------------------------------+
2942
2943The algorithm cannot be changed after initialization.
2944
2945Processing always happens on a per PCM frame basis and always assumes interleaved input and output.
2946De-interleaved processing is not supported. To process frames, use
2947`ma_resampler_process_pcm_frames()`. On input, this function takes the number of output frames you
2948can fit in the output buffer and the number of input frames contained in the input buffer. On
2949output these variables contain the number of output frames that were written to the output buffer
2950and the number of input frames that were consumed in the process. You can pass in NULL for the
2951input buffer in which case it will be treated as an infinitely large buffer of zeros. The output
2952buffer can also be NULL, in which case the processing will be treated as seek.
2953
2954The sample rate can be changed dynamically on the fly. You can change this with explicit sample
2955rates with `ma_resampler_set_rate()` and also with a decimal ratio with
2956`ma_resampler_set_rate_ratio()`. The ratio is in/out.
2957
2958Sometimes it's useful to know exactly how many input frames will be required to output a specific
2959number of frames. You can calculate this with `ma_resampler_get_required_input_frame_count()`.
2960Likewise, it's sometimes useful to know exactly how many frames would be output given a certain
2961number of input frames. You can do this with `ma_resampler_get_expected_output_frame_count()`.
2962
2963Due to the nature of how resampling works, the resampler introduces some latency. This can be
2964retrieved in terms of both the input rate and the output rate with
2965`ma_resampler_get_input_latency()` and `ma_resampler_get_output_latency()`.
2966
2967
296810.3.1. Resampling Algorithms
2969-----------------------------
2970The choice of resampling algorithm depends on your situation and requirements.
2971
2972
297310.3.1.1. Linear Resampling
2974---------------------------
2975The linear resampler is the fastest, but comes at the expense of poorer quality. There is, however,
2976some control over the quality of the linear resampler which may make it a suitable option depending
2977on your requirements.
2978
2979The linear resampler performs low-pass filtering before or after downsampling or upsampling,
2980depending on the sample rates you're converting between. When decreasing the sample rate, the
2981low-pass filter will be applied before downsampling. When increasing the rate it will be performed
2982after upsampling. By default a fourth order low-pass filter will be applied. This can be configured
2983via the `lpfOrder` configuration variable. Setting this to 0 will disable filtering.
2984
2985The low-pass filter has a cutoff frequency which defaults to half the sample rate of the lowest of
2986the input and output sample rates (Nyquist Frequency).
2987
2988The API for the linear resampler is the same as the main resampler API, only it's called
2989`ma_linear_resampler`.
2990
2991
299210.3.2. Custom Resamplers
2993-------------------------
2994You can implement a custom resampler by using the `ma_resample_algorithm_custom` resampling
2995algorithm and setting a vtable in the resampler config:
2996
2997 ```c
2998 ma_resampler_config config = ma_resampler_config_init(..., ma_resample_algorithm_custom);
2999 config.pBackendVTable = &g_customResamplerVTable;
3000 ```
3001
3002Custom resamplers are useful if the stock algorithms are not appropriate for your use case. You
3003need to implement the required functions in `ma_resampling_backend_vtable`. Note that not all
3004functions in the vtable need to be implemented, but if it's possible to implement, they should be.
3005
3006You can use the `ma_linear_resampler` object for an example on how to implement the vtable. The
3007`onGetHeapSize` callback is used to calculate the size of any internal heap allocation the custom
3008resampler will need to make given the supplied config. When you initialize the resampler via the
3009`onInit` callback, you'll be given a pointer to a heap allocation which is where you should store
3010the heap allocated data. You should not free this data in `onUninit` because miniaudio will manage
3011it for you.
3012
3013The `onProcess` callback is where the actual resampling takes place. On input, `pFrameCountIn`
3014points to a variable containing the number of frames in the `pFramesIn` buffer and
3015`pFrameCountOut` points to a variable containing the capacity in frames of the `pFramesOut` buffer.
3016On output, `pFrameCountIn` should be set to the number of input frames that were fully consumed,
3017whereas `pFrameCountOut` should be set to the number of frames that were written to `pFramesOut`.
3018
3019The `onSetRate` callback is optional and is used for dynamically changing the sample rate. If
3020dynamic rate changes are not supported, you can set this callback to NULL.
3021
3022The `onGetInputLatency` and `onGetOutputLatency` functions are used for retrieving the latency in
3023input and output rates respectively. These can be NULL in which case latency calculations will be
3024assumed to be NULL.
3025
3026The `onGetRequiredInputFrameCount` callback is used to give miniaudio a hint as to how many input
3027frames are required to be available to produce the given number of output frames. Likewise, the
3028`onGetExpectedOutputFrameCount` callback is used to determine how many output frames will be
3029produced given the specified number of input frames. miniaudio will use these as a hint, but they
3030are optional and can be set to NULL if you're unable to implement them.
3031
3032
3033
303410.4. General Data Conversion
3035-----------------------------
3036The `ma_data_converter` API can be used to wrap sample format conversion, channel conversion and
3037resampling into one operation. This is what miniaudio uses internally to convert between the format
3038requested when the device was initialized and the format of the backend's native device. The API
3039for general data conversion is very similar to the resampling API. Create a `ma_data_converter`
3040object like this:
3041
3042 ```c
3043 ma_data_converter_config config = ma_data_converter_config_init(
3044 inputFormat,
3045 outputFormat,
3046 inputChannels,
3047 outputChannels,
3048 inputSampleRate,
3049 outputSampleRate
3050 );
3051
3052 ma_data_converter converter;
3053 ma_result result = ma_data_converter_init(&config, NULL, &converter);
3054 if (result != MA_SUCCESS) {
3055 // An error occurred...
3056 }
3057 ```
3058
3059In the example above we use `ma_data_converter_config_init()` to initialize the config, however
3060there's many more properties that can be configured, such as channel maps and resampling quality.
3061Something like the following may be more suitable depending on your requirements:
3062
3063 ```c
3064 ma_data_converter_config config = ma_data_converter_config_init_default();
3065 config.formatIn = inputFormat;
3066 config.formatOut = outputFormat;
3067 config.channelsIn = inputChannels;
3068 config.channelsOut = outputChannels;
3069 config.sampleRateIn = inputSampleRate;
3070 config.sampleRateOut = outputSampleRate;
3071 ma_channel_map_init_standard(ma_standard_channel_map_flac, config.channelMapIn, sizeof(config.channelMapIn)/sizeof(config.channelMapIn[0]), config.channelCountIn);
3072 config.resampling.linear.lpfOrder = MA_MAX_FILTER_ORDER;
3073 ```
3074
3075Do the following to uninitialize the data converter:
3076
3077 ```c
3078 ma_data_converter_uninit(&converter, NULL);
3079 ```
3080
3081The following example shows how data can be processed
3082
3083 ```c
3084 ma_uint64 frameCountIn = 1000;
3085 ma_uint64 frameCountOut = 2000;
3086 ma_result result = ma_data_converter_process_pcm_frames(&converter, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut);
3087 if (result != MA_SUCCESS) {
3088 // An error occurred...
3089 }
3090
3091 // At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the number
3092 // of output frames written.
3093 ```
3094
3095The data converter supports multiple channels and is always interleaved (both input and output).
3096The channel count cannot be changed after initialization.
3097
3098Sample rates can be anything other than zero, and are always specified in hertz. They should be set
3099to something like 44100, etc. The sample rate is the only configuration property that can be
3100changed after initialization, but only if the `resampling.allowDynamicSampleRate` member of
3101`ma_data_converter_config` is set to `MA_TRUE`. To change the sample rate, use
3102`ma_data_converter_set_rate()` or `ma_data_converter_set_rate_ratio()`. The ratio must be in/out.
3103The resampling algorithm cannot be changed after initialization.
3104
3105Processing always happens on a per PCM frame basis and always assumes interleaved input and output.
3106De-interleaved processing is not supported. To process frames, use
3107`ma_data_converter_process_pcm_frames()`. On input, this function takes the number of output frames
3108you can fit in the output buffer and the number of input frames contained in the input buffer. On
3109output these variables contain the number of output frames that were written to the output buffer
3110and the number of input frames that were consumed in the process. You can pass in NULL for the
3111input buffer in which case it will be treated as an infinitely large
3112buffer of zeros. The output buffer can also be NULL, in which case the processing will be treated
3113as seek.
3114
3115Sometimes it's useful to know exactly how many input frames will be required to output a specific
3116number of frames. You can calculate this with `ma_data_converter_get_required_input_frame_count()`.
3117Likewise, it's sometimes useful to know exactly how many frames would be output given a certain
3118number of input frames. You can do this with `ma_data_converter_get_expected_output_frame_count()`.
3119
3120Due to the nature of how resampling works, the data converter introduces some latency if resampling
3121is required. This can be retrieved in terms of both the input rate and the output rate with
3122`ma_data_converter_get_input_latency()` and `ma_data_converter_get_output_latency()`.
3123
3124
3125
312611. Filtering
3127=============
3128
312911.1. Biquad Filtering
3130----------------------
3131Biquad filtering is achieved with the `ma_biquad` API. Example:
3132
3133 ```c
3134 ma_biquad_config config = ma_biquad_config_init(ma_format_f32, channels, b0, b1, b2, a0, a1, a2);
3135 ma_result result = ma_biquad_init(&config, &biquad);
3136 if (result != MA_SUCCESS) {
3137 // Error.
3138 }
3139
3140 ...
3141
3142 ma_biquad_process_pcm_frames(&biquad, pFramesOut, pFramesIn, frameCount);
3143 ```
3144
3145Biquad filtering is implemented using transposed direct form 2. The numerator coefficients are b0,
3146b1 and b2, and the denominator coefficients are a0, a1 and a2. The a0 coefficient is required and
3147coefficients must not be pre-normalized.
3148
3149Supported formats are `ma_format_s16` and `ma_format_f32`. If you need to use a different format
3150you need to convert it yourself beforehand. When using `ma_format_s16` the biquad filter will use
3151fixed point arithmetic. When using `ma_format_f32`, floating point arithmetic will be used.
3152
3153Input and output frames are always interleaved.
3154
3155Filtering can be applied in-place by passing in the same pointer for both the input and output
3156buffers, like so:
3157
3158 ```c
3159 ma_biquad_process_pcm_frames(&biquad, pMyData, pMyData, frameCount);
3160 ```
3161
3162If you need to change the values of the coefficients, but maintain the values in the registers you
3163can do so with `ma_biquad_reinit()`. This is useful if you need to change the properties of the
3164filter while keeping the values of registers valid to avoid glitching. Do not use
3165`ma_biquad_init()` for this as it will do a full initialization which involves clearing the
3166registers to 0. Note that changing the format or channel count after initialization is invalid and
3167will result in an error.
3168
3169
317011.2. Low-Pass Filtering
3171------------------------
3172Low-pass filtering is achieved with the following APIs:
3173
3174 +---------+------------------------------------------+
3175 | API | Description |
3176 +---------+------------------------------------------+
3177 | ma_lpf1 | First order low-pass filter |
3178 | ma_lpf2 | Second order low-pass filter |
3179 | ma_lpf | High order low-pass filter (Butterworth) |
3180 +---------+------------------------------------------+
3181
3182Low-pass filter example:
3183
3184 ```c
3185 ma_lpf_config config = ma_lpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
3186 ma_result result = ma_lpf_init(&config, &lpf);
3187 if (result != MA_SUCCESS) {
3188 // Error.
3189 }
3190
3191 ...
3192
3193 ma_lpf_process_pcm_frames(&lpf, pFramesOut, pFramesIn, frameCount);
3194 ```
3195
3196Supported formats are `ma_format_s16` and` ma_format_f32`. If you need to use a different format
3197you need to convert it yourself beforehand. Input and output frames are always interleaved.
3198
3199Filtering can be applied in-place by passing in the same pointer for both the input and output
3200buffers, like so:
3201
3202 ```c
3203 ma_lpf_process_pcm_frames(&lpf, pMyData, pMyData, frameCount);
3204 ```
3205
3206The maximum filter order is limited to `MA_MAX_FILTER_ORDER` which is set to 8. If you need more,
3207you can chain first and second order filters together.
3208
3209 ```c
3210 for (iFilter = 0; iFilter < filterCount; iFilter += 1) {
3211 ma_lpf2_process_pcm_frames(&lpf2[iFilter], pMyData, pMyData, frameCount);
3212 }
3213 ```
3214
3215If you need to change the configuration of the filter, but need to maintain the state of internal
3216registers you can do so with `ma_lpf_reinit()`. This may be useful if you need to change the sample
3217rate and/or cutoff frequency dynamically while maintaining smooth transitions. Note that changing the
3218format or channel count after initialization is invalid and will result in an error.
3219
3220The `ma_lpf` object supports a configurable order, but if you only need a first order filter you
3221may want to consider using `ma_lpf1`. Likewise, if you only need a second order filter you can use
3222`ma_lpf2`. The advantage of this is that they're lighter weight and a bit more efficient.
3223
3224If an even filter order is specified, a series of second order filters will be processed in a
3225chain. If an odd filter order is specified, a first order filter will be applied, followed by a
3226series of second order filters in a chain.
3227
3228
322911.3. High-Pass Filtering
3230-------------------------
3231High-pass filtering is achieved with the following APIs:
3232
3233 +---------+-------------------------------------------+
3234 | API | Description |
3235 +---------+-------------------------------------------+
3236 | ma_hpf1 | First order high-pass filter |
3237 | ma_hpf2 | Second order high-pass filter |
3238 | ma_hpf | High order high-pass filter (Butterworth) |
3239 +---------+-------------------------------------------+
3240
3241High-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_hpf1`,
3242`ma_hpf2` and `ma_hpf`. See example code for low-pass filters for example usage.
3243
3244
324511.4. Band-Pass Filtering
3246-------------------------
3247Band-pass filtering is achieved with the following APIs:
3248
3249 +---------+-------------------------------+
3250 | API | Description |
3251 +---------+-------------------------------+
3252 | ma_bpf2 | Second order band-pass filter |
3253 | ma_bpf | High order band-pass filter |
3254 +---------+-------------------------------+
3255
3256Band-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_bpf2` and
3257`ma_hpf`. See example code for low-pass filters for example usage. Note that the order for
3258band-pass filters must be an even number which means there is no first order band-pass filter,
3259unlike low-pass and high-pass filters.
3260
3261
326211.5. Notch Filtering
3263---------------------
3264Notch filtering is achieved with the following APIs:
3265
3266 +-----------+------------------------------------------+
3267 | API | Description |
3268 +-----------+------------------------------------------+
3269 | ma_notch2 | Second order notching filter |
3270 +-----------+------------------------------------------+
3271
3272
327311.6. Peaking EQ Filtering
3274-------------------------
3275Peaking filtering is achieved with the following APIs:
3276
3277 +----------+------------------------------------------+
3278 | API | Description |
3279 +----------+------------------------------------------+
3280 | ma_peak2 | Second order peaking filter |
3281 +----------+------------------------------------------+
3282
3283
328411.7. Low Shelf Filtering
3285-------------------------
3286Low shelf filtering is achieved with the following APIs:
3287
3288 +-------------+------------------------------------------+
3289 | API | Description |
3290 +-------------+------------------------------------------+
3291 | ma_loshelf2 | Second order low shelf filter |
3292 +-------------+------------------------------------------+
3293
3294Where a high-pass filter is used to eliminate lower frequencies, a low shelf filter can be used to
3295just turn them down rather than eliminate them entirely.
3296
3297
329811.8. High Shelf Filtering
3299--------------------------
3300High shelf filtering is achieved with the following APIs:
3301
3302 +-------------+------------------------------------------+
3303 | API | Description |
3304 +-------------+------------------------------------------+
3305 | ma_hishelf2 | Second order high shelf filter |
3306 +-------------+------------------------------------------+
3307
3308The high shelf filter has the same API as the low shelf filter, only you would use `ma_hishelf`
3309instead of `ma_loshelf`. Where a low shelf filter is used to adjust the volume of low frequencies,
3310the high shelf filter does the same thing for high frequencies.
3311
3312
3313
3314
331512. Waveform and Noise Generation
3316=================================
3317
331812.1. Waveforms
3319---------------
3320miniaudio supports generation of sine, square, triangle and sawtooth waveforms. This is achieved
3321with the `ma_waveform` API. Example:
3322
3323 ```c
3324 ma_waveform_config config = ma_waveform_config_init(
3325 FORMAT,
3326 CHANNELS,
3327 SAMPLE_RATE,
3328 ma_waveform_type_sine,
3329 amplitude,
3330 frequency);
3331
3332 ma_waveform waveform;
3333 ma_result result = ma_waveform_init(&config, &waveform);
3334 if (result != MA_SUCCESS) {
3335 // Error.
3336 }
3337
3338 ...
3339
3340 ma_waveform_read_pcm_frames(&waveform, pOutput, frameCount);
3341 ```
3342
3343The amplitude, frequency, type, and sample rate can be changed dynamically with
3344`ma_waveform_set_amplitude()`, `ma_waveform_set_frequency()`, `ma_waveform_set_type()`, and
3345`ma_waveform_set_sample_rate()` respectively.
3346
3347You can invert the waveform by setting the amplitude to a negative value. You can use this to
3348control whether or not a sawtooth has a positive or negative ramp, for example.
3349
3350Below are the supported waveform types:
3351
3352 +---------------------------+
3353 | Enum Name |
3354 +---------------------------+
3355 | ma_waveform_type_sine |
3356 | ma_waveform_type_square |
3357 | ma_waveform_type_triangle |
3358 | ma_waveform_type_sawtooth |
3359 +---------------------------+
3360
3361
3362
336312.2. Noise
3364-----------
3365miniaudio supports generation of white, pink and Brownian noise via the `ma_noise` API. Example:
3366
3367 ```c
3368 ma_noise_config config = ma_noise_config_init(
3369 FORMAT,
3370 CHANNELS,
3371 ma_noise_type_white,
3372 SEED,
3373 amplitude);
3374
3375 ma_noise noise;
3376 ma_result result = ma_noise_init(&config, &noise);
3377 if (result != MA_SUCCESS) {
3378 // Error.
3379 }
3380
3381 ...
3382
3383 ma_noise_read_pcm_frames(&noise, pOutput, frameCount);
3384 ```
3385
3386The noise API uses simple LCG random number generation. It supports a custom seed which is useful
3387for things like automated testing requiring reproducibility. Setting the seed to zero will default
3388to `MA_DEFAULT_LCG_SEED`.
3389
3390The amplitude and seed can be changed dynamically with `ma_noise_set_amplitude()` and
3391`ma_noise_set_seed()` respectively.
3392
3393By default, the noise API will use different values for different channels. So, for example, the
3394left side in a stereo stream will be different to the right side. To instead have each channel use
3395the same random value, set the `duplicateChannels` member of the noise config to true, like so:
3396
3397 ```c
3398 config.duplicateChannels = MA_TRUE;
3399 ```
3400
3401Below are the supported noise types.
3402
3403 +------------------------+
3404 | Enum Name |
3405 +------------------------+
3406 | ma_noise_type_white |
3407 | ma_noise_type_pink |
3408 | ma_noise_type_brownian |
3409 +------------------------+
3410
3411
3412
341313. Audio Buffers
3414=================
3415miniaudio supports reading from a buffer of raw audio data via the `ma_audio_buffer` API. This can
3416read from memory that's managed by the application, but can also handle the memory management for
3417you internally. Memory management is flexible and should support most use cases.
3418
3419Audio buffers are initialized using the standard configuration system used everywhere in miniaudio:
3420
3421 ```c
3422 ma_audio_buffer_config config = ma_audio_buffer_config_init(
3423 format,
3424 channels,
3425 sizeInFrames,
3426 pExistingData,
3427 &allocationCallbacks);
3428
3429 ma_audio_buffer buffer;
3430 result = ma_audio_buffer_init(&config, &buffer);
3431 if (result != MA_SUCCESS) {
3432 // Error.
3433 }
3434
3435 ...
3436
3437 ma_audio_buffer_uninit(&buffer);
3438 ```
3439
3440In the example above, the memory pointed to by `pExistingData` will *not* be copied and is how an
3441application can do self-managed memory allocation. If you would rather make a copy of the data, use
3442`ma_audio_buffer_init_copy()`. To uninitialize the buffer, use `ma_audio_buffer_uninit()`.
3443
3444Sometimes it can be convenient to allocate the memory for the `ma_audio_buffer` structure and the
3445raw audio data in a contiguous block of memory. That is, the raw audio data will be located
3446immediately after the `ma_audio_buffer` structure. To do this, use
3447`ma_audio_buffer_alloc_and_init()`:
3448
3449 ```c
3450 ma_audio_buffer_config config = ma_audio_buffer_config_init(
3451 format,
3452 channels,
3453 sizeInFrames,
3454 pExistingData,
3455 &allocationCallbacks);
3456
3457 ma_audio_buffer* pBuffer
3458 result = ma_audio_buffer_alloc_and_init(&config, &pBuffer);
3459 if (result != MA_SUCCESS) {
3460 // Error
3461 }
3462
3463 ...
3464
3465 ma_audio_buffer_uninit_and_free(&buffer);
3466 ```
3467
3468If you initialize the buffer with `ma_audio_buffer_alloc_and_init()` you should uninitialize it
3469with `ma_audio_buffer_uninit_and_free()`. In the example above, the memory pointed to by
3470`pExistingData` will be copied into the buffer, which is contrary to the behavior of
3471`ma_audio_buffer_init()`.
3472
3473An audio buffer has a playback cursor just like a decoder. As you read frames from the buffer, the
3474cursor moves forward. The last parameter (`loop`) can be used to determine if the buffer should
3475loop. The return value is the number of frames actually read. If this is less than the number of
3476frames requested it means the end has been reached. This should never happen if the `loop`
3477parameter is set to true. If you want to manually loop back to the start, you can do so with with
3478`ma_audio_buffer_seek_to_pcm_frame(pAudioBuffer, 0)`. Below is an example for reading data from an
3479audio buffer.
3480
3481 ```c
3482 ma_uint64 framesRead = ma_audio_buffer_read_pcm_frames(pAudioBuffer, pFramesOut, desiredFrameCount, isLooping);
3483 if (framesRead < desiredFrameCount) {
3484 // If not looping, this means the end has been reached. This should never happen in looping mode with valid input.
3485 }
3486 ```
3487
3488Sometimes you may want to avoid the cost of data movement between the internal buffer and the
3489output buffer. Instead you can use memory mapping to retrieve a pointer to a segment of data:
3490
3491 ```c
3492 void* pMappedFrames;
3493 ma_uint64 frameCount = frameCountToTryMapping;
3494 ma_result result = ma_audio_buffer_map(pAudioBuffer, &pMappedFrames, &frameCount);
3495 if (result == MA_SUCCESS) {
3496 // Map was successful. The value in frameCount will be how many frames were _actually_ mapped, which may be
3497 // less due to the end of the buffer being reached.
3498 ma_copy_pcm_frames(pFramesOut, pMappedFrames, frameCount, pAudioBuffer->format, pAudioBuffer->channels);
3499
3500 // You must unmap the buffer.
3501 ma_audio_buffer_unmap(pAudioBuffer, frameCount);
3502 }
3503 ```
3504
3505When you use memory mapping, the read cursor is increment by the frame count passed in to
3506`ma_audio_buffer_unmap()`. If you decide not to process every frame you can pass in a value smaller
3507than the value returned by `ma_audio_buffer_map()`. The disadvantage to using memory mapping is
3508that it does not handle looping for you. You can determine if the buffer is at the end for the
3509purpose of looping with `ma_audio_buffer_at_end()` or by inspecting the return value of
3510`ma_audio_buffer_unmap()` and checking if it equals `MA_AT_END`. You should not treat `MA_AT_END`
3511as an error when returned by `ma_audio_buffer_unmap()`.
3512
3513
3514
351514. Ring Buffers
3516================
3517miniaudio supports lock free (single producer, single consumer) ring buffers which are exposed via
3518the `ma_rb` and `ma_pcm_rb` APIs. The `ma_rb` API operates on bytes, whereas the `ma_pcm_rb`
3519operates on PCM frames. They are otherwise identical as `ma_pcm_rb` is just a wrapper around
3520`ma_rb`.
3521
3522Unlike most other APIs in miniaudio, ring buffers support both interleaved and deinterleaved
3523streams. The caller can also allocate their own backing memory for the ring buffer to use
3524internally for added flexibility. Otherwise the ring buffer will manage it's internal memory for
3525you.
3526
3527The examples below use the PCM frame variant of the ring buffer since that's most likely the one
3528you will want to use. To initialize a ring buffer, do something like the following:
3529
3530 ```c
3531 ma_pcm_rb rb;
3532 ma_result result = ma_pcm_rb_init(FORMAT, CHANNELS, BUFFER_SIZE_IN_FRAMES, NULL, NULL, &rb);
3533 if (result != MA_SUCCESS) {
3534 // Error
3535 }
3536 ```
3537
3538The `ma_pcm_rb_init()` function takes the sample format and channel count as parameters because
3539it's the PCM variant of the ring buffer API. For the regular ring buffer that operates on bytes you
3540would call `ma_rb_init()` which leaves these out and just takes the size of the buffer in bytes
3541instead of frames. The fourth parameter is an optional pre-allocated buffer and the fifth parameter
3542is a pointer to a `ma_allocation_callbacks` structure for custom memory allocation routines.
3543Passing in `NULL` for this results in `MA_MALLOC()` and `MA_FREE()` being used.
3544
3545Use `ma_pcm_rb_init_ex()` if you need a deinterleaved buffer. The data for each sub-buffer is
3546offset from each other based on the stride. To manage your sub-buffers you can use
3547`ma_pcm_rb_get_subbuffer_stride()`, `ma_pcm_rb_get_subbuffer_offset()` and
3548`ma_pcm_rb_get_subbuffer_ptr()`.
3549
3550Use `ma_pcm_rb_acquire_read()` and `ma_pcm_rb_acquire_write()` to retrieve a pointer to a section
3551of the ring buffer. You specify the number of frames you need, and on output it will set to what
3552was actually acquired. If the read or write pointer is positioned such that the number of frames
3553requested will require a loop, it will be clamped to the end of the buffer. Therefore, the number
3554of frames you're given may be less than the number you requested.
3555
3556After calling `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()`, you do your work on the
3557buffer and then "commit" it with `ma_pcm_rb_commit_read()` or `ma_pcm_rb_commit_write()`. This is
3558where the read/write pointers are updated. When you commit you need to pass in the buffer that was
3559returned by the earlier call to `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()` and is
3560only used for validation. The number of frames passed to `ma_pcm_rb_commit_read()` and
3561`ma_pcm_rb_commit_write()` is what's used to increment the pointers, and can be less that what was
3562originally requested.
3563
3564If you want to correct for drift between the write pointer and the read pointer you can use a
3565combination of `ma_pcm_rb_pointer_distance()`, `ma_pcm_rb_seek_read()` and
3566`ma_pcm_rb_seek_write()`. Note that you can only move the pointers forward, and you should only
3567move the read pointer forward via the consumer thread, and the write pointer forward by the
3568producer thread. If there is too much space between the pointers, move the read pointer forward. If
3569there is too little space between the pointers, move the write pointer forward.
3570
3571You can use a ring buffer at the byte level instead of the PCM frame level by using the `ma_rb`
3572API. This is exactly the same, only you will use the `ma_rb` functions instead of `ma_pcm_rb` and
3573instead of frame counts you will pass around byte counts.
3574
3575The maximum size of the buffer in bytes is `0x7FFFFFFF-(MA_SIMD_ALIGNMENT-1)` due to the most
3576significant bit being used to encode a loop flag and the internally managed buffers always being
3577aligned to `MA_SIMD_ALIGNMENT`.
3578
3579Note that the ring buffer is only thread safe when used by a single consumer thread and single
3580producer thread.
3581
3582
3583
358415. Backends
3585============
3586The following backends are supported by miniaudio. These are listed in order of default priority.
3587When no backend is specified when initializing a context or device, miniaudio will attempt to use
3588each of these backends in the order listed in the table below.
3589
3590Note that backends that are not usable by the build target will not be included in the build. For
3591example, ALSA, which is specific to Linux, will not be included in the Windows build.
3592
3593 +-------------+-----------------------+--------------------------------------------------------+
3594 | Name | Enum Name | Supported Operating Systems |
3595 +-------------+-----------------------+--------------------------------------------------------+
3596 | WASAPI | ma_backend_wasapi | Windows Vista+ |
3597 | DirectSound | ma_backend_dsound | Windows XP+ |
3598 | WinMM | ma_backend_winmm | Windows 95+ |
3599 | Core Audio | ma_backend_coreaudio | macOS, iOS |
3600 | sndio | ma_backend_sndio | OpenBSD |
3601 | audio(4) | ma_backend_audio4 | NetBSD, OpenBSD |
3602 | OSS | ma_backend_oss | FreeBSD |
3603 | PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) |
3604 | ALSA | ma_backend_alsa | Linux |
3605 | JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) |
3606 | AAudio | ma_backend_aaudio | Android 8+ |
3607 | OpenSL ES | ma_backend_opensl | Android (API level 16+) |
3608 | Web Audio | ma_backend_webaudio | Web (via Emscripten) |
3609 | Custom | ma_backend_custom | Cross Platform |
3610 | Null | ma_backend_null | Cross Platform (not used on Web) |
3611 +-------------+-----------------------+--------------------------------------------------------+
3612
3613Some backends have some nuance details you may want to be aware of.
3614
361515.1. WASAPI
3616------------
3617- Low-latency shared mode will be disabled when using an application-defined sample rate which is
3618 different to the device's native sample rate. To work around this, set `wasapi.noAutoConvertSRC`
3619 to true in the device config. This is due to IAudioClient3_InitializeSharedAudioStream() failing
3620 when the `AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM` flag is specified. Setting wasapi.noAutoConvertSRC
3621 will result in miniaudio's internal resampler being used instead which will in turn enable the
3622 use of low-latency shared mode.
3623
362415.2. PulseAudio
3625----------------
3626- If you experience bad glitching/noise on Arch Linux, consider this fix from the Arch wiki:
3627 https://wiki.archlinux.org/index.php/PulseAudio/Troubleshooting#Glitches,_skips_or_crackling.
3628 Alternatively, consider using a different backend such as ALSA.
3629
363015.3. Android
3631-------------
3632- To capture audio on Android, remember to add the RECORD_AUDIO permission to your manifest:
3633 `<uses-permission android:name="android.permission.RECORD_AUDIO" />`
3634- With OpenSL|ES, only a single ma_context can be active at any given time. This is due to a
3635 limitation with OpenSL|ES.
3636- With AAudio, only default devices are enumerated. This is due to AAudio not having an enumeration
3637 API (devices are enumerated through Java). You can however perform your own device enumeration
3638 through Java and then set the ID in the ma_device_id structure (ma_device_id.aaudio) and pass it
3639 to ma_device_init().
3640- The backend API will perform resampling where possible. The reason for this as opposed to using
3641 miniaudio's built-in resampler is to take advantage of any potential device-specific
3642 optimizations the driver may implement.
3643
3644BSD
3645---
3646- The sndio backend is currently only enabled on OpenBSD builds.
3647- The audio(4) backend is supported on OpenBSD, but you may need to disable sndiod before you can
3648 use it.
3649
365015.4. UWP
3651---------
3652- UWP only supports default playback and capture devices.
3653- UWP requires the Microphone capability to be enabled in the application's manifest (Package.appxmanifest):
3654
3655 ```
3656 <Package ...>
3657 ...
3658 <Capabilities>
3659 <DeviceCapability Name="microphone" />
3660 </Capabilities>
3661 </Package>
3662 ```
3663
366415.5. Web Audio / Emscripten
3665----------------------------
3666- You cannot use `-std=c*` compiler flags, nor `-ansi`. This only applies to the Emscripten build.
3667- The first time a context is initialized it will create a global object called "miniaudio" whose
3668 primary purpose is to act as a factory for device objects.
3669- Currently the Web Audio backend uses ScriptProcessorNode's, but this may need to change later as
3670 they've been deprecated.
3671- Google has implemented a policy in their browsers that prevent automatic media output without
3672 first receiving some kind of user input. The following web page has additional details:
3673 https://developers.google.com/web/updates/2017/09/autoplay-policy-changes. Starting the device
3674 may fail if you try to start playback without first handling some kind of user input.
3675
3676
3677
367816. Optimization Tips
3679=====================
3680See below for some tips on improving performance.
3681
368216.1. Low Level API
3683-------------------
3684- In the data callback, if your data is already clipped prior to copying it into the output buffer,
3685 set the `noClip` config option in the device config to true. This will disable miniaudio's built
3686 in clipping function.
3687- By default, miniaudio will pre-silence the data callback's output buffer. If you know that you
3688 will always write valid data to the output buffer you can disable pre-silencing by setting the
3689 `noPreSilence` config option in the device config to true.
3690
369116.2. High Level API
3692--------------------
3693- If a sound does not require doppler or pitch shifting, consider disabling pitching by
3694 initializing the sound with the `MA_SOUND_FLAG_NO_PITCH` flag.
3695- If a sound does not require spatialization, disable it by initializing the sound with the
3696 `MA_SOUND_FLAG_NO_SPATIALIZATION` flag. It can be re-enabled again post-initialization with
3697 `ma_sound_set_spatialization_enabled()`.
3698- If you know all of your sounds will always be the same sample rate, set the engine's sample
3699 rate to match that of the sounds. Likewise, if you're using a self-managed resource manager,
3700 consider setting the decoded sample rate to match your sounds. By configuring everything to
3701 use a consistent sample rate, sample rate conversion can be avoided.
3702
3703
3704
370517. Miscellaneous Notes
3706=======================
3707- Automatic stream routing is enabled on a per-backend basis. Support is explicitly enabled for
3708 WASAPI and Core Audio, however other backends such as PulseAudio may naturally support it, though
3709 not all have been tested.
3710- When compiling with VC6 and earlier, decoding is restricted to files less than 2GB in size. This
3711 is due to 64-bit file APIs not being available.
3712*/
3713
3714#ifndef miniaudio_h
3715#define miniaudio_h
3716
3717#ifdef __cplusplus
3718extern "C" {
3719#endif
3720
3721#define MA_STRINGIFY(x) #x
3722#define MA_XSTRINGIFY(x) MA_STRINGIFY(x)
3723
3724#define MA_VERSION_MAJOR 0
3725#define MA_VERSION_MINOR 11
3726#define MA_VERSION_REVISION 21
3727#define MA_VERSION_STRING MA_XSTRINGIFY(MA_VERSION_MAJOR) "." MA_XSTRINGIFY(MA_VERSION_MINOR) "." MA_XSTRINGIFY(MA_VERSION_REVISION)
3728
3729#if defined(_MSC_VER) && !defined(__clang__)
3730 #pragma warning(push)
3731 #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
3732 #pragma warning(disable:4214) /* nonstandard extension used: bit field types other than int */
3733 #pragma warning(disable:4324) /* structure was padded due to alignment specifier */
3734#elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
3735 #pragma GCC diagnostic push
3736 #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
3737 #if defined(__clang__)
3738 #pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */
3739 #endif
3740#endif
3741
3742
3743
3744#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined(_M_IA64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__powerpc64__)
3745 #define MA_SIZEOF_PTR 8
3746#else
3747 #define MA_SIZEOF_PTR 4
3748#endif
3749
3750#include <stddef.h> /* For size_t. */
3751
3752/* Sized types. */
3753#if defined(MA_USE_STDINT)
3754 #include <stdint.h>
3755 typedef int8_t ma_int8;
3756 typedef uint8_t ma_uint8;
3757 typedef int16_t ma_int16;
3758 typedef uint16_t ma_uint16;
3759 typedef int32_t ma_int32;
3760 typedef uint32_t ma_uint32;
3761 typedef int64_t ma_int64;
3762 typedef uint64_t ma_uint64;
3763#else
3764 typedef signed char ma_int8;
3765 typedef unsigned char ma_uint8;
3766 typedef signed short ma_int16;
3767 typedef unsigned short ma_uint16;
3768 typedef signed int ma_int32;
3769 typedef unsigned int ma_uint32;
3770 #if defined(_MSC_VER) && !defined(__clang__)
3771 typedef signed __int64 ma_int64;
3772 typedef unsigned __int64 ma_uint64;
3773 #else
3774 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
3775 #pragma GCC diagnostic push
3776 #pragma GCC diagnostic ignored "-Wlong-long"
3777 #if defined(__clang__)
3778 #pragma GCC diagnostic ignored "-Wc++11-long-long"
3779 #endif
3780 #endif
3781 typedef signed long long ma_int64;
3782 typedef unsigned long long ma_uint64;
3783 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
3784 #pragma GCC diagnostic pop
3785 #endif
3786 #endif
3787#endif /* MA_USE_STDINT */
3788
3789#if MA_SIZEOF_PTR == 8
3790 typedef ma_uint64 ma_uintptr;
3791#else
3792 typedef ma_uint32 ma_uintptr;
3793#endif
3794
3795typedef ma_uint8 ma_bool8;
3796typedef ma_uint32 ma_bool32;
3797#define MA_TRUE 1
3798#define MA_FALSE 0
3799
3800/* These float types are not used universally by miniaudio. It's to simplify some macro expansion for atomic types. */
3801typedef float ma_float;
3802typedef double ma_double;
3803
3804typedef void* ma_handle;
3805typedef void* ma_ptr;
3806
3807/*
3808ma_proc is annoying because when compiling with GCC we get pendantic warnings about converting
3809between `void*` and `void (*)()`. We can't use `void (*)()` with MSVC however, because we'll get
3810warning C4191 about "type cast between incompatible function types". To work around this I'm going
3811to use a different data type depending on the compiler.
3812*/
3813#if defined(__GNUC__)
3814typedef void (*ma_proc)(void);
3815#else
3816typedef void* ma_proc;
3817#endif
3818
3819#if defined(_MSC_VER) && !defined(_WCHAR_T_DEFINED)
3820typedef ma_uint16 wchar_t;
3821#endif
3822
3823/* Define NULL for some compilers. */
3824#ifndef NULL
3825#define NULL 0
3826#endif
3827
3828#if defined(SIZE_MAX)
3829 #define MA_SIZE_MAX SIZE_MAX
3830#else
3831 #define MA_SIZE_MAX 0xFFFFFFFF /* When SIZE_MAX is not defined by the standard library just default to the maximum 32-bit unsigned integer. */
3832#endif
3833
3834
3835/* Platform/backend detection. */
3836#if defined(_WIN32) || defined(__COSMOPOLITAN__)
3837 #define MA_WIN32
3838 #if defined(MA_FORCE_UWP) || (defined(WINAPI_FAMILY) && ((defined(WINAPI_FAMILY_PC_APP) && WINAPI_FAMILY == WINAPI_FAMILY_PC_APP) || (defined(WINAPI_FAMILY_PHONE_APP) && WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)))
3839 #define MA_WIN32_UWP
3840 #elif defined(WINAPI_FAMILY) && (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
3841 #define MA_WIN32_GDK
3842 #else
3843 #define MA_WIN32_DESKTOP
3844 #endif
3845#endif
3846#if !defined(_WIN32) /* If it's not Win32, assume POSIX. */
3847 #define MA_POSIX
3848
3849 /*
3850 Use the MA_NO_PTHREAD_IN_HEADER option at your own risk. This is intentionally undocumented.
3851 You can use this to avoid including pthread.h in the header section. The downside is that it
3852 results in some fixed sized structures being declared for the various types that are used in
3853 miniaudio. The risk here is that these types might be too small for a given platform. This
3854 risk is yours to take and no support will be offered if you enable this option.
3855 */
3856 #ifndef MA_NO_PTHREAD_IN_HEADER
3857 #include <pthread.h> /* Unfortunate #include, but needed for pthread_t, pthread_mutex_t and pthread_cond_t types. */
3858 typedef pthread_t ma_pthread_t;
3859 typedef pthread_mutex_t ma_pthread_mutex_t;
3860 typedef pthread_cond_t ma_pthread_cond_t;
3861 #else
3862 typedef ma_uintptr ma_pthread_t;
3863 typedef union ma_pthread_mutex_t { char __data[40]; ma_uint64 __alignment; } ma_pthread_mutex_t;
3864 typedef union ma_pthread_cond_t { char __data[48]; ma_uint64 __alignment; } ma_pthread_cond_t;
3865 #endif
3866
3867 #if defined(__unix__)
3868 #define MA_UNIX
3869 #endif
3870 #if defined(__linux__)
3871 #define MA_LINUX
3872 #endif
3873 #if defined(__APPLE__)
3874 #define MA_APPLE
3875 #endif
3876 #if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
3877 #define MA_BSD
3878 #endif
3879 #if defined(__ANDROID__)
3880 #define MA_ANDROID
3881 #endif
3882 #if defined(__EMSCRIPTEN__)
3883 #define MA_EMSCRIPTEN
3884 #endif
3885 #if defined(__ORBIS__)
3886 #define MA_ORBIS
3887 #endif
3888 #if defined(__PROSPERO__)
3889 #define MA_PROSPERO
3890 #endif
3891 #if defined(__NX__)
3892 #define MA_NX
3893 #endif
3894 #if defined(__BEOS__) || defined(__HAIKU__)
3895 #define MA_BEOS
3896 #endif
3897 #if defined(__HAIKU__)
3898 #define MA_HAIKU
3899 #endif
3900#endif
3901
3902#if defined(__has_c_attribute)
3903 #if __has_c_attribute(fallthrough)
3904 #define MA_FALLTHROUGH [[fallthrough]]
3905 #endif
3906#endif
3907#if !defined(MA_FALLTHROUGH) && defined(__has_attribute) && (defined(__clang__) || defined(__GNUC__))
3908 #if __has_attribute(fallthrough)
3909 #define MA_FALLTHROUGH __attribute__((fallthrough))
3910 #endif
3911#endif
3912#if !defined(MA_FALLTHROUGH)
3913 #define MA_FALLTHROUGH ((void)0)
3914#endif
3915
3916#ifdef _MSC_VER
3917 #define MA_INLINE __forceinline
3918
3919 /* noinline was introduced in Visual Studio 2005. */
3920 #if _MSC_VER >= 1400
3921 #define MA_NO_INLINE __declspec(noinline)
3922 #else
3923 #define MA_NO_INLINE
3924 #endif
3925#elif defined(__GNUC__)
3926 /*
3927 I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when
3928 the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some
3929 case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the
3930 command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue
3931 I am using "__inline__" only when we're compiling in strict ANSI mode.
3932 */
3933 #if defined(__STRICT_ANSI__)
3934 #define MA_GNUC_INLINE_HINT __inline__
3935 #else
3936 #define MA_GNUC_INLINE_HINT inline
3937 #endif
3938
3939 #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
3940 #define MA_INLINE MA_GNUC_INLINE_HINT __attribute__((always_inline))
3941 #define MA_NO_INLINE __attribute__((noinline))
3942 #else
3943 #define MA_INLINE MA_GNUC_INLINE_HINT
3944 #define MA_NO_INLINE __attribute__((noinline))
3945 #endif
3946#elif defined(__WATCOMC__)
3947 #define MA_INLINE __inline
3948 #define MA_NO_INLINE
3949#else
3950 #define MA_INLINE
3951 #define MA_NO_INLINE
3952#endif
3953
3954/* MA_DLL is not officially supported. You're on your own if you want to use this. */
3955#if defined(MA_DLL)
3956 #if defined(_WIN32)
3957 #define MA_DLL_IMPORT __declspec(dllimport)
3958 #define MA_DLL_EXPORT __declspec(dllexport)
3959 #define MA_DLL_PRIVATE static
3960 #else
3961 #if defined(__GNUC__) && __GNUC__ >= 4
3962 #define MA_DLL_IMPORT __attribute__((visibility("default")))
3963 #define MA_DLL_EXPORT __attribute__((visibility("default")))
3964 #define MA_DLL_PRIVATE __attribute__((visibility("hidden")))
3965 #else
3966 #define MA_DLL_IMPORT
3967 #define MA_DLL_EXPORT
3968 #define MA_DLL_PRIVATE static
3969 #endif
3970 #endif
3971#endif
3972
3973#if !defined(MA_API)
3974 #if defined(MA_DLL)
3975 #if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION)
3976 #define MA_API MA_DLL_EXPORT
3977 #else
3978 #define MA_API MA_DLL_IMPORT
3979 #endif
3980 #else
3981 #define MA_API extern
3982 #endif
3983#endif
3984
3985#if !defined(MA_STATIC)
3986 #if defined(MA_DLL)
3987 #define MA_PRIVATE MA_DLL_PRIVATE
3988 #else
3989 #define MA_PRIVATE static
3990 #endif
3991#endif
3992
3993
3994/* SIMD alignment in bytes. Currently set to 32 bytes in preparation for future AVX optimizations. */
3995#define MA_SIMD_ALIGNMENT 32
3996
3997/*
3998Special wchar_t type to ensure any structures in the public sections that reference it have a
3999consistent size across all platforms.
4000
4001On Windows, wchar_t is 2 bytes, whereas everywhere else it's 4 bytes. Since Windows likes to use
4002wchar_t for it's IDs, we need a special explicitly sized wchar type that is always 2 bytes on all
4003platforms.
4004*/
4005#if !defined(MA_POSIX) && defined(MA_WIN32)
4006typedef wchar_t ma_wchar_win32;
4007#else
4008typedef ma_uint16 ma_wchar_win32;
4009#endif
4010
4011
4012
4013/*
4014Logging Levels
4015==============
4016Log levels are only used to give logging callbacks some context as to the severity of a log message
4017so they can do filtering. All log levels will be posted to registered logging callbacks. If you
4018don't want to output a certain log level you can discriminate against the log level in the callback.
4019
4020MA_LOG_LEVEL_DEBUG
4021 Used for debugging. Useful for debug and test builds, but should be disabled in release builds.
4022
4023MA_LOG_LEVEL_INFO
4024 Informational logging. Useful for debugging. This will never be called from within the data
4025 callback.
4026
4027MA_LOG_LEVEL_WARNING
4028 Warnings. You should enable this in you development builds and action them when encounted. These
4029 logs usually indicate a potential problem or misconfiguration, but still allow you to keep
4030 running. This will never be called from within the data callback.
4031
4032MA_LOG_LEVEL_ERROR
4033 Error logging. This will be fired when an operation fails and is subsequently aborted. This can
4034 be fired from within the data callback, in which case the device will be stopped. You should
4035 always have this log level enabled.
4036*/
4037typedef enum
4038{
4039 MA_LOG_LEVEL_DEBUG = 4,
4040 MA_LOG_LEVEL_INFO = 3,
4041 MA_LOG_LEVEL_WARNING = 2,
4042 MA_LOG_LEVEL_ERROR = 1
4043} ma_log_level;
4044
4045/*
4046Variables needing to be accessed atomically should be declared with this macro for two reasons:
4047
4048 1) It allows people who read the code to identify a variable as such; and
4049 2) It forces alignment on platforms where it's required or optimal.
4050
4051Note that for x86/64, alignment is not strictly necessary, but does have some performance
4052implications. Where supported by the compiler, alignment will be used, but otherwise if the CPU
4053architecture does not require it, it will simply leave it unaligned. This is the case with old
4054versions of Visual Studio, which I've confirmed with at least VC6.
4055*/
4056#if !defined(_MSC_VER) && defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
4057 #include <stdalign.h>
4058 #define MA_ATOMIC(alignment, type) _Alignas(alignment) type
4059#else
4060 #if defined(__GNUC__)
4061 /* GCC-style compilers. */
4062 #define MA_ATOMIC(alignment, type) type __attribute__((aligned(alignment)))
4063 #elif defined(_MSC_VER) && _MSC_VER > 1200 /* 1200 = VC6. Alignment not supported, but not necessary because x86 is the only supported target. */
4064 /* MSVC. */
4065 #define MA_ATOMIC(alignment, type) __declspec(align(alignment)) type
4066 #else
4067 /* Other compilers. */
4068 #define MA_ATOMIC(alignment, type) type
4069 #endif
4070#endif
4071
4072typedef struct ma_context ma_context;
4073typedef struct ma_device ma_device;
4074
4075typedef ma_uint8 ma_channel;
4076typedef enum
4077{
4078 MA_CHANNEL_NONE = 0,
4079 MA_CHANNEL_MONO = 1,
4080 MA_CHANNEL_FRONT_LEFT = 2,
4081 MA_CHANNEL_FRONT_RIGHT = 3,
4082 MA_CHANNEL_FRONT_CENTER = 4,
4083 MA_CHANNEL_LFE = 5,
4084 MA_CHANNEL_BACK_LEFT = 6,
4085 MA_CHANNEL_BACK_RIGHT = 7,
4086 MA_CHANNEL_FRONT_LEFT_CENTER = 8,
4087 MA_CHANNEL_FRONT_RIGHT_CENTER = 9,
4088 MA_CHANNEL_BACK_CENTER = 10,
4089 MA_CHANNEL_SIDE_LEFT = 11,
4090 MA_CHANNEL_SIDE_RIGHT = 12,
4091 MA_CHANNEL_TOP_CENTER = 13,
4092 MA_CHANNEL_TOP_FRONT_LEFT = 14,
4093 MA_CHANNEL_TOP_FRONT_CENTER = 15,
4094 MA_CHANNEL_TOP_FRONT_RIGHT = 16,
4095 MA_CHANNEL_TOP_BACK_LEFT = 17,
4096 MA_CHANNEL_TOP_BACK_CENTER = 18,
4097 MA_CHANNEL_TOP_BACK_RIGHT = 19,
4098 MA_CHANNEL_AUX_0 = 20,
4099 MA_CHANNEL_AUX_1 = 21,
4100 MA_CHANNEL_AUX_2 = 22,
4101 MA_CHANNEL_AUX_3 = 23,
4102 MA_CHANNEL_AUX_4 = 24,
4103 MA_CHANNEL_AUX_5 = 25,
4104 MA_CHANNEL_AUX_6 = 26,
4105 MA_CHANNEL_AUX_7 = 27,
4106 MA_CHANNEL_AUX_8 = 28,
4107 MA_CHANNEL_AUX_9 = 29,
4108 MA_CHANNEL_AUX_10 = 30,
4109 MA_CHANNEL_AUX_11 = 31,
4110 MA_CHANNEL_AUX_12 = 32,
4111 MA_CHANNEL_AUX_13 = 33,
4112 MA_CHANNEL_AUX_14 = 34,
4113 MA_CHANNEL_AUX_15 = 35,
4114 MA_CHANNEL_AUX_16 = 36,
4115 MA_CHANNEL_AUX_17 = 37,
4116 MA_CHANNEL_AUX_18 = 38,
4117 MA_CHANNEL_AUX_19 = 39,
4118 MA_CHANNEL_AUX_20 = 40,
4119 MA_CHANNEL_AUX_21 = 41,
4120 MA_CHANNEL_AUX_22 = 42,
4121 MA_CHANNEL_AUX_23 = 43,
4122 MA_CHANNEL_AUX_24 = 44,
4123 MA_CHANNEL_AUX_25 = 45,
4124 MA_CHANNEL_AUX_26 = 46,
4125 MA_CHANNEL_AUX_27 = 47,
4126 MA_CHANNEL_AUX_28 = 48,
4127 MA_CHANNEL_AUX_29 = 49,
4128 MA_CHANNEL_AUX_30 = 50,
4129 MA_CHANNEL_AUX_31 = 51,
4130 MA_CHANNEL_LEFT = MA_CHANNEL_FRONT_LEFT,
4131 MA_CHANNEL_RIGHT = MA_CHANNEL_FRONT_RIGHT,
4132 MA_CHANNEL_POSITION_COUNT = (MA_CHANNEL_AUX_31 + 1)
4133} _ma_channel_position; /* Do not use `_ma_channel_position` directly. Use `ma_channel` instead. */
4134
4135typedef enum
4136{
4137 MA_SUCCESS = 0,
4138 MA_ERROR = -1, /* A generic error. */
4139 MA_INVALID_ARGS = -2,
4140 MA_INVALID_OPERATION = -3,
4141 MA_OUT_OF_MEMORY = -4,
4142 MA_OUT_OF_RANGE = -5,
4143 MA_ACCESS_DENIED = -6,
4144 MA_DOES_NOT_EXIST = -7,
4145 MA_ALREADY_EXISTS = -8,
4146 MA_TOO_MANY_OPEN_FILES = -9,
4147 MA_INVALID_FILE = -10,
4148 MA_TOO_BIG = -11,
4149 MA_PATH_TOO_LONG = -12,
4150 MA_NAME_TOO_LONG = -13,
4151 MA_NOT_DIRECTORY = -14,
4152 MA_IS_DIRECTORY = -15,
4153 MA_DIRECTORY_NOT_EMPTY = -16,
4154 MA_AT_END = -17,
4155 MA_NO_SPACE = -18,
4156 MA_BUSY = -19,
4157 MA_IO_ERROR = -20,
4158 MA_INTERRUPT = -21,
4159 MA_UNAVAILABLE = -22,
4160 MA_ALREADY_IN_USE = -23,
4161 MA_BAD_ADDRESS = -24,
4162 MA_BAD_SEEK = -25,
4163 MA_BAD_PIPE = -26,
4164 MA_DEADLOCK = -27,
4165 MA_TOO_MANY_LINKS = -28,
4166 MA_NOT_IMPLEMENTED = -29,
4167 MA_NO_MESSAGE = -30,
4168 MA_BAD_MESSAGE = -31,
4169 MA_NO_DATA_AVAILABLE = -32,
4170 MA_INVALID_DATA = -33,
4171 MA_TIMEOUT = -34,
4172 MA_NO_NETWORK = -35,
4173 MA_NOT_UNIQUE = -36,
4174 MA_NOT_SOCKET = -37,
4175 MA_NO_ADDRESS = -38,
4176 MA_BAD_PROTOCOL = -39,
4177 MA_PROTOCOL_UNAVAILABLE = -40,
4178 MA_PROTOCOL_NOT_SUPPORTED = -41,
4179 MA_PROTOCOL_FAMILY_NOT_SUPPORTED = -42,
4180 MA_ADDRESS_FAMILY_NOT_SUPPORTED = -43,
4181 MA_SOCKET_NOT_SUPPORTED = -44,
4182 MA_CONNECTION_RESET = -45,
4183 MA_ALREADY_CONNECTED = -46,
4184 MA_NOT_CONNECTED = -47,
4185 MA_CONNECTION_REFUSED = -48,
4186 MA_NO_HOST = -49,
4187 MA_IN_PROGRESS = -50,
4188 MA_CANCELLED = -51,
4189 MA_MEMORY_ALREADY_MAPPED = -52,
4190
4191 /* General non-standard errors. */
4192 MA_CRC_MISMATCH = -100,
4193
4194 /* General miniaudio-specific errors. */
4195 MA_FORMAT_NOT_SUPPORTED = -200,
4196 MA_DEVICE_TYPE_NOT_SUPPORTED = -201,
4197 MA_SHARE_MODE_NOT_SUPPORTED = -202,
4198 MA_NO_BACKEND = -203,
4199 MA_NO_DEVICE = -204,
4200 MA_API_NOT_FOUND = -205,
4201 MA_INVALID_DEVICE_CONFIG = -206,
4202 MA_LOOP = -207,
4203 MA_BACKEND_NOT_ENABLED = -208,
4204
4205 /* State errors. */
4206 MA_DEVICE_NOT_INITIALIZED = -300,
4207 MA_DEVICE_ALREADY_INITIALIZED = -301,
4208 MA_DEVICE_NOT_STARTED = -302,
4209 MA_DEVICE_NOT_STOPPED = -303,
4210
4211 /* Operation errors. */
4212 MA_FAILED_TO_INIT_BACKEND = -400,
4213 MA_FAILED_TO_OPEN_BACKEND_DEVICE = -401,
4214 MA_FAILED_TO_START_BACKEND_DEVICE = -402,
4215 MA_FAILED_TO_STOP_BACKEND_DEVICE = -403
4216} ma_result;
4217
4218
4219#define MA_MIN_CHANNELS 1
4220#ifndef MA_MAX_CHANNELS
4221#define MA_MAX_CHANNELS 254
4222#endif
4223
4224#ifndef MA_MAX_FILTER_ORDER
4225#define MA_MAX_FILTER_ORDER 8
4226#endif
4227
4228typedef enum
4229{
4230 ma_stream_format_pcm = 0
4231} ma_stream_format;
4232
4233typedef enum
4234{
4235 ma_stream_layout_interleaved = 0,
4236 ma_stream_layout_deinterleaved
4237} ma_stream_layout;
4238
4239typedef enum
4240{
4241 ma_dither_mode_none = 0,
4242 ma_dither_mode_rectangle,
4243 ma_dither_mode_triangle
4244} ma_dither_mode;
4245
4246typedef enum
4247{
4248 /*
4249 I like to keep these explicitly defined because they're used as a key into a lookup table. When items are
4250 added to this, make sure there are no gaps and that they're added to the lookup table in ma_get_bytes_per_sample().
4251 */
4252 ma_format_unknown = 0, /* Mainly used for indicating an error, but also used as the default for the output format for decoders. */
4253 ma_format_u8 = 1,
4254 ma_format_s16 = 2, /* Seems to be the most widely supported format. */
4255 ma_format_s24 = 3, /* Tightly packed. 3 bytes per sample. */
4256 ma_format_s32 = 4,
4257 ma_format_f32 = 5,
4258 ma_format_count
4259} ma_format;
4260
4261typedef enum
4262{
4263 /* Standard rates need to be in priority order. */
4264 ma_standard_sample_rate_48000 = 48000, /* Most common */
4265 ma_standard_sample_rate_44100 = 44100,
4266
4267 ma_standard_sample_rate_32000 = 32000, /* Lows */
4268 ma_standard_sample_rate_24000 = 24000,
4269 ma_standard_sample_rate_22050 = 22050,
4270
4271 ma_standard_sample_rate_88200 = 88200, /* Highs */
4272 ma_standard_sample_rate_96000 = 96000,
4273 ma_standard_sample_rate_176400 = 176400,
4274 ma_standard_sample_rate_192000 = 192000,
4275
4276 ma_standard_sample_rate_16000 = 16000, /* Extreme lows */
4277 ma_standard_sample_rate_11025 = 11025,
4278 ma_standard_sample_rate_8000 = 8000,
4279
4280 ma_standard_sample_rate_352800 = 352800, /* Extreme highs */
4281 ma_standard_sample_rate_384000 = 384000,
4282
4283 ma_standard_sample_rate_min = ma_standard_sample_rate_8000,
4284 ma_standard_sample_rate_max = ma_standard_sample_rate_384000,
4285 ma_standard_sample_rate_count = 14 /* Need to maintain the count manually. Make sure this is updated if items are added to enum. */
4286} ma_standard_sample_rate;
4287
4288
4289typedef enum
4290{
4291 ma_channel_mix_mode_rectangular = 0, /* Simple averaging based on the plane(s) the channel is sitting on. */
4292 ma_channel_mix_mode_simple, /* Drop excess channels; zeroed out extra channels. */
4293 ma_channel_mix_mode_custom_weights, /* Use custom weights specified in ma_channel_converter_config. */
4294 ma_channel_mix_mode_default = ma_channel_mix_mode_rectangular
4295} ma_channel_mix_mode;
4296
4297typedef enum
4298{
4299 ma_standard_channel_map_microsoft,
4300 ma_standard_channel_map_alsa,
4301 ma_standard_channel_map_rfc3551, /* Based off AIFF. */
4302 ma_standard_channel_map_flac,
4303 ma_standard_channel_map_vorbis,
4304 ma_standard_channel_map_sound4, /* FreeBSD's sound(4). */
4305 ma_standard_channel_map_sndio, /* www.sndio.org/tips.html */
4306 ma_standard_channel_map_webaudio = ma_standard_channel_map_flac, /* https://webaudio.github.io/web-audio-api/#ChannelOrdering. Only 1, 2, 4 and 6 channels are defined, but can fill in the gaps with logical assumptions. */
4307 ma_standard_channel_map_default = ma_standard_channel_map_microsoft
4308} ma_standard_channel_map;
4309
4310typedef enum
4311{
4312 ma_performance_profile_low_latency = 0,
4313 ma_performance_profile_conservative
4314} ma_performance_profile;
4315
4316
4317typedef struct
4318{
4319 void* pUserData;
4320 void* (* onMalloc)(size_t sz, void* pUserData);
4321 void* (* onRealloc)(void* p, size_t sz, void* pUserData);
4322 void (* onFree)(void* p, void* pUserData);
4323} ma_allocation_callbacks;
4324
4325typedef struct
4326{
4327 ma_int32 state;
4328} ma_lcg;
4329
4330
4331/*
4332Atomics.
4333
4334These are typesafe structures to prevent errors as a result of forgetting to reference variables atomically. It's too
4335easy to introduce subtle bugs where you accidentally do a regular assignment instead of an atomic load/store, etc. By
4336using a struct we can enforce the use of atomics at compile time.
4337
4338These types are declared in the header section because we need to reference them in structs below, but functions for
4339using them are only exposed in the implementation section. I do not want these to be part of the public API.
4340
4341There's a few downsides to this system. The first is that you need to declare a new struct for each type. Below are
4342some macros to help with the declarations. They will be named like so:
4343
4344 ma_atomic_uint32 - atomic ma_uint32
4345 ma_atomic_int32 - atomic ma_int32
4346 ma_atomic_uint64 - atomic ma_uint64
4347 ma_atomic_float - atomic float
4348 ma_atomic_bool32 - atomic ma_bool32
4349
4350The other downside is that atomic pointers are extremely messy. You need to declare a new struct for each specific
4351type of pointer you need to make atomic. For example, an atomic ma_node* will look like this:
4352
4353 MA_ATOMIC_SAFE_TYPE_IMPL_PTR(node)
4354
4355Which will declare a type struct that's named like so:
4356
4357 ma_atomic_ptr_node
4358
4359Functions to use the atomic types are declared in the implementation section. All atomic functions are prefixed with
4360the name of the struct. For example:
4361
4362 ma_atomic_uint32_set() - Atomic store of ma_uint32
4363 ma_atomic_uint32_get() - Atomic load of ma_uint32
4364 etc.
4365
4366For pointer types it's the same, which makes them a bit messy to use due to the length of each function name, but in
4367return you get type safety and enforcement of atomic operations.
4368*/
4369#define MA_ATOMIC_SAFE_TYPE_DECL(c89TypeExtension, typeSize, type) \
4370 typedef struct \
4371 { \
4372 MA_ATOMIC(typeSize, ma_##type) value; \
4373 } ma_atomic_##type; \
4374
4375#define MA_ATOMIC_SAFE_TYPE_DECL_PTR(type) \
4376 typedef struct \
4377 { \
4378 MA_ATOMIC(MA_SIZEOF_PTR, ma_##type*) value; \
4379 } ma_atomic_ptr_##type; \
4380
4381MA_ATOMIC_SAFE_TYPE_DECL(32, 4, uint32)
4382MA_ATOMIC_SAFE_TYPE_DECL(i32, 4, int32)
4383MA_ATOMIC_SAFE_TYPE_DECL(64, 8, uint64)
4384MA_ATOMIC_SAFE_TYPE_DECL(f32, 4, float)
4385MA_ATOMIC_SAFE_TYPE_DECL(32, 4, bool32)
4386
4387
4388/* Spinlocks are 32-bit for compatibility reasons. */
4389typedef ma_uint32 ma_spinlock;
4390
4391#ifndef MA_NO_THREADING
4392 /* Thread priorities should be ordered such that the default priority of the worker thread is 0. */
4393 typedef enum
4394 {
4395 ma_thread_priority_idle = -5,
4396 ma_thread_priority_lowest = -4,
4397 ma_thread_priority_low = -3,
4398 ma_thread_priority_normal = -2,
4399 ma_thread_priority_high = -1,
4400 ma_thread_priority_highest = 0,
4401 ma_thread_priority_realtime = 1,
4402 ma_thread_priority_default = 0
4403 } ma_thread_priority;
4404
4405 #if defined(MA_POSIX)
4406 typedef ma_pthread_t ma_thread;
4407 #elif defined(MA_WIN32)
4408 typedef ma_handle ma_thread;
4409 #endif
4410
4411 #if defined(MA_POSIX)
4412 typedef ma_pthread_mutex_t ma_mutex;
4413 #elif defined(MA_WIN32)
4414 typedef ma_handle ma_mutex;
4415 #endif
4416
4417 #if defined(MA_POSIX)
4418 typedef struct
4419 {
4420 ma_uint32 value;
4421 ma_pthread_mutex_t lock;
4422 ma_pthread_cond_t cond;
4423 } ma_event;
4424 #elif defined(MA_WIN32)
4425 typedef ma_handle ma_event;
4426 #endif
4427
4428 #if defined(MA_POSIX)
4429 typedef struct
4430 {
4431 int value;
4432 ma_pthread_mutex_t lock;
4433 ma_pthread_cond_t cond;
4434 } ma_semaphore;
4435 #elif defined(MA_WIN32)
4436 typedef ma_handle ma_semaphore;
4437 #endif
4438#else
4439 /* MA_NO_THREADING is set which means threading is disabled. Threading is required by some API families. If any of these are enabled we need to throw an error. */
4440 #ifndef MA_NO_DEVICE_IO
4441 #error "MA_NO_THREADING cannot be used without MA_NO_DEVICE_IO";
4442 #endif
4443#endif /* MA_NO_THREADING */
4444
4445
4446/*
4447Retrieves the version of miniaudio as separated integers. Each component can be NULL if it's not required.
4448*/
4449MA_API void ma_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision);
4450
4451/*
4452Retrieves the version of miniaudio as a string which can be useful for logging purposes.
4453*/
4454MA_API const char* ma_version_string(void);
4455
4456
4457/**************************************************************************************************************************************************************
4458
4459Logging
4460
4461**************************************************************************************************************************************************************/
4462#include <stdarg.h> /* For va_list. */
4463
4464#if defined(__has_attribute)
4465 #if __has_attribute(format)
4466 #define MA_ATTRIBUTE_FORMAT(fmt, va) __attribute__((format(printf, fmt, va)))
4467 #endif
4468#endif
4469#ifndef MA_ATTRIBUTE_FORMAT
4470#define MA_ATTRIBUTE_FORMAT(fmt, va)
4471#endif
4472
4473#ifndef MA_MAX_LOG_CALLBACKS
4474#define MA_MAX_LOG_CALLBACKS 4
4475#endif
4476
4477
4478/*
4479The callback for handling log messages.
4480
4481
4482Parameters
4483----------
4484pUserData (in)
4485 The user data pointer that was passed into ma_log_register_callback().
4486
4487logLevel (in)
4488 The log level. This can be one of the following:
4489
4490 +----------------------+
4491 | Log Level |
4492 +----------------------+
4493 | MA_LOG_LEVEL_DEBUG |
4494 | MA_LOG_LEVEL_INFO |
4495 | MA_LOG_LEVEL_WARNING |
4496 | MA_LOG_LEVEL_ERROR |
4497 +----------------------+
4498
4499pMessage (in)
4500 The log message.
4501*/
4502typedef void (* ma_log_callback_proc)(void* pUserData, ma_uint32 level, const char* pMessage);
4503
4504typedef struct
4505{
4506 ma_log_callback_proc onLog;
4507 void* pUserData;
4508} ma_log_callback;
4509
4510MA_API ma_log_callback ma_log_callback_init(ma_log_callback_proc onLog, void* pUserData);
4511
4512
4513typedef struct
4514{
4515 ma_log_callback callbacks[MA_MAX_LOG_CALLBACKS];
4516 ma_uint32 callbackCount;
4517 ma_allocation_callbacks allocationCallbacks; /* Need to store these persistently because ma_log_postv() might need to allocate a buffer on the heap. */
4518#ifndef MA_NO_THREADING
4519 ma_mutex lock; /* For thread safety just to make it easier and safer for the logging implementation. */
4520#endif
4521} ma_log;
4522
4523MA_API ma_result ma_log_init(const ma_allocation_callbacks* pAllocationCallbacks, ma_log* pLog);
4524MA_API void ma_log_uninit(ma_log* pLog);
4525MA_API ma_result ma_log_register_callback(ma_log* pLog, ma_log_callback callback);
4526MA_API ma_result ma_log_unregister_callback(ma_log* pLog, ma_log_callback callback);
4527MA_API ma_result ma_log_post(ma_log* pLog, ma_uint32 level, const char* pMessage);
4528MA_API ma_result ma_log_postv(ma_log* pLog, ma_uint32 level, const char* pFormat, va_list args);
4529MA_API ma_result ma_log_postf(ma_log* pLog, ma_uint32 level, const char* pFormat, ...) MA_ATTRIBUTE_FORMAT(3, 4);
4530
4531
4532/**************************************************************************************************************************************************************
4533
4534Biquad Filtering
4535
4536**************************************************************************************************************************************************************/
4537typedef union
4538{
4539 float f32;
4540 ma_int32 s32;
4541} ma_biquad_coefficient;
4542
4543typedef struct
4544{
4545 ma_format format;
4546 ma_uint32 channels;
4547 double b0;
4548 double b1;
4549 double b2;
4550 double a0;
4551 double a1;
4552 double a2;
4553} ma_biquad_config;
4554
4555MA_API ma_biquad_config ma_biquad_config_init(ma_format format, ma_uint32 channels, double b0, double b1, double b2, double a0, double a1, double a2);
4556
4557typedef struct
4558{
4559 ma_format format;
4560 ma_uint32 channels;
4561 ma_biquad_coefficient b0;
4562 ma_biquad_coefficient b1;
4563 ma_biquad_coefficient b2;
4564 ma_biquad_coefficient a1;
4565 ma_biquad_coefficient a2;
4566 ma_biquad_coefficient* pR1;
4567 ma_biquad_coefficient* pR2;
4568
4569 /* Memory management. */
4570 void* _pHeap;
4571 ma_bool32 _ownsHeap;
4572} ma_biquad;
4573
4574MA_API ma_result ma_biquad_get_heap_size(const ma_biquad_config* pConfig, size_t* pHeapSizeInBytes);
4575MA_API ma_result ma_biquad_init_preallocated(const ma_biquad_config* pConfig, void* pHeap, ma_biquad* pBQ);
4576MA_API ma_result ma_biquad_init(const ma_biquad_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad* pBQ);
4577MA_API void ma_biquad_uninit(ma_biquad* pBQ, const ma_allocation_callbacks* pAllocationCallbacks);
4578MA_API ma_result ma_biquad_reinit(const ma_biquad_config* pConfig, ma_biquad* pBQ);
4579MA_API ma_result ma_biquad_clear_cache(ma_biquad* pBQ);
4580MA_API ma_result ma_biquad_process_pcm_frames(ma_biquad* pBQ, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4581MA_API ma_uint32 ma_biquad_get_latency(const ma_biquad* pBQ);
4582
4583
4584/**************************************************************************************************************************************************************
4585
4586Low-Pass Filtering
4587
4588**************************************************************************************************************************************************************/
4589typedef struct
4590{
4591 ma_format format;
4592 ma_uint32 channels;
4593 ma_uint32 sampleRate;
4594 double cutoffFrequency;
4595 double q;
4596} ma_lpf1_config, ma_lpf2_config;
4597
4598MA_API ma_lpf1_config ma_lpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency);
4599MA_API ma_lpf2_config ma_lpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
4600
4601typedef struct
4602{
4603 ma_format format;
4604 ma_uint32 channels;
4605 ma_biquad_coefficient a;
4606 ma_biquad_coefficient* pR1;
4607
4608 /* Memory management. */
4609 void* _pHeap;
4610 ma_bool32 _ownsHeap;
4611} ma_lpf1;
4612
4613MA_API ma_result ma_lpf1_get_heap_size(const ma_lpf1_config* pConfig, size_t* pHeapSizeInBytes);
4614MA_API ma_result ma_lpf1_init_preallocated(const ma_lpf1_config* pConfig, void* pHeap, ma_lpf1* pLPF);
4615MA_API ma_result ma_lpf1_init(const ma_lpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf1* pLPF);
4616MA_API void ma_lpf1_uninit(ma_lpf1* pLPF, const ma_allocation_callbacks* pAllocationCallbacks);
4617MA_API ma_result ma_lpf1_reinit(const ma_lpf1_config* pConfig, ma_lpf1* pLPF);
4618MA_API ma_result ma_lpf1_clear_cache(ma_lpf1* pLPF);
4619MA_API ma_result ma_lpf1_process_pcm_frames(ma_lpf1* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4620MA_API ma_uint32 ma_lpf1_get_latency(const ma_lpf1* pLPF);
4621
4622typedef struct
4623{
4624 ma_biquad bq; /* The second order low-pass filter is implemented as a biquad filter. */
4625} ma_lpf2;
4626
4627MA_API ma_result ma_lpf2_get_heap_size(const ma_lpf2_config* pConfig, size_t* pHeapSizeInBytes);
4628MA_API ma_result ma_lpf2_init_preallocated(const ma_lpf2_config* pConfig, void* pHeap, ma_lpf2* pHPF);
4629MA_API ma_result ma_lpf2_init(const ma_lpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf2* pLPF);
4630MA_API void ma_lpf2_uninit(ma_lpf2* pLPF, const ma_allocation_callbacks* pAllocationCallbacks);
4631MA_API ma_result ma_lpf2_reinit(const ma_lpf2_config* pConfig, ma_lpf2* pLPF);
4632MA_API ma_result ma_lpf2_clear_cache(ma_lpf2* pLPF);
4633MA_API ma_result ma_lpf2_process_pcm_frames(ma_lpf2* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4634MA_API ma_uint32 ma_lpf2_get_latency(const ma_lpf2* pLPF);
4635
4636
4637typedef struct
4638{
4639 ma_format format;
4640 ma_uint32 channels;
4641 ma_uint32 sampleRate;
4642 double cutoffFrequency;
4643 ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
4644} ma_lpf_config;
4645
4646MA_API ma_lpf_config ma_lpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
4647
4648typedef struct
4649{
4650 ma_format format;
4651 ma_uint32 channels;
4652 ma_uint32 sampleRate;
4653 ma_uint32 lpf1Count;
4654 ma_uint32 lpf2Count;
4655 ma_lpf1* pLPF1;
4656 ma_lpf2* pLPF2;
4657
4658 /* Memory management. */
4659 void* _pHeap;
4660 ma_bool32 _ownsHeap;
4661} ma_lpf;
4662
4663MA_API ma_result ma_lpf_get_heap_size(const ma_lpf_config* pConfig, size_t* pHeapSizeInBytes);
4664MA_API ma_result ma_lpf_init_preallocated(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF);
4665MA_API ma_result ma_lpf_init(const ma_lpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf* pLPF);
4666MA_API void ma_lpf_uninit(ma_lpf* pLPF, const ma_allocation_callbacks* pAllocationCallbacks);
4667MA_API ma_result ma_lpf_reinit(const ma_lpf_config* pConfig, ma_lpf* pLPF);
4668MA_API ma_result ma_lpf_clear_cache(ma_lpf* pLPF);
4669MA_API ma_result ma_lpf_process_pcm_frames(ma_lpf* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4670MA_API ma_uint32 ma_lpf_get_latency(const ma_lpf* pLPF);
4671
4672
4673/**************************************************************************************************************************************************************
4674
4675High-Pass Filtering
4676
4677**************************************************************************************************************************************************************/
4678typedef struct
4679{
4680 ma_format format;
4681 ma_uint32 channels;
4682 ma_uint32 sampleRate;
4683 double cutoffFrequency;
4684 double q;
4685} ma_hpf1_config, ma_hpf2_config;
4686
4687MA_API ma_hpf1_config ma_hpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency);
4688MA_API ma_hpf2_config ma_hpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
4689
4690typedef struct
4691{
4692 ma_format format;
4693 ma_uint32 channels;
4694 ma_biquad_coefficient a;
4695 ma_biquad_coefficient* pR1;
4696
4697 /* Memory management. */
4698 void* _pHeap;
4699 ma_bool32 _ownsHeap;
4700} ma_hpf1;
4701
4702MA_API ma_result ma_hpf1_get_heap_size(const ma_hpf1_config* pConfig, size_t* pHeapSizeInBytes);
4703MA_API ma_result ma_hpf1_init_preallocated(const ma_hpf1_config* pConfig, void* pHeap, ma_hpf1* pLPF);
4704MA_API ma_result ma_hpf1_init(const ma_hpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf1* pHPF);
4705MA_API void ma_hpf1_uninit(ma_hpf1* pHPF, const ma_allocation_callbacks* pAllocationCallbacks);
4706MA_API ma_result ma_hpf1_reinit(const ma_hpf1_config* pConfig, ma_hpf1* pHPF);
4707MA_API ma_result ma_hpf1_process_pcm_frames(ma_hpf1* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4708MA_API ma_uint32 ma_hpf1_get_latency(const ma_hpf1* pHPF);
4709
4710typedef struct
4711{
4712 ma_biquad bq; /* The second order high-pass filter is implemented as a biquad filter. */
4713} ma_hpf2;
4714
4715MA_API ma_result ma_hpf2_get_heap_size(const ma_hpf2_config* pConfig, size_t* pHeapSizeInBytes);
4716MA_API ma_result ma_hpf2_init_preallocated(const ma_hpf2_config* pConfig, void* pHeap, ma_hpf2* pHPF);
4717MA_API ma_result ma_hpf2_init(const ma_hpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf2* pHPF);
4718MA_API void ma_hpf2_uninit(ma_hpf2* pHPF, const ma_allocation_callbacks* pAllocationCallbacks);
4719MA_API ma_result ma_hpf2_reinit(const ma_hpf2_config* pConfig, ma_hpf2* pHPF);
4720MA_API ma_result ma_hpf2_process_pcm_frames(ma_hpf2* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4721MA_API ma_uint32 ma_hpf2_get_latency(const ma_hpf2* pHPF);
4722
4723
4724typedef struct
4725{
4726 ma_format format;
4727 ma_uint32 channels;
4728 ma_uint32 sampleRate;
4729 double cutoffFrequency;
4730 ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
4731} ma_hpf_config;
4732
4733MA_API ma_hpf_config ma_hpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
4734
4735typedef struct
4736{
4737 ma_format format;
4738 ma_uint32 channels;
4739 ma_uint32 sampleRate;
4740 ma_uint32 hpf1Count;
4741 ma_uint32 hpf2Count;
4742 ma_hpf1* pHPF1;
4743 ma_hpf2* pHPF2;
4744
4745 /* Memory management. */
4746 void* _pHeap;
4747 ma_bool32 _ownsHeap;
4748} ma_hpf;
4749
4750MA_API ma_result ma_hpf_get_heap_size(const ma_hpf_config* pConfig, size_t* pHeapSizeInBytes);
4751MA_API ma_result ma_hpf_init_preallocated(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pLPF);
4752MA_API ma_result ma_hpf_init(const ma_hpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf* pHPF);
4753MA_API void ma_hpf_uninit(ma_hpf* pHPF, const ma_allocation_callbacks* pAllocationCallbacks);
4754MA_API ma_result ma_hpf_reinit(const ma_hpf_config* pConfig, ma_hpf* pHPF);
4755MA_API ma_result ma_hpf_process_pcm_frames(ma_hpf* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4756MA_API ma_uint32 ma_hpf_get_latency(const ma_hpf* pHPF);
4757
4758
4759/**************************************************************************************************************************************************************
4760
4761Band-Pass Filtering
4762
4763**************************************************************************************************************************************************************/
4764typedef struct
4765{
4766 ma_format format;
4767 ma_uint32 channels;
4768 ma_uint32 sampleRate;
4769 double cutoffFrequency;
4770 double q;
4771} ma_bpf2_config;
4772
4773MA_API ma_bpf2_config ma_bpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
4774
4775typedef struct
4776{
4777 ma_biquad bq; /* The second order band-pass filter is implemented as a biquad filter. */
4778} ma_bpf2;
4779
4780MA_API ma_result ma_bpf2_get_heap_size(const ma_bpf2_config* pConfig, size_t* pHeapSizeInBytes);
4781MA_API ma_result ma_bpf2_init_preallocated(const ma_bpf2_config* pConfig, void* pHeap, ma_bpf2* pBPF);
4782MA_API ma_result ma_bpf2_init(const ma_bpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf2* pBPF);
4783MA_API void ma_bpf2_uninit(ma_bpf2* pBPF, const ma_allocation_callbacks* pAllocationCallbacks);
4784MA_API ma_result ma_bpf2_reinit(const ma_bpf2_config* pConfig, ma_bpf2* pBPF);
4785MA_API ma_result ma_bpf2_process_pcm_frames(ma_bpf2* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4786MA_API ma_uint32 ma_bpf2_get_latency(const ma_bpf2* pBPF);
4787
4788
4789typedef struct
4790{
4791 ma_format format;
4792 ma_uint32 channels;
4793 ma_uint32 sampleRate;
4794 double cutoffFrequency;
4795 ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
4796} ma_bpf_config;
4797
4798MA_API ma_bpf_config ma_bpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
4799
4800typedef struct
4801{
4802 ma_format format;
4803 ma_uint32 channels;
4804 ma_uint32 bpf2Count;
4805 ma_bpf2* pBPF2;
4806
4807 /* Memory management. */
4808 void* _pHeap;
4809 ma_bool32 _ownsHeap;
4810} ma_bpf;
4811
4812MA_API ma_result ma_bpf_get_heap_size(const ma_bpf_config* pConfig, size_t* pHeapSizeInBytes);
4813MA_API ma_result ma_bpf_init_preallocated(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF);
4814MA_API ma_result ma_bpf_init(const ma_bpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf* pBPF);
4815MA_API void ma_bpf_uninit(ma_bpf* pBPF, const ma_allocation_callbacks* pAllocationCallbacks);
4816MA_API ma_result ma_bpf_reinit(const ma_bpf_config* pConfig, ma_bpf* pBPF);
4817MA_API ma_result ma_bpf_process_pcm_frames(ma_bpf* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4818MA_API ma_uint32 ma_bpf_get_latency(const ma_bpf* pBPF);
4819
4820
4821/**************************************************************************************************************************************************************
4822
4823Notching Filter
4824
4825**************************************************************************************************************************************************************/
4826typedef struct
4827{
4828 ma_format format;
4829 ma_uint32 channels;
4830 ma_uint32 sampleRate;
4831 double q;
4832 double frequency;
4833} ma_notch2_config, ma_notch_config;
4834
4835MA_API ma_notch2_config ma_notch2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency);
4836
4837typedef struct
4838{
4839 ma_biquad bq;
4840} ma_notch2;
4841
4842MA_API ma_result ma_notch2_get_heap_size(const ma_notch2_config* pConfig, size_t* pHeapSizeInBytes);
4843MA_API ma_result ma_notch2_init_preallocated(const ma_notch2_config* pConfig, void* pHeap, ma_notch2* pFilter);
4844MA_API ma_result ma_notch2_init(const ma_notch2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch2* pFilter);
4845MA_API void ma_notch2_uninit(ma_notch2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
4846MA_API ma_result ma_notch2_reinit(const ma_notch2_config* pConfig, ma_notch2* pFilter);
4847MA_API ma_result ma_notch2_process_pcm_frames(ma_notch2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4848MA_API ma_uint32 ma_notch2_get_latency(const ma_notch2* pFilter);
4849
4850
4851/**************************************************************************************************************************************************************
4852
4853Peaking EQ Filter
4854
4855**************************************************************************************************************************************************************/
4856typedef struct
4857{
4858 ma_format format;
4859 ma_uint32 channels;
4860 ma_uint32 sampleRate;
4861 double gainDB;
4862 double q;
4863 double frequency;
4864} ma_peak2_config, ma_peak_config;
4865
4866MA_API ma_peak2_config ma_peak2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
4867
4868typedef struct
4869{
4870 ma_biquad bq;
4871} ma_peak2;
4872
4873MA_API ma_result ma_peak2_get_heap_size(const ma_peak2_config* pConfig, size_t* pHeapSizeInBytes);
4874MA_API ma_result ma_peak2_init_preallocated(const ma_peak2_config* pConfig, void* pHeap, ma_peak2* pFilter);
4875MA_API ma_result ma_peak2_init(const ma_peak2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak2* pFilter);
4876MA_API void ma_peak2_uninit(ma_peak2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
4877MA_API ma_result ma_peak2_reinit(const ma_peak2_config* pConfig, ma_peak2* pFilter);
4878MA_API ma_result ma_peak2_process_pcm_frames(ma_peak2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4879MA_API ma_uint32 ma_peak2_get_latency(const ma_peak2* pFilter);
4880
4881
4882/**************************************************************************************************************************************************************
4883
4884Low Shelf Filter
4885
4886**************************************************************************************************************************************************************/
4887typedef struct
4888{
4889 ma_format format;
4890 ma_uint32 channels;
4891 ma_uint32 sampleRate;
4892 double gainDB;
4893 double shelfSlope;
4894 double frequency;
4895} ma_loshelf2_config, ma_loshelf_config;
4896
4897MA_API ma_loshelf2_config ma_loshelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency);
4898
4899typedef struct
4900{
4901 ma_biquad bq;
4902} ma_loshelf2;
4903
4904MA_API ma_result ma_loshelf2_get_heap_size(const ma_loshelf2_config* pConfig, size_t* pHeapSizeInBytes);
4905MA_API ma_result ma_loshelf2_init_preallocated(const ma_loshelf2_config* pConfig, void* pHeap, ma_loshelf2* pFilter);
4906MA_API ma_result ma_loshelf2_init(const ma_loshelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf2* pFilter);
4907MA_API void ma_loshelf2_uninit(ma_loshelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
4908MA_API ma_result ma_loshelf2_reinit(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter);
4909MA_API ma_result ma_loshelf2_process_pcm_frames(ma_loshelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4910MA_API ma_uint32 ma_loshelf2_get_latency(const ma_loshelf2* pFilter);
4911
4912
4913/**************************************************************************************************************************************************************
4914
4915High Shelf Filter
4916
4917**************************************************************************************************************************************************************/
4918typedef struct
4919{
4920 ma_format format;
4921 ma_uint32 channels;
4922 ma_uint32 sampleRate;
4923 double gainDB;
4924 double shelfSlope;
4925 double frequency;
4926} ma_hishelf2_config, ma_hishelf_config;
4927
4928MA_API ma_hishelf2_config ma_hishelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency);
4929
4930typedef struct
4931{
4932 ma_biquad bq;
4933} ma_hishelf2;
4934
4935MA_API ma_result ma_hishelf2_get_heap_size(const ma_hishelf2_config* pConfig, size_t* pHeapSizeInBytes);
4936MA_API ma_result ma_hishelf2_init_preallocated(const ma_hishelf2_config* pConfig, void* pHeap, ma_hishelf2* pFilter);
4937MA_API ma_result ma_hishelf2_init(const ma_hishelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf2* pFilter);
4938MA_API void ma_hishelf2_uninit(ma_hishelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
4939MA_API ma_result ma_hishelf2_reinit(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter);
4940MA_API ma_result ma_hishelf2_process_pcm_frames(ma_hishelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
4941MA_API ma_uint32 ma_hishelf2_get_latency(const ma_hishelf2* pFilter);
4942
4943
4944
4945/*
4946Delay
4947*/
4948typedef struct
4949{
4950 ma_uint32 channels;
4951 ma_uint32 sampleRate;
4952 ma_uint32 delayInFrames;
4953 ma_bool32 delayStart; /* Set to true to delay the start of the output; false otherwise. */
4954 float wet; /* 0..1. Default = 1. */
4955 float dry; /* 0..1. Default = 1. */
4956 float decay; /* 0..1. Default = 0 (no feedback). Feedback decay. Use this for echo. */
4957} ma_delay_config;
4958
4959MA_API ma_delay_config ma_delay_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay);
4960
4961
4962typedef struct
4963{
4964 ma_delay_config config;
4965 ma_uint32 cursor; /* Feedback is written to this cursor. Always equal or in front of the read cursor. */
4966 ma_uint32 bufferSizeInFrames;
4967 float* pBuffer;
4968} ma_delay;
4969
4970MA_API ma_result ma_delay_init(const ma_delay_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay* pDelay);
4971MA_API void ma_delay_uninit(ma_delay* pDelay, const ma_allocation_callbacks* pAllocationCallbacks);
4972MA_API ma_result ma_delay_process_pcm_frames(ma_delay* pDelay, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount);
4973MA_API void ma_delay_set_wet(ma_delay* pDelay, float value);
4974MA_API float ma_delay_get_wet(const ma_delay* pDelay);
4975MA_API void ma_delay_set_dry(ma_delay* pDelay, float value);
4976MA_API float ma_delay_get_dry(const ma_delay* pDelay);
4977MA_API void ma_delay_set_decay(ma_delay* pDelay, float value);
4978MA_API float ma_delay_get_decay(const ma_delay* pDelay);
4979
4980
4981/* Gainer for smooth volume changes. */
4982typedef struct
4983{
4984 ma_uint32 channels;
4985 ma_uint32 smoothTimeInFrames;
4986} ma_gainer_config;
4987
4988MA_API ma_gainer_config ma_gainer_config_init(ma_uint32 channels, ma_uint32 smoothTimeInFrames);
4989
4990
4991typedef struct
4992{
4993 ma_gainer_config config;
4994 ma_uint32 t;
4995 float masterVolume;
4996 float* pOldGains;
4997 float* pNewGains;
4998
4999 /* Memory management. */
5000 void* _pHeap;
5001 ma_bool32 _ownsHeap;
5002} ma_gainer;
5003
5004MA_API ma_result ma_gainer_get_heap_size(const ma_gainer_config* pConfig, size_t* pHeapSizeInBytes);
5005MA_API ma_result ma_gainer_init_preallocated(const ma_gainer_config* pConfig, void* pHeap, ma_gainer* pGainer);
5006MA_API ma_result ma_gainer_init(const ma_gainer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_gainer* pGainer);
5007MA_API void ma_gainer_uninit(ma_gainer* pGainer, const ma_allocation_callbacks* pAllocationCallbacks);
5008MA_API ma_result ma_gainer_process_pcm_frames(ma_gainer* pGainer, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
5009MA_API ma_result ma_gainer_set_gain(ma_gainer* pGainer, float newGain);
5010MA_API ma_result ma_gainer_set_gains(ma_gainer* pGainer, float* pNewGains);
5011MA_API ma_result ma_gainer_set_master_volume(ma_gainer* pGainer, float volume);
5012MA_API ma_result ma_gainer_get_master_volume(const ma_gainer* pGainer, float* pVolume);
5013
5014
5015
5016/* Stereo panner. */
5017typedef enum
5018{
5019 ma_pan_mode_balance = 0, /* Does not blend one side with the other. Technically just a balance. Compatible with other popular audio engines and therefore the default. */
5020 ma_pan_mode_pan /* A true pan. The sound from one side will "move" to the other side and blend with it. */
5021} ma_pan_mode;
5022
5023typedef struct
5024{
5025 ma_format format;
5026 ma_uint32 channels;
5027 ma_pan_mode mode;
5028 float pan;
5029} ma_panner_config;
5030
5031MA_API ma_panner_config ma_panner_config_init(ma_format format, ma_uint32 channels);
5032
5033
5034typedef struct
5035{
5036 ma_format format;
5037 ma_uint32 channels;
5038 ma_pan_mode mode;
5039 float pan; /* -1..1 where 0 is no pan, -1 is left side, +1 is right side. Defaults to 0. */
5040} ma_panner;
5041
5042MA_API ma_result ma_panner_init(const ma_panner_config* pConfig, ma_panner* pPanner);
5043MA_API ma_result ma_panner_process_pcm_frames(ma_panner* pPanner, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
5044MA_API void ma_panner_set_mode(ma_panner* pPanner, ma_pan_mode mode);
5045MA_API ma_pan_mode ma_panner_get_mode(const ma_panner* pPanner);
5046MA_API void ma_panner_set_pan(ma_panner* pPanner, float pan);
5047MA_API float ma_panner_get_pan(const ma_panner* pPanner);
5048
5049
5050
5051/* Fader. */
5052typedef struct
5053{
5054 ma_format format;
5055 ma_uint32 channels;
5056 ma_uint32 sampleRate;
5057} ma_fader_config;
5058
5059MA_API ma_fader_config ma_fader_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate);
5060
5061typedef struct
5062{
5063 ma_fader_config config;
5064 float volumeBeg; /* If volumeBeg and volumeEnd is equal to 1, no fading happens (ma_fader_process_pcm_frames() will run as a passthrough). */
5065 float volumeEnd;
5066 ma_uint64 lengthInFrames; /* The total length of the fade. */
5067 ma_int64 cursorInFrames; /* The current time in frames. Incremented by ma_fader_process_pcm_frames(). Signed because it'll be offset by startOffsetInFrames in set_fade_ex(). */
5068} ma_fader;
5069
5070MA_API ma_result ma_fader_init(const ma_fader_config* pConfig, ma_fader* pFader);
5071MA_API ma_result ma_fader_process_pcm_frames(ma_fader* pFader, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
5072MA_API void ma_fader_get_data_format(const ma_fader* pFader, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate);
5073MA_API void ma_fader_set_fade(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames);
5074MA_API void ma_fader_set_fade_ex(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames, ma_int64 startOffsetInFrames);
5075MA_API float ma_fader_get_current_volume(const ma_fader* pFader);
5076
5077
5078
5079/* Spatializer. */
5080typedef struct
5081{
5082 float x;
5083 float y;
5084 float z;
5085} ma_vec3f;
5086
5087typedef struct
5088{
5089 ma_vec3f v;
5090 ma_spinlock lock;
5091} ma_atomic_vec3f;
5092
5093typedef enum
5094{
5095 ma_attenuation_model_none, /* No distance attenuation and no spatialization. */
5096 ma_attenuation_model_inverse, /* Equivalent to OpenAL's AL_INVERSE_DISTANCE_CLAMPED. */
5097 ma_attenuation_model_linear, /* Linear attenuation. Equivalent to OpenAL's AL_LINEAR_DISTANCE_CLAMPED. */
5098 ma_attenuation_model_exponential /* Exponential attenuation. Equivalent to OpenAL's AL_EXPONENT_DISTANCE_CLAMPED. */
5099} ma_attenuation_model;
5100
5101typedef enum
5102{
5103 ma_positioning_absolute,
5104 ma_positioning_relative
5105} ma_positioning;
5106
5107typedef enum
5108{
5109 ma_handedness_right,
5110 ma_handedness_left
5111} ma_handedness;
5112
5113
5114typedef struct
5115{
5116 ma_uint32 channelsOut;
5117 ma_channel* pChannelMapOut;
5118 ma_handedness handedness; /* Defaults to right. Forward is -1 on the Z axis. In a left handed system, forward is +1 on the Z axis. */
5119 float coneInnerAngleInRadians;
5120 float coneOuterAngleInRadians;
5121 float coneOuterGain;
5122 float speedOfSound;
5123 ma_vec3f worldUp;
5124} ma_spatializer_listener_config;
5125
5126MA_API ma_spatializer_listener_config ma_spatializer_listener_config_init(ma_uint32 channelsOut);
5127
5128
5129typedef struct
5130{
5131 ma_spatializer_listener_config config;
5132 ma_atomic_vec3f position; /* The absolute position of the listener. */
5133 ma_atomic_vec3f direction; /* The direction the listener is facing. The world up vector is config.worldUp. */
5134 ma_atomic_vec3f velocity;
5135 ma_bool32 isEnabled;
5136
5137 /* Memory management. */
5138 ma_bool32 _ownsHeap;
5139 void* _pHeap;
5140} ma_spatializer_listener;
5141
5142MA_API ma_result ma_spatializer_listener_get_heap_size(const ma_spatializer_listener_config* pConfig, size_t* pHeapSizeInBytes);
5143MA_API ma_result ma_spatializer_listener_init_preallocated(const ma_spatializer_listener_config* pConfig, void* pHeap, ma_spatializer_listener* pListener);
5144MA_API ma_result ma_spatializer_listener_init(const ma_spatializer_listener_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer_listener* pListener);
5145MA_API void ma_spatializer_listener_uninit(ma_spatializer_listener* pListener, const ma_allocation_callbacks* pAllocationCallbacks);
5146MA_API ma_channel* ma_spatializer_listener_get_channel_map(ma_spatializer_listener* pListener);
5147MA_API void ma_spatializer_listener_set_cone(ma_spatializer_listener* pListener, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
5148MA_API void ma_spatializer_listener_get_cone(const ma_spatializer_listener* pListener, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
5149MA_API void ma_spatializer_listener_set_position(ma_spatializer_listener* pListener, float x, float y, float z);
5150MA_API ma_vec3f ma_spatializer_listener_get_position(const ma_spatializer_listener* pListener);
5151MA_API void ma_spatializer_listener_set_direction(ma_spatializer_listener* pListener, float x, float y, float z);
5152MA_API ma_vec3f ma_spatializer_listener_get_direction(const ma_spatializer_listener* pListener);
5153MA_API void ma_spatializer_listener_set_velocity(ma_spatializer_listener* pListener, float x, float y, float z);
5154MA_API ma_vec3f ma_spatializer_listener_get_velocity(const ma_spatializer_listener* pListener);
5155MA_API void ma_spatializer_listener_set_speed_of_sound(ma_spatializer_listener* pListener, float speedOfSound);
5156MA_API float ma_spatializer_listener_get_speed_of_sound(const ma_spatializer_listener* pListener);
5157MA_API void ma_spatializer_listener_set_world_up(ma_spatializer_listener* pListener, float x, float y, float z);
5158MA_API ma_vec3f ma_spatializer_listener_get_world_up(const ma_spatializer_listener* pListener);
5159MA_API void ma_spatializer_listener_set_enabled(ma_spatializer_listener* pListener, ma_bool32 isEnabled);
5160MA_API ma_bool32 ma_spatializer_listener_is_enabled(const ma_spatializer_listener* pListener);
5161
5162
5163typedef struct
5164{
5165 ma_uint32 channelsIn;
5166 ma_uint32 channelsOut;
5167 ma_channel* pChannelMapIn;
5168 ma_attenuation_model attenuationModel;
5169 ma_positioning positioning;
5170 ma_handedness handedness; /* Defaults to right. Forward is -1 on the Z axis. In a left handed system, forward is +1 on the Z axis. */
5171 float minGain;
5172 float maxGain;
5173 float minDistance;
5174 float maxDistance;
5175 float rolloff;
5176 float coneInnerAngleInRadians;
5177 float coneOuterAngleInRadians;
5178 float coneOuterGain;
5179 float dopplerFactor; /* Set to 0 to disable doppler effect. */
5180 float directionalAttenuationFactor; /* Set to 0 to disable directional attenuation. */
5181 float minSpatializationChannelGain; /* The minimal scaling factor to apply to channel gains when accounting for the direction of the sound relative to the listener. Must be in the range of 0..1. Smaller values means more aggressive directional panning, larger values means more subtle directional panning. */
5182 ma_uint32 gainSmoothTimeInFrames; /* When the gain of a channel changes during spatialization, the transition will be linearly interpolated over this number of frames. */
5183} ma_spatializer_config;
5184
5185MA_API ma_spatializer_config ma_spatializer_config_init(ma_uint32 channelsIn, ma_uint32 channelsOut);
5186
5187
5188typedef struct
5189{
5190 ma_uint32 channelsIn;
5191 ma_uint32 channelsOut;
5192 ma_channel* pChannelMapIn;
5193 ma_attenuation_model attenuationModel;
5194 ma_positioning positioning;
5195 ma_handedness handedness; /* Defaults to right. Forward is -1 on the Z axis. In a left handed system, forward is +1 on the Z axis. */
5196 float minGain;
5197 float maxGain;
5198 float minDistance;
5199 float maxDistance;
5200 float rolloff;
5201 float coneInnerAngleInRadians;
5202 float coneOuterAngleInRadians;
5203 float coneOuterGain;
5204 float dopplerFactor; /* Set to 0 to disable doppler effect. */
5205 float directionalAttenuationFactor; /* Set to 0 to disable directional attenuation. */
5206 ma_uint32 gainSmoothTimeInFrames; /* When the gain of a channel changes during spatialization, the transition will be linearly interpolated over this number of frames. */
5207 ma_atomic_vec3f position;
5208 ma_atomic_vec3f direction;
5209 ma_atomic_vec3f velocity; /* For doppler effect. */
5210 float dopplerPitch; /* Will be updated by ma_spatializer_process_pcm_frames() and can be used by higher level functions to apply a pitch shift for doppler effect. */
5211 float minSpatializationChannelGain;
5212 ma_gainer gainer; /* For smooth gain transitions. */
5213 float* pNewChannelGainsOut; /* An offset of _pHeap. Used by ma_spatializer_process_pcm_frames() to store new channel gains. The number of elements in this array is equal to config.channelsOut. */
5214
5215 /* Memory management. */
5216 void* _pHeap;
5217 ma_bool32 _ownsHeap;
5218} ma_spatializer;
5219
5220MA_API ma_result ma_spatializer_get_heap_size(const ma_spatializer_config* pConfig, size_t* pHeapSizeInBytes);
5221MA_API ma_result ma_spatializer_init_preallocated(const ma_spatializer_config* pConfig, void* pHeap, ma_spatializer* pSpatializer);
5222MA_API ma_result ma_spatializer_init(const ma_spatializer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer* pSpatializer);
5223MA_API void ma_spatializer_uninit(ma_spatializer* pSpatializer, const ma_allocation_callbacks* pAllocationCallbacks);
5224MA_API ma_result ma_spatializer_process_pcm_frames(ma_spatializer* pSpatializer, ma_spatializer_listener* pListener, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
5225MA_API ma_result ma_spatializer_set_master_volume(ma_spatializer* pSpatializer, float volume);
5226MA_API ma_result ma_spatializer_get_master_volume(const ma_spatializer* pSpatializer, float* pVolume);
5227MA_API ma_uint32 ma_spatializer_get_input_channels(const ma_spatializer* pSpatializer);
5228MA_API ma_uint32 ma_spatializer_get_output_channels(const ma_spatializer* pSpatializer);
5229MA_API void ma_spatializer_set_attenuation_model(ma_spatializer* pSpatializer, ma_attenuation_model attenuationModel);
5230MA_API ma_attenuation_model ma_spatializer_get_attenuation_model(const ma_spatializer* pSpatializer);
5231MA_API void ma_spatializer_set_positioning(ma_spatializer* pSpatializer, ma_positioning positioning);
5232MA_API ma_positioning ma_spatializer_get_positioning(const ma_spatializer* pSpatializer);
5233MA_API void ma_spatializer_set_rolloff(ma_spatializer* pSpatializer, float rolloff);
5234MA_API float ma_spatializer_get_rolloff(const ma_spatializer* pSpatializer);
5235MA_API void ma_spatializer_set_min_gain(ma_spatializer* pSpatializer, float minGain);
5236MA_API float ma_spatializer_get_min_gain(const ma_spatializer* pSpatializer);
5237MA_API void ma_spatializer_set_max_gain(ma_spatializer* pSpatializer, float maxGain);
5238MA_API float ma_spatializer_get_max_gain(const ma_spatializer* pSpatializer);
5239MA_API void ma_spatializer_set_min_distance(ma_spatializer* pSpatializer, float minDistance);
5240MA_API float ma_spatializer_get_min_distance(const ma_spatializer* pSpatializer);
5241MA_API void ma_spatializer_set_max_distance(ma_spatializer* pSpatializer, float maxDistance);
5242MA_API float ma_spatializer_get_max_distance(const ma_spatializer* pSpatializer);
5243MA_API void ma_spatializer_set_cone(ma_spatializer* pSpatializer, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
5244MA_API void ma_spatializer_get_cone(const ma_spatializer* pSpatializer, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
5245MA_API void ma_spatializer_set_doppler_factor(ma_spatializer* pSpatializer, float dopplerFactor);
5246MA_API float ma_spatializer_get_doppler_factor(const ma_spatializer* pSpatializer);
5247MA_API void ma_spatializer_set_directional_attenuation_factor(ma_spatializer* pSpatializer, float directionalAttenuationFactor);
5248MA_API float ma_spatializer_get_directional_attenuation_factor(const ma_spatializer* pSpatializer);
5249MA_API void ma_spatializer_set_position(ma_spatializer* pSpatializer, float x, float y, float z);
5250MA_API ma_vec3f ma_spatializer_get_position(const ma_spatializer* pSpatializer);
5251MA_API void ma_spatializer_set_direction(ma_spatializer* pSpatializer, float x, float y, float z);
5252MA_API ma_vec3f ma_spatializer_get_direction(const ma_spatializer* pSpatializer);
5253MA_API void ma_spatializer_set_velocity(ma_spatializer* pSpatializer, float x, float y, float z);
5254MA_API ma_vec3f ma_spatializer_get_velocity(const ma_spatializer* pSpatializer);
5255MA_API void ma_spatializer_get_relative_position_and_direction(const ma_spatializer* pSpatializer, const ma_spatializer_listener* pListener, ma_vec3f* pRelativePos, ma_vec3f* pRelativeDir);
5256
5257
5258
5259/************************************************************************************************************************************************************
5260*************************************************************************************************************************************************************
5261
5262DATA CONVERSION
5263===============
5264
5265This section contains the APIs for data conversion. You will find everything here for channel mapping, sample format conversion, resampling, etc.
5266
5267*************************************************************************************************************************************************************
5268************************************************************************************************************************************************************/
5269
5270/**************************************************************************************************************************************************************
5271
5272Resampling
5273
5274**************************************************************************************************************************************************************/
5275typedef struct
5276{
5277 ma_format format;
5278 ma_uint32 channels;
5279 ma_uint32 sampleRateIn;
5280 ma_uint32 sampleRateOut;
5281 ma_uint32 lpfOrder; /* The low-pass filter order. Setting this to 0 will disable low-pass filtering. */
5282 double lpfNyquistFactor; /* 0..1. Defaults to 1. 1 = Half the sampling frequency (Nyquist Frequency), 0.5 = Quarter the sampling frequency (half Nyquest Frequency), etc. */
5283} ma_linear_resampler_config;
5284
5285MA_API ma_linear_resampler_config ma_linear_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
5286
5287typedef struct
5288{
5289 ma_linear_resampler_config config;
5290 ma_uint32 inAdvanceInt;
5291 ma_uint32 inAdvanceFrac;
5292 ma_uint32 inTimeInt;
5293 ma_uint32 inTimeFrac;
5294 union
5295 {
5296 float* f32;
5297 ma_int16* s16;
5298 } x0; /* The previous input frame. */
5299 union
5300 {
5301 float* f32;
5302 ma_int16* s16;
5303 } x1; /* The next input frame. */
5304 ma_lpf lpf;
5305
5306 /* Memory management. */
5307 void* _pHeap;
5308 ma_bool32 _ownsHeap;
5309} ma_linear_resampler;
5310
5311MA_API ma_result ma_linear_resampler_get_heap_size(const ma_linear_resampler_config* pConfig, size_t* pHeapSizeInBytes);
5312MA_API ma_result ma_linear_resampler_init_preallocated(const ma_linear_resampler_config* pConfig, void* pHeap, ma_linear_resampler* pResampler);
5313MA_API ma_result ma_linear_resampler_init(const ma_linear_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_linear_resampler* pResampler);
5314MA_API void ma_linear_resampler_uninit(ma_linear_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks);
5315MA_API ma_result ma_linear_resampler_process_pcm_frames(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
5316MA_API ma_result ma_linear_resampler_set_rate(ma_linear_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
5317MA_API ma_result ma_linear_resampler_set_rate_ratio(ma_linear_resampler* pResampler, float ratioInOut);
5318MA_API ma_uint64 ma_linear_resampler_get_input_latency(const ma_linear_resampler* pResampler);
5319MA_API ma_uint64 ma_linear_resampler_get_output_latency(const ma_linear_resampler* pResampler);
5320MA_API ma_result ma_linear_resampler_get_required_input_frame_count(const ma_linear_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount);
5321MA_API ma_result ma_linear_resampler_get_expected_output_frame_count(const ma_linear_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount);
5322MA_API ma_result ma_linear_resampler_reset(ma_linear_resampler* pResampler);
5323
5324
5325typedef struct ma_resampler_config ma_resampler_config;
5326
5327typedef void ma_resampling_backend;
5328typedef struct
5329{
5330 ma_result (* onGetHeapSize )(void* pUserData, const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes);
5331 ma_result (* onInit )(void* pUserData, const ma_resampler_config* pConfig, void* pHeap, ma_resampling_backend** ppBackend);
5332 void (* onUninit )(void* pUserData, ma_resampling_backend* pBackend, const ma_allocation_callbacks* pAllocationCallbacks);
5333 ma_result (* onProcess )(void* pUserData, ma_resampling_backend* pBackend, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
5334 ma_result (* onSetRate )(void* pUserData, ma_resampling_backend* pBackend, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); /* Optional. Rate changes will be disabled. */
5335 ma_uint64 (* onGetInputLatency )(void* pUserData, const ma_resampling_backend* pBackend); /* Optional. Latency will be reported as 0. */
5336 ma_uint64 (* onGetOutputLatency )(void* pUserData, const ma_resampling_backend* pBackend); /* Optional. Latency will be reported as 0. */
5337 ma_result (* onGetRequiredInputFrameCount )(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount); /* Optional. Latency mitigation will be disabled. */
5338 ma_result (* onGetExpectedOutputFrameCount)(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount); /* Optional. Latency mitigation will be disabled. */
5339 ma_result (* onReset )(void* pUserData, ma_resampling_backend* pBackend);
5340} ma_resampling_backend_vtable;
5341
5342typedef enum
5343{
5344 ma_resample_algorithm_linear = 0, /* Fastest, lowest quality. Optional low-pass filtering. Default. */
5345 ma_resample_algorithm_custom,
5346} ma_resample_algorithm;
5347
5348struct ma_resampler_config
5349{
5350 ma_format format; /* Must be either ma_format_f32 or ma_format_s16. */
5351 ma_uint32 channels;
5352 ma_uint32 sampleRateIn;
5353 ma_uint32 sampleRateOut;
5354 ma_resample_algorithm algorithm; /* When set to ma_resample_algorithm_custom, pBackendVTable will be used. */
5355 ma_resampling_backend_vtable* pBackendVTable;
5356 void* pBackendUserData;
5357 struct
5358 {
5359 ma_uint32 lpfOrder;
5360 } linear;
5361};
5362
5363MA_API ma_resampler_config ma_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut, ma_resample_algorithm algorithm);
5364
5365typedef struct
5366{
5367 ma_resampling_backend* pBackend;
5368 ma_resampling_backend_vtable* pBackendVTable;
5369 void* pBackendUserData;
5370 ma_format format;
5371 ma_uint32 channels;
5372 ma_uint32 sampleRateIn;
5373 ma_uint32 sampleRateOut;
5374 union
5375 {
5376 ma_linear_resampler linear;
5377 } state; /* State for stock resamplers so we can avoid a malloc. For stock resamplers, pBackend will point here. */
5378
5379 /* Memory management. */
5380 void* _pHeap;
5381 ma_bool32 _ownsHeap;
5382} ma_resampler;
5383
5384MA_API ma_result ma_resampler_get_heap_size(const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes);
5385MA_API ma_result ma_resampler_init_preallocated(const ma_resampler_config* pConfig, void* pHeap, ma_resampler* pResampler);
5386
5387/*
5388Initializes a new resampler object from a config.
5389*/
5390MA_API ma_result ma_resampler_init(const ma_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_resampler* pResampler);
5391
5392/*
5393Uninitializes a resampler.
5394*/
5395MA_API void ma_resampler_uninit(ma_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks);
5396
5397/*
5398Converts the given input data.
5399
5400Both the input and output frames must be in the format specified in the config when the resampler was initialized.
5401
5402On input, [pFrameCountOut] contains the number of output frames to process. On output it contains the number of output frames that
5403were actually processed, which may be less than the requested amount which will happen if there's not enough input data. You can use
5404ma_resampler_get_expected_output_frame_count() to know how many output frames will be processed for a given number of input frames.
5405
5406On input, [pFrameCountIn] contains the number of input frames contained in [pFramesIn]. On output it contains the number of whole
5407input frames that were actually processed. You can use ma_resampler_get_required_input_frame_count() to know how many input frames
5408you should provide for a given number of output frames. [pFramesIn] can be NULL, in which case zeroes will be used instead.
5409
5410If [pFramesOut] is NULL, a seek is performed. In this case, if [pFrameCountOut] is not NULL it will seek by the specified number of
5411output frames. Otherwise, if [pFramesCountOut] is NULL and [pFrameCountIn] is not NULL, it will seek by the specified number of input
5412frames. When seeking, [pFramesIn] is allowed to NULL, in which case the internal timing state will be updated, but no input will be
5413processed. In this case, any internal filter state will be updated as if zeroes were passed in.
5414
5415It is an error for [pFramesOut] to be non-NULL and [pFrameCountOut] to be NULL.
5416
5417It is an error for both [pFrameCountOut] and [pFrameCountIn] to be NULL.
5418*/
5419MA_API ma_result ma_resampler_process_pcm_frames(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
5420
5421
5422/*
5423Sets the input and output sample rate.
5424*/
5425MA_API ma_result ma_resampler_set_rate(ma_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
5426
5427/*
5428Sets the input and output sample rate as a ratio.
5429
5430The ration is in/out.
5431*/
5432MA_API ma_result ma_resampler_set_rate_ratio(ma_resampler* pResampler, float ratio);
5433
5434/*
5435Retrieves the latency introduced by the resampler in input frames.
5436*/
5437MA_API ma_uint64 ma_resampler_get_input_latency(const ma_resampler* pResampler);
5438
5439/*
5440Retrieves the latency introduced by the resampler in output frames.
5441*/
5442MA_API ma_uint64 ma_resampler_get_output_latency(const ma_resampler* pResampler);
5443
5444/*
5445Calculates the number of whole input frames that would need to be read from the client in order to output the specified
5446number of output frames.
5447
5448The returned value does not include cached input frames. It only returns the number of extra frames that would need to be
5449read from the input buffer in order to output the specified number of output frames.
5450*/
5451MA_API ma_result ma_resampler_get_required_input_frame_count(const ma_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount);
5452
5453/*
5454Calculates the number of whole output frames that would be output after fully reading and consuming the specified number of
5455input frames.
5456*/
5457MA_API ma_result ma_resampler_get_expected_output_frame_count(const ma_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount);
5458
5459/*
5460Resets the resampler's timer and clears it's internal cache.
5461*/
5462MA_API ma_result ma_resampler_reset(ma_resampler* pResampler);
5463
5464
5465/**************************************************************************************************************************************************************
5466
5467Channel Conversion
5468
5469**************************************************************************************************************************************************************/
5470typedef enum
5471{
5472 ma_channel_conversion_path_unknown,
5473 ma_channel_conversion_path_passthrough,
5474 ma_channel_conversion_path_mono_out, /* Converting to mono. */
5475 ma_channel_conversion_path_mono_in, /* Converting from mono. */
5476 ma_channel_conversion_path_shuffle, /* Simple shuffle. Will use this when all channels are present in both input and output channel maps, but just in a different order. */
5477 ma_channel_conversion_path_weights /* Blended based on weights. */
5478} ma_channel_conversion_path;
5479
5480typedef enum
5481{
5482 ma_mono_expansion_mode_duplicate = 0, /* The default. */
5483 ma_mono_expansion_mode_average, /* Average the mono channel across all channels. */
5484 ma_mono_expansion_mode_stereo_only, /* Duplicate to the left and right channels only and ignore the others. */
5485 ma_mono_expansion_mode_default = ma_mono_expansion_mode_duplicate
5486} ma_mono_expansion_mode;
5487
5488typedef struct
5489{
5490 ma_format format;
5491 ma_uint32 channelsIn;
5492 ma_uint32 channelsOut;
5493 const ma_channel* pChannelMapIn;
5494 const ma_channel* pChannelMapOut;
5495 ma_channel_mix_mode mixingMode;
5496 ma_bool32 calculateLFEFromSpatialChannels; /* When an output LFE channel is present, but no input LFE, set to true to set the output LFE to the average of all spatial channels (LR, FR, etc.). Ignored when an input LFE is present. */
5497 float** ppWeights; /* [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. */
5498} ma_channel_converter_config;
5499
5500MA_API ma_channel_converter_config ma_channel_converter_config_init(ma_format format, ma_uint32 channelsIn, const ma_channel* pChannelMapIn, ma_uint32 channelsOut, const ma_channel* pChannelMapOut, ma_channel_mix_mode mixingMode);
5501
5502typedef struct
5503{
5504 ma_format format;
5505 ma_uint32 channelsIn;
5506 ma_uint32 channelsOut;
5507 ma_channel_mix_mode mixingMode;
5508 ma_channel_conversion_path conversionPath;
5509 ma_channel* pChannelMapIn;
5510 ma_channel* pChannelMapOut;
5511 ma_uint8* pShuffleTable; /* Indexed by output channel index. */
5512 union
5513 {
5514 float** f32;
5515 ma_int32** s16;
5516 } weights; /* [in][out] */
5517
5518 /* Memory management. */
5519 void* _pHeap;
5520 ma_bool32 _ownsHeap;
5521} ma_channel_converter;
5522
5523MA_API ma_result ma_channel_converter_get_heap_size(const ma_channel_converter_config* pConfig, size_t* pHeapSizeInBytes);
5524MA_API ma_result ma_channel_converter_init_preallocated(const ma_channel_converter_config* pConfig, void* pHeap, ma_channel_converter* pConverter);
5525MA_API ma_result ma_channel_converter_init(const ma_channel_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_channel_converter* pConverter);
5526MA_API void ma_channel_converter_uninit(ma_channel_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks);
5527MA_API ma_result ma_channel_converter_process_pcm_frames(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
5528MA_API ma_result ma_channel_converter_get_input_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
5529MA_API ma_result ma_channel_converter_get_output_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
5530
5531
5532/**************************************************************************************************************************************************************
5533
5534Data Conversion
5535
5536**************************************************************************************************************************************************************/
5537typedef struct
5538{
5539 ma_format formatIn;
5540 ma_format formatOut;
5541 ma_uint32 channelsIn;
5542 ma_uint32 channelsOut;
5543 ma_uint32 sampleRateIn;
5544 ma_uint32 sampleRateOut;
5545 ma_channel* pChannelMapIn;
5546 ma_channel* pChannelMapOut;
5547 ma_dither_mode ditherMode;
5548 ma_channel_mix_mode channelMixMode;
5549 ma_bool32 calculateLFEFromSpatialChannels; /* When an output LFE channel is present, but no input LFE, set to true to set the output LFE to the average of all spatial channels (LR, FR, etc.). Ignored when an input LFE is present. */
5550 float** ppChannelWeights; /* [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. */
5551 ma_bool32 allowDynamicSampleRate;
5552 ma_resampler_config resampling;
5553} ma_data_converter_config;
5554
5555MA_API ma_data_converter_config ma_data_converter_config_init_default(void);
5556MA_API ma_data_converter_config ma_data_converter_config_init(ma_format formatIn, ma_format formatOut, ma_uint32 channelsIn, ma_uint32 channelsOut, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
5557
5558
5559typedef enum
5560{
5561 ma_data_converter_execution_path_passthrough, /* No conversion. */
5562 ma_data_converter_execution_path_format_only, /* Only format conversion. */
5563 ma_data_converter_execution_path_channels_only, /* Only channel conversion. */
5564 ma_data_converter_execution_path_resample_only, /* Only resampling. */
5565 ma_data_converter_execution_path_resample_first, /* All conversions, but resample as the first step. */
5566 ma_data_converter_execution_path_channels_first /* All conversions, but channels as the first step. */
5567} ma_data_converter_execution_path;
5568
5569typedef struct
5570{
5571 ma_format formatIn;
5572 ma_format formatOut;
5573 ma_uint32 channelsIn;
5574 ma_uint32 channelsOut;
5575 ma_uint32 sampleRateIn;
5576 ma_uint32 sampleRateOut;
5577 ma_dither_mode ditherMode;
5578 ma_data_converter_execution_path executionPath; /* The execution path the data converter will follow when processing. */
5579 ma_channel_converter channelConverter;
5580 ma_resampler resampler;
5581 ma_bool8 hasPreFormatConversion;
5582 ma_bool8 hasPostFormatConversion;
5583 ma_bool8 hasChannelConverter;
5584 ma_bool8 hasResampler;
5585 ma_bool8 isPassthrough;
5586
5587 /* Memory management. */
5588 ma_bool8 _ownsHeap;
5589 void* _pHeap;
5590} ma_data_converter;
5591
5592MA_API ma_result ma_data_converter_get_heap_size(const ma_data_converter_config* pConfig, size_t* pHeapSizeInBytes);
5593MA_API ma_result ma_data_converter_init_preallocated(const ma_data_converter_config* pConfig, void* pHeap, ma_data_converter* pConverter);
5594MA_API ma_result ma_data_converter_init(const ma_data_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_converter* pConverter);
5595MA_API void ma_data_converter_uninit(ma_data_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks);
5596MA_API ma_result ma_data_converter_process_pcm_frames(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
5597MA_API ma_result ma_data_converter_set_rate(ma_data_converter* pConverter, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
5598MA_API ma_result ma_data_converter_set_rate_ratio(ma_data_converter* pConverter, float ratioInOut);
5599MA_API ma_uint64 ma_data_converter_get_input_latency(const ma_data_converter* pConverter);
5600MA_API ma_uint64 ma_data_converter_get_output_latency(const ma_data_converter* pConverter);
5601MA_API ma_result ma_data_converter_get_required_input_frame_count(const ma_data_converter* pConverter, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount);
5602MA_API ma_result ma_data_converter_get_expected_output_frame_count(const ma_data_converter* pConverter, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount);
5603MA_API ma_result ma_data_converter_get_input_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
5604MA_API ma_result ma_data_converter_get_output_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
5605MA_API ma_result ma_data_converter_reset(ma_data_converter* pConverter);
5606
5607
5608/************************************************************************************************************************************************************
5609
5610Format Conversion
5611
5612************************************************************************************************************************************************************/
5613MA_API void ma_pcm_u8_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5614MA_API void ma_pcm_u8_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5615MA_API void ma_pcm_u8_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5616MA_API void ma_pcm_u8_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5617MA_API void ma_pcm_s16_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5618MA_API void ma_pcm_s16_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5619MA_API void ma_pcm_s16_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5620MA_API void ma_pcm_s16_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5621MA_API void ma_pcm_s24_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5622MA_API void ma_pcm_s24_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5623MA_API void ma_pcm_s24_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5624MA_API void ma_pcm_s24_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5625MA_API void ma_pcm_s32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5626MA_API void ma_pcm_s32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5627MA_API void ma_pcm_s32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5628MA_API void ma_pcm_s32_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5629MA_API void ma_pcm_f32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5630MA_API void ma_pcm_f32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5631MA_API void ma_pcm_f32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5632MA_API void ma_pcm_f32_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
5633MA_API void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode);
5634MA_API void ma_convert_pcm_frames_format(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 frameCount, ma_uint32 channels, ma_dither_mode ditherMode);
5635
5636/*
5637Deinterleaves an interleaved buffer.
5638*/
5639MA_API void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames);
5640
5641/*
5642Interleaves a group of deinterleaved buffers.
5643*/
5644MA_API void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames);
5645
5646
5647/************************************************************************************************************************************************************
5648
5649Channel Maps
5650
5651************************************************************************************************************************************************************/
5652/*
5653This is used in the shuffle table to indicate that the channel index is undefined and should be ignored.
5654*/
5655#define MA_CHANNEL_INDEX_NULL 255
5656
5657/*
5658Retrieves the channel position of the specified channel in the given channel map.
5659
5660The pChannelMap parameter can be null, in which case miniaudio's default channel map will be assumed.
5661*/
5662MA_API ma_channel ma_channel_map_get_channel(const ma_channel* pChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex);
5663
5664/*
5665Initializes a blank channel map.
5666
5667When a blank channel map is specified anywhere it indicates that the native channel map should be used.
5668*/
5669MA_API void ma_channel_map_init_blank(ma_channel* pChannelMap, ma_uint32 channels);
5670
5671/*
5672Helper for retrieving a standard channel map.
5673
5674The output channel map buffer must have a capacity of at least `channelMapCap`.
5675*/
5676MA_API void ma_channel_map_init_standard(ma_standard_channel_map standardChannelMap, ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channels);
5677
5678/*
5679Copies a channel map.
5680
5681Both input and output channel map buffers must have a capacity of at at least `channels`.
5682*/
5683MA_API void ma_channel_map_copy(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels);
5684
5685/*
5686Copies a channel map if one is specified, otherwise copies the default channel map.
5687
5688The output buffer must have a capacity of at least `channels`. If not NULL, the input channel map must also have a capacity of at least `channels`.
5689*/
5690MA_API void ma_channel_map_copy_or_default(ma_channel* pOut, size_t channelMapCapOut, const ma_channel* pIn, ma_uint32 channels);
5691
5692
5693/*
5694Determines whether or not a channel map is valid.
5695
5696A blank channel map is valid (all channels set to MA_CHANNEL_NONE). The way a blank channel map is handled is context specific, but
5697is usually treated as a passthrough.
5698
5699Invalid channel maps:
5700 - A channel map with no channels
5701 - A channel map with more than one channel and a mono channel
5702
5703The channel map buffer must have a capacity of at least `channels`.
5704*/
5705MA_API ma_bool32 ma_channel_map_is_valid(const ma_channel* pChannelMap, ma_uint32 channels);
5706
5707/*
5708Helper for comparing two channel maps for equality.
5709
5710This assumes the channel count is the same between the two.
5711
5712Both channels map buffers must have a capacity of at least `channels`.
5713*/
5714MA_API ma_bool32 ma_channel_map_is_equal(const ma_channel* pChannelMapA, const ma_channel* pChannelMapB, ma_uint32 channels);
5715
5716/*
5717Helper for determining if a channel map is blank (all channels set to MA_CHANNEL_NONE).
5718
5719The channel map buffer must have a capacity of at least `channels`.
5720*/
5721MA_API ma_bool32 ma_channel_map_is_blank(const ma_channel* pChannelMap, ma_uint32 channels);
5722
5723/*
5724Helper for determining whether or not a channel is present in the given channel map.
5725
5726The channel map buffer must have a capacity of at least `channels`.
5727*/
5728MA_API ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition);
5729
5730/*
5731Find a channel position in the given channel map. Returns MA_TRUE if the channel is found; MA_FALSE otherwise. The
5732index of the channel is output to `pChannelIndex`.
5733
5734The channel map buffer must have a capacity of at least `channels`.
5735*/
5736MA_API ma_bool32 ma_channel_map_find_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition, ma_uint32* pChannelIndex);
5737
5738/*
5739Generates a string representing the given channel map.
5740
5741This is for printing and debugging purposes, not serialization/deserialization.
5742
5743Returns the length of the string, not including the null terminator.
5744*/
5745MA_API size_t ma_channel_map_to_string(const ma_channel* pChannelMap, ma_uint32 channels, char* pBufferOut, size_t bufferCap);
5746
5747/*
5748Retrieves a human readable version of a channel position.
5749*/
5750MA_API const char* ma_channel_position_to_string(ma_channel channel);
5751
5752
5753/************************************************************************************************************************************************************
5754
5755Conversion Helpers
5756
5757************************************************************************************************************************************************************/
5758
5759/*
5760High-level helper for doing a full format conversion in one go. Returns the number of output frames. Call this with pOut set to NULL to
5761determine the required size of the output buffer. frameCountOut should be set to the capacity of pOut. If pOut is NULL, frameCountOut is
5762ignored.
5763
5764A return value of 0 indicates an error.
5765
5766This function is useful for one-off bulk conversions, but if you're streaming data you should use the ma_data_converter APIs instead.
5767*/
5768MA_API ma_uint64 ma_convert_frames(void* pOut, ma_uint64 frameCountOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, const void* pIn, ma_uint64 frameCountIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn);
5769MA_API ma_uint64 ma_convert_frames_ex(void* pOut, ma_uint64 frameCountOut, const void* pIn, ma_uint64 frameCountIn, const ma_data_converter_config* pConfig);
5770
5771
5772/************************************************************************************************************************************************************
5773
5774Data Source
5775
5776************************************************************************************************************************************************************/
5777typedef void ma_data_source;
5778
5779#define MA_DATA_SOURCE_SELF_MANAGED_RANGE_AND_LOOP_POINT 0x00000001
5780
5781typedef struct
5782{
5783 ma_result (* onRead)(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
5784 ma_result (* onSeek)(ma_data_source* pDataSource, ma_uint64 frameIndex);
5785 ma_result (* onGetDataFormat)(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
5786 ma_result (* onGetCursor)(ma_data_source* pDataSource, ma_uint64* pCursor);
5787 ma_result (* onGetLength)(ma_data_source* pDataSource, ma_uint64* pLength);
5788 ma_result (* onSetLooping)(ma_data_source* pDataSource, ma_bool32 isLooping);
5789 ma_uint32 flags;
5790} ma_data_source_vtable;
5791
5792typedef ma_data_source* (* ma_data_source_get_next_proc)(ma_data_source* pDataSource);
5793
5794typedef struct
5795{
5796 const ma_data_source_vtable* vtable;
5797} ma_data_source_config;
5798
5799MA_API ma_data_source_config ma_data_source_config_init(void);
5800
5801
5802typedef struct
5803{
5804 const ma_data_source_vtable* vtable;
5805 ma_uint64 rangeBegInFrames;
5806 ma_uint64 rangeEndInFrames; /* Set to -1 for unranged (default). */
5807 ma_uint64 loopBegInFrames; /* Relative to rangeBegInFrames. */
5808 ma_uint64 loopEndInFrames; /* Relative to rangeBegInFrames. Set to -1 for the end of the range. */
5809 ma_data_source* pCurrent; /* When non-NULL, the data source being initialized will act as a proxy and will route all operations to pCurrent. Used in conjunction with pNext/onGetNext for seamless chaining. */
5810 ma_data_source* pNext; /* When set to NULL, onGetNext will be used. */
5811 ma_data_source_get_next_proc onGetNext; /* Will be used when pNext is NULL. If both are NULL, no next will be used. */
5812 MA_ATOMIC(4, ma_bool32) isLooping;
5813} ma_data_source_base;
5814
5815MA_API ma_result ma_data_source_init(const ma_data_source_config* pConfig, ma_data_source* pDataSource);
5816MA_API void ma_data_source_uninit(ma_data_source* pDataSource);
5817MA_API ma_result ma_data_source_read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); /* Must support pFramesOut = NULL in which case a forward seek should be performed. */
5818MA_API ma_result ma_data_source_seek_pcm_frames(ma_data_source* pDataSource, ma_uint64 frameCount, ma_uint64* pFramesSeeked); /* Can only seek forward. Equivalent to ma_data_source_read_pcm_frames(pDataSource, NULL, frameCount, &framesRead); */
5819MA_API ma_result ma_data_source_seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex);
5820MA_API ma_result ma_data_source_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
5821MA_API ma_result ma_data_source_get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor);
5822MA_API ma_result ma_data_source_get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength); /* Returns MA_NOT_IMPLEMENTED if the length is unknown or cannot be determined. Decoders can return this. */
5823MA_API ma_result ma_data_source_get_cursor_in_seconds(ma_data_source* pDataSource, float* pCursor);
5824MA_API ma_result ma_data_source_get_length_in_seconds(ma_data_source* pDataSource, float* pLength);
5825MA_API ma_result ma_data_source_set_looping(ma_data_source* pDataSource, ma_bool32 isLooping);
5826MA_API ma_bool32 ma_data_source_is_looping(const ma_data_source* pDataSource);
5827MA_API ma_result ma_data_source_set_range_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 rangeBegInFrames, ma_uint64 rangeEndInFrames);
5828MA_API void ma_data_source_get_range_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pRangeBegInFrames, ma_uint64* pRangeEndInFrames);
5829MA_API ma_result ma_data_source_set_loop_point_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 loopBegInFrames, ma_uint64 loopEndInFrames);
5830MA_API void ma_data_source_get_loop_point_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pLoopBegInFrames, ma_uint64* pLoopEndInFrames);
5831MA_API ma_result ma_data_source_set_current(ma_data_source* pDataSource, ma_data_source* pCurrentDataSource);
5832MA_API ma_data_source* ma_data_source_get_current(const ma_data_source* pDataSource);
5833MA_API ma_result ma_data_source_set_next(ma_data_source* pDataSource, ma_data_source* pNextDataSource);
5834MA_API ma_data_source* ma_data_source_get_next(const ma_data_source* pDataSource);
5835MA_API ma_result ma_data_source_set_next_callback(ma_data_source* pDataSource, ma_data_source_get_next_proc onGetNext);
5836MA_API ma_data_source_get_next_proc ma_data_source_get_next_callback(const ma_data_source* pDataSource);
5837
5838
5839typedef struct
5840{
5841 ma_data_source_base ds;
5842 ma_format format;
5843 ma_uint32 channels;
5844 ma_uint32 sampleRate;
5845 ma_uint64 cursor;
5846 ma_uint64 sizeInFrames;
5847 const void* pData;
5848} ma_audio_buffer_ref;
5849
5850MA_API ma_result ma_audio_buffer_ref_init(ma_format format, ma_uint32 channels, const void* pData, ma_uint64 sizeInFrames, ma_audio_buffer_ref* pAudioBufferRef);
5851MA_API void ma_audio_buffer_ref_uninit(ma_audio_buffer_ref* pAudioBufferRef);
5852MA_API ma_result ma_audio_buffer_ref_set_data(ma_audio_buffer_ref* pAudioBufferRef, const void* pData, ma_uint64 sizeInFrames);
5853MA_API ma_uint64 ma_audio_buffer_ref_read_pcm_frames(ma_audio_buffer_ref* pAudioBufferRef, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop);
5854MA_API ma_result ma_audio_buffer_ref_seek_to_pcm_frame(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameIndex);
5855MA_API ma_result ma_audio_buffer_ref_map(ma_audio_buffer_ref* pAudioBufferRef, void** ppFramesOut, ma_uint64* pFrameCount);
5856MA_API ma_result ma_audio_buffer_ref_unmap(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameCount); /* Returns MA_AT_END if the end has been reached. This should be considered successful. */
5857MA_API ma_bool32 ma_audio_buffer_ref_at_end(const ma_audio_buffer_ref* pAudioBufferRef);
5858MA_API ma_result ma_audio_buffer_ref_get_cursor_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pCursor);
5859MA_API ma_result ma_audio_buffer_ref_get_length_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pLength);
5860MA_API ma_result ma_audio_buffer_ref_get_available_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pAvailableFrames);
5861
5862
5863
5864typedef struct
5865{
5866 ma_format format;
5867 ma_uint32 channels;
5868 ma_uint32 sampleRate;
5869 ma_uint64 sizeInFrames;
5870 const void* pData; /* If set to NULL, will allocate a block of memory for you. */
5871 ma_allocation_callbacks allocationCallbacks;
5872} ma_audio_buffer_config;
5873
5874MA_API ma_audio_buffer_config ma_audio_buffer_config_init(ma_format format, ma_uint32 channels, ma_uint64 sizeInFrames, const void* pData, const ma_allocation_callbacks* pAllocationCallbacks);
5875
5876typedef struct
5877{
5878 ma_audio_buffer_ref ref;
5879 ma_allocation_callbacks allocationCallbacks;
5880 ma_bool32 ownsData; /* Used to control whether or not miniaudio owns the data buffer. If set to true, pData will be freed in ma_audio_buffer_uninit(). */
5881 ma_uint8 _pExtraData[1]; /* For allocating a buffer with the memory located directly after the other memory of the structure. */
5882} ma_audio_buffer;
5883
5884MA_API ma_result ma_audio_buffer_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer);
5885MA_API ma_result ma_audio_buffer_init_copy(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer);
5886MA_API ma_result ma_audio_buffer_alloc_and_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer** ppAudioBuffer); /* Always copies the data. Doesn't make sense to use this otherwise. Use ma_audio_buffer_uninit_and_free() to uninit. */
5887MA_API void ma_audio_buffer_uninit(ma_audio_buffer* pAudioBuffer);
5888MA_API void ma_audio_buffer_uninit_and_free(ma_audio_buffer* pAudioBuffer);
5889MA_API ma_uint64 ma_audio_buffer_read_pcm_frames(ma_audio_buffer* pAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop);
5890MA_API ma_result ma_audio_buffer_seek_to_pcm_frame(ma_audio_buffer* pAudioBuffer, ma_uint64 frameIndex);
5891MA_API ma_result ma_audio_buffer_map(ma_audio_buffer* pAudioBuffer, void** ppFramesOut, ma_uint64* pFrameCount);
5892MA_API ma_result ma_audio_buffer_unmap(ma_audio_buffer* pAudioBuffer, ma_uint64 frameCount); /* Returns MA_AT_END if the end has been reached. This should be considered successful. */
5893MA_API ma_bool32 ma_audio_buffer_at_end(const ma_audio_buffer* pAudioBuffer);
5894MA_API ma_result ma_audio_buffer_get_cursor_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pCursor);
5895MA_API ma_result ma_audio_buffer_get_length_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pLength);
5896MA_API ma_result ma_audio_buffer_get_available_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pAvailableFrames);
5897
5898
5899/*
5900Paged Audio Buffer
5901==================
5902A paged audio buffer is made up of a linked list of pages. It's expandable, but not shrinkable. It
5903can be used for cases where audio data is streamed in asynchronously while allowing data to be read
5904at the same time.
5905
5906This is lock-free, but not 100% thread safe. You can append a page and read from the buffer across
5907simultaneously across different threads, however only one thread at a time can append, and only one
5908thread at a time can read and seek.
5909*/
5910typedef struct ma_paged_audio_buffer_page ma_paged_audio_buffer_page;
5911struct ma_paged_audio_buffer_page
5912{
5913 MA_ATOMIC(MA_SIZEOF_PTR, ma_paged_audio_buffer_page*) pNext;
5914 ma_uint64 sizeInFrames;
5915 ma_uint8 pAudioData[1];
5916};
5917
5918typedef struct
5919{
5920 ma_format format;
5921 ma_uint32 channels;
5922 ma_paged_audio_buffer_page head; /* Dummy head for the lock-free algorithm. Always has a size of 0. */
5923 MA_ATOMIC(MA_SIZEOF_PTR, ma_paged_audio_buffer_page*) pTail; /* Never null. Initially set to &head. */
5924} ma_paged_audio_buffer_data;
5925
5926MA_API ma_result ma_paged_audio_buffer_data_init(ma_format format, ma_uint32 channels, ma_paged_audio_buffer_data* pData);
5927MA_API void ma_paged_audio_buffer_data_uninit(ma_paged_audio_buffer_data* pData, const ma_allocation_callbacks* pAllocationCallbacks);
5928MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_head(ma_paged_audio_buffer_data* pData);
5929MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_tail(ma_paged_audio_buffer_data* pData);
5930MA_API ma_result ma_paged_audio_buffer_data_get_length_in_pcm_frames(ma_paged_audio_buffer_data* pData, ma_uint64* pLength);
5931MA_API ma_result ma_paged_audio_buffer_data_allocate_page(ma_paged_audio_buffer_data* pData, ma_uint64 pageSizeInFrames, const void* pInitialData, const ma_allocation_callbacks* pAllocationCallbacks, ma_paged_audio_buffer_page** ppPage);
5932MA_API ma_result ma_paged_audio_buffer_data_free_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage, const ma_allocation_callbacks* pAllocationCallbacks);
5933MA_API ma_result ma_paged_audio_buffer_data_append_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage);
5934MA_API ma_result ma_paged_audio_buffer_data_allocate_and_append_page(ma_paged_audio_buffer_data* pData, ma_uint32 pageSizeInFrames, const void* pInitialData, const ma_allocation_callbacks* pAllocationCallbacks);
5935
5936
5937typedef struct
5938{
5939 ma_paged_audio_buffer_data* pData; /* Must not be null. */
5940} ma_paged_audio_buffer_config;
5941
5942MA_API ma_paged_audio_buffer_config ma_paged_audio_buffer_config_init(ma_paged_audio_buffer_data* pData);
5943
5944
5945typedef struct
5946{
5947 ma_data_source_base ds;
5948 ma_paged_audio_buffer_data* pData; /* Audio data is read from here. Cannot be null. */
5949 ma_paged_audio_buffer_page* pCurrent;
5950 ma_uint64 relativeCursor; /* Relative to the current page. */
5951 ma_uint64 absoluteCursor;
5952} ma_paged_audio_buffer;
5953
5954MA_API ma_result ma_paged_audio_buffer_init(const ma_paged_audio_buffer_config* pConfig, ma_paged_audio_buffer* pPagedAudioBuffer);
5955MA_API void ma_paged_audio_buffer_uninit(ma_paged_audio_buffer* pPagedAudioBuffer);
5956MA_API ma_result ma_paged_audio_buffer_read_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead); /* Returns MA_AT_END if no more pages available. */
5957MA_API ma_result ma_paged_audio_buffer_seek_to_pcm_frame(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64 frameIndex);
5958MA_API ma_result ma_paged_audio_buffer_get_cursor_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pCursor);
5959MA_API ma_result ma_paged_audio_buffer_get_length_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pLength);
5960
5961
5962
5963/************************************************************************************************************************************************************
5964
5965Ring Buffer
5966
5967************************************************************************************************************************************************************/
5968typedef struct
5969{
5970 void* pBuffer;
5971 ma_uint32 subbufferSizeInBytes;
5972 ma_uint32 subbufferCount;
5973 ma_uint32 subbufferStrideInBytes;
5974 MA_ATOMIC(4, ma_uint32) encodedReadOffset; /* Most significant bit is the loop flag. Lower 31 bits contains the actual offset in bytes. Must be used atomically. */
5975 MA_ATOMIC(4, ma_uint32) encodedWriteOffset; /* Most significant bit is the loop flag. Lower 31 bits contains the actual offset in bytes. Must be used atomically. */
5976 ma_bool8 ownsBuffer; /* Used to know whether or not miniaudio is responsible for free()-ing the buffer. */
5977 ma_bool8 clearOnWriteAcquire; /* When set, clears the acquired write buffer before returning from ma_rb_acquire_write(). */
5978 ma_allocation_callbacks allocationCallbacks;
5979} ma_rb;
5980
5981MA_API ma_result ma_rb_init_ex(size_t subbufferSizeInBytes, size_t subbufferCount, size_t subbufferStrideInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB);
5982MA_API ma_result ma_rb_init(size_t bufferSizeInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB);
5983MA_API void ma_rb_uninit(ma_rb* pRB);
5984MA_API void ma_rb_reset(ma_rb* pRB);
5985MA_API ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut);
5986MA_API ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes);
5987MA_API ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut);
5988MA_API ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes);
5989MA_API ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes);
5990MA_API ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes);
5991MA_API ma_int32 ma_rb_pointer_distance(ma_rb* pRB); /* Returns the distance between the write pointer and the read pointer. Should never be negative for a correct program. Will return the number of bytes that can be read before the read pointer hits the write pointer. */
5992MA_API ma_uint32 ma_rb_available_read(ma_rb* pRB);
5993MA_API ma_uint32 ma_rb_available_write(ma_rb* pRB);
5994MA_API size_t ma_rb_get_subbuffer_size(ma_rb* pRB);
5995MA_API size_t ma_rb_get_subbuffer_stride(ma_rb* pRB);
5996MA_API size_t ma_rb_get_subbuffer_offset(ma_rb* pRB, size_t subbufferIndex);
5997MA_API void* ma_rb_get_subbuffer_ptr(ma_rb* pRB, size_t subbufferIndex, void* pBuffer);
5998
5999
6000typedef struct
6001{
6002 ma_data_source_base ds;
6003 ma_rb rb;
6004 ma_format format;
6005 ma_uint32 channels;
6006 ma_uint32 sampleRate; /* Not required for the ring buffer itself, but useful for associating the data with some sample rate, particularly for data sources. */
6007} ma_pcm_rb;
6008
6009MA_API ma_result ma_pcm_rb_init_ex(ma_format format, ma_uint32 channels, ma_uint32 subbufferSizeInFrames, ma_uint32 subbufferCount, ma_uint32 subbufferStrideInFrames, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_pcm_rb* pRB);
6010MA_API ma_result ma_pcm_rb_init(ma_format format, ma_uint32 channels, ma_uint32 bufferSizeInFrames, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_pcm_rb* pRB);
6011MA_API void ma_pcm_rb_uninit(ma_pcm_rb* pRB);
6012MA_API void ma_pcm_rb_reset(ma_pcm_rb* pRB);
6013MA_API ma_result ma_pcm_rb_acquire_read(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut);
6014MA_API ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames);
6015MA_API ma_result ma_pcm_rb_acquire_write(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut);
6016MA_API ma_result ma_pcm_rb_commit_write(ma_pcm_rb* pRB, ma_uint32 sizeInFrames);
6017MA_API ma_result ma_pcm_rb_seek_read(ma_pcm_rb* pRB, ma_uint32 offsetInFrames);
6018MA_API ma_result ma_pcm_rb_seek_write(ma_pcm_rb* pRB, ma_uint32 offsetInFrames);
6019MA_API ma_int32 ma_pcm_rb_pointer_distance(ma_pcm_rb* pRB); /* Return value is in frames. */
6020MA_API ma_uint32 ma_pcm_rb_available_read(ma_pcm_rb* pRB);
6021MA_API ma_uint32 ma_pcm_rb_available_write(ma_pcm_rb* pRB);
6022MA_API ma_uint32 ma_pcm_rb_get_subbuffer_size(ma_pcm_rb* pRB);
6023MA_API ma_uint32 ma_pcm_rb_get_subbuffer_stride(ma_pcm_rb* pRB);
6024MA_API ma_uint32 ma_pcm_rb_get_subbuffer_offset(ma_pcm_rb* pRB, ma_uint32 subbufferIndex);
6025MA_API void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void* pBuffer);
6026MA_API ma_format ma_pcm_rb_get_format(const ma_pcm_rb* pRB);
6027MA_API ma_uint32 ma_pcm_rb_get_channels(const ma_pcm_rb* pRB);
6028MA_API ma_uint32 ma_pcm_rb_get_sample_rate(const ma_pcm_rb* pRB);
6029MA_API void ma_pcm_rb_set_sample_rate(ma_pcm_rb* pRB, ma_uint32 sampleRate);
6030
6031
6032/*
6033The idea of the duplex ring buffer is to act as the intermediary buffer when running two asynchronous devices in a duplex set up. The
6034capture device writes to it, and then a playback device reads from it.
6035
6036At the moment this is just a simple naive implementation, but in the future I want to implement some dynamic resampling to seamlessly
6037handle desyncs. Note that the API is work in progress and may change at any time in any version.
6038
6039The size of the buffer is based on the capture side since that's what'll be written to the buffer. It is based on the capture period size
6040in frames. The internal sample rate of the capture device is also needed in order to calculate the size.
6041*/
6042typedef struct
6043{
6044 ma_pcm_rb rb;
6045} ma_duplex_rb;
6046
6047MA_API ma_result ma_duplex_rb_init(ma_format captureFormat, ma_uint32 captureChannels, ma_uint32 sampleRate, ma_uint32 captureInternalSampleRate, ma_uint32 captureInternalPeriodSizeInFrames, const ma_allocation_callbacks* pAllocationCallbacks, ma_duplex_rb* pRB);
6048MA_API ma_result ma_duplex_rb_uninit(ma_duplex_rb* pRB);
6049
6050
6051/************************************************************************************************************************************************************
6052
6053Miscellaneous Helpers
6054
6055************************************************************************************************************************************************************/
6056/*
6057Retrieves a human readable description of the given result code.
6058*/
6059MA_API const char* ma_result_description(ma_result result);
6060
6061/*
6062malloc()
6063*/
6064MA_API void* ma_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
6065
6066/*
6067calloc()
6068*/
6069MA_API void* ma_calloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
6070
6071/*
6072realloc()
6073*/
6074MA_API void* ma_realloc(void* p, size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
6075
6076/*
6077free()
6078*/
6079MA_API void ma_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
6080
6081/*
6082Performs an aligned malloc, with the assumption that the alignment is a power of 2.
6083*/
6084MA_API void* ma_aligned_malloc(size_t sz, size_t alignment, const ma_allocation_callbacks* pAllocationCallbacks);
6085
6086/*
6087Free's an aligned malloc'd buffer.
6088*/
6089MA_API void ma_aligned_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
6090
6091/*
6092Retrieves a friendly name for a format.
6093*/
6094MA_API const char* ma_get_format_name(ma_format format);
6095
6096/*
6097Blends two frames in floating point format.
6098*/
6099MA_API void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels);
6100
6101/*
6102Retrieves the size of a sample in bytes for the given format.
6103
6104This API is efficient and is implemented using a lookup table.
6105
6106Thread Safety: SAFE
6107 This API is pure.
6108*/
6109MA_API ma_uint32 ma_get_bytes_per_sample(ma_format format);
6110static MA_INLINE ma_uint32 ma_get_bytes_per_frame(ma_format format, ma_uint32 channels) { return ma_get_bytes_per_sample(format) * channels; }
6111
6112/*
6113Converts a log level to a string.
6114*/
6115MA_API const char* ma_log_level_to_string(ma_uint32 logLevel);
6116
6117
6118
6119
6120/************************************************************************************************************************************************************
6121
6122Synchronization
6123
6124************************************************************************************************************************************************************/
6125/*
6126Locks a spinlock.
6127*/
6128MA_API ma_result ma_spinlock_lock(volatile ma_spinlock* pSpinlock);
6129
6130/*
6131Locks a spinlock, but does not yield() when looping.
6132*/
6133MA_API ma_result ma_spinlock_lock_noyield(volatile ma_spinlock* pSpinlock);
6134
6135/*
6136Unlocks a spinlock.
6137*/
6138MA_API ma_result ma_spinlock_unlock(volatile ma_spinlock* pSpinlock);
6139
6140
6141#ifndef MA_NO_THREADING
6142
6143/*
6144Creates a mutex.
6145
6146A mutex must be created from a valid context. A mutex is initially unlocked.
6147*/
6148MA_API ma_result ma_mutex_init(ma_mutex* pMutex);
6149
6150/*
6151Deletes a mutex.
6152*/
6153MA_API void ma_mutex_uninit(ma_mutex* pMutex);
6154
6155/*
6156Locks a mutex with an infinite timeout.
6157*/
6158MA_API void ma_mutex_lock(ma_mutex* pMutex);
6159
6160/*
6161Unlocks a mutex.
6162*/
6163MA_API void ma_mutex_unlock(ma_mutex* pMutex);
6164
6165
6166/*
6167Initializes an auto-reset event.
6168*/
6169MA_API ma_result ma_event_init(ma_event* pEvent);
6170
6171/*
6172Uninitializes an auto-reset event.
6173*/
6174MA_API void ma_event_uninit(ma_event* pEvent);
6175
6176/*
6177Waits for the specified auto-reset event to become signalled.
6178*/
6179MA_API ma_result ma_event_wait(ma_event* pEvent);
6180
6181/*
6182Signals the specified auto-reset event.
6183*/
6184MA_API ma_result ma_event_signal(ma_event* pEvent);
6185#endif /* MA_NO_THREADING */
6186
6187
6188/*
6189Fence
6190=====
6191This locks while the counter is larger than 0. Counter can be incremented and decremented by any
6192thread, but care needs to be taken when waiting. It is possible for one thread to acquire the
6193fence just as another thread returns from ma_fence_wait().
6194
6195The idea behind a fence is to allow you to wait for a group of operations to complete. When an
6196operation starts, the counter is incremented which locks the fence. When the operation completes,
6197the fence will be released which decrements the counter. ma_fence_wait() will block until the
6198counter hits zero.
6199
6200If threading is disabled, ma_fence_wait() will spin on the counter.
6201*/
6202typedef struct
6203{
6204#ifndef MA_NO_THREADING
6205 ma_event e;
6206#endif
6207 ma_uint32 counter;
6208} ma_fence;
6209
6210MA_API ma_result ma_fence_init(ma_fence* pFence);
6211MA_API void ma_fence_uninit(ma_fence* pFence);
6212MA_API ma_result ma_fence_acquire(ma_fence* pFence); /* Increment counter. */
6213MA_API ma_result ma_fence_release(ma_fence* pFence); /* Decrement counter. */
6214MA_API ma_result ma_fence_wait(ma_fence* pFence); /* Wait for counter to reach 0. */
6215
6216
6217
6218/*
6219Notification callback for asynchronous operations.
6220*/
6221typedef void ma_async_notification;
6222
6223typedef struct
6224{
6225 void (* onSignal)(ma_async_notification* pNotification);
6226} ma_async_notification_callbacks;
6227
6228MA_API ma_result ma_async_notification_signal(ma_async_notification* pNotification);
6229
6230
6231/*
6232Simple polling notification.
6233
6234This just sets a variable when the notification has been signalled which is then polled with ma_async_notification_poll_is_signalled()
6235*/
6236typedef struct
6237{
6238 ma_async_notification_callbacks cb;
6239 ma_bool32 signalled;
6240} ma_async_notification_poll;
6241
6242MA_API ma_result ma_async_notification_poll_init(ma_async_notification_poll* pNotificationPoll);
6243MA_API ma_bool32 ma_async_notification_poll_is_signalled(const ma_async_notification_poll* pNotificationPoll);
6244
6245
6246/*
6247Event Notification
6248
6249This uses an ma_event. If threading is disabled (MA_NO_THREADING), initialization will fail.
6250*/
6251typedef struct
6252{
6253 ma_async_notification_callbacks cb;
6254#ifndef MA_NO_THREADING
6255 ma_event e;
6256#endif
6257} ma_async_notification_event;
6258
6259MA_API ma_result ma_async_notification_event_init(ma_async_notification_event* pNotificationEvent);
6260MA_API ma_result ma_async_notification_event_uninit(ma_async_notification_event* pNotificationEvent);
6261MA_API ma_result ma_async_notification_event_wait(ma_async_notification_event* pNotificationEvent);
6262MA_API ma_result ma_async_notification_event_signal(ma_async_notification_event* pNotificationEvent);
6263
6264
6265
6266
6267/************************************************************************************************************************************************************
6268
6269Job Queue
6270
6271************************************************************************************************************************************************************/
6272
6273/*
6274Slot Allocator
6275--------------
6276The idea of the slot allocator is for it to be used in conjunction with a fixed sized buffer. You use the slot allocator to allocator an index that can be used
6277as the insertion point for an object.
6278
6279Slots are reference counted to help mitigate the ABA problem in the lock-free queue we use for tracking jobs.
6280
6281The slot index is stored in the low 32 bits. The reference counter is stored in the high 32 bits:
6282
6283 +-----------------+-----------------+
6284 | 32 Bits | 32 Bits |
6285 +-----------------+-----------------+
6286 | Reference Count | Slot Index |
6287 +-----------------+-----------------+
6288*/
6289typedef struct
6290{
6291 ma_uint32 capacity; /* The number of slots to make available. */
6292} ma_slot_allocator_config;
6293
6294MA_API ma_slot_allocator_config ma_slot_allocator_config_init(ma_uint32 capacity);
6295
6296
6297typedef struct
6298{
6299 MA_ATOMIC(4, ma_uint32) bitfield; /* Must be used atomically because the allocation and freeing routines need to make copies of this which must never be optimized away by the compiler. */
6300} ma_slot_allocator_group;
6301
6302typedef struct
6303{
6304 ma_slot_allocator_group* pGroups; /* Slots are grouped in chunks of 32. */
6305 ma_uint32* pSlots; /* 32 bits for reference counting for ABA mitigation. */
6306 ma_uint32 count; /* Allocation count. */
6307 ma_uint32 capacity;
6308
6309 /* Memory management. */
6310 ma_bool32 _ownsHeap;
6311 void* _pHeap;
6312} ma_slot_allocator;
6313
6314MA_API ma_result ma_slot_allocator_get_heap_size(const ma_slot_allocator_config* pConfig, size_t* pHeapSizeInBytes);
6315MA_API ma_result ma_slot_allocator_init_preallocated(const ma_slot_allocator_config* pConfig, void* pHeap, ma_slot_allocator* pAllocator);
6316MA_API ma_result ma_slot_allocator_init(const ma_slot_allocator_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_slot_allocator* pAllocator);
6317MA_API void ma_slot_allocator_uninit(ma_slot_allocator* pAllocator, const ma_allocation_callbacks* pAllocationCallbacks);
6318MA_API ma_result ma_slot_allocator_alloc(ma_slot_allocator* pAllocator, ma_uint64* pSlot);
6319MA_API ma_result ma_slot_allocator_free(ma_slot_allocator* pAllocator, ma_uint64 slot);
6320
6321
6322typedef struct ma_job ma_job;
6323
6324/*
6325Callback for processing a job. Each job type will have their own processing callback which will be
6326called by ma_job_process().
6327*/
6328typedef ma_result (* ma_job_proc)(ma_job* pJob);
6329
6330/* When a job type is added here an callback needs to be added go "g_jobVTable" in the implementation section. */
6331typedef enum
6332{
6333 /* Miscellaneous. */
6334 MA_JOB_TYPE_QUIT = 0,
6335 MA_JOB_TYPE_CUSTOM,
6336
6337 /* Resource Manager. */
6338 MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE,
6339 MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE,
6340 MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE,
6341 MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER,
6342 MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER,
6343 MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM,
6344 MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM,
6345 MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM,
6346 MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM,
6347
6348 /* Device. */
6349 MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE,
6350
6351 /* Count. Must always be last. */
6352 MA_JOB_TYPE_COUNT
6353} ma_job_type;
6354
6355struct ma_job
6356{
6357 union
6358 {
6359 struct
6360 {
6361 ma_uint16 code; /* Job type. */
6362 ma_uint16 slot; /* Index into a ma_slot_allocator. */
6363 ma_uint32 refcount;
6364 } breakup;
6365 ma_uint64 allocation;
6366 } toc; /* 8 bytes. We encode the job code into the slot allocation data to save space. */
6367 MA_ATOMIC(8, ma_uint64) next; /* refcount + slot for the next item. Does not include the job code. */
6368 ma_uint32 order; /* Execution order. Used to create a data dependency and ensure a job is executed in order. Usage is contextual depending on the job type. */
6369
6370 union
6371 {
6372 /* Miscellaneous. */
6373 struct
6374 {
6375 ma_job_proc proc;
6376 ma_uintptr data0;
6377 ma_uintptr data1;
6378 } custom;
6379
6380 /* Resource Manager */
6381 union
6382 {
6383 struct
6384 {
6385 /*ma_resource_manager**/ void* pResourceManager;
6386 /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode;
6387 char* pFilePath;
6388 wchar_t* pFilePathW;
6389 ma_uint32 flags; /* Resource manager data source flags that were used when initializing the data buffer. */
6390 ma_async_notification* pInitNotification; /* Signalled when the data buffer has been initialized and the format/channels/rate can be retrieved. */
6391 ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. Will be passed through to MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE when decoding. */
6392 ma_fence* pInitFence; /* Released when initialization of the decoder is complete. */
6393 ma_fence* pDoneFence; /* Released if initialization of the decoder fails. Passed through to PAGE_DATA_BUFFER_NODE untouched if init is successful. */
6394 } loadDataBufferNode;
6395 struct
6396 {
6397 /*ma_resource_manager**/ void* pResourceManager;
6398 /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode;
6399 ma_async_notification* pDoneNotification;
6400 ma_fence* pDoneFence;
6401 } freeDataBufferNode;
6402 struct
6403 {
6404 /*ma_resource_manager**/ void* pResourceManager;
6405 /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode;
6406 /*ma_decoder**/ void* pDecoder;
6407 ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. */
6408 ma_fence* pDoneFence; /* Passed through from LOAD_DATA_BUFFER_NODE and released when the data buffer completes decoding or an error occurs. */
6409 } pageDataBufferNode;
6410
6411 struct
6412 {
6413 /*ma_resource_manager_data_buffer**/ void* pDataBuffer;
6414 ma_async_notification* pInitNotification; /* Signalled when the data buffer has been initialized and the format/channels/rate can be retrieved. */
6415 ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. */
6416 ma_fence* pInitFence; /* Released when the data buffer has been initialized and the format/channels/rate can be retrieved. */
6417 ma_fence* pDoneFence; /* Released when the data buffer has been fully decoded. */
6418 ma_uint64 rangeBegInPCMFrames;
6419 ma_uint64 rangeEndInPCMFrames;
6420 ma_uint64 loopPointBegInPCMFrames;
6421 ma_uint64 loopPointEndInPCMFrames;
6422 ma_uint32 isLooping;
6423 } loadDataBuffer;
6424 struct
6425 {
6426 /*ma_resource_manager_data_buffer**/ void* pDataBuffer;
6427 ma_async_notification* pDoneNotification;
6428 ma_fence* pDoneFence;
6429 } freeDataBuffer;
6430
6431 struct
6432 {
6433 /*ma_resource_manager_data_stream**/ void* pDataStream;
6434 char* pFilePath; /* Allocated when the job is posted, freed by the job thread after loading. */
6435 wchar_t* pFilePathW; /* ^ As above ^. Only used if pFilePath is NULL. */
6436 ma_uint64 initialSeekPoint;
6437 ma_async_notification* pInitNotification; /* Signalled after the first two pages have been decoded and frames can be read from the stream. */
6438 ma_fence* pInitFence;
6439 } loadDataStream;
6440 struct
6441 {
6442 /*ma_resource_manager_data_stream**/ void* pDataStream;
6443 ma_async_notification* pDoneNotification;
6444 ma_fence* pDoneFence;
6445 } freeDataStream;
6446 struct
6447 {
6448 /*ma_resource_manager_data_stream**/ void* pDataStream;
6449 ma_uint32 pageIndex; /* The index of the page to decode into. */
6450 } pageDataStream;
6451 struct
6452 {
6453 /*ma_resource_manager_data_stream**/ void* pDataStream;
6454 ma_uint64 frameIndex;
6455 } seekDataStream;
6456 } resourceManager;
6457
6458 /* Device. */
6459 union
6460 {
6461 union
6462 {
6463 struct
6464 {
6465 /*ma_device**/ void* pDevice;
6466 /*ma_device_type*/ ma_uint32 deviceType;
6467 } reroute;
6468 } aaudio;
6469 } device;
6470 } data;
6471};
6472
6473MA_API ma_job ma_job_init(ma_uint16 code);
6474MA_API ma_result ma_job_process(ma_job* pJob);
6475
6476
6477/*
6478When set, ma_job_queue_next() will not wait and no semaphore will be signaled in
6479ma_job_queue_post(). ma_job_queue_next() will return MA_NO_DATA_AVAILABLE if nothing is available.
6480
6481This flag should always be used for platforms that do not support multithreading.
6482*/
6483typedef enum
6484{
6485 MA_JOB_QUEUE_FLAG_NON_BLOCKING = 0x00000001
6486} ma_job_queue_flags;
6487
6488typedef struct
6489{
6490 ma_uint32 flags;
6491 ma_uint32 capacity; /* The maximum number of jobs that can fit in the queue at a time. */
6492} ma_job_queue_config;
6493
6494MA_API ma_job_queue_config ma_job_queue_config_init(ma_uint32 flags, ma_uint32 capacity);
6495
6496
6497typedef struct
6498{
6499 ma_uint32 flags; /* Flags passed in at initialization time. */
6500 ma_uint32 capacity; /* The maximum number of jobs that can fit in the queue at a time. Set by the config. */
6501 MA_ATOMIC(8, ma_uint64) head; /* The first item in the list. Required for removing from the top of the list. */
6502 MA_ATOMIC(8, ma_uint64) tail; /* The last item in the list. Required for appending to the end of the list. */
6503#ifndef MA_NO_THREADING
6504 ma_semaphore sem; /* Only used when MA_JOB_QUEUE_FLAG_NON_BLOCKING is unset. */
6505#endif
6506 ma_slot_allocator allocator;
6507 ma_job* pJobs;
6508#ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
6509 ma_spinlock lock;
6510#endif
6511
6512 /* Memory management. */
6513 void* _pHeap;
6514 ma_bool32 _ownsHeap;
6515} ma_job_queue;
6516
6517MA_API ma_result ma_job_queue_get_heap_size(const ma_job_queue_config* pConfig, size_t* pHeapSizeInBytes);
6518MA_API ma_result ma_job_queue_init_preallocated(const ma_job_queue_config* pConfig, void* pHeap, ma_job_queue* pQueue);
6519MA_API ma_result ma_job_queue_init(const ma_job_queue_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_job_queue* pQueue);
6520MA_API void ma_job_queue_uninit(ma_job_queue* pQueue, const ma_allocation_callbacks* pAllocationCallbacks);
6521MA_API ma_result ma_job_queue_post(ma_job_queue* pQueue, const ma_job* pJob);
6522MA_API ma_result ma_job_queue_next(ma_job_queue* pQueue, ma_job* pJob); /* Returns MA_CANCELLED if the next job is a quit job. */
6523
6524
6525
6526/************************************************************************************************************************************************************
6527*************************************************************************************************************************************************************
6528
6529DEVICE I/O
6530==========
6531
6532This section contains the APIs for device playback and capture. Here is where you'll find ma_device_init(), etc.
6533
6534*************************************************************************************************************************************************************
6535************************************************************************************************************************************************************/
6536#ifndef MA_NO_DEVICE_IO
6537/* Some backends are only supported on certain platforms. */
6538#if defined(MA_WIN32)
6539 #define MA_SUPPORT_WASAPI
6540
6541 #if defined(MA_WIN32_DESKTOP) /* DirectSound and WinMM backends are only supported on desktops. */
6542 #define MA_SUPPORT_DSOUND
6543 #define MA_SUPPORT_WINMM
6544
6545 /* Don't enable JACK here if compiling with Cosmopolitan. It'll be enabled in the Linux section below. */
6546 #if !defined(__COSMOPOLITAN__)
6547 #define MA_SUPPORT_JACK /* JACK is technically supported on Windows, but I don't know how many people use it in practice... */
6548 #endif
6549 #endif
6550#endif
6551#if defined(MA_UNIX) && !defined(MA_ORBIS) && !defined(MA_PROSPERO)
6552 #if defined(MA_LINUX)
6553 #if !defined(MA_ANDROID) && !defined(__COSMOPOLITAN__) /* ALSA is not supported on Android. */
6554 #define MA_SUPPORT_ALSA
6555 #endif
6556 #endif
6557 #if !defined(MA_BSD) && !defined(MA_ANDROID) && !defined(MA_EMSCRIPTEN)
6558 #define MA_SUPPORT_PULSEAUDIO
6559 #define MA_SUPPORT_JACK
6560 #endif
6561 #if defined(__OpenBSD__) /* <-- Change this to "#if defined(MA_BSD)" to enable sndio on all BSD flavors. */
6562 #define MA_SUPPORT_SNDIO /* sndio is only supported on OpenBSD for now. May be expanded later if there's demand. */
6563 #endif
6564 #if defined(__NetBSD__) || defined(__OpenBSD__)
6565 #define MA_SUPPORT_AUDIO4 /* Only support audio(4) on platforms with known support. */
6566 #endif
6567 #if defined(__FreeBSD__) || defined(__DragonFly__)
6568 #define MA_SUPPORT_OSS /* Only support OSS on specific platforms with known support. */
6569 #endif
6570#endif
6571#if defined(MA_ANDROID)
6572 #define MA_SUPPORT_AAUDIO
6573 #define MA_SUPPORT_OPENSL
6574#endif
6575#if defined(MA_APPLE)
6576 #define MA_SUPPORT_COREAUDIO
6577#endif
6578#if defined(MA_EMSCRIPTEN)
6579 #define MA_SUPPORT_WEBAUDIO
6580#endif
6581
6582/* All platforms should support custom backends. */
6583#define MA_SUPPORT_CUSTOM
6584
6585/* Explicitly disable the Null backend for Emscripten because it uses a background thread which is not properly supported right now. */
6586#if !defined(MA_EMSCRIPTEN)
6587#define MA_SUPPORT_NULL
6588#endif
6589
6590
6591#if defined(MA_SUPPORT_WASAPI) && !defined(MA_NO_WASAPI) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WASAPI))
6592 #define MA_HAS_WASAPI
6593#endif
6594#if defined(MA_SUPPORT_DSOUND) && !defined(MA_NO_DSOUND) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_DSOUND))
6595 #define MA_HAS_DSOUND
6596#endif
6597#if defined(MA_SUPPORT_WINMM) && !defined(MA_NO_WINMM) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WINMM))
6598 #define MA_HAS_WINMM
6599#endif
6600#if defined(MA_SUPPORT_ALSA) && !defined(MA_NO_ALSA) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_ALSA))
6601 #define MA_HAS_ALSA
6602#endif
6603#if defined(MA_SUPPORT_PULSEAUDIO) && !defined(MA_NO_PULSEAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_PULSEAUDIO))
6604 #define MA_HAS_PULSEAUDIO
6605#endif
6606#if defined(MA_SUPPORT_JACK) && !defined(MA_NO_JACK) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_JACK))
6607 #define MA_HAS_JACK
6608#endif
6609#if defined(MA_SUPPORT_COREAUDIO) && !defined(MA_NO_COREAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_COREAUDIO))
6610 #define MA_HAS_COREAUDIO
6611#endif
6612#if defined(MA_SUPPORT_SNDIO) && !defined(MA_NO_SNDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_SNDIO))
6613 #define MA_HAS_SNDIO
6614#endif
6615#if defined(MA_SUPPORT_AUDIO4) && !defined(MA_NO_AUDIO4) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_AUDIO4))
6616 #define MA_HAS_AUDIO4
6617#endif
6618#if defined(MA_SUPPORT_OSS) && !defined(MA_NO_OSS) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_OSS))
6619 #define MA_HAS_OSS
6620#endif
6621#if defined(MA_SUPPORT_AAUDIO) && !defined(MA_NO_AAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_AAUDIO))
6622 #define MA_HAS_AAUDIO
6623#endif
6624#if defined(MA_SUPPORT_OPENSL) && !defined(MA_NO_OPENSL) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_OPENSL))
6625 #define MA_HAS_OPENSL
6626#endif
6627#if defined(MA_SUPPORT_WEBAUDIO) && !defined(MA_NO_WEBAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WEBAUDIO))
6628 #define MA_HAS_WEBAUDIO
6629#endif
6630#if defined(MA_SUPPORT_CUSTOM) && !defined(MA_NO_CUSTOM) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_CUSTOM))
6631 #define MA_HAS_CUSTOM
6632#endif
6633#if defined(MA_SUPPORT_NULL) && !defined(MA_NO_NULL) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_NULL))
6634 #define MA_HAS_NULL
6635#endif
6636
6637typedef enum
6638{
6639 ma_device_state_uninitialized = 0,
6640 ma_device_state_stopped = 1, /* The device's default state after initialization. */
6641 ma_device_state_started = 2, /* The device is started and is requesting and/or delivering audio data. */
6642 ma_device_state_starting = 3, /* Transitioning from a stopped state to started. */
6643 ma_device_state_stopping = 4 /* Transitioning from a started state to stopped. */
6644} ma_device_state;
6645
6646MA_ATOMIC_SAFE_TYPE_DECL(i32, 4, device_state)
6647
6648
6649#ifdef MA_SUPPORT_WASAPI
6650/* We need a IMMNotificationClient object for WASAPI. */
6651typedef struct
6652{
6653 void* lpVtbl;
6654 ma_uint32 counter;
6655 ma_device* pDevice;
6656} ma_IMMNotificationClient;
6657#endif
6658
6659/* Backend enums must be in priority order. */
6660typedef enum
6661{
6662 ma_backend_wasapi,
6663 ma_backend_dsound,
6664 ma_backend_winmm,
6665 ma_backend_coreaudio,
6666 ma_backend_sndio,
6667 ma_backend_audio4,
6668 ma_backend_oss,
6669 ma_backend_pulseaudio,
6670 ma_backend_alsa,
6671 ma_backend_jack,
6672 ma_backend_aaudio,
6673 ma_backend_opensl,
6674 ma_backend_webaudio,
6675 ma_backend_custom, /* <-- Custom backend, with callbacks defined by the context config. */
6676 ma_backend_null /* <-- Must always be the last item. Lowest priority, and used as the terminator for backend enumeration. */
6677} ma_backend;
6678
6679#define MA_BACKEND_COUNT (ma_backend_null+1)
6680
6681
6682/*
6683Device job thread. This is used by backends that require asynchronous processing of certain
6684operations. It is not used by all backends.
6685
6686The device job thread is made up of a thread and a job queue. You can post a job to the thread with
6687ma_device_job_thread_post(). The thread will do the processing of the job.
6688*/
6689typedef struct
6690{
6691 ma_bool32 noThread; /* Set this to true if you want to process jobs yourself. */
6692 ma_uint32 jobQueueCapacity;
6693 ma_uint32 jobQueueFlags;
6694} ma_device_job_thread_config;
6695
6696MA_API ma_device_job_thread_config ma_device_job_thread_config_init(void);
6697
6698typedef struct
6699{
6700 ma_thread thread;
6701 ma_job_queue jobQueue;
6702 ma_bool32 _hasThread;
6703} ma_device_job_thread;
6704
6705MA_API ma_result ma_device_job_thread_init(const ma_device_job_thread_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_device_job_thread* pJobThread);
6706MA_API void ma_device_job_thread_uninit(ma_device_job_thread* pJobThread, const ma_allocation_callbacks* pAllocationCallbacks);
6707MA_API ma_result ma_device_job_thread_post(ma_device_job_thread* pJobThread, const ma_job* pJob);
6708MA_API ma_result ma_device_job_thread_next(ma_device_job_thread* pJobThread, ma_job* pJob);
6709
6710
6711
6712/* Device notification types. */
6713typedef enum
6714{
6715 ma_device_notification_type_started,
6716 ma_device_notification_type_stopped,
6717 ma_device_notification_type_rerouted,
6718 ma_device_notification_type_interruption_began,
6719 ma_device_notification_type_interruption_ended,
6720 ma_device_notification_type_unlocked
6721} ma_device_notification_type;
6722
6723typedef struct
6724{
6725 ma_device* pDevice;
6726 ma_device_notification_type type;
6727 union
6728 {
6729 struct
6730 {
6731 int _unused;
6732 } started;
6733 struct
6734 {
6735 int _unused;
6736 } stopped;
6737 struct
6738 {
6739 int _unused;
6740 } rerouted;
6741 struct
6742 {
6743 int _unused;
6744 } interruption;
6745 } data;
6746} ma_device_notification;
6747
6748/*
6749The notification callback for when the application should be notified of a change to the device.
6750
6751This callback is used for notifying the application of changes such as when the device has started,
6752stopped, rerouted or an interruption has occurred. Note that not all backends will post all
6753notification types. For example, some backends will perform automatic stream routing without any
6754kind of notification to the host program which means miniaudio will never know about it and will
6755never be able to fire the rerouted notification. You should keep this in mind when designing your
6756program.
6757
6758The stopped notification will *not* get fired when a device is rerouted.
6759
6760
6761Parameters
6762----------
6763pNotification (in)
6764 A pointer to a structure containing information about the event. Use the `pDevice` member of
6765 this object to retrieve the relevant device. The `type` member can be used to discriminate
6766 against each of the notification types.
6767
6768
6769Remarks
6770-------
6771Do not restart or uninitialize the device from the callback.
6772
6773Not all notifications will be triggered by all backends, however the started and stopped events
6774should be reliable for all backends. Some backends do not have a good way to detect device
6775stoppages due to unplugging the device which may result in the stopped callback not getting
6776fired. This has been observed with at least one BSD variant.
6777
6778The rerouted notification is fired *after* the reroute has occurred. The stopped notification will
6779*not* get fired when a device is rerouted. The following backends are known to do automatic stream
6780rerouting, but do not have a way to be notified of the change:
6781
6782 * DirectSound
6783
6784The interruption notifications are used on mobile platforms for detecting when audio is interrupted
6785due to things like an incoming phone call. Currently this is only implemented on iOS. None of the
6786Android backends will report this notification.
6787*/
6788typedef void (* ma_device_notification_proc)(const ma_device_notification* pNotification);
6789
6790
6791/*
6792The callback for processing audio data from the device.
6793
6794The data callback is fired by miniaudio whenever the device needs to have more data delivered to a playback device, or when a capture device has some data
6795available. This is called as soon as the backend asks for more data which means it may be called with inconsistent frame counts. You cannot assume the
6796callback will be fired with a consistent frame count.
6797
6798
6799Parameters
6800----------
6801pDevice (in)
6802 A pointer to the relevant device.
6803
6804pOutput (out)
6805 A pointer to the output buffer that will receive audio data that will later be played back through the speakers. This will be non-null for a playback or
6806 full-duplex device and null for a capture and loopback device.
6807
6808pInput (in)
6809 A pointer to the buffer containing input data from a recording device. This will be non-null for a capture, full-duplex or loopback device and null for a
6810 playback device.
6811
6812frameCount (in)
6813 The number of PCM frames to process. Note that this will not necessarily be equal to what you requested when you initialized the device. The
6814 `periodSizeInFrames` and `periodSizeInMilliseconds` members of the device config are just hints, and are not necessarily exactly what you'll get. You must
6815 not assume this will always be the same value each time the callback is fired.
6816
6817
6818Remarks
6819-------
6820You cannot stop and start the device from inside the callback or else you'll get a deadlock. You must also not uninitialize the device from inside the
6821callback. The following APIs cannot be called from inside the callback:
6822
6823 ma_device_init()
6824 ma_device_init_ex()
6825 ma_device_uninit()
6826 ma_device_start()
6827 ma_device_stop()
6828
6829The proper way to stop the device is to call `ma_device_stop()` from a different thread, normally the main application thread.
6830*/
6831typedef void (* ma_device_data_proc)(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount);
6832
6833
6834
6835
6836/*
6837DEPRECATED. Use ma_device_notification_proc instead.
6838
6839The callback for when the device has been stopped.
6840
6841This will be called when the device is stopped explicitly with `ma_device_stop()` and also called implicitly when the device is stopped through external forces
6842such as being unplugged or an internal error occurring.
6843
6844
6845Parameters
6846----------
6847pDevice (in)
6848 A pointer to the device that has just stopped.
6849
6850
6851Remarks
6852-------
6853Do not restart or uninitialize the device from the callback.
6854*/
6855typedef void (* ma_stop_proc)(ma_device* pDevice); /* DEPRECATED. Use ma_device_notification_proc instead. */
6856
6857typedef enum
6858{
6859 ma_device_type_playback = 1,
6860 ma_device_type_capture = 2,
6861 ma_device_type_duplex = ma_device_type_playback | ma_device_type_capture, /* 3 */
6862 ma_device_type_loopback = 4
6863} ma_device_type;
6864
6865typedef enum
6866{
6867 ma_share_mode_shared = 0,
6868 ma_share_mode_exclusive
6869} ma_share_mode;
6870
6871/* iOS/tvOS/watchOS session categories. */
6872typedef enum
6873{
6874 ma_ios_session_category_default = 0, /* AVAudioSessionCategoryPlayAndRecord. */
6875 ma_ios_session_category_none, /* Leave the session category unchanged. */
6876 ma_ios_session_category_ambient, /* AVAudioSessionCategoryAmbient */
6877 ma_ios_session_category_solo_ambient, /* AVAudioSessionCategorySoloAmbient */
6878 ma_ios_session_category_playback, /* AVAudioSessionCategoryPlayback */
6879 ma_ios_session_category_record, /* AVAudioSessionCategoryRecord */
6880 ma_ios_session_category_play_and_record, /* AVAudioSessionCategoryPlayAndRecord */
6881 ma_ios_session_category_multi_route /* AVAudioSessionCategoryMultiRoute */
6882} ma_ios_session_category;
6883
6884/* iOS/tvOS/watchOS session category options */
6885typedef enum
6886{
6887 ma_ios_session_category_option_mix_with_others = 0x01, /* AVAudioSessionCategoryOptionMixWithOthers */
6888 ma_ios_session_category_option_duck_others = 0x02, /* AVAudioSessionCategoryOptionDuckOthers */
6889 ma_ios_session_category_option_allow_bluetooth = 0x04, /* AVAudioSessionCategoryOptionAllowBluetooth */
6890 ma_ios_session_category_option_default_to_speaker = 0x08, /* AVAudioSessionCategoryOptionDefaultToSpeaker */
6891 ma_ios_session_category_option_interrupt_spoken_audio_and_mix_with_others = 0x11, /* AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers */
6892 ma_ios_session_category_option_allow_bluetooth_a2dp = 0x20, /* AVAudioSessionCategoryOptionAllowBluetoothA2DP */
6893 ma_ios_session_category_option_allow_air_play = 0x40, /* AVAudioSessionCategoryOptionAllowAirPlay */
6894} ma_ios_session_category_option;
6895
6896/* OpenSL stream types. */
6897typedef enum
6898{
6899 ma_opensl_stream_type_default = 0, /* Leaves the stream type unset. */
6900 ma_opensl_stream_type_voice, /* SL_ANDROID_STREAM_VOICE */
6901 ma_opensl_stream_type_system, /* SL_ANDROID_STREAM_SYSTEM */
6902 ma_opensl_stream_type_ring, /* SL_ANDROID_STREAM_RING */
6903 ma_opensl_stream_type_media, /* SL_ANDROID_STREAM_MEDIA */
6904 ma_opensl_stream_type_alarm, /* SL_ANDROID_STREAM_ALARM */
6905 ma_opensl_stream_type_notification /* SL_ANDROID_STREAM_NOTIFICATION */
6906} ma_opensl_stream_type;
6907
6908/* OpenSL recording presets. */
6909typedef enum
6910{
6911 ma_opensl_recording_preset_default = 0, /* Leaves the input preset unset. */
6912 ma_opensl_recording_preset_generic, /* SL_ANDROID_RECORDING_PRESET_GENERIC */
6913 ma_opensl_recording_preset_camcorder, /* SL_ANDROID_RECORDING_PRESET_CAMCORDER */
6914 ma_opensl_recording_preset_voice_recognition, /* SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION */
6915 ma_opensl_recording_preset_voice_communication, /* SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION */
6916 ma_opensl_recording_preset_voice_unprocessed /* SL_ANDROID_RECORDING_PRESET_UNPROCESSED */
6917} ma_opensl_recording_preset;
6918
6919/* WASAPI audio thread priority characteristics. */
6920typedef enum
6921{
6922 ma_wasapi_usage_default = 0,
6923 ma_wasapi_usage_games,
6924 ma_wasapi_usage_pro_audio,
6925} ma_wasapi_usage;
6926
6927/* AAudio usage types. */
6928typedef enum
6929{
6930 ma_aaudio_usage_default = 0, /* Leaves the usage type unset. */
6931 ma_aaudio_usage_media, /* AAUDIO_USAGE_MEDIA */
6932 ma_aaudio_usage_voice_communication, /* AAUDIO_USAGE_VOICE_COMMUNICATION */
6933 ma_aaudio_usage_voice_communication_signalling, /* AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING */
6934 ma_aaudio_usage_alarm, /* AAUDIO_USAGE_ALARM */
6935 ma_aaudio_usage_notification, /* AAUDIO_USAGE_NOTIFICATION */
6936 ma_aaudio_usage_notification_ringtone, /* AAUDIO_USAGE_NOTIFICATION_RINGTONE */
6937 ma_aaudio_usage_notification_event, /* AAUDIO_USAGE_NOTIFICATION_EVENT */
6938 ma_aaudio_usage_assistance_accessibility, /* AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY */
6939 ma_aaudio_usage_assistance_navigation_guidance, /* AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE */
6940 ma_aaudio_usage_assistance_sonification, /* AAUDIO_USAGE_ASSISTANCE_SONIFICATION */
6941 ma_aaudio_usage_game, /* AAUDIO_USAGE_GAME */
6942 ma_aaudio_usage_assitant, /* AAUDIO_USAGE_ASSISTANT */
6943 ma_aaudio_usage_emergency, /* AAUDIO_SYSTEM_USAGE_EMERGENCY */
6944 ma_aaudio_usage_safety, /* AAUDIO_SYSTEM_USAGE_SAFETY */
6945 ma_aaudio_usage_vehicle_status, /* AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS */
6946 ma_aaudio_usage_announcement /* AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT */
6947} ma_aaudio_usage;
6948
6949/* AAudio content types. */
6950typedef enum
6951{
6952 ma_aaudio_content_type_default = 0, /* Leaves the content type unset. */
6953 ma_aaudio_content_type_speech, /* AAUDIO_CONTENT_TYPE_SPEECH */
6954 ma_aaudio_content_type_music, /* AAUDIO_CONTENT_TYPE_MUSIC */
6955 ma_aaudio_content_type_movie, /* AAUDIO_CONTENT_TYPE_MOVIE */
6956 ma_aaudio_content_type_sonification /* AAUDIO_CONTENT_TYPE_SONIFICATION */
6957} ma_aaudio_content_type;
6958
6959/* AAudio input presets. */
6960typedef enum
6961{
6962 ma_aaudio_input_preset_default = 0, /* Leaves the input preset unset. */
6963 ma_aaudio_input_preset_generic, /* AAUDIO_INPUT_PRESET_GENERIC */
6964 ma_aaudio_input_preset_camcorder, /* AAUDIO_INPUT_PRESET_CAMCORDER */
6965 ma_aaudio_input_preset_voice_recognition, /* AAUDIO_INPUT_PRESET_VOICE_RECOGNITION */
6966 ma_aaudio_input_preset_voice_communication, /* AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION */
6967 ma_aaudio_input_preset_unprocessed, /* AAUDIO_INPUT_PRESET_UNPROCESSED */
6968 ma_aaudio_input_preset_voice_performance /* AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE */
6969} ma_aaudio_input_preset;
6970
6971typedef enum
6972{
6973 ma_aaudio_allow_capture_default = 0, /* Leaves the allowed capture policy unset. */
6974 ma_aaudio_allow_capture_by_all, /* AAUDIO_ALLOW_CAPTURE_BY_ALL */
6975 ma_aaudio_allow_capture_by_system, /* AAUDIO_ALLOW_CAPTURE_BY_SYSTEM */
6976 ma_aaudio_allow_capture_by_none /* AAUDIO_ALLOW_CAPTURE_BY_NONE */
6977} ma_aaudio_allowed_capture_policy;
6978
6979typedef union
6980{
6981 ma_int64 counter;
6982 double counterD;
6983} ma_timer;
6984
6985typedef union
6986{
6987 ma_wchar_win32 wasapi[64]; /* WASAPI uses a wchar_t string for identification. */
6988 ma_uint8 dsound[16]; /* DirectSound uses a GUID for identification. */
6989 /*UINT_PTR*/ ma_uint32 winmm; /* When creating a device, WinMM expects a Win32 UINT_PTR for device identification. In practice it's actually just a UINT. */
6990 char alsa[256]; /* ALSA uses a name string for identification. */
6991 char pulse[256]; /* PulseAudio uses a name string for identification. */
6992 int jack; /* JACK always uses default devices. */
6993 char coreaudio[256]; /* Core Audio uses a string for identification. */
6994 char sndio[256]; /* "snd/0", etc. */
6995 char audio4[256]; /* "/dev/audio", etc. */
6996 char oss[64]; /* "dev/dsp0", etc. "dev/dsp" for the default device. */
6997 ma_int32 aaudio; /* AAudio uses a 32-bit integer for identification. */
6998 ma_uint32 opensl; /* OpenSL|ES uses a 32-bit unsigned integer for identification. */
6999 char webaudio[32]; /* Web Audio always uses default devices for now, but if this changes it'll be a GUID. */
7000 union
7001 {
7002 int i;
7003 char s[256];
7004 void* p;
7005 } custom; /* The custom backend could be anything. Give them a few options. */
7006 int nullbackend; /* The null backend uses an integer for device IDs. */
7007} ma_device_id;
7008
7009
7010typedef struct ma_context_config ma_context_config;
7011typedef struct ma_device_config ma_device_config;
7012typedef struct ma_backend_callbacks ma_backend_callbacks;
7013
7014#define MA_DATA_FORMAT_FLAG_EXCLUSIVE_MODE (1U << 1) /* If set, this is supported in exclusive mode. Otherwise not natively supported by exclusive mode. */
7015
7016#ifndef MA_MAX_DEVICE_NAME_LENGTH
7017#define MA_MAX_DEVICE_NAME_LENGTH 255
7018#endif
7019
7020typedef struct
7021{
7022 /* Basic info. This is the only information guaranteed to be filled in during device enumeration. */
7023 ma_device_id id;
7024 char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* +1 for null terminator. */
7025 ma_bool32 isDefault;
7026
7027 ma_uint32 nativeDataFormatCount;
7028 struct
7029 {
7030 ma_format format; /* Sample format. If set to ma_format_unknown, all sample formats are supported. */
7031 ma_uint32 channels; /* If set to 0, all channels are supported. */
7032 ma_uint32 sampleRate; /* If set to 0, all sample rates are supported. */
7033 ma_uint32 flags; /* A combination of MA_DATA_FORMAT_FLAG_* flags. */
7034 } nativeDataFormats[/*ma_format_count * ma_standard_sample_rate_count * MA_MAX_CHANNELS*/ 64]; /* Not sure how big to make this. There can be *many* permutations for virtual devices which can support anything. */
7035} ma_device_info;
7036
7037struct ma_device_config
7038{
7039 ma_device_type deviceType;
7040 ma_uint32 sampleRate;
7041 ma_uint32 periodSizeInFrames;
7042 ma_uint32 periodSizeInMilliseconds;
7043 ma_uint32 periods;
7044 ma_performance_profile performanceProfile;
7045 ma_bool8 noPreSilencedOutputBuffer; /* When set to true, the contents of the output buffer passed into the data callback will be left undefined rather than initialized to silence. */
7046 ma_bool8 noClip; /* When set to true, the contents of the output buffer passed into the data callback will not be clipped after returning. Only applies when the playback sample format is f32. */
7047 ma_bool8 noDisableDenormals; /* Do not disable denormals when firing the data callback. */
7048 ma_bool8 noFixedSizedCallback; /* Disables strict fixed-sized data callbacks. Setting this to true will result in the period size being treated only as a hint to the backend. This is an optimization for those who don't need fixed sized callbacks. */
7049 ma_device_data_proc dataCallback;
7050 ma_device_notification_proc notificationCallback;
7051 ma_stop_proc stopCallback;
7052 void* pUserData;
7053 ma_resampler_config resampling;
7054 struct
7055 {
7056 const ma_device_id* pDeviceID;
7057 ma_format format;
7058 ma_uint32 channels;
7059 ma_channel* pChannelMap;
7060 ma_channel_mix_mode channelMixMode;
7061 ma_bool32 calculateLFEFromSpatialChannels; /* When an output LFE channel is present, but no input LFE, set to true to set the output LFE to the average of all spatial channels (LR, FR, etc.). Ignored when an input LFE is present. */
7062 ma_share_mode shareMode;
7063 } playback;
7064 struct
7065 {
7066 const ma_device_id* pDeviceID;
7067 ma_format format;
7068 ma_uint32 channels;
7069 ma_channel* pChannelMap;
7070 ma_channel_mix_mode channelMixMode;
7071 ma_bool32 calculateLFEFromSpatialChannels; /* When an output LFE channel is present, but no input LFE, set to true to set the output LFE to the average of all spatial channels (LR, FR, etc.). Ignored when an input LFE is present. */
7072 ma_share_mode shareMode;
7073 } capture;
7074
7075 struct
7076 {
7077 ma_wasapi_usage usage; /* When configured, uses Avrt APIs to set the thread characteristics. */
7078 ma_bool8 noAutoConvertSRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */
7079 ma_bool8 noDefaultQualitySRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */
7080 ma_bool8 noAutoStreamRouting; /* Disables automatic stream routing. */
7081 ma_bool8 noHardwareOffloading; /* Disables WASAPI's hardware offloading feature. */
7082 ma_uint32 loopbackProcessID; /* The process ID to include or exclude for loopback mode. Set to 0 to capture audio from all processes. Ignored when an explicit device ID is specified. */
7083 ma_bool8 loopbackProcessExclude; /* When set to true, excludes the process specified by loopbackProcessID. By default, the process will be included. */
7084 } wasapi;
7085 struct
7086 {
7087 ma_bool32 noMMap; /* Disables MMap mode. */
7088 ma_bool32 noAutoFormat; /* Opens the ALSA device with SND_PCM_NO_AUTO_FORMAT. */
7089 ma_bool32 noAutoChannels; /* Opens the ALSA device with SND_PCM_NO_AUTO_CHANNELS. */
7090 ma_bool32 noAutoResample; /* Opens the ALSA device with SND_PCM_NO_AUTO_RESAMPLE. */
7091 } alsa;
7092 struct
7093 {
7094 const char* pStreamNamePlayback;
7095 const char* pStreamNameCapture;
7096 } pulse;
7097 struct
7098 {
7099 ma_bool32 allowNominalSampleRateChange; /* Desktop only. When enabled, allows changing of the sample rate at the operating system level. */
7100 } coreaudio;
7101 struct
7102 {
7103 ma_opensl_stream_type streamType;
7104 ma_opensl_recording_preset recordingPreset;
7105 ma_bool32 enableCompatibilityWorkarounds;
7106 } opensl;
7107 struct
7108 {
7109 ma_aaudio_usage usage;
7110 ma_aaudio_content_type contentType;
7111 ma_aaudio_input_preset inputPreset;
7112 ma_aaudio_allowed_capture_policy allowedCapturePolicy;
7113 ma_bool32 noAutoStartAfterReroute;
7114 ma_bool32 enableCompatibilityWorkarounds;
7115 } aaudio;
7116};
7117
7118
7119/*
7120The callback for handling device enumeration. This is fired from `ma_context_enumerate_devices()`.
7121
7122
7123Parameters
7124----------
7125pContext (in)
7126 A pointer to the context performing the enumeration.
7127
7128deviceType (in)
7129 The type of the device being enumerated. This will always be either `ma_device_type_playback` or `ma_device_type_capture`.
7130
7131pInfo (in)
7132 A pointer to a `ma_device_info` containing the ID and name of the enumerated device. Note that this will not include detailed information about the device,
7133 only basic information (ID and name). The reason for this is that it would otherwise require opening the backend device to probe for the information which
7134 is too inefficient.
7135
7136pUserData (in)
7137 The user data pointer passed into `ma_context_enumerate_devices()`.
7138*/
7139typedef ma_bool32 (* ma_enum_devices_callback_proc)(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData);
7140
7141
7142/*
7143Describes some basic details about a playback or capture device.
7144*/
7145typedef struct
7146{
7147 const ma_device_id* pDeviceID;
7148 ma_share_mode shareMode;
7149 ma_format format;
7150 ma_uint32 channels;
7151 ma_uint32 sampleRate;
7152 ma_channel channelMap[MA_MAX_CHANNELS];
7153 ma_uint32 periodSizeInFrames;
7154 ma_uint32 periodSizeInMilliseconds;
7155 ma_uint32 periodCount;
7156} ma_device_descriptor;
7157
7158/*
7159These are the callbacks required to be implemented for a backend. These callbacks are grouped into two parts: context and device. There is one context
7160to many devices. A device is created from a context.
7161
7162The general flow goes like this:
7163
7164 1) A context is created with `onContextInit()`
7165 1a) Available devices can be enumerated with `onContextEnumerateDevices()` if required.
7166 1b) Detailed information about a device can be queried with `onContextGetDeviceInfo()` if required.
7167 2) A device is created from the context that was created in the first step using `onDeviceInit()`, and optionally a device ID that was
7168 selected from device enumeration via `onContextEnumerateDevices()`.
7169 3) A device is started or stopped with `onDeviceStart()` / `onDeviceStop()`
7170 4) Data is delivered to and from the device by the backend. This is always done based on the native format returned by the prior call
7171 to `onDeviceInit()`. Conversion between the device's native format and the format requested by the application will be handled by
7172 miniaudio internally.
7173
7174Initialization of the context is quite simple. You need to do any necessary initialization of internal objects and then output the
7175callbacks defined in this structure.
7176
7177Once the context has been initialized you can initialize a device. Before doing so, however, the application may want to know which
7178physical devices are available. This is where `onContextEnumerateDevices()` comes in. This is fairly simple. For each device, fire the
7179given callback with, at a minimum, the basic information filled out in `ma_device_info`. When the callback returns `MA_FALSE`, enumeration
7180needs to stop and the `onContextEnumerateDevices()` function returns with a success code.
7181
7182Detailed device information can be retrieved from a device ID using `onContextGetDeviceInfo()`. This takes as input the device type and ID,
7183and on output returns detailed information about the device in `ma_device_info`. The `onContextGetDeviceInfo()` callback must handle the
7184case when the device ID is NULL, in which case information about the default device needs to be retrieved.
7185
7186Once the context has been created and the device ID retrieved (if using anything other than the default device), the device can be created.
7187This is a little bit more complicated than initialization of the context due to it's more complicated configuration. When initializing a
7188device, a duplex device may be requested. This means a separate data format needs to be specified for both playback and capture. On input,
7189the data format is set to what the application wants. On output it's set to the native format which should match as closely as possible to
7190the requested format. The conversion between the format requested by the application and the device's native format will be handled
7191internally by miniaudio.
7192
7193On input, if the sample format is set to `ma_format_unknown`, the backend is free to use whatever sample format it desires, so long as it's
7194supported by miniaudio. When the channel count is set to 0, the backend should use the device's native channel count. The same applies for
7195sample rate. For the channel map, the default should be used when `ma_channel_map_is_blank()` returns true (all channels set to
7196`MA_CHANNEL_NONE`). On input, the `periodSizeInFrames` or `periodSizeInMilliseconds` option should always be set. The backend should
7197inspect both of these variables. If `periodSizeInFrames` is set, it should take priority, otherwise it needs to be derived from the period
7198size in milliseconds (`periodSizeInMilliseconds`) and the sample rate, keeping in mind that the sample rate may be 0, in which case the
7199sample rate will need to be determined before calculating the period size in frames. On output, all members of the `ma_device_descriptor`
7200object should be set to a valid value, except for `periodSizeInMilliseconds` which is optional (`periodSizeInFrames` *must* be set).
7201
7202Starting and stopping of the device is done with `onDeviceStart()` and `onDeviceStop()` and should be self-explanatory. If the backend uses
7203asynchronous reading and writing, `onDeviceStart()` and `onDeviceStop()` should always be implemented.
7204
7205The handling of data delivery between the application and the device is the most complicated part of the process. To make this a bit
7206easier, some helper callbacks are available. If the backend uses a blocking read/write style of API, the `onDeviceRead()` and
7207`onDeviceWrite()` callbacks can optionally be implemented. These are blocking and work just like reading and writing from a file. If the
7208backend uses a callback for data delivery, that callback must call `ma_device_handle_backend_data_callback()` from within it's callback.
7209This allows miniaudio to then process any necessary data conversion and then pass it to the miniaudio data callback.
7210
7211If the backend requires absolute flexibility with it's data delivery, it can optionally implement the `onDeviceDataLoop()` callback
7212which will allow it to implement the logic that will run on the audio thread. This is much more advanced and is completely optional.
7213
7214The audio thread should run data delivery logic in a loop while `ma_device_get_state() == ma_device_state_started` and no errors have been
7215encountered. Do not start or stop the device here. That will be handled from outside the `onDeviceDataLoop()` callback.
7216
7217The invocation of the `onDeviceDataLoop()` callback will be handled by miniaudio. When you start the device, miniaudio will fire this
7218callback. When the device is stopped, the `ma_device_get_state() == ma_device_state_started` condition will fail and the loop will be terminated
7219which will then fall through to the part that stops the device. For an example on how to implement the `onDeviceDataLoop()` callback,
7220look at `ma_device_audio_thread__default_read_write()`. Implement the `onDeviceDataLoopWakeup()` callback if you need a mechanism to
7221wake up the audio thread.
7222
7223If the backend supports an optimized retrieval of device information from an initialized `ma_device` object, it should implement the
7224`onDeviceGetInfo()` callback. This is optional, in which case it will fall back to `onContextGetDeviceInfo()` which is less efficient.
7225*/
7226struct ma_backend_callbacks
7227{
7228 ma_result (* onContextInit)(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks);
7229 ma_result (* onContextUninit)(ma_context* pContext);
7230 ma_result (* onContextEnumerateDevices)(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData);
7231 ma_result (* onContextGetDeviceInfo)(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo);
7232 ma_result (* onDeviceInit)(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture);
7233 ma_result (* onDeviceUninit)(ma_device* pDevice);
7234 ma_result (* onDeviceStart)(ma_device* pDevice);
7235 ma_result (* onDeviceStop)(ma_device* pDevice);
7236 ma_result (* onDeviceRead)(ma_device* pDevice, void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesRead);
7237 ma_result (* onDeviceWrite)(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten);
7238 ma_result (* onDeviceDataLoop)(ma_device* pDevice);
7239 ma_result (* onDeviceDataLoopWakeup)(ma_device* pDevice);
7240 ma_result (* onDeviceGetInfo)(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo);
7241};
7242
7243struct ma_context_config
7244{
7245 ma_log* pLog;
7246 ma_thread_priority threadPriority;
7247 size_t threadStackSize;
7248 void* pUserData;
7249 ma_allocation_callbacks allocationCallbacks;
7250 struct
7251 {
7252 ma_bool32 useVerboseDeviceEnumeration;
7253 } alsa;
7254 struct
7255 {
7256 const char* pApplicationName;
7257 const char* pServerName;
7258 ma_bool32 tryAutoSpawn; /* Enables autospawning of the PulseAudio daemon if necessary. */
7259 } pulse;
7260 struct
7261 {
7262 ma_ios_session_category sessionCategory;
7263 ma_uint32 sessionCategoryOptions;
7264 ma_bool32 noAudioSessionActivate; /* iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:true] on initialization. */
7265 ma_bool32 noAudioSessionDeactivate; /* iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:false] on uninitialization. */
7266 } coreaudio;
7267 struct
7268 {
7269 const char* pClientName;
7270 ma_bool32 tryStartServer;
7271 } jack;
7272 ma_backend_callbacks custom;
7273};
7274
7275/* WASAPI specific structure for some commands which must run on a common thread due to bugs in WASAPI. */
7276typedef struct
7277{
7278 int code;
7279 ma_event* pEvent; /* This will be signalled when the event is complete. */
7280 union
7281 {
7282 struct
7283 {
7284 int _unused;
7285 } quit;
7286 struct
7287 {
7288 ma_device_type deviceType;
7289 void* pAudioClient;
7290 void** ppAudioClientService;
7291 ma_result* pResult; /* The result from creating the audio client service. */
7292 } createAudioClient;
7293 struct
7294 {
7295 ma_device* pDevice;
7296 ma_device_type deviceType;
7297 } releaseAudioClient;
7298 } data;
7299} ma_context_command__wasapi;
7300
7301struct ma_context
7302{
7303 ma_backend_callbacks callbacks;
7304 ma_backend backend; /* DirectSound, ALSA, etc. */
7305 ma_log* pLog;
7306 ma_log log; /* Only used if the log is owned by the context. The pLog member will be set to &log in this case. */
7307 ma_thread_priority threadPriority;
7308 size_t threadStackSize;
7309 void* pUserData;
7310 ma_allocation_callbacks allocationCallbacks;
7311 ma_mutex deviceEnumLock; /* Used to make ma_context_get_devices() thread safe. */
7312 ma_mutex deviceInfoLock; /* Used to make ma_context_get_device_info() thread safe. */
7313 ma_uint32 deviceInfoCapacity; /* Total capacity of pDeviceInfos. */
7314 ma_uint32 playbackDeviceInfoCount;
7315 ma_uint32 captureDeviceInfoCount;
7316 ma_device_info* pDeviceInfos; /* Playback devices first, then capture. */
7317
7318 union
7319 {
7320#ifdef MA_SUPPORT_WASAPI
7321 struct
7322 {
7323 ma_thread commandThread;
7324 ma_mutex commandLock;
7325 ma_semaphore commandSem;
7326 ma_uint32 commandIndex;
7327 ma_uint32 commandCount;
7328 ma_context_command__wasapi commands[4];
7329 ma_handle hAvrt;
7330 ma_proc AvSetMmThreadCharacteristicsA;
7331 ma_proc AvRevertMmThreadcharacteristics;
7332 ma_handle hMMDevapi;
7333 ma_proc ActivateAudioInterfaceAsync;
7334 } wasapi;
7335#endif
7336#ifdef MA_SUPPORT_DSOUND
7337 struct
7338 {
7339 ma_handle hDSoundDLL;
7340 ma_proc DirectSoundCreate;
7341 ma_proc DirectSoundEnumerateA;
7342 ma_proc DirectSoundCaptureCreate;
7343 ma_proc DirectSoundCaptureEnumerateA;
7344 } dsound;
7345#endif
7346#ifdef MA_SUPPORT_WINMM
7347 struct
7348 {
7349 ma_handle hWinMM;
7350 ma_proc waveOutGetNumDevs;
7351 ma_proc waveOutGetDevCapsA;
7352 ma_proc waveOutOpen;
7353 ma_proc waveOutClose;
7354 ma_proc waveOutPrepareHeader;
7355 ma_proc waveOutUnprepareHeader;
7356 ma_proc waveOutWrite;
7357 ma_proc waveOutReset;
7358 ma_proc waveInGetNumDevs;
7359 ma_proc waveInGetDevCapsA;
7360 ma_proc waveInOpen;
7361 ma_proc waveInClose;
7362 ma_proc waveInPrepareHeader;
7363 ma_proc waveInUnprepareHeader;
7364 ma_proc waveInAddBuffer;
7365 ma_proc waveInStart;
7366 ma_proc waveInReset;
7367 } winmm;
7368#endif
7369#ifdef MA_SUPPORT_ALSA
7370 struct
7371 {
7372 ma_handle asoundSO;
7373 ma_proc snd_pcm_open;
7374 ma_proc snd_pcm_close;
7375 ma_proc snd_pcm_hw_params_sizeof;
7376 ma_proc snd_pcm_hw_params_any;
7377 ma_proc snd_pcm_hw_params_set_format;
7378 ma_proc snd_pcm_hw_params_set_format_first;
7379 ma_proc snd_pcm_hw_params_get_format_mask;
7380 ma_proc snd_pcm_hw_params_set_channels;
7381 ma_proc snd_pcm_hw_params_set_channels_near;
7382 ma_proc snd_pcm_hw_params_set_channels_minmax;
7383 ma_proc snd_pcm_hw_params_set_rate_resample;
7384 ma_proc snd_pcm_hw_params_set_rate;
7385 ma_proc snd_pcm_hw_params_set_rate_near;
7386 ma_proc snd_pcm_hw_params_set_buffer_size_near;
7387 ma_proc snd_pcm_hw_params_set_periods_near;
7388 ma_proc snd_pcm_hw_params_set_access;
7389 ma_proc snd_pcm_hw_params_get_format;
7390 ma_proc snd_pcm_hw_params_get_channels;
7391 ma_proc snd_pcm_hw_params_get_channels_min;
7392 ma_proc snd_pcm_hw_params_get_channels_max;
7393 ma_proc snd_pcm_hw_params_get_rate;
7394 ma_proc snd_pcm_hw_params_get_rate_min;
7395 ma_proc snd_pcm_hw_params_get_rate_max;
7396 ma_proc snd_pcm_hw_params_get_buffer_size;
7397 ma_proc snd_pcm_hw_params_get_periods;
7398 ma_proc snd_pcm_hw_params_get_access;
7399 ma_proc snd_pcm_hw_params_test_format;
7400 ma_proc snd_pcm_hw_params_test_channels;
7401 ma_proc snd_pcm_hw_params_test_rate;
7402 ma_proc snd_pcm_hw_params;
7403 ma_proc snd_pcm_sw_params_sizeof;
7404 ma_proc snd_pcm_sw_params_current;
7405 ma_proc snd_pcm_sw_params_get_boundary;
7406 ma_proc snd_pcm_sw_params_set_avail_min;
7407 ma_proc snd_pcm_sw_params_set_start_threshold;
7408 ma_proc snd_pcm_sw_params_set_stop_threshold;
7409 ma_proc snd_pcm_sw_params;
7410 ma_proc snd_pcm_format_mask_sizeof;
7411 ma_proc snd_pcm_format_mask_test;
7412 ma_proc snd_pcm_get_chmap;
7413 ma_proc snd_pcm_state;
7414 ma_proc snd_pcm_prepare;
7415 ma_proc snd_pcm_start;
7416 ma_proc snd_pcm_drop;
7417 ma_proc snd_pcm_drain;
7418 ma_proc snd_pcm_reset;
7419 ma_proc snd_device_name_hint;
7420 ma_proc snd_device_name_get_hint;
7421 ma_proc snd_card_get_index;
7422 ma_proc snd_device_name_free_hint;
7423 ma_proc snd_pcm_mmap_begin;
7424 ma_proc snd_pcm_mmap_commit;
7425 ma_proc snd_pcm_recover;
7426 ma_proc snd_pcm_readi;
7427 ma_proc snd_pcm_writei;
7428 ma_proc snd_pcm_avail;
7429 ma_proc snd_pcm_avail_update;
7430 ma_proc snd_pcm_wait;
7431 ma_proc snd_pcm_nonblock;
7432 ma_proc snd_pcm_info;
7433 ma_proc snd_pcm_info_sizeof;
7434 ma_proc snd_pcm_info_get_name;
7435 ma_proc snd_pcm_poll_descriptors;
7436 ma_proc snd_pcm_poll_descriptors_count;
7437 ma_proc snd_pcm_poll_descriptors_revents;
7438 ma_proc snd_config_update_free_global;
7439
7440 ma_mutex internalDeviceEnumLock;
7441 ma_bool32 useVerboseDeviceEnumeration;
7442 } alsa;
7443#endif
7444#ifdef MA_SUPPORT_PULSEAUDIO
7445 struct
7446 {
7447 ma_handle pulseSO;
7448 ma_proc pa_mainloop_new;
7449 ma_proc pa_mainloop_free;
7450 ma_proc pa_mainloop_quit;
7451 ma_proc pa_mainloop_get_api;
7452 ma_proc pa_mainloop_iterate;
7453 ma_proc pa_mainloop_wakeup;
7454 ma_proc pa_threaded_mainloop_new;
7455 ma_proc pa_threaded_mainloop_free;
7456 ma_proc pa_threaded_mainloop_start;
7457 ma_proc pa_threaded_mainloop_stop;
7458 ma_proc pa_threaded_mainloop_lock;
7459 ma_proc pa_threaded_mainloop_unlock;
7460 ma_proc pa_threaded_mainloop_wait;
7461 ma_proc pa_threaded_mainloop_signal;
7462 ma_proc pa_threaded_mainloop_accept;
7463 ma_proc pa_threaded_mainloop_get_retval;
7464 ma_proc pa_threaded_mainloop_get_api;
7465 ma_proc pa_threaded_mainloop_in_thread;
7466 ma_proc pa_threaded_mainloop_set_name;
7467 ma_proc pa_context_new;
7468 ma_proc pa_context_unref;
7469 ma_proc pa_context_connect;
7470 ma_proc pa_context_disconnect;
7471 ma_proc pa_context_set_state_callback;
7472 ma_proc pa_context_get_state;
7473 ma_proc pa_context_get_sink_info_list;
7474 ma_proc pa_context_get_source_info_list;
7475 ma_proc pa_context_get_sink_info_by_name;
7476 ma_proc pa_context_get_source_info_by_name;
7477 ma_proc pa_operation_unref;
7478 ma_proc pa_operation_get_state;
7479 ma_proc pa_channel_map_init_extend;
7480 ma_proc pa_channel_map_valid;
7481 ma_proc pa_channel_map_compatible;
7482 ma_proc pa_stream_new;
7483 ma_proc pa_stream_unref;
7484 ma_proc pa_stream_connect_playback;
7485 ma_proc pa_stream_connect_record;
7486 ma_proc pa_stream_disconnect;
7487 ma_proc pa_stream_get_state;
7488 ma_proc pa_stream_get_sample_spec;
7489 ma_proc pa_stream_get_channel_map;
7490 ma_proc pa_stream_get_buffer_attr;
7491 ma_proc pa_stream_set_buffer_attr;
7492 ma_proc pa_stream_get_device_name;
7493 ma_proc pa_stream_set_write_callback;
7494 ma_proc pa_stream_set_read_callback;
7495 ma_proc pa_stream_set_suspended_callback;
7496 ma_proc pa_stream_set_moved_callback;
7497 ma_proc pa_stream_is_suspended;
7498 ma_proc pa_stream_flush;
7499 ma_proc pa_stream_drain;
7500 ma_proc pa_stream_is_corked;
7501 ma_proc pa_stream_cork;
7502 ma_proc pa_stream_trigger;
7503 ma_proc pa_stream_begin_write;
7504 ma_proc pa_stream_write;
7505 ma_proc pa_stream_peek;
7506 ma_proc pa_stream_drop;
7507 ma_proc pa_stream_writable_size;
7508 ma_proc pa_stream_readable_size;
7509
7510 /*pa_mainloop**/ ma_ptr pMainLoop;
7511 /*pa_context**/ ma_ptr pPulseContext;
7512 char* pApplicationName; /* Set when the context is initialized. Used by devices for their local pa_context objects. */
7513 char* pServerName; /* Set when the context is initialized. Used by devices for their local pa_context objects. */
7514 } pulse;
7515#endif
7516#ifdef MA_SUPPORT_JACK
7517 struct
7518 {
7519 ma_handle jackSO;
7520 ma_proc jack_client_open;
7521 ma_proc jack_client_close;
7522 ma_proc jack_client_name_size;
7523 ma_proc jack_set_process_callback;
7524 ma_proc jack_set_buffer_size_callback;
7525 ma_proc jack_on_shutdown;
7526 ma_proc jack_get_sample_rate;
7527 ma_proc jack_get_buffer_size;
7528 ma_proc jack_get_ports;
7529 ma_proc jack_activate;
7530 ma_proc jack_deactivate;
7531 ma_proc jack_connect;
7532 ma_proc jack_port_register;
7533 ma_proc jack_port_name;
7534 ma_proc jack_port_get_buffer;
7535 ma_proc jack_free;
7536
7537 char* pClientName;
7538 ma_bool32 tryStartServer;
7539 } jack;
7540#endif
7541#ifdef MA_SUPPORT_COREAUDIO
7542 struct
7543 {
7544 ma_handle hCoreFoundation;
7545 ma_proc CFStringGetCString;
7546 ma_proc CFRelease;
7547
7548 ma_handle hCoreAudio;
7549 ma_proc AudioObjectGetPropertyData;
7550 ma_proc AudioObjectGetPropertyDataSize;
7551 ma_proc AudioObjectSetPropertyData;
7552 ma_proc AudioObjectAddPropertyListener;
7553 ma_proc AudioObjectRemovePropertyListener;
7554
7555 ma_handle hAudioUnit; /* Could possibly be set to AudioToolbox on later versions of macOS. */
7556 ma_proc AudioComponentFindNext;
7557 ma_proc AudioComponentInstanceDispose;
7558 ma_proc AudioComponentInstanceNew;
7559 ma_proc AudioOutputUnitStart;
7560 ma_proc AudioOutputUnitStop;
7561 ma_proc AudioUnitAddPropertyListener;
7562 ma_proc AudioUnitGetPropertyInfo;
7563 ma_proc AudioUnitGetProperty;
7564 ma_proc AudioUnitSetProperty;
7565 ma_proc AudioUnitInitialize;
7566 ma_proc AudioUnitRender;
7567
7568 /*AudioComponent*/ ma_ptr component;
7569 ma_bool32 noAudioSessionDeactivate; /* For tracking whether or not the iOS audio session should be explicitly deactivated. Set from the config in ma_context_init__coreaudio(). */
7570 } coreaudio;
7571#endif
7572#ifdef MA_SUPPORT_SNDIO
7573 struct
7574 {
7575 ma_handle sndioSO;
7576 ma_proc sio_open;
7577 ma_proc sio_close;
7578 ma_proc sio_setpar;
7579 ma_proc sio_getpar;
7580 ma_proc sio_getcap;
7581 ma_proc sio_start;
7582 ma_proc sio_stop;
7583 ma_proc sio_read;
7584 ma_proc sio_write;
7585 ma_proc sio_onmove;
7586 ma_proc sio_nfds;
7587 ma_proc sio_pollfd;
7588 ma_proc sio_revents;
7589 ma_proc sio_eof;
7590 ma_proc sio_setvol;
7591 ma_proc sio_onvol;
7592 ma_proc sio_initpar;
7593 } sndio;
7594#endif
7595#ifdef MA_SUPPORT_AUDIO4
7596 struct
7597 {
7598 int _unused;
7599 } audio4;
7600#endif
7601#ifdef MA_SUPPORT_OSS
7602 struct
7603 {
7604 int versionMajor;
7605 int versionMinor;
7606 } oss;
7607#endif
7608#ifdef MA_SUPPORT_AAUDIO
7609 struct
7610 {
7611 ma_handle hAAudio; /* libaaudio.so */
7612 ma_proc AAudio_createStreamBuilder;
7613 ma_proc AAudioStreamBuilder_delete;
7614 ma_proc AAudioStreamBuilder_setDeviceId;
7615 ma_proc AAudioStreamBuilder_setDirection;
7616 ma_proc AAudioStreamBuilder_setSharingMode;
7617 ma_proc AAudioStreamBuilder_setFormat;
7618 ma_proc AAudioStreamBuilder_setChannelCount;
7619 ma_proc AAudioStreamBuilder_setSampleRate;
7620 ma_proc AAudioStreamBuilder_setBufferCapacityInFrames;
7621 ma_proc AAudioStreamBuilder_setFramesPerDataCallback;
7622 ma_proc AAudioStreamBuilder_setDataCallback;
7623 ma_proc AAudioStreamBuilder_setErrorCallback;
7624 ma_proc AAudioStreamBuilder_setPerformanceMode;
7625 ma_proc AAudioStreamBuilder_setUsage;
7626 ma_proc AAudioStreamBuilder_setContentType;
7627 ma_proc AAudioStreamBuilder_setInputPreset;
7628 ma_proc AAudioStreamBuilder_setAllowedCapturePolicy;
7629 ma_proc AAudioStreamBuilder_openStream;
7630 ma_proc AAudioStream_close;
7631 ma_proc AAudioStream_getState;
7632 ma_proc AAudioStream_waitForStateChange;
7633 ma_proc AAudioStream_getFormat;
7634 ma_proc AAudioStream_getChannelCount;
7635 ma_proc AAudioStream_getSampleRate;
7636 ma_proc AAudioStream_getBufferCapacityInFrames;
7637 ma_proc AAudioStream_getFramesPerDataCallback;
7638 ma_proc AAudioStream_getFramesPerBurst;
7639 ma_proc AAudioStream_requestStart;
7640 ma_proc AAudioStream_requestStop;
7641 ma_device_job_thread jobThread; /* For processing operations outside of the error callback, specifically device disconnections and rerouting. */
7642 } aaudio;
7643#endif
7644#ifdef MA_SUPPORT_OPENSL
7645 struct
7646 {
7647 ma_handle libOpenSLES;
7648 ma_handle SL_IID_ENGINE;
7649 ma_handle SL_IID_AUDIOIODEVICECAPABILITIES;
7650 ma_handle SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
7651 ma_handle SL_IID_RECORD;
7652 ma_handle SL_IID_PLAY;
7653 ma_handle SL_IID_OUTPUTMIX;
7654 ma_handle SL_IID_ANDROIDCONFIGURATION;
7655 ma_proc slCreateEngine;
7656 } opensl;
7657#endif
7658#ifdef MA_SUPPORT_WEBAUDIO
7659 struct
7660 {
7661 int _unused;
7662 } webaudio;
7663#endif
7664#ifdef MA_SUPPORT_NULL
7665 struct
7666 {
7667 int _unused;
7668 } null_backend;
7669#endif
7670 };
7671
7672 union
7673 {
7674#if defined(MA_WIN32)
7675 struct
7676 {
7677 /*HMODULE*/ ma_handle hOle32DLL;
7678 ma_proc CoInitialize;
7679 ma_proc CoInitializeEx;
7680 ma_proc CoUninitialize;
7681 ma_proc CoCreateInstance;
7682 ma_proc CoTaskMemFree;
7683 ma_proc PropVariantClear;
7684 ma_proc StringFromGUID2;
7685
7686 /*HMODULE*/ ma_handle hUser32DLL;
7687 ma_proc GetForegroundWindow;
7688 ma_proc GetDesktopWindow;
7689
7690 /*HMODULE*/ ma_handle hAdvapi32DLL;
7691 ma_proc RegOpenKeyExA;
7692 ma_proc RegCloseKey;
7693 ma_proc RegQueryValueExA;
7694
7695 /*HRESULT*/ long CoInitializeResult;
7696 } win32;
7697#endif
7698#ifdef MA_POSIX
7699 struct
7700 {
7701 int _unused;
7702 } posix;
7703#endif
7704 int _unused;
7705 };
7706};
7707
7708struct ma_device
7709{
7710 ma_context* pContext;
7711 ma_device_type type;
7712 ma_uint32 sampleRate;
7713 ma_atomic_device_state state; /* The state of the device is variable and can change at any time on any thread. Must be used atomically. */
7714 ma_device_data_proc onData; /* Set once at initialization time and should not be changed after. */
7715 ma_device_notification_proc onNotification; /* Set once at initialization time and should not be changed after. */
7716 ma_stop_proc onStop; /* DEPRECATED. Use the notification callback instead. Set once at initialization time and should not be changed after. */
7717 void* pUserData; /* Application defined data. */
7718 ma_mutex startStopLock;
7719 ma_event wakeupEvent;
7720 ma_event startEvent;
7721 ma_event stopEvent;
7722 ma_thread thread;
7723 ma_result workResult; /* This is set by the worker thread after it's finished doing a job. */
7724 ma_bool8 isOwnerOfContext; /* When set to true, uninitializing the device will also uninitialize the context. Set to true when NULL is passed into ma_device_init(). */
7725 ma_bool8 noPreSilencedOutputBuffer;
7726 ma_bool8 noClip;
7727 ma_bool8 noDisableDenormals;
7728 ma_bool8 noFixedSizedCallback;
7729 ma_atomic_float masterVolumeFactor; /* Linear 0..1. Can be read and written simultaneously by different threads. Must be used atomically. */
7730 ma_duplex_rb duplexRB; /* Intermediary buffer for duplex device on asynchronous backends. */
7731 struct
7732 {
7733 ma_resample_algorithm algorithm;
7734 ma_resampling_backend_vtable* pBackendVTable;
7735 void* pBackendUserData;
7736 struct
7737 {
7738 ma_uint32 lpfOrder;
7739 } linear;
7740 } resampling;
7741 struct
7742 {
7743 ma_device_id* pID; /* Set to NULL if using default ID, otherwise set to the address of "id". */
7744 ma_device_id id; /* If using an explicit device, will be set to a copy of the ID used for initialization. Otherwise cleared to 0. */
7745 char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* Maybe temporary. Likely to be replaced with a query API. */
7746 ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */
7747 ma_format format;
7748 ma_uint32 channels;
7749 ma_channel channelMap[MA_MAX_CHANNELS];
7750 ma_format internalFormat;
7751 ma_uint32 internalChannels;
7752 ma_uint32 internalSampleRate;
7753 ma_channel internalChannelMap[MA_MAX_CHANNELS];
7754 ma_uint32 internalPeriodSizeInFrames;
7755 ma_uint32 internalPeriods;
7756 ma_channel_mix_mode channelMixMode;
7757 ma_bool32 calculateLFEFromSpatialChannels;
7758 ma_data_converter converter;
7759 void* pIntermediaryBuffer; /* For implementing fixed sized buffer callbacks. Will be null if using variable sized callbacks. */
7760 ma_uint32 intermediaryBufferCap;
7761 ma_uint32 intermediaryBufferLen; /* How many valid frames are sitting in the intermediary buffer. */
7762 void* pInputCache; /* In external format. Can be null. */
7763 ma_uint64 inputCacheCap;
7764 ma_uint64 inputCacheConsumed;
7765 ma_uint64 inputCacheRemaining;
7766 } playback;
7767 struct
7768 {
7769 ma_device_id* pID; /* Set to NULL if using default ID, otherwise set to the address of "id". */
7770 ma_device_id id; /* If using an explicit device, will be set to a copy of the ID used for initialization. Otherwise cleared to 0. */
7771 char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* Maybe temporary. Likely to be replaced with a query API. */
7772 ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */
7773 ma_format format;
7774 ma_uint32 channels;
7775 ma_channel channelMap[MA_MAX_CHANNELS];
7776 ma_format internalFormat;
7777 ma_uint32 internalChannels;
7778 ma_uint32 internalSampleRate;
7779 ma_channel internalChannelMap[MA_MAX_CHANNELS];
7780 ma_uint32 internalPeriodSizeInFrames;
7781 ma_uint32 internalPeriods;
7782 ma_channel_mix_mode channelMixMode;
7783 ma_bool32 calculateLFEFromSpatialChannels;
7784 ma_data_converter converter;
7785 void* pIntermediaryBuffer; /* For implementing fixed sized buffer callbacks. Will be null if using variable sized callbacks. */
7786 ma_uint32 intermediaryBufferCap;
7787 ma_uint32 intermediaryBufferLen; /* How many valid frames are sitting in the intermediary buffer. */
7788 } capture;
7789
7790 union
7791 {
7792#ifdef MA_SUPPORT_WASAPI
7793 struct
7794 {
7795 /*IAudioClient**/ ma_ptr pAudioClientPlayback;
7796 /*IAudioClient**/ ma_ptr pAudioClientCapture;
7797 /*IAudioRenderClient**/ ma_ptr pRenderClient;
7798 /*IAudioCaptureClient**/ ma_ptr pCaptureClient;
7799 /*IMMDeviceEnumerator**/ ma_ptr pDeviceEnumerator; /* Used for IMMNotificationClient notifications. Required for detecting default device changes. */
7800 ma_IMMNotificationClient notificationClient;
7801 /*HANDLE*/ ma_handle hEventPlayback; /* Auto reset. Initialized to signaled. */
7802 /*HANDLE*/ ma_handle hEventCapture; /* Auto reset. Initialized to unsignaled. */
7803 ma_uint32 actualBufferSizeInFramesPlayback; /* Value from GetBufferSize(). internalPeriodSizeInFrames is not set to the _actual_ buffer size when low-latency shared mode is being used due to the way the IAudioClient3 API works. */
7804 ma_uint32 actualBufferSizeInFramesCapture;
7805 ma_uint32 originalPeriodSizeInFrames;
7806 ma_uint32 originalPeriodSizeInMilliseconds;
7807 ma_uint32 originalPeriods;
7808 ma_performance_profile originalPerformanceProfile;
7809 ma_uint32 periodSizeInFramesPlayback;
7810 ma_uint32 periodSizeInFramesCapture;
7811 void* pMappedBufferCapture;
7812 ma_uint32 mappedBufferCaptureCap;
7813 ma_uint32 mappedBufferCaptureLen;
7814 void* pMappedBufferPlayback;
7815 ma_uint32 mappedBufferPlaybackCap;
7816 ma_uint32 mappedBufferPlaybackLen;
7817 ma_atomic_bool32 isStartedCapture; /* Can be read and written simultaneously across different threads. Must be used atomically, and must be 32-bit. */
7818 ma_atomic_bool32 isStartedPlayback; /* Can be read and written simultaneously across different threads. Must be used atomically, and must be 32-bit. */
7819 ma_uint32 loopbackProcessID;
7820 ma_bool8 loopbackProcessExclude;
7821 ma_bool8 noAutoConvertSRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */
7822 ma_bool8 noDefaultQualitySRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */
7823 ma_bool8 noHardwareOffloading;
7824 ma_bool8 allowCaptureAutoStreamRouting;
7825 ma_bool8 allowPlaybackAutoStreamRouting;
7826 ma_bool8 isDetachedPlayback;
7827 ma_bool8 isDetachedCapture;
7828 ma_wasapi_usage usage;
7829 void* hAvrtHandle;
7830 ma_mutex rerouteLock;
7831 } wasapi;
7832#endif
7833#ifdef MA_SUPPORT_DSOUND
7834 struct
7835 {
7836 /*LPDIRECTSOUND*/ ma_ptr pPlayback;
7837 /*LPDIRECTSOUNDBUFFER*/ ma_ptr pPlaybackPrimaryBuffer;
7838 /*LPDIRECTSOUNDBUFFER*/ ma_ptr pPlaybackBuffer;
7839 /*LPDIRECTSOUNDCAPTURE*/ ma_ptr pCapture;
7840 /*LPDIRECTSOUNDCAPTUREBUFFER*/ ma_ptr pCaptureBuffer;
7841 } dsound;
7842#endif
7843#ifdef MA_SUPPORT_WINMM
7844 struct
7845 {
7846 /*HWAVEOUT*/ ma_handle hDevicePlayback;
7847 /*HWAVEIN*/ ma_handle hDeviceCapture;
7848 /*HANDLE*/ ma_handle hEventPlayback;
7849 /*HANDLE*/ ma_handle hEventCapture;
7850 ma_uint32 fragmentSizeInFrames;
7851 ma_uint32 iNextHeaderPlayback; /* [0,periods). Used as an index into pWAVEHDRPlayback. */
7852 ma_uint32 iNextHeaderCapture; /* [0,periods). Used as an index into pWAVEHDRCapture. */
7853 ma_uint32 headerFramesConsumedPlayback; /* The number of PCM frames consumed in the buffer in pWAVEHEADER[iNextHeader]. */
7854 ma_uint32 headerFramesConsumedCapture; /* ^^^ */
7855 /*WAVEHDR**/ ma_uint8* pWAVEHDRPlayback; /* One instantiation for each period. */
7856 /*WAVEHDR**/ ma_uint8* pWAVEHDRCapture; /* One instantiation for each period. */
7857 ma_uint8* pIntermediaryBufferPlayback;
7858 ma_uint8* pIntermediaryBufferCapture;
7859 ma_uint8* _pHeapData; /* Used internally and is used for the heap allocated data for the intermediary buffer and the WAVEHDR structures. */
7860 } winmm;
7861#endif
7862#ifdef MA_SUPPORT_ALSA
7863 struct
7864 {
7865 /*snd_pcm_t**/ ma_ptr pPCMPlayback;
7866 /*snd_pcm_t**/ ma_ptr pPCMCapture;
7867 /*struct pollfd**/ void* pPollDescriptorsPlayback;
7868 /*struct pollfd**/ void* pPollDescriptorsCapture;
7869 int pollDescriptorCountPlayback;
7870 int pollDescriptorCountCapture;
7871 int wakeupfdPlayback; /* eventfd for waking up from poll() when the playback device is stopped. */
7872 int wakeupfdCapture; /* eventfd for waking up from poll() when the capture device is stopped. */
7873 ma_bool8 isUsingMMapPlayback;
7874 ma_bool8 isUsingMMapCapture;
7875 } alsa;
7876#endif
7877#ifdef MA_SUPPORT_PULSEAUDIO
7878 struct
7879 {
7880 /*pa_mainloop**/ ma_ptr pMainLoop;
7881 /*pa_context**/ ma_ptr pPulseContext;
7882 /*pa_stream**/ ma_ptr pStreamPlayback;
7883 /*pa_stream**/ ma_ptr pStreamCapture;
7884 } pulse;
7885#endif
7886#ifdef MA_SUPPORT_JACK
7887 struct
7888 {
7889 /*jack_client_t**/ ma_ptr pClient;
7890 /*jack_port_t**/ ma_ptr* ppPortsPlayback;
7891 /*jack_port_t**/ ma_ptr* ppPortsCapture;
7892 float* pIntermediaryBufferPlayback; /* Typed as a float because JACK is always floating point. */
7893 float* pIntermediaryBufferCapture;
7894 } jack;
7895#endif
7896#ifdef MA_SUPPORT_COREAUDIO
7897 struct
7898 {
7899 ma_uint32 deviceObjectIDPlayback;
7900 ma_uint32 deviceObjectIDCapture;
7901 /*AudioUnit*/ ma_ptr audioUnitPlayback;
7902 /*AudioUnit*/ ma_ptr audioUnitCapture;
7903 /*AudioBufferList**/ ma_ptr pAudioBufferList; /* Only used for input devices. */
7904 ma_uint32 audioBufferCapInFrames; /* Only used for input devices. The capacity in frames of each buffer in pAudioBufferList. */
7905 ma_event stopEvent;
7906 ma_uint32 originalPeriodSizeInFrames;
7907 ma_uint32 originalPeriodSizeInMilliseconds;
7908 ma_uint32 originalPeriods;
7909 ma_performance_profile originalPerformanceProfile;
7910 ma_bool32 isDefaultPlaybackDevice;
7911 ma_bool32 isDefaultCaptureDevice;
7912 ma_bool32 isSwitchingPlaybackDevice; /* <-- Set to true when the default device has changed and miniaudio is in the process of switching. */
7913 ma_bool32 isSwitchingCaptureDevice; /* <-- Set to true when the default device has changed and miniaudio is in the process of switching. */
7914 void* pNotificationHandler; /* Only used on mobile platforms. Obj-C object for handling route changes. */
7915 } coreaudio;
7916#endif
7917#ifdef MA_SUPPORT_SNDIO
7918 struct
7919 {
7920 ma_ptr handlePlayback;
7921 ma_ptr handleCapture;
7922 ma_bool32 isStartedPlayback;
7923 ma_bool32 isStartedCapture;
7924 } sndio;
7925#endif
7926#ifdef MA_SUPPORT_AUDIO4
7927 struct
7928 {
7929 int fdPlayback;
7930 int fdCapture;
7931 } audio4;
7932#endif
7933#ifdef MA_SUPPORT_OSS
7934 struct
7935 {
7936 int fdPlayback;
7937 int fdCapture;
7938 } oss;
7939#endif
7940#ifdef MA_SUPPORT_AAUDIO
7941 struct
7942 {
7943 /*AAudioStream**/ ma_ptr pStreamPlayback;
7944 /*AAudioStream**/ ma_ptr pStreamCapture;
7945 ma_aaudio_usage usage;
7946 ma_aaudio_content_type contentType;
7947 ma_aaudio_input_preset inputPreset;
7948 ma_aaudio_allowed_capture_policy allowedCapturePolicy;
7949 ma_bool32 noAutoStartAfterReroute;
7950 } aaudio;
7951#endif
7952#ifdef MA_SUPPORT_OPENSL
7953 struct
7954 {
7955 /*SLObjectItf*/ ma_ptr pOutputMixObj;
7956 /*SLOutputMixItf*/ ma_ptr pOutputMix;
7957 /*SLObjectItf*/ ma_ptr pAudioPlayerObj;
7958 /*SLPlayItf*/ ma_ptr pAudioPlayer;
7959 /*SLObjectItf*/ ma_ptr pAudioRecorderObj;
7960 /*SLRecordItf*/ ma_ptr pAudioRecorder;
7961 /*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueuePlayback;
7962 /*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueueCapture;
7963 ma_bool32 isDrainingCapture;
7964 ma_bool32 isDrainingPlayback;
7965 ma_uint32 currentBufferIndexPlayback;
7966 ma_uint32 currentBufferIndexCapture;
7967 ma_uint8* pBufferPlayback; /* This is malloc()'d and is used for storing audio data. Typed as ma_uint8 for easy offsetting. */
7968 ma_uint8* pBufferCapture;
7969 } opensl;
7970#endif
7971#ifdef MA_SUPPORT_WEBAUDIO
7972 struct
7973 {
7974 /* AudioWorklets path. */
7975 /* EMSCRIPTEN_WEBAUDIO_T */ int audioContext;
7976 /* EMSCRIPTEN_WEBAUDIO_T */ int audioWorklet;
7977 float* pIntermediaryBuffer;
7978 void* pStackBuffer;
7979 ma_result initResult; /* Set to MA_BUSY while initialization is in progress. */
7980 int deviceIndex; /* We store the device in a list on the JavaScript side. This is used to map our C object to the JS object. */
7981 } webaudio;
7982#endif
7983#ifdef MA_SUPPORT_NULL
7984 struct
7985 {
7986 ma_thread deviceThread;
7987 ma_event operationEvent;
7988 ma_event operationCompletionEvent;
7989 ma_semaphore operationSemaphore;
7990 ma_uint32 operation;
7991 ma_result operationResult;
7992 ma_timer timer;
7993 double priorRunTime;
7994 ma_uint32 currentPeriodFramesRemainingPlayback;
7995 ma_uint32 currentPeriodFramesRemainingCapture;
7996 ma_uint64 lastProcessedFramePlayback;
7997 ma_uint64 lastProcessedFrameCapture;
7998 ma_atomic_bool32 isStarted; /* Read and written by multiple threads. Must be used atomically, and must be 32-bit for compiler compatibility. */
7999 } null_device;
8000#endif
8001 };
8002};
8003#if defined(_MSC_VER) && !defined(__clang__)
8004 #pragma warning(pop)
8005#elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
8006 #pragma GCC diagnostic pop /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
8007#endif
8008
8009/*
8010Initializes a `ma_context_config` object.
8011
8012
8013Return Value
8014------------
8015A `ma_context_config` initialized to defaults.
8016
8017
8018Remarks
8019-------
8020You must always use this to initialize the default state of the `ma_context_config` object. Not using this will result in your program breaking when miniaudio
8021is updated and new members are added to `ma_context_config`. It also sets logical defaults.
8022
8023You can override members of the returned object by changing it's members directly.
8024
8025
8026See Also
8027--------
8028ma_context_init()
8029*/
8030MA_API ma_context_config ma_context_config_init(void);
8031
8032/*
8033Initializes a context.
8034
8035The context is used for selecting and initializing an appropriate backend and to represent the backend at a more global level than that of an individual
8036device. There is one context to many devices, and a device is created from a context. A context is required to enumerate devices.
8037
8038
8039Parameters
8040----------
8041backends (in, optional)
8042 A list of backends to try initializing, in priority order. Can be NULL, in which case it uses default priority order.
8043
8044backendCount (in, optional)
8045 The number of items in `backend`. Ignored if `backend` is NULL.
8046
8047pConfig (in, optional)
8048 The context configuration.
8049
8050pContext (in)
8051 A pointer to the context object being initialized.
8052
8053
8054Return Value
8055------------
8056MA_SUCCESS if successful; any other error code otherwise.
8057
8058
8059Thread Safety
8060-------------
8061Unsafe. Do not call this function across multiple threads as some backends read and write to global state.
8062
8063
8064Remarks
8065-------
8066When `backends` is NULL, the default priority order will be used. Below is a list of backends in priority order:
8067
8068 |-------------|-----------------------|--------------------------------------------------------|
8069 | Name | Enum Name | Supported Operating Systems |
8070 |-------------|-----------------------|--------------------------------------------------------|
8071 | WASAPI | ma_backend_wasapi | Windows Vista+ |
8072 | DirectSound | ma_backend_dsound | Windows XP+ |
8073 | WinMM | ma_backend_winmm | Windows XP+ (may work on older versions, but untested) |
8074 | Core Audio | ma_backend_coreaudio | macOS, iOS |
8075 | ALSA | ma_backend_alsa | Linux |
8076 | PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) |
8077 | JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) |
8078 | sndio | ma_backend_sndio | OpenBSD |
8079 | audio(4) | ma_backend_audio4 | NetBSD, OpenBSD |
8080 | OSS | ma_backend_oss | FreeBSD |
8081 | AAudio | ma_backend_aaudio | Android 8+ |
8082 | OpenSL|ES | ma_backend_opensl | Android (API level 16+) |
8083 | Web Audio | ma_backend_webaudio | Web (via Emscripten) |
8084 | Null | ma_backend_null | Cross Platform (not used on Web) |
8085 |-------------|-----------------------|--------------------------------------------------------|
8086
8087The context can be configured via the `pConfig` argument. The config object is initialized with `ma_context_config_init()`. Individual configuration settings
8088can then be set directly on the structure. Below are the members of the `ma_context_config` object.
8089
8090 pLog
8091 A pointer to the `ma_log` to post log messages to. Can be NULL if the application does not
8092 require logging. See the `ma_log` API for details on how to use the logging system.
8093
8094 threadPriority
8095 The desired priority to use for the audio thread. Allowable values include the following:
8096
8097 |--------------------------------------|
8098 | Thread Priority |
8099 |--------------------------------------|
8100 | ma_thread_priority_idle |
8101 | ma_thread_priority_lowest |
8102 | ma_thread_priority_low |
8103 | ma_thread_priority_normal |
8104 | ma_thread_priority_high |
8105 | ma_thread_priority_highest (default) |
8106 | ma_thread_priority_realtime |
8107 | ma_thread_priority_default |
8108 |--------------------------------------|
8109
8110 threadStackSize
8111 The desired size of the stack for the audio thread. Defaults to the operating system's default.
8112
8113 pUserData
8114 A pointer to application-defined data. This can be accessed from the context object directly such as `context.pUserData`.
8115
8116 allocationCallbacks
8117 Structure containing custom allocation callbacks. Leaving this at defaults will cause it to use MA_MALLOC, MA_REALLOC and MA_FREE. These allocation
8118 callbacks will be used for anything tied to the context, including devices.
8119
8120 alsa.useVerboseDeviceEnumeration
8121 ALSA will typically enumerate many different devices which can be intrusive and not user-friendly. To combat this, miniaudio will enumerate only unique
8122 card/device pairs by default. The problem with this is that you lose a bit of flexibility and control. Setting alsa.useVerboseDeviceEnumeration makes
8123 it so the ALSA backend includes all devices. Defaults to false.
8124
8125 pulse.pApplicationName
8126 PulseAudio only. The application name to use when initializing the PulseAudio context with `pa_context_new()`.
8127
8128 pulse.pServerName
8129 PulseAudio only. The name of the server to connect to with `pa_context_connect()`.
8130
8131 pulse.tryAutoSpawn
8132 PulseAudio only. Whether or not to try automatically starting the PulseAudio daemon. Defaults to false. If you set this to true, keep in mind that
8133 miniaudio uses a trial and error method to find the most appropriate backend, and this will result in the PulseAudio daemon starting which may be
8134 intrusive for the end user.
8135
8136 coreaudio.sessionCategory
8137 iOS only. The session category to use for the shared AudioSession instance. Below is a list of allowable values and their Core Audio equivalents.
8138
8139 |-----------------------------------------|-------------------------------------|
8140 | miniaudio Token | Core Audio Token |
8141 |-----------------------------------------|-------------------------------------|
8142 | ma_ios_session_category_ambient | AVAudioSessionCategoryAmbient |
8143 | ma_ios_session_category_solo_ambient | AVAudioSessionCategorySoloAmbient |
8144 | ma_ios_session_category_playback | AVAudioSessionCategoryPlayback |
8145 | ma_ios_session_category_record | AVAudioSessionCategoryRecord |
8146 | ma_ios_session_category_play_and_record | AVAudioSessionCategoryPlayAndRecord |
8147 | ma_ios_session_category_multi_route | AVAudioSessionCategoryMultiRoute |
8148 | ma_ios_session_category_none | AVAudioSessionCategoryAmbient |
8149 | ma_ios_session_category_default | AVAudioSessionCategoryAmbient |
8150 |-----------------------------------------|-------------------------------------|
8151
8152 coreaudio.sessionCategoryOptions
8153 iOS only. Session category options to use with the shared AudioSession instance. Below is a list of allowable values and their Core Audio equivalents.
8154
8155 |---------------------------------------------------------------------------|------------------------------------------------------------------|
8156 | miniaudio Token | Core Audio Token |
8157 |---------------------------------------------------------------------------|------------------------------------------------------------------|
8158 | ma_ios_session_category_option_mix_with_others | AVAudioSessionCategoryOptionMixWithOthers |
8159 | ma_ios_session_category_option_duck_others | AVAudioSessionCategoryOptionDuckOthers |
8160 | ma_ios_session_category_option_allow_bluetooth | AVAudioSessionCategoryOptionAllowBluetooth |
8161 | ma_ios_session_category_option_default_to_speaker | AVAudioSessionCategoryOptionDefaultToSpeaker |
8162 | ma_ios_session_category_option_interrupt_spoken_audio_and_mix_with_others | AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers |
8163 | ma_ios_session_category_option_allow_bluetooth_a2dp | AVAudioSessionCategoryOptionAllowBluetoothA2DP |
8164 | ma_ios_session_category_option_allow_air_play | AVAudioSessionCategoryOptionAllowAirPlay |
8165 |---------------------------------------------------------------------------|------------------------------------------------------------------|
8166
8167 coreaudio.noAudioSessionActivate
8168 iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:true] on initialization.
8169
8170 coreaudio.noAudioSessionDeactivate
8171 iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:false] on uninitialization.
8172
8173 jack.pClientName
8174 The name of the client to pass to `jack_client_open()`.
8175
8176 jack.tryStartServer