Debian Codegraph @

extras/miniaudio_split/miniaudio.h

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