/*
Audio playback and capture library. Choice of public domain or MIT-0. See license statements at the end of this file.
miniaudio - v0.10.31 - 2020-01-17
David Reid - mackron@gmail.com
Website: https://miniaud.io
Documentation: https://miniaud.io/docs
GitHub: https://github.com/mackron/miniaudio
*/
/*
1. Introduction
===============
miniaudio is a single file library for audio playback and capture. To use it, do the following in one .c file:
```c
#define MINIAUDIO_IMPLEMENTATION
#include "miniaudio.h"
```
You can do `#include "miniaudio.h"` in other parts of the program just like any other header.
miniaudio uses the concept of a "device" as the abstraction for physical devices. The idea is that you choose a physical device to emit or capture audio from,
and then move data to/from the device when miniaudio tells you to. Data is delivered to and from devices asynchronously via a callback which you specify when
initializing the device.
When initializing the device you first need to configure it. The device configuration allows you to specify things like the format of the data delivered via
the callback, the size of the internal buffer and the ID of the device you want to emit or capture audio from.
Once you have the device configuration set up you can initialize the device. When initializing a device you need to allocate memory for the device object
beforehand. This gives the application complete control over how the memory is allocated. In the example below we initialize a playback device on the stack,
but you could allocate it on the heap if that suits your situation better.
```c
void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
{
// In playback mode copy data to pOutput. In capture mode read data from pInput. In full-duplex mode, both
// pOutput and pInput will be valid and you can move data from pInput into pOutput. Never process more than
// frameCount frames.
}
int main()
{
ma_device_config config = ma_device_config_init(ma_device_type_playback);
config.playback.format = ma_format_f32; // Set to ma_format_unknown to use the device's native format.
config.playback.channels = 2; // Set to 0 to use the device's native channel count.
config.sampleRate = 48000; // Set to 0 to use the device's native sample rate.
config.dataCallback = data_callback; // This function will be called when miniaudio needs more data.
config.pUserData = pMyCustomData; // Can be accessed from the device object (device.pUserData).
ma_device device;
if (ma_device_init(NULL, &config, &device) != MA_SUCCESS) {
return -1; // Failed to initialize the device.
}
ma_device_start(&device); // The device is sleeping by default so you'll need to start it manually.
// Do something here. Probably your program's main loop.
ma_device_uninit(&device); // This will stop the device so no need to do that manually.
return 0;
}
```
In the example above, `data_callback()` is where audio data is written and read from the device. The idea is in playback mode you cause sound to be emitted
from the speakers by writing audio data to the output buffer (`pOutput` in the example). In capture mode you read data from the input buffer (`pInput`) to
extract sound captured by the microphone. The `frameCount` parameter tells you how many frames can be written to the output buffer and read from the input
buffer. A "frame" is one sample for each channel. For example, in a stereo stream (2 channels), one frame is 2 samples: one for the left, one for the right.
The channel count is defined by the device config. The size in bytes of an individual sample is defined by the sample format which is also specified in the
device config. Multi-channel audio data is always interleaved, which means the samples for each frame are stored next to each other in memory. For example, in
a stereo stream the first pair of samples will be the left and right samples for the first frame, the second pair of samples will be the left and right samples
for the second frame, etc.
The configuration of the device is defined by the `ma_device_config` structure. The config object is always initialized with `ma_device_config_init()`. It's
important to always initialize the config with this function as it initializes it with logical defaults and ensures your program doesn't break when new members
are added to the `ma_device_config` structure. The example above uses a fairly simple and standard device configuration. The call to `ma_device_config_init()`
takes a single parameter, which is whether or not the device is a playback, capture, duplex or loopback device (loopback devices are not supported on all
backends). The `config.playback.format` member sets the sample format which can be one of the following (all formats are native-endian):
+---------------+----------------------------------------+---------------------------+
| Symbol | Description | Range |
+---------------+----------------------------------------+---------------------------+
| ma_format_f32 | 32-bit floating point | [-1, 1] |
| ma_format_s16 | 16-bit signed integer | [-32768, 32767] |
| ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] |
| ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] |
| ma_format_u8 | 8-bit unsigned integer | [0, 255] |
+---------------+----------------------------------------+---------------------------+
The `config.playback.channels` member sets the number of channels to use with the device. The channel count cannot exceed MA_MAX_CHANNELS. The
`config.sampleRate` member sets the sample rate (which must be the same for both playback and capture in full-duplex configurations). This is usually set to
44100 or 48000, but can be set to anything. It's recommended to keep this between 8000 and 384000, however.
Note that leaving the format, channel count and/or sample rate at their default values will result in the internal device's native configuration being used
which is useful if you want to avoid the overhead of miniaudio's automatic data conversion.
In addition to the sample format, channel count and sample rate, the data callback and user data pointer are also set via the config. The user data pointer is
not passed into the callback as a parameter, but is instead set to the `pUserData` member of `ma_device` which you can access directly since all miniaudio
structures are transparent.
Initializing the device is done with `ma_device_init()`. This will return a result code telling you what went wrong, if anything. On success it will return
`MA_SUCCESS`. After initialization is complete the device will be in a stopped state. To start it, use `ma_device_start()`. Uninitializing the device will stop
it, which is what the example above does, but you can also stop the device with `ma_device_stop()`. To resume the device simply call `ma_device_start()` again.
Note that it's important to never stop or start the device from inside the callback. This will result in a deadlock. Instead you set a variable or signal an
event indicating that the device needs to stop and handle it in a different thread. The following APIs must never be called inside the callback:
```c
ma_device_init()
ma_device_init_ex()
ma_device_uninit()
ma_device_start()
ma_device_stop()
```
You must never try uninitializing and reinitializing a device inside the callback. You must also never try to stop and start it from inside the callback. There
are a few other things you shouldn't do in the callback depending on your requirements, however this isn't so much a thread-safety thing, but rather a
real-time processing thing which is beyond the scope of this introduction.
The example above demonstrates the initialization of a playback device, but it works exactly the same for capture. All you need to do is change the device type
from `ma_device_type_playback` to `ma_device_type_capture` when setting up the config, like so:
```c
ma_device_config config = ma_device_config_init(ma_device_type_capture);
config.capture.format = MY_FORMAT;
config.capture.channels = MY_CHANNEL_COUNT;
```
In the data callback you just read from the input buffer (`pInput` in the example above) and leave the output buffer alone (it will be set to NULL when the
device type is set to `ma_device_type_capture`).
These are the available device types and how you should handle the buffers in the callback:
+-------------------------+--------------------------------------------------------+
| Device Type | Callback Behavior |
+-------------------------+--------------------------------------------------------+
| ma_device_type_playback | Write to output buffer, leave input buffer untouched. |
| ma_device_type_capture | Read from input buffer, leave output buffer untouched. |
| ma_device_type_duplex | Read from input buffer, write to output buffer. |
| ma_device_type_loopback | Read from input buffer, leave output buffer untouched. |
+-------------------------+--------------------------------------------------------+
You will notice in the example above that the sample format and channel count is specified separately for playback and capture. This is to support different
data formats between the playback and capture devices in a full-duplex system. An example may be that you want to capture audio data as a monaural stream (one
channel), but output sound to a stereo speaker system. Note that if you use different formats between playback and capture in a full-duplex configuration you
will need to convert the data yourself. There are functions available to help you do this which will be explained later.
The example above did not specify a physical device to connect to which means it will use the operating system's default device. If you have multiple physical
devices connected and you want to use a specific one you will need to specify the device ID in the configuration, like so:
```c
config.playback.pDeviceID = pMyPlaybackDeviceID; // Only if requesting a playback or duplex device.
config.capture.pDeviceID = pMyCaptureDeviceID; // Only if requesting a capture, duplex or loopback device.
```
To retrieve the device ID you will need to perform device enumeration, however this requires the use of a new concept called the "context". Conceptually
speaking the context sits above the device. There is one context to many devices. The purpose of the context is to represent the backend at a more global level
and to perform operations outside the scope of an individual device. Mainly it is used for performing run-time linking against backend libraries, initializing
backends and enumerating devices. The example below shows how to enumerate devices.
```c
ma_context context;
if (ma_context_init(NULL, 0, NULL, &context) != MA_SUCCESS) {
// Error.
}
ma_device_info* pPlaybackInfos;
ma_uint32 playbackCount;
ma_device_info* pCaptureInfos;
ma_uint32 captureCount;
if (ma_context_get_devices(&context, &pPlaybackInfos, &playbackCount, &pCaptureInfos, &captureCount) != MA_SUCCESS) {
// Error.
}
// Loop over each device info and do something with it. Here we just print the name with their index. You may want
// to give the user the opportunity to choose which device they'd prefer.
for (ma_uint32 iDevice = 0; iDevice < playbackCount; iDevice += 1) {
printf("%d - %s\n", iDevice, pPlaybackInfos[iDevice].name);
}
ma_device_config config = ma_device_config_init(ma_device_type_playback);
config.playback.pDeviceID = &pPlaybackInfos[chosenPlaybackDeviceIndex].id;
config.playback.format = MY_FORMAT;
config.playback.channels = MY_CHANNEL_COUNT;
config.sampleRate = MY_SAMPLE_RATE;
config.dataCallback = data_callback;
config.pUserData = pMyCustomData;
ma_device device;
if (ma_device_init(&context, &config, &device) != MA_SUCCESS) {
// Error
}
...
ma_device_uninit(&device);
ma_context_uninit(&context);
```
The first thing we do in this example is initialize a `ma_context` object with `ma_context_init()`. The first parameter is a pointer to a list of `ma_backend`
values which are used to override the default backend priorities. When this is NULL, as in this example, miniaudio's default priorities are used. The second
parameter is the number of backends listed in the array pointed to by the first parameter. The third parameter is a pointer to a `ma_context_config` object
which can be NULL, in which case defaults are used. The context configuration is used for setting the logging callback, custom memory allocation callbacks,
user-defined data and some backend-specific configurations.
Once the context has been initialized you can enumerate devices. In the example above we use the simpler `ma_context_get_devices()`, however you can also use a
callback for handling devices by using `ma_context_enumerate_devices()`. When using `ma_context_get_devices()` you provide a pointer to a pointer that will,
upon output, be set to a pointer to a buffer containing a list of `ma_device_info` structures. You also provide a pointer to an unsigned integer that will
receive the number of items in the returned buffer. Do not free the returned buffers as their memory is managed internally by miniaudio.
The `ma_device_info` structure contains an `id` member which is the ID you pass to the device config. It also contains the name of the device which is useful
for presenting a list of devices to the user via the UI.
When creating your own context you will want to pass it to `ma_device_init()` when initializing the device. Passing in NULL, like we do in the first example,
will result in miniaudio creating the context for you, which you don't want to do since you've already created a context. Note that internally the context is
only tracked by it's pointer which means you must not change the location of the `ma_context` object. If this is an issue, consider using `malloc()` to
allocate memory for the context.
2. Building
===========
miniaudio should work cleanly out of the box without the need to download or install any dependencies. See below for platform-specific details.
2.1. Windows
------------
The Windows build should compile cleanly on all popular compilers without the need to configure any include paths nor link to any libraries.
2.2. macOS and iOS
------------------
The macOS build should compile cleanly without the need to download any dependencies nor link to any libraries or frameworks. The iOS build needs to be
compiled as Objective-C and will need to link the relevant frameworks but should compile cleanly out of the box with Xcode. Compiling through the command line
requires linking to `-lpthread` and `-lm`.
Due to the way miniaudio links to frameworks at runtime, your application may not pass Apple's notarization process. To fix this there are two options. The
first is to use the `MA_NO_RUNTIME_LINKING` option, like so:
```c
#ifdef __APPLE__
#define MA_NO_RUNTIME_LINKING
#endif
#define MINIAUDIO_IMPLEMENTATION
#include "miniaudio.h"
```
This will require linking with `-framework CoreFoundation -framework CoreAudio -framework AudioUnit`. Alternatively, if you would rather keep using runtime
linking you can add the following to your entitlements.xcent file:
```
com.apple.security.cs.allow-dyld-environment-variables
com.apple.security.cs.allow-unsigned-executable-memory
```
2.3. Linux
----------
The Linux build only requires linking to `-ldl`, `-lpthread` and `-lm`. You do not need any development packages.
2.4. BSD
--------
The BSD build only requires linking to `-lpthread` and `-lm`. NetBSD uses audio(4), OpenBSD uses sndio and FreeBSD uses OSS.
2.5. Android
------------
AAudio is the highest priority backend on Android. This should work out of the box without needing any kind of compiler configuration. Support for AAudio
starts with Android 8 which means older versions will fall back to OpenSL|ES which requires API level 16+.
There have been reports that the OpenSL|ES backend fails to initialize on some Android based devices due to `dlopen()` failing to open "libOpenSLES.so". If
this happens on your platform you'll need to disable run-time linking with `MA_NO_RUNTIME_LINKING` and link with -lOpenSLES.
2.6. Emscripten
---------------
The Emscripten build emits Web Audio JavaScript directly and should compile cleanly out of the box. You cannot use -std=c* compiler flags, nor -ansi.
2.7. Build Options
------------------
`#define` these options before including miniaudio.h.
+----------------------------------+--------------------------------------------------------------------+
| Option | Description |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_WASAPI | Disables the WASAPI backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_DSOUND | Disables the DirectSound backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_WINMM | Disables the WinMM backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_ALSA | Disables the ALSA backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_PULSEAUDIO | Disables the PulseAudio backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_JACK | Disables the JACK backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_COREAUDIO | Disables the Core Audio backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_SNDIO | Disables the sndio backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_AUDIO4 | Disables the audio(4) backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_OSS | Disables the OSS backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_AAUDIO | Disables the AAudio backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_OPENSL | Disables the OpenSL|ES backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_WEBAUDIO | Disables the Web Audio backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_NULL | Disables the null backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_ONLY_SPECIFIC_BACKENDS | Disables all backends by default and requires `MA_ENABLE_*` to |
| | enable specific backends. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_WASAPI | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the WASAPI backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_DSOUND | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the DirectSound backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_WINMM | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the WinMM backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_ALSA | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the ALSA backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_PULSEAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the PulseAudio backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_JACK | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the JACK backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_COREAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the Core Audio backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_SNDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the sndio backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_AUDIO4 | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the audio(4) backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_OSS | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the OSS backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_AAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the AAudio backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_OPENSL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the OpenSL|ES backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_WEBAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the Web Audio backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_ENABLE_NULL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
| | enable the null backend. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_DECODING | Disables decoding APIs. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_ENCODING | Disables encoding APIs. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_WAV | Disables the built-in WAV decoder and encoder. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_FLAC | Disables the built-in FLAC decoder. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_MP3 | Disables the built-in MP3 decoder. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_DEVICE_IO | Disables playback and recording. This will disable ma_context and |
| | ma_device APIs. This is useful if you only want to use miniaudio's |
| | data conversion and/or decoding APIs. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_THREADING | Disables the ma_thread, ma_mutex, ma_semaphore and ma_event APIs. |
| | This option is useful if you only need to use miniaudio for data |
| | conversion, decoding and/or encoding. Some families of APIs |
| | require threading which means the following options must also be |
| | set: |
| | |
| | ``` |
| | MA_NO_DEVICE_IO |
| | ``` |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_GENERATION | Disables generation APIs such a ma_waveform and ma_noise. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_SSE2 | Disables SSE2 optimizations. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_AVX2 | Disables AVX2 optimizations. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_AVX512 | Disables AVX-512 optimizations. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_NEON | Disables NEON optimizations. |
+----------------------------------+--------------------------------------------------------------------+
| MA_NO_RUNTIME_LINKING | Disables runtime linking. This is useful for passing Apple's |
| | notarization process. When enabling this, you may need to avoid |
| | using `-std=c89` or `-std=c99` on Linux builds or else you may end |
| | up with compilation errors due to conflicts with `timespec` and |
| | `timeval` data types. |
| | |
| | You may need to enable this if your target platform does not allow |
| | runtime linking via `dlopen()`. |
+----------------------------------+--------------------------------------------------------------------+
| MA_LOG_LEVEL [level] | Sets the logging level. Set `level` to one of the following: |
| | |
| | ``` |
| | MA_LOG_LEVEL_VERBOSE |
| | MA_LOG_LEVEL_INFO |
| | MA_LOG_LEVEL_WARNING |
| | MA_LOG_LEVEL_ERROR |
| | ``` |
+----------------------------------+--------------------------------------------------------------------+
| MA_DEBUG_OUTPUT | Enable `printf()` debug output. |
+----------------------------------+--------------------------------------------------------------------+
| MA_COINIT_VALUE | Windows only. The value to pass to internal calls to |
| | `CoInitializeEx()`. Defaults to `COINIT_MULTITHREADED`. |
+----------------------------------+--------------------------------------------------------------------+
| MA_API | Controls how public APIs should be decorated. Default is `extern`. |
+----------------------------------+--------------------------------------------------------------------+
| MA_DLL | If set, configures MA_API to either import or export APIs |
| | depending on whether or not the implementation is being defined. |
| | If defining the implementation, MA_API will be configured to |
| | export. Otherwise it will be configured to import. This has no |
| | effect if MA_API is defined externally. |
+----------------------------------+--------------------------------------------------------------------+
3. Definitions
==============
This section defines common terms used throughout miniaudio. Unfortunately there is often ambiguity in the use of terms throughout the audio space, so this
section is intended to clarify how miniaudio uses each term.
3.1. Sample
-----------
A sample is a single unit of audio data. If the sample format is f32, then one sample is one 32-bit floating point number.
3.2. Frame / PCM Frame
----------------------
A frame is a group of samples equal to the number of channels. For a stereo stream a frame is 2 samples, a mono frame is 1 sample, a 5.1 surround sound frame
is 6 samples, etc. The terms "frame" and "PCM frame" are the same thing in miniaudio. Note that this is different to a compressed frame. If ever miniaudio
needs to refer to a compressed frame, such as a FLAC frame, it will always clarify what it's referring to with something like "FLAC frame".
3.3. Channel
------------
A stream of monaural audio that is emitted from an individual speaker in a speaker system, or received from an individual microphone in a microphone system. A
stereo stream has two channels (a left channel, and a right channel), a 5.1 surround sound system has 6 channels, etc. Some audio systems refer to a channel as
a complex audio stream that's mixed with other channels to produce the final mix - this is completely different to miniaudio's use of the term "channel" and
should not be confused.
3.4. Sample Rate
----------------
The sample rate in miniaudio is always expressed in Hz, such as 44100, 48000, etc. It's the number of PCM frames that are processed per second.
3.5. Formats
------------
Throughout miniaudio you will see references to different sample formats:
+---------------+----------------------------------------+---------------------------+
| Symbol | Description | Range |
+---------------+----------------------------------------+---------------------------+
| ma_format_f32 | 32-bit floating point | [-1, 1] |
| ma_format_s16 | 16-bit signed integer | [-32768, 32767] |
| ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] |
| ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] |
| ma_format_u8 | 8-bit unsigned integer | [0, 255] |
+---------------+----------------------------------------+---------------------------+
All formats are native-endian.
4. Decoding
===========
The `ma_decoder` API is used for reading audio files. Decoders are completely decoupled from devices and can be used independently. The following formats are
supported:
+---------+------------------+----------+
| Format | Decoding Backend | Built-In |
+---------+------------------+----------+
| WAV | dr_wav | Yes |
| MP3 | dr_mp3 | Yes |
| FLAC | dr_flac | Yes |
| Vorbis | stb_vorbis | No |
+---------+------------------+----------+
Vorbis is supported via stb_vorbis which can be enabled by including the header section before the implementation of miniaudio, like the following:
```c
#define STB_VORBIS_HEADER_ONLY
#include "extras/stb_vorbis.c" // Enables Vorbis decoding.
#define MINIAUDIO_IMPLEMENTATION
#include "miniaudio.h"
// The stb_vorbis implementation must come after the implementation of miniaudio.
#undef STB_VORBIS_HEADER_ONLY
#include "extras/stb_vorbis.c"
```
A copy of stb_vorbis is included in the "extras" folder in the miniaudio repository (https://github.com/mackron/miniaudio).
Built-in decoders are amalgamated into the implementation section of miniaudio. You can disable the built-in decoders by specifying one or more of the
following options before the miniaudio implementation:
```c
#define MA_NO_WAV
#define MA_NO_MP3
#define MA_NO_FLAC
```
Disabling built-in decoding libraries is useful if you use these libraries independantly of the `ma_decoder` API.
A decoder can be initialized from a file with `ma_decoder_init_file()`, a block of memory with `ma_decoder_init_memory()`, or from data delivered via callbacks
with `ma_decoder_init()`. Here is an example for loading a decoder from a file:
```c
ma_decoder decoder;
ma_result result = ma_decoder_init_file("MySong.mp3", NULL, &decoder);
if (result != MA_SUCCESS) {
return false; // An error occurred.
}
...
ma_decoder_uninit(&decoder);
```
When initializing a decoder, you can optionally pass in a pointer to a `ma_decoder_config` object (the `NULL` argument in the example above) which allows you
to configure the output format, channel count, sample rate and channel map:
```c
ma_decoder_config config = ma_decoder_config_init(ma_format_f32, 2, 48000);
```
When passing in `NULL` for decoder config in `ma_decoder_init*()`, the output format will be the same as that defined by the decoding backend.
Data is read from the decoder as PCM frames. This will return the number of PCM frames actually read. If the return value is less than the requested number of
PCM frames it means you've reached the end:
```c
ma_uint64 framesRead = ma_decoder_read_pcm_frames(pDecoder, pFrames, framesToRead);
if (framesRead < framesToRead) {
// Reached the end.
}
```
You can also seek to a specific frame like so:
```c
ma_result result = ma_decoder_seek_to_pcm_frame(pDecoder, targetFrame);
if (result != MA_SUCCESS) {
return false; // An error occurred.
}
```
If you want to loop back to the start, you can simply seek back to the first PCM frame:
```c
ma_decoder_seek_to_pcm_frame(pDecoder, 0);
```
When loading a decoder, miniaudio uses a trial and error technique to find the appropriate decoding backend. This can be unnecessarily inefficient if the type
is already known. In this case you can use the `_wav`, `_mp3`, etc. varients of the aforementioned initialization APIs:
```c
ma_decoder_init_wav()
ma_decoder_init_mp3()
ma_decoder_init_memory_wav()
ma_decoder_init_memory_mp3()
ma_decoder_init_file_wav()
ma_decoder_init_file_mp3()
etc.
```
The `ma_decoder_init_file()` API will try using the file extension to determine which decoding backend to prefer.
5. Encoding
===========
The `ma_encoding` API is used for writing audio files. The only supported output format is WAV which is achieved via dr_wav which is amalgamated into the
implementation section of miniaudio. This can be disabled by specifying the following option before the implementation of miniaudio:
```c
#define MA_NO_WAV
```
An encoder can be initialized to write to a file with `ma_encoder_init_file()` or from data delivered via callbacks with `ma_encoder_init()`. Below is an
example for initializing an encoder to output to a file.
```c
ma_encoder_config config = ma_encoder_config_init(ma_resource_format_wav, FORMAT, CHANNELS, SAMPLE_RATE);
ma_encoder encoder;
ma_result result = ma_encoder_init_file("my_file.wav", &config, &encoder);
if (result != MA_SUCCESS) {
// Error
}
...
ma_encoder_uninit(&encoder);
```
When initializing an encoder you must specify a config which is initialized with `ma_encoder_config_init()`. Here you must specify the file type, the output
sample format, output channel count and output sample rate. The following file types are supported:
+------------------------+-------------+
| Enum | Description |
+------------------------+-------------+
| ma_resource_format_wav | WAV |
+------------------------+-------------+
If the format, channel count or sample rate is not supported by the output file type an error will be returned. The encoder will not perform data conversion so
you will need to convert it before outputting any audio data. To output audio data, use `ma_encoder_write_pcm_frames()`, like in the example below:
```c
framesWritten = ma_encoder_write_pcm_frames(&encoder, pPCMFramesToWrite, framesToWrite);
```
Encoders must be uninitialized with `ma_encoder_uninit()`.
6. Data Conversion
==================
A data conversion API is included with miniaudio which supports the majority of data conversion requirements. This supports conversion between sample formats,
channel counts (with channel mapping) and sample rates.
6.1. Sample Format Conversion
-----------------------------
Conversion between sample formats is achieved with the `ma_pcm_*_to_*()`, `ma_pcm_convert()` and `ma_convert_pcm_frames_format()` APIs. Use `ma_pcm_*_to_*()`
to convert between two specific formats. Use `ma_pcm_convert()` to convert based on a `ma_format` variable. Use `ma_convert_pcm_frames_format()` to convert
PCM frames where you want to specify the frame count and channel count as a variable instead of the total sample count.
6.1.1. Dithering
----------------
Dithering can be set using the ditherMode parameter.
The different dithering modes include the following, in order of efficiency:
+-----------+--------------------------+
| Type | Enum Token |
+-----------+--------------------------+
| None | ma_dither_mode_none |
| Rectangle | ma_dither_mode_rectangle |
| Triangle | ma_dither_mode_triangle |
+-----------+--------------------------+
Note that even if the dither mode is set to something other than `ma_dither_mode_none`, it will be ignored for conversions where dithering is not needed.
Dithering is available for the following conversions:
```
s16 -> u8
s24 -> u8
s32 -> u8
f32 -> u8
s24 -> s16
s32 -> s16
f32 -> s16
```
Note that it is not an error to pass something other than ma_dither_mode_none for conversions where dither is not used. It will just be ignored.
6.2. Channel Conversion
-----------------------
Channel conversion is used for channel rearrangement and conversion from one channel count to another. The `ma_channel_converter` API is used for channel
conversion. Below is an example of initializing a simple channel converter which converts from mono to stereo.
```c
ma_channel_converter_config config = ma_channel_converter_config_init(
ma_format, // Sample format
1, // Input channels
NULL, // Input channel map
2, // Output channels
NULL, // Output channel map
ma_channel_mix_mode_default); // The mixing algorithm to use when combining channels.
result = ma_channel_converter_init(&config, &converter);
if (result != MA_SUCCESS) {
// Error.
}
```
To perform the conversion simply call `ma_channel_converter_process_pcm_frames()` like so:
```c
ma_result result = ma_channel_converter_process_pcm_frames(&converter, pFramesOut, pFramesIn, frameCount);
if (result != MA_SUCCESS) {
// Error.
}
```
It is up to the caller to ensure the output buffer is large enough to accomodate the new PCM frames.
Input and output PCM frames are always interleaved. Deinterleaved layouts are not supported.
6.2.1. Channel Mapping
----------------------
In addition to converting from one channel count to another, like the example above, the channel converter can also be used to rearrange channels. When
initializing the channel converter, you can optionally pass in channel maps for both the input and output frames. If the channel counts are the same, and each
channel map contains the same channel positions with the exception that they're in a different order, a simple shuffling of the channels will be performed. If,
however, there is not a 1:1 mapping of channel positions, or the channel counts differ, the input channels will be mixed based on a mixing mode which is
specified when initializing the `ma_channel_converter_config` object.
When converting from mono to multi-channel, the mono channel is simply copied to each output channel. When going the other way around, the audio of each output
channel is simply averaged and copied to the mono channel.
In more complicated cases blending is used. The `ma_channel_mix_mode_simple` mode will drop excess channels and silence extra channels. For example, converting
from 4 to 2 channels, the 3rd and 4th channels will be dropped, whereas converting from 2 to 4 channels will put silence into the 3rd and 4th channels.
The `ma_channel_mix_mode_rectangle` mode uses spacial locality based on a rectangle to compute a simple distribution between input and output. Imagine sitting
in the middle of a room, with speakers on the walls representing channel positions. The MA_CHANNEL_FRONT_LEFT position can be thought of as being in the corner
of the front and left walls.
Finally, the `ma_channel_mix_mode_custom_weights` mode can be used to use custom user-defined weights. Custom weights can be passed in as the last parameter of
`ma_channel_converter_config_init()`.
Predefined channel maps can be retrieved with `ma_get_standard_channel_map()`. This takes a `ma_standard_channel_map` enum as it's first parameter, which can
be one of the following:
+-----------------------------------+-----------------------------------------------------------+
| Name | Description |
+-----------------------------------+-----------------------------------------------------------+
| ma_standard_channel_map_default | Default channel map used by miniaudio. See below. |
| ma_standard_channel_map_microsoft | Channel map used by Microsoft's bitfield channel maps. |
| ma_standard_channel_map_alsa | Default ALSA channel map. |
| ma_standard_channel_map_rfc3551 | RFC 3551. Based on AIFF. |
| ma_standard_channel_map_flac | FLAC channel map. |
| ma_standard_channel_map_vorbis | Vorbis channel map. |
| ma_standard_channel_map_sound4 | FreeBSD's sound(4). |
| ma_standard_channel_map_sndio | sndio channel map. http://www.sndio.org/tips.html. |
| ma_standard_channel_map_webaudio | https://webaudio.github.io/web-audio-api/#ChannelOrdering |
+-----------------------------------+-----------------------------------------------------------+
Below are the channel maps used by default in miniaudio (`ma_standard_channel_map_default`):
+---------------+---------------------------------+
| Channel Count | Mapping |
+---------------+---------------------------------+
| 1 (Mono) | 0: MA_CHANNEL_MONO |
+---------------+---------------------------------+
| 2 (Stereo) | 0: MA_CHANNEL_FRONT_LEFT
|
| | 1: MA_CHANNEL_FRONT_RIGHT |
+---------------+---------------------------------+
| 3 | 0: MA_CHANNEL_FRONT_LEFT
|
| | 1: MA_CHANNEL_FRONT_RIGHT
|
| | 2: MA_CHANNEL_FRONT_CENTER |
+---------------+---------------------------------+
| 4 (Surround) | 0: MA_CHANNEL_FRONT_LEFT
|
| | 1: MA_CHANNEL_FRONT_RIGHT
|
| | 2: MA_CHANNEL_FRONT_CENTER
|
| | 3: MA_CHANNEL_BACK_CENTER |
+---------------+---------------------------------+
| 5 | 0: MA_CHANNEL_FRONT_LEFT
|
| | 1: MA_CHANNEL_FRONT_RIGHT
|
| | 2: MA_CHANNEL_FRONT_CENTER
|
| | 3: MA_CHANNEL_BACK_LEFT
|
| | 4: MA_CHANNEL_BACK_RIGHT |
+---------------+---------------------------------+
| 6 (5.1) | 0: MA_CHANNEL_FRONT_LEFT
|
| | 1: MA_CHANNEL_FRONT_RIGHT
|
| | 2: MA_CHANNEL_FRONT_CENTER
|
| | 3: MA_CHANNEL_LFE
|
| | 4: MA_CHANNEL_SIDE_LEFT
|
| | 5: MA_CHANNEL_SIDE_RIGHT |
+---------------+---------------------------------+
| 7 | 0: MA_CHANNEL_FRONT_LEFT
|
| | 1: MA_CHANNEL_FRONT_RIGHT
|
| | 2: MA_CHANNEL_FRONT_CENTER
|
| | 3: MA_CHANNEL_LFE
|
| | 4: MA_CHANNEL_BACK_CENTER
|
| | 4: MA_CHANNEL_SIDE_LEFT
|
| | 5: MA_CHANNEL_SIDE_RIGHT |
+---------------+---------------------------------+
| 8 (7.1) | 0: MA_CHANNEL_FRONT_LEFT
|
| | 1: MA_CHANNEL_FRONT_RIGHT
|
| | 2: MA_CHANNEL_FRONT_CENTER
|
| | 3: MA_CHANNEL_LFE
|
| | 4: MA_CHANNEL_BACK_LEFT
|
| | 5: MA_CHANNEL_BACK_RIGHT
|
| | 6: MA_CHANNEL_SIDE_LEFT
|
| | 7: MA_CHANNEL_SIDE_RIGHT |
+---------------+---------------------------------+
| Other | All channels set to 0. This |
| | is equivalent to the same |
| | mapping as the device. |
+---------------+---------------------------------+
6.3. Resampling
---------------
Resampling is achieved with the `ma_resampler` object. To create a resampler object, do something like the following:
```c
ma_resampler_config config = ma_resampler_config_init(
ma_format_s16,
channels,
sampleRateIn,
sampleRateOut,
ma_resample_algorithm_linear);
ma_resampler resampler;
ma_result result = ma_resampler_init(&config, &resampler);
if (result != MA_SUCCESS) {
// An error occurred...
}
```
Do the following to uninitialize the resampler:
```c
ma_resampler_uninit(&resampler);
```
The following example shows how data can be processed
```c
ma_uint64 frameCountIn = 1000;
ma_uint64 frameCountOut = 2000;
ma_result result = ma_resampler_process_pcm_frames(&resampler, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut);
if (result != MA_SUCCESS) {
// An error occurred...
}
// At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the
// number of output frames written.
```
To initialize the resampler you first need to set up a config (`ma_resampler_config`) with `ma_resampler_config_init()`. You need to specify the sample format
you want to use, the number of channels, the input and output sample rate, and the algorithm.
The sample format can be either `ma_format_s16` or `ma_format_f32`. If you need a different format you will need to perform pre- and post-conversions yourself
where necessary. Note that the format is the same for both input and output. The format cannot be changed after initialization.
The resampler supports multiple channels and is always interleaved (both input and output). The channel count cannot be changed after initialization.
The sample rates can be anything other than zero, and are always specified in hertz. They should be set to something like 44100, etc. The sample rate is the
only configuration property that can be changed after initialization.
The miniaudio resampler supports multiple algorithms:
+-----------+------------------------------+
| Algorithm | Enum Token |
+-----------+------------------------------+
| Linear | ma_resample_algorithm_linear |
| Speex | ma_resample_algorithm_speex |
+-----------+------------------------------+
Because Speex is not public domain it is strictly opt-in and the code is stored in separate files. if you opt-in to the Speex backend you will need to consider
it's license, the text of which can be found in it's source files in "extras/speex_resampler". Details on how to opt-in to the Speex resampler is explained in
the Speex Resampler section below.
The algorithm cannot be changed after initialization.
Processing always happens on a per PCM frame basis and always assumes interleaved input and output. De-interleaved processing is not supported. To process
frames, use `ma_resampler_process_pcm_frames()`. On input, this function takes the number of output frames you can fit in the output buffer and the number of
input frames contained in the input buffer. On output these variables contain the number of output frames that were written to the output buffer and the
number of input frames that were consumed in the process. You can pass in NULL for the input buffer in which case it will be treated as an infinitely large
buffer of zeros. The output buffer can also be NULL, in which case the processing will be treated as seek.
The sample rate can be changed dynamically on the fly. You can change this with explicit sample rates with `ma_resampler_set_rate()` and also with a decimal
ratio with `ma_resampler_set_rate_ratio()`. The ratio is in/out.
Sometimes it's useful to know exactly how many input frames will be required to output a specific number of frames. You can calculate this with
`ma_resampler_get_required_input_frame_count()`. Likewise, it's sometimes useful to know exactly how many frames would be output given a certain number of
input frames. You can do this with `ma_resampler_get_expected_output_frame_count()`.
Due to the nature of how resampling works, the resampler introduces some latency. This can be retrieved in terms of both the input rate and the output rate
with `ma_resampler_get_input_latency()` and `ma_resampler_get_output_latency()`.
6.3.1. Resampling Algorithms
----------------------------
The choice of resampling algorithm depends on your situation and requirements. The linear resampler is the most efficient and has the least amount of latency,
but at the expense of poorer quality. The Speex resampler is higher quality, but slower with more latency. It also performs several heap allocations internally
for memory management.
6.3.1.1. Linear Resampling
--------------------------
The linear resampler is the fastest, but comes at the expense of poorer quality. There is, however, some control over the quality of the linear resampler which
may make it a suitable option depending on your requirements.
The linear resampler performs low-pass filtering before or after downsampling or upsampling, depending on the sample rates you're converting between. When
decreasing the sample rate, the low-pass filter will be applied before downsampling. When increasing the rate it will be performed after upsampling. By default
a fourth order low-pass filter will be applied. This can be configured via the `lpfOrder` configuration variable. Setting this to 0 will disable filtering.
The low-pass filter has a cutoff frequency which defaults to half the sample rate of the lowest of the input and output sample rates (Nyquist Frequency). This
can be controlled with the `lpfNyquistFactor` config variable. This defaults to 1, and should be in the range of 0..1, although a value of 0 does not make
sense and should be avoided. A value of 1 will use the Nyquist Frequency as the cutoff. A value of 0.5 will use half the Nyquist Frequency as the cutoff, etc.
Values less than 1 will result in more washed out sound due to more of the higher frequencies being removed. This config variable has no impact on performance
and is a purely perceptual configuration.
The API for the linear resampler is the same as the main resampler API, only it's called `ma_linear_resampler`.
6.3.1.2. Speex Resampling
-------------------------
The Speex resampler is made up of third party code which is released under the BSD license. Because it is licensed differently to miniaudio, which is public
domain, it is strictly opt-in and all of it's code is stored in separate files. If you opt-in to the Speex resampler you must consider the license text in it's
source files. To opt-in, you must first `#include` the following file before the implementation of miniaudio.h:
```c
#include "extras/speex_resampler/ma_speex_resampler.h"
```
Both the header and implementation is contained within the same file. The implementation can be included in your program like so:
```c
#define MINIAUDIO_SPEEX_RESAMPLER_IMPLEMENTATION
#include "extras/speex_resampler/ma_speex_resampler.h"
```
Note that even if you opt-in to the Speex backend, miniaudio won't use it unless you explicitly ask for it in the respective config of the object you are
initializing. If you try to use the Speex resampler without opting in, initialization of the `ma_resampler` object will fail with `MA_NO_BACKEND`.
The only configuration option to consider with the Speex resampler is the `speex.quality` config variable. This is a value between 0 and 10, with 0 being
the fastest with the poorest quality and 10 being the slowest with the highest quality. The default value is 3.
6.4. General Data Conversion
----------------------------
The `ma_data_converter` API can be used to wrap sample format conversion, channel conversion and resampling into one operation. This is what miniaudio uses
internally to convert between the format requested when the device was initialized and the format of the backend's native device. The API for general data
conversion is very similar to the resampling API. Create a `ma_data_converter` object like this:
```c
ma_data_converter_config config = ma_data_converter_config_init(
inputFormat,
outputFormat,
inputChannels,
outputChannels,
inputSampleRate,
outputSampleRate
);
ma_data_converter converter;
ma_result result = ma_data_converter_init(&config, &converter);
if (result != MA_SUCCESS) {
// An error occurred...
}
```
In the example above we use `ma_data_converter_config_init()` to initialize the config, however there's many more properties that can be configured, such as
channel maps and resampling quality. Something like the following may be more suitable depending on your requirements:
```c
ma_data_converter_config config = ma_data_converter_config_init_default();
config.formatIn = inputFormat;
config.formatOut = outputFormat;
config.channelsIn = inputChannels;
config.channelsOut = outputChannels;
config.sampleRateIn = inputSampleRate;
config.sampleRateOut = outputSampleRate;
ma_get_standard_channel_map(ma_standard_channel_map_flac, config.channelCountIn, config.channelMapIn);
config.resampling.linear.lpfOrder = MA_MAX_FILTER_ORDER;
```
Do the following to uninitialize the data converter:
```c
ma_data_converter_uninit(&converter);
```
The following example shows how data can be processed
```c
ma_uint64 frameCountIn = 1000;
ma_uint64 frameCountOut = 2000;
ma_result result = ma_data_converter_process_pcm_frames(&converter, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut);
if (result != MA_SUCCESS) {
// An error occurred...
}
// At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the number
// of output frames written.
```
The data converter supports multiple channels and is always interleaved (both input and output). The channel count cannot be changed after initialization.
Sample rates can be anything other than zero, and are always specified in hertz. They should be set to something like 44100, etc. The sample rate is the only
configuration property that can be changed after initialization, but only if the `resampling.allowDynamicSampleRate` member of `ma_data_converter_config` is
set to `MA_TRUE`. To change the sample rate, use `ma_data_converter_set_rate()` or `ma_data_converter_set_rate_ratio()`. The ratio must be in/out. The
resampling algorithm cannot be changed after initialization.
Processing always happens on a per PCM frame basis and always assumes interleaved input and output. De-interleaved processing is not supported. To process
frames, use `ma_data_converter_process_pcm_frames()`. On input, this function takes the number of output frames you can fit in the output buffer and the number
of input frames contained in the input buffer. On output these variables contain the number of output frames that were written to the output buffer and the
number of input frames that were consumed in the process. You can pass in NULL for the input buffer in which case it will be treated as an infinitely large
buffer of zeros. The output buffer can also be NULL, in which case the processing will be treated as seek.
Sometimes it's useful to know exactly how many input frames will be required to output a specific number of frames. You can calculate this with
`ma_data_converter_get_required_input_frame_count()`. Likewise, it's sometimes useful to know exactly how many frames would be output given a certain number of
input frames. You can do this with `ma_data_converter_get_expected_output_frame_count()`.
Due to the nature of how resampling works, the data converter introduces some latency if resampling is required. This can be retrieved in terms of both the
input rate and the output rate with `ma_data_converter_get_input_latency()` and `ma_data_converter_get_output_latency()`.
7. Filtering
============
7.1. Biquad Filtering
---------------------
Biquad filtering is achieved with the `ma_biquad` API. Example:
```c
ma_biquad_config config = ma_biquad_config_init(ma_format_f32, channels, b0, b1, b2, a0, a1, a2);
ma_result result = ma_biquad_init(&config, &biquad);
if (result != MA_SUCCESS) {
// Error.
}
...
ma_biquad_process_pcm_frames(&biquad, pFramesOut, pFramesIn, frameCount);
```
Biquad filtering is implemented using transposed direct form 2. The numerator coefficients are b0, b1 and b2, and the denominator coefficients are a0, a1 and
a2. The a0 coefficient is required and coefficients must not be pre-normalized.
Supported formats are `ma_format_s16` and `ma_format_f32`. If you need to use a different format you need to convert it yourself beforehand. When using
`ma_format_s16` the biquad filter will use fixed point arithmetic. When using `ma_format_f32`, floating point arithmetic will be used.
Input and output frames are always interleaved.
Filtering can be applied in-place by passing in the same pointer for both the input and output buffers, like so:
```c
ma_biquad_process_pcm_frames(&biquad, pMyData, pMyData, frameCount);
```
If you need to change the values of the coefficients, but maintain the values in the registers you can do so with `ma_biquad_reinit()`. This is useful if you
need to change the properties of the filter while keeping the values of registers valid to avoid glitching. Do not use `ma_biquad_init()` for this as it will
do a full initialization which involves clearing the registers to 0. Note that changing the format or channel count after initialization is invalid and will
result in an error.
7.2. Low-Pass Filtering
-----------------------
Low-pass filtering is achieved with the following APIs:
+---------+------------------------------------------+
| API | Description |
+---------+------------------------------------------+
| ma_lpf1 | First order low-pass filter |
| ma_lpf2 | Second order low-pass filter |
| ma_lpf | High order low-pass filter (Butterworth) |
+---------+------------------------------------------+
Low-pass filter example:
```c
ma_lpf_config config = ma_lpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
ma_result result = ma_lpf_init(&config, &lpf);
if (result != MA_SUCCESS) {
// Error.
}
...
ma_lpf_process_pcm_frames(&lpf, pFramesOut, pFramesIn, frameCount);
```
Supported formats are `ma_format_s16` and` ma_format_f32`. If you need to use a different format you need to convert it yourself beforehand. Input and output
frames are always interleaved.
Filtering can be applied in-place by passing in the same pointer for both the input and output buffers, like so:
```c
ma_lpf_process_pcm_frames(&lpf, pMyData, pMyData, frameCount);
```
The maximum filter order is limited to `MA_MAX_FILTER_ORDER` which is set to 8. If you need more, you can chain first and second order filters together.
```c
for (iFilter = 0; iFilter < filterCount; iFilter += 1) {
ma_lpf2_process_pcm_frames(&lpf2[iFilter], pMyData, pMyData, frameCount);
}
```
If you need to change the configuration of the filter, but need to maintain the state of internal registers you can do so with `ma_lpf_reinit()`. This may be
useful if you need to change the sample rate and/or cutoff frequency dynamically while maintaing smooth transitions. Note that changing the format or channel
count after initialization is invalid and will result in an error.
The `ma_lpf` object supports a configurable order, but if you only need a first order filter you may want to consider using `ma_lpf1`. Likewise, if you only
need a second order filter you can use `ma_lpf2`. The advantage of this is that they're lighter weight and a bit more efficient.
If an even filter order is specified, a series of second order filters will be processed in a chain. If an odd filter order is specified, a first order filter
will be applied, followed by a series of second order filters in a chain.
7.3. High-Pass Filtering
------------------------
High-pass filtering is achieved with the following APIs:
+---------+-------------------------------------------+
| API | Description |
+---------+-------------------------------------------+
| ma_hpf1 | First order high-pass filter |
| ma_hpf2 | Second order high-pass filter |
| ma_hpf | High order high-pass filter (Butterworth) |
+---------+-------------------------------------------+
High-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_hpf1`, `ma_hpf2` and `ma_hpf`. See example code for low-pass filters
for example usage.
7.4. Band-Pass Filtering
------------------------
Band-pass filtering is achieved with the following APIs:
+---------+-------------------------------+
| API | Description |
+---------+-------------------------------+
| ma_bpf2 | Second order band-pass filter |
| ma_bpf | High order band-pass filter |
+---------+-------------------------------+
Band-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_bpf2` and `ma_hpf`. See example code for low-pass filters for example
usage. Note that the order for band-pass filters must be an even number which means there is no first order band-pass filter, unlike low-pass and high-pass
filters.
7.5. Notch Filtering
--------------------
Notch filtering is achieved with the following APIs:
+-----------+------------------------------------------+
| API | Description |
+-----------+------------------------------------------+
| ma_notch2 | Second order notching filter |
+-----------+------------------------------------------+
7.6. Peaking EQ Filtering
-------------------------
Peaking filtering is achieved with the following APIs:
+----------+------------------------------------------+
| API | Description |
+----------+------------------------------------------+
| ma_peak2 | Second order peaking filter |
+----------+------------------------------------------+
7.7. Low Shelf Filtering
------------------------
Low shelf filtering is achieved with the following APIs:
+-------------+------------------------------------------+
| API | Description |
+-------------+------------------------------------------+
| ma_loshelf2 | Second order low shelf filter |
+-------------+------------------------------------------+
Where a high-pass filter is used to eliminate lower frequencies, a low shelf filter can be used to just turn them down rather than eliminate them entirely.
7.8. High Shelf Filtering
-------------------------
High shelf filtering is achieved with the following APIs:
+-------------+------------------------------------------+
| API | Description |
+-------------+------------------------------------------+
| ma_hishelf2 | Second order high shelf filter |
+-------------+------------------------------------------+
The high shelf filter has the same API as the low shelf filter, only you would use `ma_hishelf` instead of `ma_loshelf`. Where a low shelf filter is used to
adjust the volume of low frequencies, the high shelf filter does the same thing for high frequencies.
8. Waveform and Noise Generation
================================
8.1. Waveforms
--------------
miniaudio supports generation of sine, square, triangle and sawtooth waveforms. This is achieved with the `ma_waveform` API. Example:
```c
ma_waveform_config config = ma_waveform_config_init(
FORMAT,
CHANNELS,
SAMPLE_RATE,
ma_waveform_type_sine,
amplitude,
frequency);
ma_waveform waveform;
ma_result result = ma_waveform_init(&config, &waveform);
if (result != MA_SUCCESS) {
// Error.
}
...
ma_waveform_read_pcm_frames(&waveform, pOutput, frameCount);
```
The amplitude, frequency, type, and sample rate can be changed dynamically with `ma_waveform_set_amplitude()`, `ma_waveform_set_frequency()`,
`ma_waveform_set_type()`, and `ma_waveform_set_sample_rate()` respectively.
You can invert the waveform by setting the amplitude to a negative value. You can use this to control whether or not a sawtooth has a positive or negative
ramp, for example.
Below are the supported waveform types:
+---------------------------+
| Enum Name |
+---------------------------+
| ma_waveform_type_sine |
| ma_waveform_type_square |
| ma_waveform_type_triangle |
| ma_waveform_type_sawtooth |
+---------------------------+
8.2. Noise
----------
miniaudio supports generation of white, pink and Brownian noise via the `ma_noise` API. Example:
```c
ma_noise_config config = ma_noise_config_init(
FORMAT,
CHANNELS,
ma_noise_type_white,
SEED,
amplitude);
ma_noise noise;
ma_result result = ma_noise_init(&config, &noise);
if (result != MA_SUCCESS) {
// Error.
}
...
ma_noise_read_pcm_frames(&noise, pOutput, frameCount);
```
The noise API uses simple LCG random number generation. It supports a custom seed which is useful for things like automated testing requiring reproducibility.
Setting the seed to zero will default to `MA_DEFAULT_LCG_SEED`.
The amplitude, seed, and type can be changed dynamically with `ma_noise_set_amplitude()`, `ma_noise_set_seed()`, and `ma_noise_set_type()` respectively.
By default, the noise API will use different values for different channels. So, for example, the left side in a stereo stream will be different to the right
side. To instead have each channel use the same random value, set the `duplicateChannels` member of the noise config to true, like so:
```c
config.duplicateChannels = MA_TRUE;
```
Below are the supported noise types.
+------------------------+
| Enum Name |
+------------------------+
| ma_noise_type_white |
| ma_noise_type_pink |
| ma_noise_type_brownian |
+------------------------+
9. Audio Buffers
================
miniaudio supports reading from a buffer of raw audio data via the `ma_audio_buffer` API. This can read from memory that's managed by the application, but
can also handle the memory management for you internally. Memory management is flexible and should support most use cases.
Audio buffers are initialised using the standard configuration system used everywhere in miniaudio:
```c
ma_audio_buffer_config config = ma_audio_buffer_config_init(
format,
channels,
sizeInFrames,
pExistingData,
&allocationCallbacks);
ma_audio_buffer buffer;
result = ma_audio_buffer_init(&config, &buffer);
if (result != MA_SUCCESS) {
// Error.
}
...
ma_audio_buffer_uninit(&buffer);
```
In the example above, the memory pointed to by `pExistingData` will *not* be copied and is how an application can do self-managed memory allocation. If you
would rather make a copy of the data, use `ma_audio_buffer_init_copy()`. To uninitialize the buffer, use `ma_audio_buffer_uninit()`.
Sometimes it can be convenient to allocate the memory for the `ma_audio_buffer` structure and the raw audio data in a contiguous block of memory. That is,
the raw audio data will be located immediately after the `ma_audio_buffer` structure. To do this, use `ma_audio_buffer_alloc_and_init()`:
```c
ma_audio_buffer_config config = ma_audio_buffer_config_init(
format,
channels,
sizeInFrames,
pExistingData,
&allocationCallbacks);
ma_audio_buffer* pBuffer
result = ma_audio_buffer_alloc_and_init(&config, &pBuffer);
if (result != MA_SUCCESS) {
// Error
}
...
ma_audio_buffer_uninit_and_free(&buffer);
```
If you initialize the buffer with `ma_audio_buffer_alloc_and_init()` you should uninitialize it with `ma_audio_buffer_uninit_and_free()`. In the example above,
the memory pointed to by `pExistingData` will be copied into the buffer, which is contrary to the behavior of `ma_audio_buffer_init()`.
An audio buffer has a playback cursor just like a decoder. As you read frames from the buffer, the cursor moves forward. The last parameter (`loop`) can be
used to determine if the buffer should loop. The return value is the number of frames actually read. If this is less than the number of frames requested it
means the end has been reached. This should never happen if the `loop` parameter is set to true. If you want to manually loop back to the start, you can do so
with with `ma_audio_buffer_seek_to_pcm_frame(pAudioBuffer, 0)`. Below is an example for reading data from an audio buffer.
```c
ma_uint64 framesRead = ma_audio_buffer_read_pcm_frames(pAudioBuffer, pFramesOut, desiredFrameCount, isLooping);
if (framesRead < desiredFrameCount) {
// If not looping, this means the end has been reached. This should never happen in looping mode with valid input.
}
```
Sometimes you may want to avoid the cost of data movement between the internal buffer and the output buffer. Instead you can use memory mapping to retrieve a
pointer to a segment of data:
```c
void* pMappedFrames;
ma_uint64 frameCount = frameCountToTryMapping;
ma_result result = ma_audio_buffer_map(pAudioBuffer, &pMappedFrames, &frameCount);
if (result == MA_SUCCESS) {
// Map was successful. The value in frameCount will be how many frames were _actually_ mapped, which may be
// less due to the end of the buffer being reached.
ma_copy_pcm_frames(pFramesOut, pMappedFrames, frameCount, pAudioBuffer->format, pAudioBuffer->channels);
// You must unmap the buffer.
ma_audio_buffer_unmap(pAudioBuffer, frameCount);
}
```
When you use memory mapping, the read cursor is increment by the frame count passed in to `ma_audio_buffer_unmap()`. If you decide not to process every frame
you can pass in a value smaller than the value returned by `ma_audio_buffer_map()`. The disadvantage to using memory mapping is that it does not handle looping
for you. You can determine if the buffer is at the end for the purpose of looping with `ma_audio_buffer_at_end()` or by inspecting the return value of
`ma_audio_buffer_unmap()` and checking if it equals `MA_AT_END`. You should not treat `MA_AT_END` as an error when returned by `ma_audio_buffer_unmap()`.
10. Ring Buffers
================
miniaudio supports lock free (single producer, single consumer) ring buffers which are exposed via the `ma_rb` and `ma_pcm_rb` APIs. The `ma_rb` API operates
on bytes, whereas the `ma_pcm_rb` operates on PCM frames. They are otherwise identical as `ma_pcm_rb` is just a wrapper around `ma_rb`.
Unlike most other APIs in miniaudio, ring buffers support both interleaved and deinterleaved streams. The caller can also allocate their own backing memory for
the ring buffer to use internally for added flexibility. Otherwise the ring buffer will manage it's internal memory for you.
The examples below use the PCM frame variant of the ring buffer since that's most likely the one you will want to use. To initialize a ring buffer, do
something like the following:
```c
ma_pcm_rb rb;
ma_result result = ma_pcm_rb_init(FORMAT, CHANNELS, BUFFER_SIZE_IN_FRAMES, NULL, NULL, &rb);
if (result != MA_SUCCESS) {
// Error
}
```
The `ma_pcm_rb_init()` function takes the sample format and channel count as parameters because it's the PCM varient of the ring buffer API. For the regular
ring buffer that operates on bytes you would call `ma_rb_init()` which leaves these out and just takes the size of the buffer in bytes instead of frames. The
fourth parameter is an optional pre-allocated buffer and the fifth parameter is a pointer to a `ma_allocation_callbacks` structure for custom memory allocation
routines. Passing in `NULL` for this results in `MA_MALLOC()` and `MA_FREE()` being used.
Use `ma_pcm_rb_init_ex()` if you need a deinterleaved buffer. The data for each sub-buffer is offset from each other based on the stride. To manage your
sub-buffers you can use `ma_pcm_rb_get_subbuffer_stride()`, `ma_pcm_rb_get_subbuffer_offset()` and `ma_pcm_rb_get_subbuffer_ptr()`.
Use `ma_pcm_rb_acquire_read()` and `ma_pcm_rb_acquire_write()` to retrieve a pointer to a section of the ring buffer. You specify the number of frames you
need, and on output it will set to what was actually acquired. If the read or write pointer is positioned such that the number of frames requested will require
a loop, it will be clamped to the end of the buffer. Therefore, the number of frames you're given may be less than the number you requested.
After calling `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()`, you do your work on the buffer and then "commit" it with `ma_pcm_rb_commit_read()` or
`ma_pcm_rb_commit_write()`. This is where the read/write pointers are updated. When you commit you need to pass in the buffer that was returned by the earlier
call to `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()` and is only used for validation. The number of frames passed to `ma_pcm_rb_commit_read()` and
`ma_pcm_rb_commit_write()` is what's used to increment the pointers, and can be less that what was originally requested.
If you want to correct for drift between the write pointer and the read pointer you can use a combination of `ma_pcm_rb_pointer_distance()`,
`ma_pcm_rb_seek_read()` and `ma_pcm_rb_seek_write()`. Note that you can only move the pointers forward, and you should only move the read pointer forward via
the consumer thread, and the write pointer forward by the producer thread. If there is too much space between the pointers, move the read pointer forward. If
there is too little space between the pointers, move the write pointer forward.
You can use a ring buffer at the byte level instead of the PCM frame level by using the `ma_rb` API. This is exactly the same, only you will use the `ma_rb`
functions instead of `ma_pcm_rb` and instead of frame counts you will pass around byte counts.
The maximum size of the buffer in bytes is `0x7FFFFFFF-(MA_SIMD_ALIGNMENT-1)` due to the most significant bit being used to encode a loop flag and the internally
managed buffers always being aligned to MA_SIMD_ALIGNMENT.
Note that the ring buffer is only thread safe when used by a single consumer thread and single producer thread.
11. Backends
============
The following backends are supported by miniaudio.
+-------------+-----------------------+--------------------------------------------------------+
| Name | Enum Name | Supported Operating Systems |
+-------------+-----------------------+--------------------------------------------------------+
| WASAPI | ma_backend_wasapi | Windows Vista+ |
| DirectSound | ma_backend_dsound | Windows XP+ |
| WinMM | ma_backend_winmm | Windows XP+ (may work on older versions, but untested) |
| Core Audio | ma_backend_coreaudio | macOS, iOS |
| ALSA | ma_backend_alsa | Linux |
| PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) |
| JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) |
| sndio | ma_backend_sndio | OpenBSD |
| audio(4) | ma_backend_audio4 | NetBSD, OpenBSD |
| OSS | ma_backend_oss | FreeBSD |
| AAudio | ma_backend_aaudio | Android 8+ |
| OpenSL ES | ma_backend_opensl | Android (API level 16+) |
| Web Audio | ma_backend_webaudio | Web (via Emscripten) |
| Custom | ma_backend_custom | Cross Platform |
| Null | ma_backend_null | Cross Platform (not used on Web) |
+-------------+-----------------------+--------------------------------------------------------+
Some backends have some nuance details you may want to be aware of.
11.1. WASAPI
------------
- Low-latency shared mode will be disabled when using an application-defined sample rate which is different to the device's native sample rate. To work around
this, set `wasapi.noAutoConvertSRC` to true in the device config. This is due to IAudioClient3_InitializeSharedAudioStream() failing when the
`AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM` flag is specified. Setting wasapi.noAutoConvertSRC will result in miniaudio's internal resampler being used instead
which will in turn enable the use of low-latency shared mode.
11.2. PulseAudio
----------------
- If you experience bad glitching/noise on Arch Linux, consider this fix from the Arch wiki:
https://wiki.archlinux.org/index.php/PulseAudio/Troubleshooting#Glitches,_skips_or_crackling. Alternatively, consider using a different backend such as ALSA.
11.3. Android
-------------
- To capture audio on Android, remember to add the RECORD_AUDIO permission to your manifest: ``
- With OpenSL|ES, only a single ma_context can be active at any given time. This is due to a limitation with OpenSL|ES.
- With AAudio, only default devices are enumerated. This is due to AAudio not having an enumeration API (devices are enumerated through Java). You can however
perform your own device enumeration through Java and then set the ID in the ma_device_id structure (ma_device_id.aaudio) and pass it to ma_device_init().
- The backend API will perform resampling where possible. The reason for this as opposed to using miniaudio's built-in resampler is to take advantage of any
potential device-specific optimizations the driver may implement.
11.4. UWP
---------
- UWP only supports default playback and capture devices.
- UWP requires the Microphone capability to be enabled in the application's manifest (Package.appxmanifest):
```
...
```
11.5. Web Audio / Emscripten
----------------------------
- You cannot use `-std=c*` compiler flags, nor `-ansi`. This only applies to the Emscripten build.
- The first time a context is initialized it will create a global object called "miniaudio" whose primary purpose is to act as a factory for device objects.
- Currently the Web Audio backend uses ScriptProcessorNode's, but this may need to change later as they've been deprecated.
- Google has implemented a policy in their browsers that prevent automatic media output without first receiving some kind of user input. The following web page
has additional details: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes. Starting the device may fail if you try to start playback
without first handling some kind of user input.
12. Miscellaneous Notes
=======================
- Automatic stream routing is enabled on a per-backend basis. Support is explicitly enabled for WASAPI and Core Audio, however other backends such as
PulseAudio may naturally support it, though not all have been tested.
- The contents of the output buffer passed into the data callback will always be pre-initialized to silence unless the `noPreZeroedOutputBuffer` config variable
in `ma_device_config` is set to true, in which case it'll be undefined which will require you to write something to the entire buffer.
- By default miniaudio will automatically clip samples. This only applies when the playback sample format is configured as `ma_format_f32`. If you are doing
clipping yourself, you can disable this overhead by setting `noClip` to true in the device config.
- The sndio backend is currently only enabled on OpenBSD builds.
- The audio(4) backend is supported on OpenBSD, but you may need to disable sndiod before you can use it.
- Note that GCC and Clang requires `-msse2`, `-mavx2`, etc. for SIMD optimizations.
- When compiling with VC6 and earlier, decoding is restricted to files less than 2GB in size. This is due to 64-bit file APIs not being available.
*/
#ifndef miniaudio_h
#define miniaudio_h
#ifdef __cplusplus
extern "C" {
#endif
#define MA_STRINGIFY(x) #x
#define MA_XSTRINGIFY(x) MA_STRINGIFY(x)
#define MA_VERSION_MAJOR 0
#define MA_VERSION_MINOR 10
#define MA_VERSION_REVISION 31
#define MA_VERSION_STRING MA_XSTRINGIFY(MA_VERSION_MAJOR) "." MA_XSTRINGIFY(MA_VERSION_MINOR) "." MA_XSTRINGIFY(MA_VERSION_REVISION)
#if defined(_MSC_VER) && !defined(__clang__)
#pragma warning(push)
#pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
#pragma warning(disable:4214) /* nonstandard extension used: bit field types other than int */
#pragma warning(disable:4324) /* structure was padded due to alignment specifier */
#elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
#if defined(__clang__)
#pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */
#endif
#endif
/* Platform/backend detection. */
#ifdef _WIN32
#define MA_WIN32
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP || WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
#define MA_WIN32_UWP
#else
#define MA_WIN32_DESKTOP
#endif
#else
#define MA_POSIX
#include /* Unfortunate #include, but needed for pthread_t, pthread_mutex_t and pthread_cond_t types. */
#ifdef __unix__
#define MA_UNIX
#if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
#define MA_BSD
#endif
#endif
#ifdef __linux__
#define MA_LINUX
#endif
#ifdef __APPLE__
#define MA_APPLE
#endif
#ifdef __ANDROID__
#define MA_ANDROID
#endif
#ifdef __EMSCRIPTEN__
#define MA_EMSCRIPTEN
#endif
#endif
#include /* For size_t. */
/* Sized types. */
typedef signed char ma_int8;
typedef unsigned char ma_uint8;
typedef signed short ma_int16;
typedef unsigned short ma_uint16;
typedef signed int ma_int32;
typedef unsigned int ma_uint32;
#if defined(_MSC_VER)
typedef signed __int64 ma_int64;
typedef unsigned __int64 ma_uint64;
#else
#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlong-long"
#if defined(__clang__)
#pragma GCC diagnostic ignored "-Wc++11-long-long"
#endif
#endif
typedef signed long long ma_int64;
typedef unsigned long long ma_uint64;
#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
#pragma GCC diagnostic pop
#endif
#endif
#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
typedef ma_uint64 ma_uintptr;
#else
typedef ma_uint32 ma_uintptr;
#endif
typedef ma_uint8 ma_bool8;
typedef ma_uint32 ma_bool32;
#define MA_TRUE 1
#define MA_FALSE 0
typedef void* ma_handle;
typedef void* ma_ptr;
typedef void (* ma_proc)(void);
#if defined(_MSC_VER) && !defined(_WCHAR_T_DEFINED)
typedef ma_uint16 wchar_t;
#endif
/* Define NULL for some compilers. */
#ifndef NULL
#define NULL 0
#endif
#if defined(SIZE_MAX)
#define MA_SIZE_MAX SIZE_MAX
#else
#define MA_SIZE_MAX 0xFFFFFFFF /* When SIZE_MAX is not defined by the standard library just default to the maximum 32-bit unsigned integer. */
#endif
#ifdef _MSC_VER
#define MA_INLINE __forceinline
#elif defined(__GNUC__)
/*
I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when
the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some
case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the
command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue
I am using "__inline__" only when we're compiling in strict ANSI mode.
*/
#if defined(__STRICT_ANSI__)
#define MA_INLINE __inline__ __attribute__((always_inline))
#else
#define MA_INLINE inline __attribute__((always_inline))
#endif
#elif defined(__WATCOMC__)
#define MA_INLINE __inline
#else
#define MA_INLINE
#endif
#if !defined(MA_API)
#if defined(MA_DLL)
#if defined(_WIN32)
#define MA_DLL_IMPORT __declspec(dllimport)
#define MA_DLL_EXPORT __declspec(dllexport)
#define MA_DLL_PRIVATE static
#else
#if defined(__GNUC__) && __GNUC__ >= 4
#define MA_DLL_IMPORT __attribute__((visibility("default")))
#define MA_DLL_EXPORT __attribute__((visibility("default")))
#define MA_DLL_PRIVATE __attribute__((visibility("hidden")))
#else
#define MA_DLL_IMPORT
#define MA_DLL_EXPORT
#define MA_DLL_PRIVATE static
#endif
#endif
#if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION)
#define MA_API MA_DLL_EXPORT
#else
#define MA_API MA_DLL_IMPORT
#endif
#define MA_PRIVATE MA_DLL_PRIVATE
#else
#define MA_API extern
#define MA_PRIVATE static
#endif
#endif
/* SIMD alignment in bytes. Currently set to 64 bytes in preparation for future AVX-512 optimizations. */
#define MA_SIMD_ALIGNMENT 64
/*
Logging Levels
==============
A log level will automatically include the lower levels. For example, verbose logging will enable everything. The warning log level will only include warnings
and errors, but will ignore informational and verbose logging. If you only want to handle a specific log level, implement a custom log callback (see
ma_context_init() for details) and interrogate the `logLevel` parameter.
By default the log level will be set to MA_LOG_LEVEL_ERROR, but you can change this by defining MA_LOG_LEVEL before the implementation of miniaudio.
MA_LOG_LEVEL_VERBOSE
Mainly intended for debugging. This will enable all log levels and can be triggered from within the data callback so care must be taken when enabling this
in production environments.
MA_LOG_LEVEL_INFO
Informational logging. Useful for debugging. This will also enable warning and error logs. This will never be called from within the data callback.
MA_LOG_LEVEL_WARNING
Warnings. You should enable this in you development builds and action them when encounted. This will also enable error logs. These logs usually indicate a
potential problem or misconfiguration, but still allow you to keep running. This will never be called from within the data callback.
MA_LOG_LEVEL_ERROR
Error logging. This will be fired when an operation fails and is subsequently aborted. This can be fired from within the data callback, in which case the
device will be stopped. You should always have this log level enabled.
*/
#define MA_LOG_LEVEL_VERBOSE 4
#define MA_LOG_LEVEL_INFO 3
#define MA_LOG_LEVEL_WARNING 2
#define MA_LOG_LEVEL_ERROR 1
#ifndef MA_LOG_LEVEL
#define MA_LOG_LEVEL MA_LOG_LEVEL_ERROR
#endif
/*
An annotation for variables which must be used atomically. This doesn't actually do anything - it's
just used as a way for humans to identify variables that should be used atomically.
*/
#define MA_ATOMIC
typedef struct ma_context ma_context;
typedef struct ma_device ma_device;
typedef ma_uint8 ma_channel;
#define MA_CHANNEL_NONE 0
#define MA_CHANNEL_MONO 1
#define MA_CHANNEL_FRONT_LEFT 2
#define MA_CHANNEL_FRONT_RIGHT 3
#define MA_CHANNEL_FRONT_CENTER 4
#define MA_CHANNEL_LFE 5
#define MA_CHANNEL_BACK_LEFT 6
#define MA_CHANNEL_BACK_RIGHT 7
#define MA_CHANNEL_FRONT_LEFT_CENTER 8
#define MA_CHANNEL_FRONT_RIGHT_CENTER 9
#define MA_CHANNEL_BACK_CENTER 10
#define MA_CHANNEL_SIDE_LEFT 11
#define MA_CHANNEL_SIDE_RIGHT 12
#define MA_CHANNEL_TOP_CENTER 13
#define MA_CHANNEL_TOP_FRONT_LEFT 14
#define MA_CHANNEL_TOP_FRONT_CENTER 15
#define MA_CHANNEL_TOP_FRONT_RIGHT 16
#define MA_CHANNEL_TOP_BACK_LEFT 17
#define MA_CHANNEL_TOP_BACK_CENTER 18
#define MA_CHANNEL_TOP_BACK_RIGHT 19
#define MA_CHANNEL_AUX_0 20
#define MA_CHANNEL_AUX_1 21
#define MA_CHANNEL_AUX_2 22
#define MA_CHANNEL_AUX_3 23
#define MA_CHANNEL_AUX_4 24
#define MA_CHANNEL_AUX_5 25
#define MA_CHANNEL_AUX_6 26
#define MA_CHANNEL_AUX_7 27
#define MA_CHANNEL_AUX_8 28
#define MA_CHANNEL_AUX_9 29
#define MA_CHANNEL_AUX_10 30
#define MA_CHANNEL_AUX_11 31
#define MA_CHANNEL_AUX_12 32
#define MA_CHANNEL_AUX_13 33
#define MA_CHANNEL_AUX_14 34
#define MA_CHANNEL_AUX_15 35
#define MA_CHANNEL_AUX_16 36
#define MA_CHANNEL_AUX_17 37
#define MA_CHANNEL_AUX_18 38
#define MA_CHANNEL_AUX_19 39
#define MA_CHANNEL_AUX_20 40
#define MA_CHANNEL_AUX_21 41
#define MA_CHANNEL_AUX_22 42
#define MA_CHANNEL_AUX_23 43
#define MA_CHANNEL_AUX_24 44
#define MA_CHANNEL_AUX_25 45
#define MA_CHANNEL_AUX_26 46
#define MA_CHANNEL_AUX_27 47
#define MA_CHANNEL_AUX_28 48
#define MA_CHANNEL_AUX_29 49
#define MA_CHANNEL_AUX_30 50
#define MA_CHANNEL_AUX_31 51
#define MA_CHANNEL_LEFT MA_CHANNEL_FRONT_LEFT
#define MA_CHANNEL_RIGHT MA_CHANNEL_FRONT_RIGHT
#define MA_CHANNEL_POSITION_COUNT (MA_CHANNEL_AUX_31 + 1)
typedef int ma_result;
#define MA_SUCCESS 0
#define MA_ERROR -1 /* A generic error. */
#define MA_INVALID_ARGS -2
#define MA_INVALID_OPERATION -3
#define MA_OUT_OF_MEMORY -4
#define MA_OUT_OF_RANGE -5
#define MA_ACCESS_DENIED -6
#define MA_DOES_NOT_EXIST -7
#define MA_ALREADY_EXISTS -8
#define MA_TOO_MANY_OPEN_FILES -9
#define MA_INVALID_FILE -10
#define MA_TOO_BIG -11
#define MA_PATH_TOO_LONG -12
#define MA_NAME_TOO_LONG -13
#define MA_NOT_DIRECTORY -14
#define MA_IS_DIRECTORY -15
#define MA_DIRECTORY_NOT_EMPTY -16
#define MA_END_OF_FILE -17
#define MA_NO_SPACE -18
#define MA_BUSY -19
#define MA_IO_ERROR -20
#define MA_INTERRUPT -21
#define MA_UNAVAILABLE -22
#define MA_ALREADY_IN_USE -23
#define MA_BAD_ADDRESS -24
#define MA_BAD_SEEK -25
#define MA_BAD_PIPE -26
#define MA_DEADLOCK -27
#define MA_TOO_MANY_LINKS -28
#define MA_NOT_IMPLEMENTED -29
#define MA_NO_MESSAGE -30
#define MA_BAD_MESSAGE -31
#define MA_NO_DATA_AVAILABLE -32
#define MA_INVALID_DATA -33
#define MA_TIMEOUT -34
#define MA_NO_NETWORK -35
#define MA_NOT_UNIQUE -36
#define MA_NOT_SOCKET -37
#define MA_NO_ADDRESS -38
#define MA_BAD_PROTOCOL -39
#define MA_PROTOCOL_UNAVAILABLE -40
#define MA_PROTOCOL_NOT_SUPPORTED -41
#define MA_PROTOCOL_FAMILY_NOT_SUPPORTED -42
#define MA_ADDRESS_FAMILY_NOT_SUPPORTED -43
#define MA_SOCKET_NOT_SUPPORTED -44
#define MA_CONNECTION_RESET -45
#define MA_ALREADY_CONNECTED -46
#define MA_NOT_CONNECTED -47
#define MA_CONNECTION_REFUSED -48
#define MA_NO_HOST -49
#define MA_IN_PROGRESS -50
#define MA_CANCELLED -51
#define MA_MEMORY_ALREADY_MAPPED -52
#define MA_AT_END -53
/* General miniaudio-specific errors. */
#define MA_FORMAT_NOT_SUPPORTED -100
#define MA_DEVICE_TYPE_NOT_SUPPORTED -101
#define MA_SHARE_MODE_NOT_SUPPORTED -102
#define MA_NO_BACKEND -103
#define MA_NO_DEVICE -104
#define MA_API_NOT_FOUND -105
#define MA_INVALID_DEVICE_CONFIG -106
#define MA_LOOP -107
/* State errors. */
#define MA_DEVICE_NOT_INITIALIZED -200
#define MA_DEVICE_ALREADY_INITIALIZED -201
#define MA_DEVICE_NOT_STARTED -202
#define MA_DEVICE_NOT_STOPPED -203
/* Operation errors. */
#define MA_FAILED_TO_INIT_BACKEND -300
#define MA_FAILED_TO_OPEN_BACKEND_DEVICE -301
#define MA_FAILED_TO_START_BACKEND_DEVICE -302
#define MA_FAILED_TO_STOP_BACKEND_DEVICE -303
/* Standard sample rates. */
#define MA_SAMPLE_RATE_8000 8000
#define MA_SAMPLE_RATE_11025 11025
#define MA_SAMPLE_RATE_16000 16000
#define MA_SAMPLE_RATE_22050 22050
#define MA_SAMPLE_RATE_24000 24000
#define MA_SAMPLE_RATE_32000 32000
#define MA_SAMPLE_RATE_44100 44100
#define MA_SAMPLE_RATE_48000 48000
#define MA_SAMPLE_RATE_88200 88200
#define MA_SAMPLE_RATE_96000 96000
#define MA_SAMPLE_RATE_176400 176400
#define MA_SAMPLE_RATE_192000 192000
#define MA_SAMPLE_RATE_352800 352800
#define MA_SAMPLE_RATE_384000 384000
#define MA_MIN_CHANNELS 1
#ifndef MA_MAX_CHANNELS
#define MA_MAX_CHANNELS 32
#endif
#define MA_MIN_SAMPLE_RATE MA_SAMPLE_RATE_8000
#define MA_MAX_SAMPLE_RATE MA_SAMPLE_RATE_384000
#ifndef MA_MAX_FILTER_ORDER
#define MA_MAX_FILTER_ORDER 8
#endif
typedef enum
{
ma_stream_format_pcm = 0
} ma_stream_format;
typedef enum
{
ma_stream_layout_interleaved = 0,
ma_stream_layout_deinterleaved
} ma_stream_layout;
typedef enum
{
ma_dither_mode_none = 0,
ma_dither_mode_rectangle,
ma_dither_mode_triangle
} ma_dither_mode;
typedef enum
{
/*
I like to keep these explicitly defined because they're used as a key into a lookup table. When items are
added to this, make sure there are no gaps and that they're added to the lookup table in ma_get_bytes_per_sample().
*/
ma_format_unknown = 0, /* Mainly used for indicating an error, but also used as the default for the output format for decoders. */
ma_format_u8 = 1,
ma_format_s16 = 2, /* Seems to be the most widely supported format. */
ma_format_s24 = 3, /* Tightly packed. 3 bytes per sample. */
ma_format_s32 = 4,
ma_format_f32 = 5,
ma_format_count
} ma_format;
typedef enum
{
ma_channel_mix_mode_rectangular = 0, /* Simple averaging based on the plane(s) the channel is sitting on. */
ma_channel_mix_mode_simple, /* Drop excess channels; zeroed out extra channels. */
ma_channel_mix_mode_custom_weights, /* Use custom weights specified in ma_channel_router_config. */
ma_channel_mix_mode_planar_blend = ma_channel_mix_mode_rectangular,
ma_channel_mix_mode_default = ma_channel_mix_mode_planar_blend
} ma_channel_mix_mode;
typedef enum
{
ma_standard_channel_map_microsoft,
ma_standard_channel_map_alsa,
ma_standard_channel_map_rfc3551, /* Based off AIFF. */
ma_standard_channel_map_flac,
ma_standard_channel_map_vorbis,
ma_standard_channel_map_sound4, /* FreeBSD's sound(4). */
ma_standard_channel_map_sndio, /* www.sndio.org/tips.html */
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. */
ma_standard_channel_map_default = ma_standard_channel_map_microsoft
} ma_standard_channel_map;
typedef enum
{
ma_performance_profile_low_latency = 0,
ma_performance_profile_conservative
} ma_performance_profile;
typedef struct
{
void* pUserData;
void* (* onMalloc)(size_t sz, void* pUserData);
void* (* onRealloc)(void* p, size_t sz, void* pUserData);
void (* onFree)(void* p, void* pUserData);
} ma_allocation_callbacks;
typedef struct
{
ma_int32 state;
} ma_lcg;
#ifndef MA_NO_THREADING
/* Thread priorities should be ordered such that the default priority of the worker thread is 0. */
typedef enum
{
ma_thread_priority_idle = -5,
ma_thread_priority_lowest = -4,
ma_thread_priority_low = -3,
ma_thread_priority_normal = -2,
ma_thread_priority_high = -1,
ma_thread_priority_highest = 0,
ma_thread_priority_realtime = 1,
ma_thread_priority_default = 0
} ma_thread_priority;
typedef unsigned char ma_spinlock;
#if defined(MA_WIN32)
typedef ma_handle ma_thread;
#endif
#if defined(MA_POSIX)
typedef pthread_t ma_thread;
#endif
#if defined(MA_WIN32)
typedef ma_handle ma_mutex;
#endif
#if defined(MA_POSIX)
typedef pthread_mutex_t ma_mutex;
#endif
#if defined(MA_WIN32)
typedef ma_handle ma_event;
#endif
#if defined(MA_POSIX)
typedef struct
{
ma_uint32 value;
pthread_mutex_t lock;
pthread_cond_t cond;
} ma_event;
#endif /* MA_POSIX */
#if defined(MA_WIN32)
typedef ma_handle ma_semaphore;
#endif
#if defined(MA_POSIX)
typedef struct
{
int value;
pthread_mutex_t lock;
pthread_cond_t cond;
} ma_semaphore;
#endif /* MA_POSIX */
#else
/* 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. */
#ifndef MA_NO_DEVICE_IO
#error "MA_NO_THREADING cannot be used without MA_NO_DEVICE_IO";
#endif
#endif /* MA_NO_THREADING */
/*
Retrieves the version of miniaudio as separated integers. Each component can be NULL if it's not required.
*/
MA_API void ma_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision);
/*
Retrieves the version of miniaudio as a string which can be useful for logging purposes.
*/
MA_API const char* ma_version_string(void);
/**************************************************************************************************************************************************************
Biquad Filtering
**************************************************************************************************************************************************************/
typedef union
{
float f32;
ma_int32 s32;
} ma_biquad_coefficient;
typedef struct
{
ma_format format;
ma_uint32 channels;
double b0;
double b1;
double b2;
double a0;
double a1;
double a2;
} ma_biquad_config;
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);
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_biquad_coefficient b0;
ma_biquad_coefficient b1;
ma_biquad_coefficient b2;
ma_biquad_coefficient a1;
ma_biquad_coefficient a2;
ma_biquad_coefficient r1[MA_MAX_CHANNELS];
ma_biquad_coefficient r2[MA_MAX_CHANNELS];
} ma_biquad;
MA_API ma_result ma_biquad_init(const ma_biquad_config* pConfig, ma_biquad* pBQ);
MA_API ma_result ma_biquad_reinit(const ma_biquad_config* pConfig, ma_biquad* pBQ);
MA_API ma_result ma_biquad_process_pcm_frames(ma_biquad* pBQ, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_biquad_get_latency(const ma_biquad* pBQ);
/**************************************************************************************************************************************************************
Low-Pass Filtering
**************************************************************************************************************************************************************/
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
double cutoffFrequency;
double q;
} ma_lpf1_config, ma_lpf2_config;
MA_API ma_lpf1_config ma_lpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency);
MA_API ma_lpf2_config ma_lpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_biquad_coefficient a;
ma_biquad_coefficient r1[MA_MAX_CHANNELS];
} ma_lpf1;
MA_API ma_result ma_lpf1_init(const ma_lpf1_config* pConfig, ma_lpf1* pLPF);
MA_API ma_result ma_lpf1_reinit(const ma_lpf1_config* pConfig, ma_lpf1* pLPF);
MA_API ma_result ma_lpf1_process_pcm_frames(ma_lpf1* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_lpf1_get_latency(const ma_lpf1* pLPF);
typedef struct
{
ma_biquad bq; /* The second order low-pass filter is implemented as a biquad filter. */
} ma_lpf2;
MA_API ma_result ma_lpf2_init(const ma_lpf2_config* pConfig, ma_lpf2* pLPF);
MA_API ma_result ma_lpf2_reinit(const ma_lpf2_config* pConfig, ma_lpf2* pLPF);
MA_API ma_result ma_lpf2_process_pcm_frames(ma_lpf2* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_lpf2_get_latency(const ma_lpf2* pLPF);
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
double cutoffFrequency;
ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
} ma_lpf_config;
MA_API ma_lpf_config ma_lpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
ma_uint32 lpf1Count;
ma_uint32 lpf2Count;
ma_lpf1 lpf1[1];
ma_lpf2 lpf2[MA_MAX_FILTER_ORDER/2];
} ma_lpf;
MA_API ma_result ma_lpf_init(const ma_lpf_config* pConfig, ma_lpf* pLPF);
MA_API ma_result ma_lpf_reinit(const ma_lpf_config* pConfig, ma_lpf* pLPF);
MA_API ma_result ma_lpf_process_pcm_frames(ma_lpf* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_lpf_get_latency(const ma_lpf* pLPF);
/**************************************************************************************************************************************************************
High-Pass Filtering
**************************************************************************************************************************************************************/
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
double cutoffFrequency;
double q;
} ma_hpf1_config, ma_hpf2_config;
MA_API ma_hpf1_config ma_hpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency);
MA_API ma_hpf2_config ma_hpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_biquad_coefficient a;
ma_biquad_coefficient r1[MA_MAX_CHANNELS];
} ma_hpf1;
MA_API ma_result ma_hpf1_init(const ma_hpf1_config* pConfig, ma_hpf1* pHPF);
MA_API ma_result ma_hpf1_reinit(const ma_hpf1_config* pConfig, ma_hpf1* pHPF);
MA_API ma_result ma_hpf1_process_pcm_frames(ma_hpf1* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_hpf1_get_latency(const ma_hpf1* pHPF);
typedef struct
{
ma_biquad bq; /* The second order high-pass filter is implemented as a biquad filter. */
} ma_hpf2;
MA_API ma_result ma_hpf2_init(const ma_hpf2_config* pConfig, ma_hpf2* pHPF);
MA_API ma_result ma_hpf2_reinit(const ma_hpf2_config* pConfig, ma_hpf2* pHPF);
MA_API ma_result ma_hpf2_process_pcm_frames(ma_hpf2* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_hpf2_get_latency(const ma_hpf2* pHPF);
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
double cutoffFrequency;
ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
} ma_hpf_config;
MA_API ma_hpf_config ma_hpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
ma_uint32 hpf1Count;
ma_uint32 hpf2Count;
ma_hpf1 hpf1[1];
ma_hpf2 hpf2[MA_MAX_FILTER_ORDER/2];
} ma_hpf;
MA_API ma_result ma_hpf_init(const ma_hpf_config* pConfig, ma_hpf* pHPF);
MA_API ma_result ma_hpf_reinit(const ma_hpf_config* pConfig, ma_hpf* pHPF);
MA_API ma_result ma_hpf_process_pcm_frames(ma_hpf* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_hpf_get_latency(const ma_hpf* pHPF);
/**************************************************************************************************************************************************************
Band-Pass Filtering
**************************************************************************************************************************************************************/
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
double cutoffFrequency;
double q;
} ma_bpf2_config;
MA_API ma_bpf2_config ma_bpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
typedef struct
{
ma_biquad bq; /* The second order band-pass filter is implemented as a biquad filter. */
} ma_bpf2;
MA_API ma_result ma_bpf2_init(const ma_bpf2_config* pConfig, ma_bpf2* pBPF);
MA_API ma_result ma_bpf2_reinit(const ma_bpf2_config* pConfig, ma_bpf2* pBPF);
MA_API ma_result ma_bpf2_process_pcm_frames(ma_bpf2* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_bpf2_get_latency(const ma_bpf2* pBPF);
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
double cutoffFrequency;
ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
} ma_bpf_config;
MA_API ma_bpf_config ma_bpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 bpf2Count;
ma_bpf2 bpf2[MA_MAX_FILTER_ORDER/2];
} ma_bpf;
MA_API ma_result ma_bpf_init(const ma_bpf_config* pConfig, ma_bpf* pBPF);
MA_API ma_result ma_bpf_reinit(const ma_bpf_config* pConfig, ma_bpf* pBPF);
MA_API ma_result ma_bpf_process_pcm_frames(ma_bpf* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_bpf_get_latency(const ma_bpf* pBPF);
/**************************************************************************************************************************************************************
Notching Filter
**************************************************************************************************************************************************************/
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
double q;
double frequency;
} ma_notch2_config;
MA_API ma_notch2_config ma_notch2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency);
typedef struct
{
ma_biquad bq;
} ma_notch2;
MA_API ma_result ma_notch2_init(const ma_notch2_config* pConfig, ma_notch2* pFilter);
MA_API ma_result ma_notch2_reinit(const ma_notch2_config* pConfig, ma_notch2* pFilter);
MA_API ma_result ma_notch2_process_pcm_frames(ma_notch2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_notch2_get_latency(const ma_notch2* pFilter);
/**************************************************************************************************************************************************************
Peaking EQ Filter
**************************************************************************************************************************************************************/
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
double gainDB;
double q;
double frequency;
} ma_peak2_config;
MA_API ma_peak2_config ma_peak2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
typedef struct
{
ma_biquad bq;
} ma_peak2;
MA_API ma_result ma_peak2_init(const ma_peak2_config* pConfig, ma_peak2* pFilter);
MA_API ma_result ma_peak2_reinit(const ma_peak2_config* pConfig, ma_peak2* pFilter);
MA_API ma_result ma_peak2_process_pcm_frames(ma_peak2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_peak2_get_latency(const ma_peak2* pFilter);
/**************************************************************************************************************************************************************
Low Shelf Filter
**************************************************************************************************************************************************************/
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
double gainDB;
double shelfSlope;
double frequency;
} ma_loshelf2_config;
MA_API ma_loshelf2_config ma_loshelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency);
typedef struct
{
ma_biquad bq;
} ma_loshelf2;
MA_API ma_result ma_loshelf2_init(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter);
MA_API ma_result ma_loshelf2_reinit(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter);
MA_API ma_result ma_loshelf2_process_pcm_frames(ma_loshelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_loshelf2_get_latency(const ma_loshelf2* pFilter);
/**************************************************************************************************************************************************************
High Shelf Filter
**************************************************************************************************************************************************************/
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
double gainDB;
double shelfSlope;
double frequency;
} ma_hishelf2_config;
MA_API ma_hishelf2_config ma_hishelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency);
typedef struct
{
ma_biquad bq;
} ma_hishelf2;
MA_API ma_result ma_hishelf2_init(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter);
MA_API ma_result ma_hishelf2_reinit(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter);
MA_API ma_result ma_hishelf2_process_pcm_frames(ma_hishelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
MA_API ma_uint32 ma_hishelf2_get_latency(const ma_hishelf2* pFilter);
/************************************************************************************************************************************************************
*************************************************************************************************************************************************************
DATA CONVERSION
===============
This section contains the APIs for data conversion. You will find everything here for channel mapping, sample format conversion, resampling, etc.
*************************************************************************************************************************************************************
************************************************************************************************************************************************************/
/**************************************************************************************************************************************************************
Resampling
**************************************************************************************************************************************************************/
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRateIn;
ma_uint32 sampleRateOut;
ma_uint32 lpfOrder; /* The low-pass filter order. Setting this to 0 will disable low-pass filtering. */
double lpfNyquistFactor; /* 0..1. Defaults to 1. 1 = Half the sampling frequency (Nyquist Frequency), 0.5 = Quarter the sampling frequency (half Nyquest Frequency), etc. */
} ma_linear_resampler_config;
MA_API ma_linear_resampler_config ma_linear_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
typedef struct
{
ma_linear_resampler_config config;
ma_uint32 inAdvanceInt;
ma_uint32 inAdvanceFrac;
ma_uint32 inTimeInt;
ma_uint32 inTimeFrac;
union
{
float f32[MA_MAX_CHANNELS];
ma_int16 s16[MA_MAX_CHANNELS];
} x0; /* The previous input frame. */
union
{
float f32[MA_MAX_CHANNELS];
ma_int16 s16[MA_MAX_CHANNELS];
} x1; /* The next input frame. */
ma_lpf lpf;
} ma_linear_resampler;
MA_API ma_result ma_linear_resampler_init(const ma_linear_resampler_config* pConfig, ma_linear_resampler* pResampler);
MA_API void ma_linear_resampler_uninit(ma_linear_resampler* pResampler);
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);
MA_API ma_result ma_linear_resampler_set_rate(ma_linear_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
MA_API ma_result ma_linear_resampler_set_rate_ratio(ma_linear_resampler* pResampler, float ratioInOut);
MA_API ma_uint64 ma_linear_resampler_get_required_input_frame_count(const ma_linear_resampler* pResampler, ma_uint64 outputFrameCount);
MA_API ma_uint64 ma_linear_resampler_get_expected_output_frame_count(const ma_linear_resampler* pResampler, ma_uint64 inputFrameCount);
MA_API ma_uint64 ma_linear_resampler_get_input_latency(const ma_linear_resampler* pResampler);
MA_API ma_uint64 ma_linear_resampler_get_output_latency(const ma_linear_resampler* pResampler);
typedef enum
{
ma_resample_algorithm_linear = 0, /* Fastest, lowest quality. Optional low-pass filtering. Default. */
ma_resample_algorithm_speex
} ma_resample_algorithm;
typedef struct
{
ma_format format; /* Must be either ma_format_f32 or ma_format_s16. */
ma_uint32 channels;
ma_uint32 sampleRateIn;
ma_uint32 sampleRateOut;
ma_resample_algorithm algorithm;
struct
{
ma_uint32 lpfOrder;
double lpfNyquistFactor;
} linear;
struct
{
int quality; /* 0 to 10. Defaults to 3. */
} speex;
} ma_resampler_config;
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);
typedef struct
{
ma_resampler_config config;
union
{
ma_linear_resampler linear;
struct
{
void* pSpeexResamplerState; /* SpeexResamplerState* */
} speex;
} state;
} ma_resampler;
/*
Initializes a new resampler object from a config.
*/
MA_API ma_result ma_resampler_init(const ma_resampler_config* pConfig, ma_resampler* pResampler);
/*
Uninitializes a resampler.
*/
MA_API void ma_resampler_uninit(ma_resampler* pResampler);
/*
Converts the given input data.
Both the input and output frames must be in the format specified in the config when the resampler was initilized.
On input, [pFrameCountOut] contains the number of output frames to process. On output it contains the number of output frames that
were actually processed, which may be less than the requested amount which will happen if there's not enough input data. You can use
ma_resampler_get_expected_output_frame_count() to know how many output frames will be processed for a given number of input frames.
On input, [pFrameCountIn] contains the number of input frames contained in [pFramesIn]. On output it contains the number of whole
input frames that were actually processed. You can use ma_resampler_get_required_input_frame_count() to know how many input frames
you should provide for a given number of output frames. [pFramesIn] can be NULL, in which case zeroes will be used instead.
If [pFramesOut] is NULL, a seek is performed. In this case, if [pFrameCountOut] is not NULL it will seek by the specified number of
output frames. Otherwise, if [pFramesCountOut] is NULL and [pFrameCountIn] is not NULL, it will seek by the specified number of input
frames. When seeking, [pFramesIn] is allowed to NULL, in which case the internal timing state will be updated, but no input will be
processed. In this case, any internal filter state will be updated as if zeroes were passed in.
It is an error for [pFramesOut] to be non-NULL and [pFrameCountOut] to be NULL.
It is an error for both [pFrameCountOut] and [pFrameCountIn] to be NULL.
*/
MA_API ma_result ma_resampler_process_pcm_frames(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
/*
Sets the input and output sample sample rate.
*/
MA_API ma_result ma_resampler_set_rate(ma_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
/*
Sets the input and output sample rate as a ratio.
The ration is in/out.
*/
MA_API ma_result ma_resampler_set_rate_ratio(ma_resampler* pResampler, float ratio);
/*
Calculates the number of whole input frames that would need to be read from the client in order to output the specified
number of output frames.
The returned value does not include cached input frames. It only returns the number of extra frames that would need to be
read from the input buffer in order to output the specified number of output frames.
*/
MA_API ma_uint64 ma_resampler_get_required_input_frame_count(const ma_resampler* pResampler, ma_uint64 outputFrameCount);
/*
Calculates the number of whole output frames that would be output after fully reading and consuming the specified number of
input frames.
*/
MA_API ma_uint64 ma_resampler_get_expected_output_frame_count(const ma_resampler* pResampler, ma_uint64 inputFrameCount);
/*
Retrieves the latency introduced by the resampler in input frames.
*/
MA_API ma_uint64 ma_resampler_get_input_latency(const ma_resampler* pResampler);
/*
Retrieves the latency introduced by the resampler in output frames.
*/
MA_API ma_uint64 ma_resampler_get_output_latency(const ma_resampler* pResampler);
/**************************************************************************************************************************************************************
Channel Conversion
**************************************************************************************************************************************************************/
typedef struct
{
ma_format format;
ma_uint32 channelsIn;
ma_uint32 channelsOut;
ma_channel channelMapIn[MA_MAX_CHANNELS];
ma_channel channelMapOut[MA_MAX_CHANNELS];
ma_channel_mix_mode mixingMode;
float weights[MA_MAX_CHANNELS][MA_MAX_CHANNELS]; /* [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. */
} ma_channel_converter_config;
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);
typedef struct
{
ma_format format;
ma_uint32 channelsIn;
ma_uint32 channelsOut;
ma_channel channelMapIn[MA_MAX_CHANNELS];
ma_channel channelMapOut[MA_MAX_CHANNELS];
ma_channel_mix_mode mixingMode;
union
{
float f32[MA_MAX_CHANNELS][MA_MAX_CHANNELS];
ma_int32 s16[MA_MAX_CHANNELS][MA_MAX_CHANNELS];
} weights;
ma_bool8 isPassthrough;
ma_bool8 isSimpleShuffle;
ma_bool8 isSimpleMonoExpansion;
ma_bool8 isStereoToMono;
ma_uint8 shuffleTable[MA_MAX_CHANNELS];
} ma_channel_converter;
MA_API ma_result ma_channel_converter_init(const ma_channel_converter_config* pConfig, ma_channel_converter* pConverter);
MA_API void ma_channel_converter_uninit(ma_channel_converter* pConverter);
MA_API ma_result ma_channel_converter_process_pcm_frames(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
/**************************************************************************************************************************************************************
Data Conversion
**************************************************************************************************************************************************************/
typedef struct
{
ma_format formatIn;
ma_format formatOut;
ma_uint32 channelsIn;
ma_uint32 channelsOut;
ma_uint32 sampleRateIn;
ma_uint32 sampleRateOut;
ma_channel channelMapIn[MA_MAX_CHANNELS];
ma_channel channelMapOut[MA_MAX_CHANNELS];
ma_dither_mode ditherMode;
ma_channel_mix_mode channelMixMode;
float channelWeights[MA_MAX_CHANNELS][MA_MAX_CHANNELS]; /* [in][out]. Only used when channelMixMode is set to ma_channel_mix_mode_custom_weights. */
struct
{
ma_resample_algorithm algorithm;
ma_bool32 allowDynamicSampleRate;
struct
{
ma_uint32 lpfOrder;
double lpfNyquistFactor;
} linear;
struct
{
int quality;
} speex;
} resampling;
} ma_data_converter_config;
MA_API ma_data_converter_config ma_data_converter_config_init_default(void);
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);
typedef struct
{
ma_data_converter_config config;
ma_channel_converter channelConverter;
ma_resampler resampler;
ma_bool8 hasPreFormatConversion;
ma_bool8 hasPostFormatConversion;
ma_bool8 hasChannelConverter;
ma_bool8 hasResampler;
ma_bool8 isPassthrough;
} ma_data_converter;
MA_API ma_result ma_data_converter_init(const ma_data_converter_config* pConfig, ma_data_converter* pConverter);
MA_API void ma_data_converter_uninit(ma_data_converter* pConverter);
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);
MA_API ma_result ma_data_converter_set_rate(ma_data_converter* pConverter, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
MA_API ma_result ma_data_converter_set_rate_ratio(ma_data_converter* pConverter, float ratioInOut);
MA_API ma_uint64 ma_data_converter_get_required_input_frame_count(const ma_data_converter* pConverter, ma_uint64 outputFrameCount);
MA_API ma_uint64 ma_data_converter_get_expected_output_frame_count(const ma_data_converter* pConverter, ma_uint64 inputFrameCount);
MA_API ma_uint64 ma_data_converter_get_input_latency(const ma_data_converter* pConverter);
MA_API ma_uint64 ma_data_converter_get_output_latency(const ma_data_converter* pConverter);
/************************************************************************************************************************************************************
Format Conversion
************************************************************************************************************************************************************/
MA_API void ma_pcm_u8_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_u8_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_u8_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_u8_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_s16_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_s16_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_s16_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_s16_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_s24_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_s24_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_s24_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_s24_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_s32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_s32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_s32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_s32_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_f32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_f32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_f32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_f32_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
MA_API void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode);
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);
/*
Deinterleaves an interleaved buffer.
*/
MA_API void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames);
/*
Interleaves a group of deinterleaved buffers.
*/
MA_API void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames);
/************************************************************************************************************************************************************
Channel Maps
************************************************************************************************************************************************************/
/*
Initializes a blank channel map.
When a blank channel map is specified anywhere it indicates that the native channel map should be used.
*/
MA_API void ma_channel_map_init_blank(ma_uint32 channels, ma_channel* pChannelMap);
/*
Helper for retrieving a standard channel map.
The output channel map buffer must have a capacity of at least `channels`.
*/
MA_API void ma_get_standard_channel_map(ma_standard_channel_map standardChannelMap, ma_uint32 channels, ma_channel* pChannelMap);
/*
Copies a channel map.
Both input and output channel map buffers must have a capacity of at at least `channels`.
*/
MA_API void ma_channel_map_copy(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels);
/*
Copies a channel map if one is specified, otherwise copies the default channel map.
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`.
*/
MA_API void ma_channel_map_copy_or_default(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels);
/*
Determines whether or not a channel map is valid.
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
is usually treated as a passthrough.
Invalid channel maps:
- A channel map with no channels
- A channel map with more than one channel and a mono channel
The channel map buffer must have a capacity of at least `channels`.
*/
MA_API ma_bool32 ma_channel_map_valid(ma_uint32 channels, const ma_channel* pChannelMap);
/*
Helper for comparing two channel maps for equality.
This assumes the channel count is the same between the two.
Both channels map buffers must have a capacity of at least `channels`.
*/
MA_API ma_bool32 ma_channel_map_equal(ma_uint32 channels, const ma_channel* pChannelMapA, const ma_channel* pChannelMapB);
/*
Helper for determining if a channel map is blank (all channels set to MA_CHANNEL_NONE).
The channel map buffer must have a capacity of at least `channels`.
*/
MA_API ma_bool32 ma_channel_map_blank(ma_uint32 channels, const ma_channel* pChannelMap);
/*
Helper for determining whether or not a channel is present in the given channel map.
The channel map buffer must have a capacity of at least `channels`.
*/
MA_API ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition);
/************************************************************************************************************************************************************
Conversion Helpers
************************************************************************************************************************************************************/
/*
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
determine the required size of the output buffer. frameCountOut should be set to the capacity of pOut. If pOut is NULL, frameCountOut is
ignored.
A return value of 0 indicates an error.
This function is useful for one-off bulk conversions, but if you're streaming data you should use the ma_data_converter APIs instead.
*/
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);
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);
/************************************************************************************************************************************************************
Ring Buffer
************************************************************************************************************************************************************/
typedef struct
{
void* pBuffer;
ma_uint32 subbufferSizeInBytes;
ma_uint32 subbufferCount;
ma_uint32 subbufferStrideInBytes;
MA_ATOMIC ma_uint32 encodedReadOffset; /* Most significant bit is the loop flag. Lower 31 bits contains the actual offset in bytes. Must be used atomically. */
MA_ATOMIC ma_uint32 encodedWriteOffset; /* Most significant bit is the loop flag. Lower 31 bits contains the actual offset in bytes. Must be used atomically. */
ma_bool8 ownsBuffer; /* Used to know whether or not miniaudio is responsible for free()-ing the buffer. */
ma_bool8 clearOnWriteAcquire; /* When set, clears the acquired write buffer before returning from ma_rb_acquire_write(). */
ma_allocation_callbacks allocationCallbacks;
} ma_rb;
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);
MA_API ma_result ma_rb_init(size_t bufferSizeInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB);
MA_API void ma_rb_uninit(ma_rb* pRB);
MA_API void ma_rb_reset(ma_rb* pRB);
MA_API ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut);
MA_API ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes, void* pBufferOut);
MA_API ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut);
MA_API ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes, void* pBufferOut);
MA_API ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes);
MA_API ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes);
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. */
MA_API ma_uint32 ma_rb_available_read(ma_rb* pRB);
MA_API ma_uint32 ma_rb_available_write(ma_rb* pRB);
MA_API size_t ma_rb_get_subbuffer_size(ma_rb* pRB);
MA_API size_t ma_rb_get_subbuffer_stride(ma_rb* pRB);
MA_API size_t ma_rb_get_subbuffer_offset(ma_rb* pRB, size_t subbufferIndex);
MA_API void* ma_rb_get_subbuffer_ptr(ma_rb* pRB, size_t subbufferIndex, void* pBuffer);
typedef struct
{
ma_rb rb;
ma_format format;
ma_uint32 channels;
} ma_pcm_rb;
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);
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);
MA_API void ma_pcm_rb_uninit(ma_pcm_rb* pRB);
MA_API void ma_pcm_rb_reset(ma_pcm_rb* pRB);
MA_API ma_result ma_pcm_rb_acquire_read(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut);
MA_API ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames, void* pBufferOut);
MA_API ma_result ma_pcm_rb_acquire_write(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut);
MA_API ma_result ma_pcm_rb_commit_write(ma_pcm_rb* pRB, ma_uint32 sizeInFrames, void* pBufferOut);
MA_API ma_result ma_pcm_rb_seek_read(ma_pcm_rb* pRB, ma_uint32 offsetInFrames);
MA_API ma_result ma_pcm_rb_seek_write(ma_pcm_rb* pRB, ma_uint32 offsetInFrames);
MA_API ma_int32 ma_pcm_rb_pointer_distance(ma_pcm_rb* pRB); /* Return value is in frames. */
MA_API ma_uint32 ma_pcm_rb_available_read(ma_pcm_rb* pRB);
MA_API ma_uint32 ma_pcm_rb_available_write(ma_pcm_rb* pRB);
MA_API ma_uint32 ma_pcm_rb_get_subbuffer_size(ma_pcm_rb* pRB);
MA_API ma_uint32 ma_pcm_rb_get_subbuffer_stride(ma_pcm_rb* pRB);
MA_API ma_uint32 ma_pcm_rb_get_subbuffer_offset(ma_pcm_rb* pRB, ma_uint32 subbufferIndex);
MA_API void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void* pBuffer);
/*
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
capture device writes to it, and then a playback device reads from it.
At the moment this is just a simple naive implementation, but in the future I want to implement some dynamic resampling to seamlessly
handle desyncs. Note that the API is work in progress and may change at any time in any version.
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
in frames. The internal sample rate of the capture device is also needed in order to calculate the size.
*/
typedef struct
{
ma_pcm_rb rb;
} ma_duplex_rb;
MA_API ma_result ma_duplex_rb_init(ma_uint32 inputSampleRate, ma_format captureFormat, ma_uint32 captureChannels, ma_uint32 captureSampleRate, ma_uint32 capturePeriodSizeInFrames, const ma_allocation_callbacks* pAllocationCallbacks, ma_duplex_rb* pRB);
MA_API ma_result ma_duplex_rb_uninit(ma_duplex_rb* pRB);
/************************************************************************************************************************************************************
Miscellaneous Helpers
************************************************************************************************************************************************************/
/*
Retrieves a human readable description of the given result code.
*/
MA_API const char* ma_result_description(ma_result result);
/*
malloc(). Calls MA_MALLOC().
*/
MA_API void* ma_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
/*
realloc(). Calls MA_REALLOC().
*/
MA_API void* ma_realloc(void* p, size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
/*
free(). Calls MA_FREE().
*/
MA_API void ma_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
/*
Performs an aligned malloc, with the assumption that the alignment is a power of 2.
*/
MA_API void* ma_aligned_malloc(size_t sz, size_t alignment, const ma_allocation_callbacks* pAllocationCallbacks);
/*
Free's an aligned malloc'd buffer.
*/
MA_API void ma_aligned_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
/*
Retrieves a friendly name for a format.
*/
MA_API const char* ma_get_format_name(ma_format format);
/*
Blends two frames in floating point format.
*/
MA_API void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels);
/*
Retrieves the size of a sample in bytes for the given format.
This API is efficient and is implemented using a lookup table.
Thread Safety: SAFE
This API is pure.
*/
MA_API ma_uint32 ma_get_bytes_per_sample(ma_format format);
static MA_INLINE ma_uint32 ma_get_bytes_per_frame(ma_format format, ma_uint32 channels) { return ma_get_bytes_per_sample(format) * channels; }
/*
Converts a log level to a string.
*/
MA_API const char* ma_log_level_to_string(ma_uint32 logLevel);
/************************************************************************************************************************************************************
*************************************************************************************************************************************************************
DEVICE I/O
==========
This section contains the APIs for device playback and capture. Here is where you'll find ma_device_init(), etc.
*************************************************************************************************************************************************************
************************************************************************************************************************************************************/
#ifndef MA_NO_DEVICE_IO
/* Some backends are only supported on certain platforms. */
#if defined(MA_WIN32)
#define MA_SUPPORT_WASAPI
#if defined(MA_WIN32_DESKTOP) /* DirectSound and WinMM backends are only supported on desktops. */
#define MA_SUPPORT_DSOUND
#define MA_SUPPORT_WINMM
#define MA_SUPPORT_JACK /* JACK is technically supported on Windows, but I don't know how many people use it in practice... */
#endif
#endif
#if defined(MA_UNIX)
#if defined(MA_LINUX)
#if !defined(MA_ANDROID) /* ALSA is not supported on Android. */
#define MA_SUPPORT_ALSA
#endif
#endif
#if !defined(MA_BSD) && !defined(MA_ANDROID) && !defined(MA_EMSCRIPTEN)
#define MA_SUPPORT_PULSEAUDIO
#define MA_SUPPORT_JACK
#endif
#if defined(MA_ANDROID)
#define MA_SUPPORT_AAUDIO
#define MA_SUPPORT_OPENSL
#endif
#if defined(__OpenBSD__) /* <-- Change this to "#if defined(MA_BSD)" to enable sndio on all BSD flavors. */
#define MA_SUPPORT_SNDIO /* sndio is only supported on OpenBSD for now. May be expanded later if there's demand. */
#endif
#if defined(__NetBSD__) || defined(__OpenBSD__)
#define MA_SUPPORT_AUDIO4 /* Only support audio(4) on platforms with known support. */
#endif
#if defined(__FreeBSD__) || defined(__DragonFly__)
#define MA_SUPPORT_OSS /* Only support OSS on specific platforms with known support. */
#endif
#endif
#if defined(MA_APPLE)
#define MA_SUPPORT_COREAUDIO
#endif
#if defined(MA_EMSCRIPTEN)
#define MA_SUPPORT_WEBAUDIO
#endif
/* All platforms should support custom backends. */
#define MA_SUPPORT_CUSTOM
/* Explicitly disable the Null backend for Emscripten because it uses a background thread which is not properly supported right now. */
#if !defined(MA_EMSCRIPTEN)
#define MA_SUPPORT_NULL
#endif
#if defined(MA_SUPPORT_WASAPI) && !defined(MA_NO_WASAPI) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WASAPI))
#define MA_HAS_WASAPI
#endif
#if defined(MA_SUPPORT_DSOUND) && !defined(MA_NO_DSOUND) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_DSOUND))
#define MA_HAS_DSOUND
#endif
#if defined(MA_SUPPORT_WINMM) && !defined(MA_NO_WINMM) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WINMM))
#define MA_HAS_WINMM
#endif
#if defined(MA_SUPPORT_ALSA) && !defined(MA_NO_ALSA) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_ALSA))
#define MA_HAS_ALSA
#endif
#if defined(MA_SUPPORT_PULSEAUDIO) && !defined(MA_NO_PULSEAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_PULSEAUDIO))
#define MA_HAS_PULSEAUDIO
#endif
#if defined(MA_SUPPORT_JACK) && !defined(MA_NO_JACK) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_JACK))
#define MA_HAS_JACK
#endif
#if defined(MA_SUPPORT_COREAUDIO) && !defined(MA_NO_COREAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_COREAUDIO))
#define MA_HAS_COREAUDIO
#endif
#if defined(MA_SUPPORT_SNDIO) && !defined(MA_NO_SNDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_SNDIO))
#define MA_HAS_SNDIO
#endif
#if defined(MA_SUPPORT_AUDIO4) && !defined(MA_NO_AUDIO4) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_AUDIO4))
#define MA_HAS_AUDIO4
#endif
#if defined(MA_SUPPORT_OSS) && !defined(MA_NO_OSS) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_OSS))
#define MA_HAS_OSS
#endif
#if defined(MA_SUPPORT_AAUDIO) && !defined(MA_NO_AAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_AAUDIO))
#define MA_HAS_AAUDIO
#endif
#if defined(MA_SUPPORT_OPENSL) && !defined(MA_NO_OPENSL) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_OPENSL))
#define MA_HAS_OPENSL
#endif
#if defined(MA_SUPPORT_WEBAUDIO) && !defined(MA_NO_WEBAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WEBAUDIO))
#define MA_HAS_WEBAUDIO
#endif
#if defined(MA_SUPPORT_CUSTOM) && !defined(MA_NO_CUSTOM) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_CUSTOM))
#define MA_HAS_CUSTOM
#endif
#if defined(MA_SUPPORT_NULL) && !defined(MA_NO_NULL) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_NULL))
#define MA_HAS_NULL
#endif
#define MA_STATE_UNINITIALIZED 0
#define MA_STATE_STOPPED 1 /* The device's default state after initialization. */
#define MA_STATE_STARTED 2 /* The device is started and is requesting and/or delivering audio data. */
#define MA_STATE_STARTING 3 /* Transitioning from a stopped state to started. */
#define MA_STATE_STOPPING 4 /* Transitioning from a started state to stopped. */
#ifdef MA_SUPPORT_WASAPI
/* We need a IMMNotificationClient object for WASAPI. */
typedef struct
{
void* lpVtbl;
ma_uint32 counter;
ma_device* pDevice;
} ma_IMMNotificationClient;
#endif
/* Backend enums must be in priority order. */
typedef enum
{
ma_backend_wasapi,
ma_backend_dsound,
ma_backend_winmm,
ma_backend_coreaudio,
ma_backend_sndio,
ma_backend_audio4,
ma_backend_oss,
ma_backend_pulseaudio,
ma_backend_alsa,
ma_backend_jack,
ma_backend_aaudio,
ma_backend_opensl,
ma_backend_webaudio,
ma_backend_custom, /* <-- Custom backend, with callbacks defined by the context config. */
ma_backend_null /* <-- Must always be the last item. Lowest priority, and used as the terminator for backend enumeration. */
} ma_backend;
#define MA_BACKEND_COUNT (ma_backend_null+1)
/*
The callback for processing audio data from the device.
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
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
callback will be fired with a consistent frame count.
Parameters
----------
pDevice (in)
A pointer to the relevant device.
pOutput (out)
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
full-duplex device and null for a capture and loopback device.
pInput (in)
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
playback device.
frameCount (in)
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
`periodSizeInFrames` and `periodSizeInMilliseconds` members of the device config are just hints, and are not necessarily exactly what you'll get. You must
not assume this will always be the same value each time the callback is fired.
Remarks
-------
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
callback. The following APIs cannot be called from inside the callback:
ma_device_init()
ma_device_init_ex()
ma_device_uninit()
ma_device_start()
ma_device_stop()
The proper way to stop the device is to call `ma_device_stop()` from a different thread, normally the main application thread.
*/
typedef void (* ma_device_callback_proc)(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount);
/*
The callback for when the device has been stopped.
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
such as being unplugged or an internal error occuring.
Parameters
----------
pDevice (in)
A pointer to the device that has just stopped.
Remarks
-------
Do not restart or uninitialize the device from the callback.
*/
typedef void (* ma_stop_proc)(ma_device* pDevice);
/*
The callback for handling log messages.
Parameters
----------
pContext (in)
A pointer to the context the log message originated from.
pDevice (in)
A pointer to the device the log message originate from, if any. This can be null, in which case the message came from the context.
logLevel (in)
The log level. This can be one of the following:
+----------------------+
| Log Level |
+----------------------+
| MA_LOG_LEVEL_VERBOSE |
| MA_LOG_LEVEL_INFO |
| MA_LOG_LEVEL_WARNING |
| MA_LOG_LEVEL_ERROR |
+----------------------+
message (in)
The log message.
Remarks
-------
Do not modify the state of the device from inside the callback.
*/
typedef void (* ma_log_proc)(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message);
typedef enum
{
ma_device_type_playback = 1,
ma_device_type_capture = 2,
ma_device_type_duplex = ma_device_type_playback | ma_device_type_capture, /* 3 */
ma_device_type_loopback = 4
} ma_device_type;
typedef enum
{
ma_share_mode_shared = 0,
ma_share_mode_exclusive
} ma_share_mode;
/* iOS/tvOS/watchOS session categories. */
typedef enum
{
ma_ios_session_category_default = 0, /* AVAudioSessionCategoryPlayAndRecord with AVAudioSessionCategoryOptionDefaultToSpeaker. */
ma_ios_session_category_none, /* Leave the session category unchanged. */
ma_ios_session_category_ambient, /* AVAudioSessionCategoryAmbient */
ma_ios_session_category_solo_ambient, /* AVAudioSessionCategorySoloAmbient */
ma_ios_session_category_playback, /* AVAudioSessionCategoryPlayback */
ma_ios_session_category_record, /* AVAudioSessionCategoryRecord */
ma_ios_session_category_play_and_record, /* AVAudioSessionCategoryPlayAndRecord */
ma_ios_session_category_multi_route /* AVAudioSessionCategoryMultiRoute */
} ma_ios_session_category;
/* iOS/tvOS/watchOS session category options */
typedef enum
{
ma_ios_session_category_option_mix_with_others = 0x01, /* AVAudioSessionCategoryOptionMixWithOthers */
ma_ios_session_category_option_duck_others = 0x02, /* AVAudioSessionCategoryOptionDuckOthers */
ma_ios_session_category_option_allow_bluetooth = 0x04, /* AVAudioSessionCategoryOptionAllowBluetooth */
ma_ios_session_category_option_default_to_speaker = 0x08, /* AVAudioSessionCategoryOptionDefaultToSpeaker */
ma_ios_session_category_option_interrupt_spoken_audio_and_mix_with_others = 0x11, /* AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers */
ma_ios_session_category_option_allow_bluetooth_a2dp = 0x20, /* AVAudioSessionCategoryOptionAllowBluetoothA2DP */
ma_ios_session_category_option_allow_air_play = 0x40, /* AVAudioSessionCategoryOptionAllowAirPlay */
} ma_ios_session_category_option;
/* OpenSL stream types. */
typedef enum
{
ma_opensl_stream_type_default = 0, /* Leaves the stream type unset. */
ma_opensl_stream_type_voice, /* SL_ANDROID_STREAM_VOICE */
ma_opensl_stream_type_system, /* SL_ANDROID_STREAM_SYSTEM */
ma_opensl_stream_type_ring, /* SL_ANDROID_STREAM_RING */
ma_opensl_stream_type_media, /* SL_ANDROID_STREAM_MEDIA */
ma_opensl_stream_type_alarm, /* SL_ANDROID_STREAM_ALARM */
ma_opensl_stream_type_notification /* SL_ANDROID_STREAM_NOTIFICATION */
} ma_opensl_stream_type;
/* OpenSL recording presets. */
typedef enum
{
ma_opensl_recording_preset_default = 0, /* Leaves the input preset unset. */
ma_opensl_recording_preset_generic, /* SL_ANDROID_RECORDING_PRESET_GENERIC */
ma_opensl_recording_preset_camcorder, /* SL_ANDROID_RECORDING_PRESET_CAMCORDER */
ma_opensl_recording_preset_voice_recognition, /* SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION */
ma_opensl_recording_preset_voice_communication, /* SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION */
ma_opensl_recording_preset_voice_unprocessed /* SL_ANDROID_RECORDING_PRESET_UNPROCESSED */
} ma_opensl_recording_preset;
/* AAudio usage types. */
typedef enum
{
ma_aaudio_usage_default = 0, /* Leaves the usage type unset. */
ma_aaudio_usage_announcement, /* AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT */
ma_aaudio_usage_emergency, /* AAUDIO_SYSTEM_USAGE_EMERGENCY */
ma_aaudio_usage_safety, /* AAUDIO_SYSTEM_USAGE_SAFETY */
ma_aaudio_usage_vehicle_status, /* AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS */
ma_aaudio_usage_alarm, /* AAUDIO_USAGE_ALARM */
ma_aaudio_usage_assistance_accessibility, /* AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY */
ma_aaudio_usage_assistance_navigation_guidance, /* AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE */
ma_aaudio_usage_assistance_sonification, /* AAUDIO_USAGE_ASSISTANCE_SONIFICATION */
ma_aaudio_usage_assitant, /* AAUDIO_USAGE_ASSISTANT */
ma_aaudio_usage_game, /* AAUDIO_USAGE_GAME */
ma_aaudio_usage_media, /* AAUDIO_USAGE_MEDIA */
ma_aaudio_usage_notification, /* AAUDIO_USAGE_NOTIFICATION */
ma_aaudio_usage_notification_event, /* AAUDIO_USAGE_NOTIFICATION_EVENT */
ma_aaudio_usage_notification_ringtone, /* AAUDIO_USAGE_NOTIFICATION_RINGTONE */
ma_aaudio_usage_voice_communication, /* AAUDIO_USAGE_VOICE_COMMUNICATION */
ma_aaudio_usage_voice_communication_signalling /* AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING */
} ma_aaudio_usage;
/* AAudio content types. */
typedef enum
{
ma_aaudio_content_type_default = 0, /* Leaves the content type unset. */
ma_aaudio_content_type_movie, /* AAUDIO_CONTENT_TYPE_MOVIE */
ma_aaudio_content_type_music, /* AAUDIO_CONTENT_TYPE_MUSIC */
ma_aaudio_content_type_sonification, /* AAUDIO_CONTENT_TYPE_SONIFICATION */
ma_aaudio_content_type_speech /* AAUDIO_CONTENT_TYPE_SPEECH */
} ma_aaudio_content_type;
/* AAudio input presets. */
typedef enum
{
ma_aaudio_input_preset_default = 0, /* Leaves the input preset unset. */
ma_aaudio_input_preset_generic, /* AAUDIO_INPUT_PRESET_GENERIC */
ma_aaudio_input_preset_camcorder, /* AAUDIO_INPUT_PRESET_CAMCORDER */
ma_aaudio_input_preset_unprocessed, /* AAUDIO_INPUT_PRESET_UNPROCESSED */
ma_aaudio_input_preset_voice_recognition, /* AAUDIO_INPUT_PRESET_VOICE_RECOGNITION */
ma_aaudio_input_preset_voice_communication, /* AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION */
ma_aaudio_input_preset_voice_performance /* AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE */
} ma_aaudio_input_preset;
typedef union
{
ma_int64 counter;
double counterD;
} ma_timer;
typedef union
{
wchar_t wasapi[64]; /* WASAPI uses a wchar_t string for identification. */
ma_uint8 dsound[16]; /* DirectSound uses a GUID for identification. */
/*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. */
char alsa[256]; /* ALSA uses a name string for identification. */
char pulse[256]; /* PulseAudio uses a name string for identification. */
int jack; /* JACK always uses default devices. */
char coreaudio[256]; /* Core Audio uses a string for identification. */
char sndio[256]; /* "snd/0", etc. */
char audio4[256]; /* "/dev/audio", etc. */
char oss[64]; /* "dev/dsp0", etc. "dev/dsp" for the default device. */
ma_int32 aaudio; /* AAudio uses a 32-bit integer for identification. */
ma_uint32 opensl; /* OpenSL|ES uses a 32-bit unsigned integer for identification. */
char webaudio[32]; /* Web Audio always uses default devices for now, but if this changes it'll be a GUID. */
union
{
int i;
char s[256];
void* p;
} custom; /* The custom backend could be anything. Give them a few options. */
int nullbackend; /* The null backend uses an integer for device IDs. */
} ma_device_id;
typedef struct ma_context_config ma_context_config;
typedef struct ma_device_config ma_device_config;
typedef struct ma_backend_callbacks ma_backend_callbacks;
#define MA_DATA_FORMAT_FLAG_EXCLUSIVE_MODE (1U << 1) /* If set, this is supported in exclusive mode. Otherwise not natively supported by exclusive mode. */
typedef struct
{
/* Basic info. This is the only information guaranteed to be filled in during device enumeration. */
ma_device_id id;
char name[256];
ma_bool32 isDefault;
/*
Detailed info. As much of this is filled as possible with ma_context_get_device_info(). Note that you are allowed to initialize
a device with settings outside of this range, but it just means the data will be converted using miniaudio's data conversion
pipeline before sending the data to/from the device. Most programs will need to not worry about these values, but it's provided
here mainly for informational purposes or in the rare case that someone might find it useful.
These will be set to 0 when returned by ma_context_enumerate_devices() or ma_context_get_devices().
*/
ma_uint32 formatCount;
ma_format formats[ma_format_count];
ma_uint32 minChannels;
ma_uint32 maxChannels;
ma_uint32 minSampleRate;
ma_uint32 maxSampleRate;
/* Experimental. Don't use these right now. */
ma_uint32 nativeDataFormatCount;
struct
{
ma_format format; /* Sample format. If set to ma_format_unknown, all sample formats are supported. */
ma_uint32 channels; /* If set to 0, all channels are supported. */
ma_uint32 sampleRate; /* If set to 0, all sample rates are supported. */
ma_uint32 flags;
} nativeDataFormats[64];
} ma_device_info;
struct ma_device_config
{
ma_device_type deviceType;
ma_uint32 sampleRate;
ma_uint32 periodSizeInFrames;
ma_uint32 periodSizeInMilliseconds;
ma_uint32 periods;
ma_performance_profile performanceProfile;
ma_bool8 noPreZeroedOutputBuffer; /* When set to true, the contents of the output buffer passed into the data callback will be left undefined rather than initialized to zero. */
ma_bool8 noClip; /* When set to true, the contents of the output buffer passed into the data callback will be clipped after returning. Only applies when the playback sample format is f32. */
ma_device_callback_proc dataCallback;
ma_stop_proc stopCallback;
void* pUserData;
struct
{
ma_resample_algorithm algorithm;
struct
{
ma_uint32 lpfOrder;
} linear;
struct
{
int quality;
} speex;
} resampling;
struct
{
const ma_device_id* pDeviceID;
ma_format format;
ma_uint32 channels;
ma_channel channelMap[MA_MAX_CHANNELS];
ma_channel_mix_mode channelMixMode;
ma_share_mode shareMode;
} playback;
struct
{
const ma_device_id* pDeviceID;
ma_format format;
ma_uint32 channels;
ma_channel channelMap[MA_MAX_CHANNELS];
ma_channel_mix_mode channelMixMode;
ma_share_mode shareMode;
} capture;
struct
{
ma_bool8 noAutoConvertSRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */
ma_bool8 noDefaultQualitySRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */
ma_bool8 noAutoStreamRouting; /* Disables automatic stream routing. */
ma_bool8 noHardwareOffloading; /* Disables WASAPI's hardware offloading feature. */
} wasapi;
struct
{
ma_bool32 noMMap; /* Disables MMap mode. */
ma_bool32 noAutoFormat; /* Opens the ALSA device with SND_PCM_NO_AUTO_FORMAT. */
ma_bool32 noAutoChannels; /* Opens the ALSA device with SND_PCM_NO_AUTO_CHANNELS. */
ma_bool32 noAutoResample; /* Opens the ALSA device with SND_PCM_NO_AUTO_RESAMPLE. */
} alsa;
struct
{
const char* pStreamNamePlayback;
const char* pStreamNameCapture;
} pulse;
struct
{
ma_bool32 allowNominalSampleRateChange; /* Desktop only. When enabled, allows changing of the sample rate at the operating system level. */
} coreaudio;
struct
{
ma_opensl_stream_type streamType;
ma_opensl_recording_preset recordingPreset;
} opensl;
struct
{
ma_aaudio_usage usage;
ma_aaudio_content_type contentType;
ma_aaudio_input_preset inputPreset;
} aaudio;
};
/*
The callback for handling device enumeration. This is fired from `ma_context_enumerated_devices()`.
Parameters
----------
pContext (in)
A pointer to the context performing the enumeration.
deviceType (in)
The type of the device being enumerated. This will always be either `ma_device_type_playback` or `ma_device_type_capture`.
pInfo (in)
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,
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
is too inefficient.
pUserData (in)
The user data pointer passed into `ma_context_enumerate_devices()`.
*/
typedef ma_bool32 (* ma_enum_devices_callback_proc)(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData);
/*
Describes some basic details about a playback or capture device.
*/
typedef struct
{
const ma_device_id* pDeviceID;
ma_share_mode shareMode;
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
ma_channel channelMap[MA_MAX_CHANNELS];
ma_uint32 periodSizeInFrames;
ma_uint32 periodSizeInMilliseconds;
ma_uint32 periodCount;
} ma_device_descriptor;
/*
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
to many devices. A device is created from a context.
The general flow goes like this:
1) A context is created with `onContextInit()`
1a) Available devices can be enumerated with `onContextEnumerateDevices()` if required.
1b) Detailed information about a device can be queried with `onContextGetDeviceInfo()` if required.
2) A device is created from the context that was created in the first step using `onDeviceInit()`, and optionally a device ID that was
selected from device enumeration via `onContextEnumerateDevices()`.
3) A device is started or stopped with `onDeviceStart()` / `onDeviceStop()`
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
to `onDeviceInit()`. Conversion between the device's native format and the format requested by the application will be handled by
miniaudio internally.
Initialization of the context is quite simple. You need to do any necessary initialization of internal objects and then output the
callbacks defined in this structure.
Once the context has been initialized you can initialize a device. Before doing so, however, the application may want to know which
physical devices are available. This is where `onContextEnumerateDevices()` comes in. This is fairly simple. For each device, fire the
given callback with, at a minimum, the basic information filled out in `ma_device_info`. When the callback returns `MA_FALSE`, enumeration
needs to stop and the `onContextEnumerateDevices()` function return with a success code.
Detailed device information can be retrieved from a device ID using `onContextGetDeviceInfo()`. This takes as input the device type and ID,
and on output returns detailed information about the device in `ma_device_info`. The `onContextGetDeviceInfo()` callback must handle the
case when the device ID is NULL, in which case information about the default device needs to be retrieved.
Once the context has been created and the device ID retrieved (if using anything other than the default device), the device can be created.
This is a little bit more complicated than initialization of the context due to it's more complicated configuration. When initializing a
device, a duplex device may be requested. This means a separate data format needs to be specified for both playback and capture. On input,
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
the requested format. The conversion between the format requested by the application and the device's native format will be handled
internally by miniaudio.
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
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
sample rate. For the channel map, the default should be used when `ma_channel_map_blank()` returns true (all channels set to
`MA_CHANNEL_NONE`). On input, the `periodSizeInFrames` or `periodSizeInMilliseconds` option should always be set. The backend should
inspect both of these variables. If `periodSizeInFrames` is set, it should take priority, otherwise it needs to be derived from the period
size in milliseconds (`periodSizeInMilliseconds`) and the sample rate, keeping in mind that the sample rate may be 0, in which case the
sample rate will need to be determined before calculating the period size in frames. On output, all members of the `ma_device_data_format`
object should be set to a valid value, except for `periodSizeInMilliseconds` which is optional (`periodSizeInFrames` *must* be set).
Starting and stopping of the device is done with `onDeviceStart()` and `onDeviceStop()` and should be self-explanatory. If the backend uses
asynchronous reading and writing, `onDeviceStart()` and `onDeviceStop()` should always be implemented.
The handling of data delivery between the application and the device is the most complicated part of the process. To make this a bit
easier, some helper callbacks are available. If the backend uses a blocking read/write style of API, the `onDeviceRead()` and
`onDeviceWrite()` callbacks can optionally be implemented. These are blocking and work just like reading and writing from a file. If the
backend uses a callback for data delivery, that callback must call `ma_device_handle_backend_data_callback()` from within it's callback.
This allows miniaudio to then process any necessary data conversion and then pass it to the miniaudio data callback.
If the backend requires absolute flexibility with it's data delivery, it can optionally implement the `onDeviceWorkerThread()` callback
which will allow it to implement the logic that will run on the audio thread. This is much more advanced and is completely optional.
The audio thread should run data delivery logic in a loop while `ma_device_get_state() == MA_STATE_STARTED` and no errors have been
encounted. Do not start or stop the device here. That will be handled from outside the `onDeviceAudioThread()` callback.
The invocation of the `onDeviceAudioThread()` callback will be handled by miniaudio. When you start the device, miniaudio will fire this
callback. When the device is stopped, the `ma_device_get_state() == MA_STATE_STARTED` condition will fail and the loop will be terminated
which will then fall through to the part that stops the device. For an example on how to implement the `onDeviceAudioThread()` callback,
look at `ma_device_audio_thread__default_read_write()`.
*/
struct ma_backend_callbacks
{
ma_result (* onContextInit)(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks);
ma_result (* onContextUninit)(ma_context* pContext);
ma_result (* onContextEnumerateDevices)(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData);
ma_result (* onContextGetDeviceInfo)(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo);
ma_result (* onDeviceInit)(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture);
ma_result (* onDeviceUninit)(ma_device* pDevice);
ma_result (* onDeviceStart)(ma_device* pDevice);
ma_result (* onDeviceStop)(ma_device* pDevice);
ma_result (* onDeviceRead)(ma_device* pDevice, void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesRead);
ma_result (* onDeviceWrite)(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten);
ma_result (* onDeviceAudioThread)(ma_device* pDevice);
};
struct ma_context_config
{
ma_log_proc logCallback;
ma_thread_priority threadPriority;
size_t threadStackSize;
void* pUserData;
ma_allocation_callbacks allocationCallbacks;
struct
{
ma_bool32 useVerboseDeviceEnumeration;
} alsa;
struct
{
const char* pApplicationName;
const char* pServerName;
ma_bool32 tryAutoSpawn; /* Enables autospawning of the PulseAudio daemon if necessary. */
} pulse;
struct
{
ma_ios_session_category sessionCategory;
ma_uint32 sessionCategoryOptions;
ma_bool32 noAudioSessionActivate; /* iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:true] on initialization. */
ma_bool32 noAudioSessionDeactivate; /* iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:false] on uninitialization. */
} coreaudio;
struct
{
const char* pClientName;
ma_bool32 tryStartServer;
} jack;
ma_backend_callbacks custom;
};
struct ma_context
{
ma_backend_callbacks callbacks;
ma_backend backend; /* DirectSound, ALSA, etc. */
ma_log_proc logCallback;
ma_thread_priority threadPriority;
size_t threadStackSize;
void* pUserData;
ma_allocation_callbacks allocationCallbacks;
ma_mutex deviceEnumLock; /* Used to make ma_context_get_devices() thread safe. */
ma_mutex deviceInfoLock; /* Used to make ma_context_get_device_info() thread safe. */
ma_uint32 deviceInfoCapacity; /* Total capacity of pDeviceInfos. */
ma_uint32 playbackDeviceInfoCount;
ma_uint32 captureDeviceInfoCount;
ma_device_info* pDeviceInfos; /* Playback devices first, then capture. */
ma_bool8 isBackendAsynchronous; /* Set when the context is initialized. Set to 1 for asynchronous backends such as Core Audio and JACK. Do not modify. */
ma_result (* onUninit )(ma_context* pContext);
ma_result (* onEnumDevices )(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData); /* Return false from the callback to stop enumeration. */
ma_result (* onGetDeviceInfo )(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo);
ma_result (* onDeviceInit )(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice);
void (* onDeviceUninit )(ma_device* pDevice);
ma_result (* onDeviceStart )(ma_device* pDevice);
ma_result (* onDeviceStop )(ma_device* pDevice);
ma_result (* onDeviceMainLoop)(ma_device* pDevice);
union
{
#ifdef MA_SUPPORT_WASAPI
struct
{
int _unused;
} wasapi;
#endif
#ifdef MA_SUPPORT_DSOUND
struct
{
ma_handle hDSoundDLL;
ma_proc DirectSoundCreate;
ma_proc DirectSoundEnumerateA;
ma_proc DirectSoundCaptureCreate;
ma_proc DirectSoundCaptureEnumerateA;
} dsound;
#endif
#ifdef MA_SUPPORT_WINMM
struct
{
ma_handle hWinMM;
ma_proc waveOutGetNumDevs;
ma_proc waveOutGetDevCapsA;
ma_proc waveOutOpen;
ma_proc waveOutClose;
ma_proc waveOutPrepareHeader;
ma_proc waveOutUnprepareHeader;
ma_proc waveOutWrite;
ma_proc waveOutReset;
ma_proc waveInGetNumDevs;
ma_proc waveInGetDevCapsA;
ma_proc waveInOpen;
ma_proc waveInClose;
ma_proc waveInPrepareHeader;
ma_proc waveInUnprepareHeader;
ma_proc waveInAddBuffer;
ma_proc waveInStart;
ma_proc waveInReset;
} winmm;
#endif
#ifdef MA_SUPPORT_ALSA
struct
{
ma_handle asoundSO;
ma_proc snd_pcm_open;
ma_proc snd_pcm_close;
ma_proc snd_pcm_hw_params_sizeof;
ma_proc snd_pcm_hw_params_any;
ma_proc snd_pcm_hw_params_set_format;
ma_proc snd_pcm_hw_params_set_format_first;
ma_proc snd_pcm_hw_params_get_format_mask;
ma_proc snd_pcm_hw_params_set_channels_near;
ma_proc snd_pcm_hw_params_set_rate_resample;
ma_proc snd_pcm_hw_params_set_rate_near;
ma_proc snd_pcm_hw_params_set_buffer_size_near;
ma_proc snd_pcm_hw_params_set_periods_near;
ma_proc snd_pcm_hw_params_set_access;
ma_proc snd_pcm_hw_params_get_format;
ma_proc snd_pcm_hw_params_get_channels;
ma_proc snd_pcm_hw_params_get_channels_min;
ma_proc snd_pcm_hw_params_get_channels_max;
ma_proc snd_pcm_hw_params_get_rate;
ma_proc snd_pcm_hw_params_get_rate_min;
ma_proc snd_pcm_hw_params_get_rate_max;
ma_proc snd_pcm_hw_params_get_buffer_size;
ma_proc snd_pcm_hw_params_get_periods;
ma_proc snd_pcm_hw_params_get_access;
ma_proc snd_pcm_hw_params;
ma_proc snd_pcm_sw_params_sizeof;
ma_proc snd_pcm_sw_params_current;
ma_proc snd_pcm_sw_params_get_boundary;
ma_proc snd_pcm_sw_params_set_avail_min;
ma_proc snd_pcm_sw_params_set_start_threshold;
ma_proc snd_pcm_sw_params_set_stop_threshold;
ma_proc snd_pcm_sw_params;
ma_proc snd_pcm_format_mask_sizeof;
ma_proc snd_pcm_format_mask_test;
ma_proc snd_pcm_get_chmap;
ma_proc snd_pcm_state;
ma_proc snd_pcm_prepare;
ma_proc snd_pcm_start;
ma_proc snd_pcm_drop;
ma_proc snd_pcm_drain;
ma_proc snd_device_name_hint;
ma_proc snd_device_name_get_hint;
ma_proc snd_card_get_index;
ma_proc snd_device_name_free_hint;
ma_proc snd_pcm_mmap_begin;
ma_proc snd_pcm_mmap_commit;
ma_proc snd_pcm_recover;
ma_proc snd_pcm_readi;
ma_proc snd_pcm_writei;
ma_proc snd_pcm_avail;
ma_proc snd_pcm_avail_update;
ma_proc snd_pcm_wait;
ma_proc snd_pcm_info;
ma_proc snd_pcm_info_sizeof;
ma_proc snd_pcm_info_get_name;
ma_proc snd_config_update_free_global;
ma_mutex internalDeviceEnumLock;
ma_bool32 useVerboseDeviceEnumeration;
} alsa;
#endif
#ifdef MA_SUPPORT_PULSEAUDIO
struct
{
ma_handle pulseSO;
ma_proc pa_mainloop_new;
ma_proc pa_mainloop_free;
ma_proc pa_mainloop_quit;
ma_proc pa_mainloop_get_api;
ma_proc pa_mainloop_iterate;
ma_proc pa_mainloop_wakeup;
ma_proc pa_threaded_mainloop_new;
ma_proc pa_threaded_mainloop_free;
ma_proc pa_threaded_mainloop_start;
ma_proc pa_threaded_mainloop_stop;
ma_proc pa_threaded_mainloop_lock;
ma_proc pa_threaded_mainloop_unlock;
ma_proc pa_threaded_mainloop_wait;
ma_proc pa_threaded_mainloop_signal;
ma_proc pa_threaded_mainloop_accept;
ma_proc pa_threaded_mainloop_get_retval;
ma_proc pa_threaded_mainloop_get_api;
ma_proc pa_threaded_mainloop_in_thread;
ma_proc pa_threaded_mainloop_set_name;
ma_proc pa_context_new;
ma_proc pa_context_unref;
ma_proc pa_context_connect;
ma_proc pa_context_disconnect;
ma_proc pa_context_set_state_callback;
ma_proc pa_context_get_state;
ma_proc pa_context_get_sink_info_list;
ma_proc pa_context_get_source_info_list;
ma_proc pa_context_get_sink_info_by_name;
ma_proc pa_context_get_source_info_by_name;
ma_proc pa_operation_unref;
ma_proc pa_operation_get_state;
ma_proc pa_channel_map_init_extend;
ma_proc pa_channel_map_valid;
ma_proc pa_channel_map_compatible;
ma_proc pa_stream_new;
ma_proc pa_stream_unref;
ma_proc pa_stream_connect_playback;
ma_proc pa_stream_connect_record;
ma_proc pa_stream_disconnect;
ma_proc pa_stream_get_state;
ma_proc pa_stream_get_sample_spec;
ma_proc pa_stream_get_channel_map;
ma_proc pa_stream_get_buffer_attr;
ma_proc pa_stream_set_buffer_attr;
ma_proc pa_stream_get_device_name;
ma_proc pa_stream_set_write_callback;
ma_proc pa_stream_set_read_callback;
ma_proc pa_stream_flush;
ma_proc pa_stream_drain;
ma_proc pa_stream_is_corked;
ma_proc pa_stream_cork;
ma_proc pa_stream_trigger;
ma_proc pa_stream_begin_write;
ma_proc pa_stream_write;
ma_proc pa_stream_peek;
ma_proc pa_stream_drop;
ma_proc pa_stream_writable_size;
ma_proc pa_stream_readable_size;
/*pa_threaded_mainloop**/ ma_ptr pMainLoop;
/*pa_context**/ ma_ptr pPulseContext;
} pulse;
#endif
#ifdef MA_SUPPORT_JACK
struct
{
ma_handle jackSO;
ma_proc jack_client_open;
ma_proc jack_client_close;
ma_proc jack_client_name_size;
ma_proc jack_set_process_callback;
ma_proc jack_set_buffer_size_callback;
ma_proc jack_on_shutdown;
ma_proc jack_get_sample_rate;
ma_proc jack_get_buffer_size;
ma_proc jack_get_ports;
ma_proc jack_activate;
ma_proc jack_deactivate;
ma_proc jack_connect;
ma_proc jack_port_register;
ma_proc jack_port_name;
ma_proc jack_port_get_buffer;
ma_proc jack_free;
char* pClientName;
ma_bool32 tryStartServer;
} jack;
#endif
#ifdef MA_SUPPORT_COREAUDIO
struct
{
ma_handle hCoreFoundation;
ma_proc CFStringGetCString;
ma_proc CFRelease;
ma_handle hCoreAudio;
ma_proc AudioObjectGetPropertyData;
ma_proc AudioObjectGetPropertyDataSize;
ma_proc AudioObjectSetPropertyData;
ma_proc AudioObjectAddPropertyListener;
ma_proc AudioObjectRemovePropertyListener;
ma_handle hAudioUnit; /* Could possibly be set to AudioToolbox on later versions of macOS. */
ma_proc AudioComponentFindNext;
ma_proc AudioComponentInstanceDispose;
ma_proc AudioComponentInstanceNew;
ma_proc AudioOutputUnitStart;
ma_proc AudioOutputUnitStop;
ma_proc AudioUnitAddPropertyListener;
ma_proc AudioUnitGetPropertyInfo;
ma_proc AudioUnitGetProperty;
ma_proc AudioUnitSetProperty;
ma_proc AudioUnitInitialize;
ma_proc AudioUnitRender;
/*AudioComponent*/ ma_ptr component;
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(). */
} coreaudio;
#endif
#ifdef MA_SUPPORT_SNDIO
struct
{
ma_handle sndioSO;
ma_proc sio_open;
ma_proc sio_close;
ma_proc sio_setpar;
ma_proc sio_getpar;
ma_proc sio_getcap;
ma_proc sio_start;
ma_proc sio_stop;
ma_proc sio_read;
ma_proc sio_write;
ma_proc sio_onmove;
ma_proc sio_nfds;
ma_proc sio_pollfd;
ma_proc sio_revents;
ma_proc sio_eof;
ma_proc sio_setvol;
ma_proc sio_onvol;
ma_proc sio_initpar;
} sndio;
#endif
#ifdef MA_SUPPORT_AUDIO4
struct
{
int _unused;
} audio4;
#endif
#ifdef MA_SUPPORT_OSS
struct
{
int versionMajor;
int versionMinor;
} oss;
#endif
#ifdef MA_SUPPORT_AAUDIO
struct
{
ma_handle hAAudio; /* libaaudio.so */
ma_proc AAudio_createStreamBuilder;
ma_proc AAudioStreamBuilder_delete;
ma_proc AAudioStreamBuilder_setDeviceId;
ma_proc AAudioStreamBuilder_setDirection;
ma_proc AAudioStreamBuilder_setSharingMode;
ma_proc AAudioStreamBuilder_setFormat;
ma_proc AAudioStreamBuilder_setChannelCount;
ma_proc AAudioStreamBuilder_setSampleRate;
ma_proc AAudioStreamBuilder_setBufferCapacityInFrames;
ma_proc AAudioStreamBuilder_setFramesPerDataCallback;
ma_proc AAudioStreamBuilder_setDataCallback;
ma_proc AAudioStreamBuilder_setErrorCallback;
ma_proc AAudioStreamBuilder_setPerformanceMode;
ma_proc AAudioStreamBuilder_setUsage;
ma_proc AAudioStreamBuilder_setContentType;
ma_proc AAudioStreamBuilder_setInputPreset;
ma_proc AAudioStreamBuilder_openStream;
ma_proc AAudioStream_close;
ma_proc AAudioStream_getState;
ma_proc AAudioStream_waitForStateChange;
ma_proc AAudioStream_getFormat;
ma_proc AAudioStream_getChannelCount;
ma_proc AAudioStream_getSampleRate;
ma_proc AAudioStream_getBufferCapacityInFrames;
ma_proc AAudioStream_getFramesPerDataCallback;
ma_proc AAudioStream_getFramesPerBurst;
ma_proc AAudioStream_requestStart;
ma_proc AAudioStream_requestStop;
} aaudio;
#endif
#ifdef MA_SUPPORT_OPENSL
struct
{
ma_handle libOpenSLES;
ma_handle SL_IID_ENGINE;
ma_handle SL_IID_AUDIOIODEVICECAPABILITIES;
ma_handle SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
ma_handle SL_IID_RECORD;
ma_handle SL_IID_PLAY;
ma_handle SL_IID_OUTPUTMIX;
ma_handle SL_IID_ANDROIDCONFIGURATION;
ma_proc slCreateEngine;
} opensl;
#endif
#ifdef MA_SUPPORT_WEBAUDIO
struct
{
int _unused;
} webaudio;
#endif
#ifdef MA_SUPPORT_NULL
struct
{
int _unused;
} null_backend;
#endif
};
union
{
#ifdef MA_WIN32
struct
{
/*HMODULE*/ ma_handle hOle32DLL;
ma_proc CoInitializeEx;
ma_proc CoUninitialize;
ma_proc CoCreateInstance;
ma_proc CoTaskMemFree;
ma_proc PropVariantClear;
ma_proc StringFromGUID2;
/*HMODULE*/ ma_handle hUser32DLL;
ma_proc GetForegroundWindow;
ma_proc GetDesktopWindow;
/*HMODULE*/ ma_handle hAdvapi32DLL;
ma_proc RegOpenKeyExA;
ma_proc RegCloseKey;
ma_proc RegQueryValueExA;
} win32;
#endif
#ifdef MA_POSIX
struct
{
ma_handle pthreadSO;
ma_proc pthread_create;
ma_proc pthread_join;
ma_proc pthread_mutex_init;
ma_proc pthread_mutex_destroy;
ma_proc pthread_mutex_lock;
ma_proc pthread_mutex_unlock;
ma_proc pthread_cond_init;
ma_proc pthread_cond_destroy;
ma_proc pthread_cond_wait;
ma_proc pthread_cond_signal;
ma_proc pthread_attr_init;
ma_proc pthread_attr_destroy;
ma_proc pthread_attr_setschedpolicy;
ma_proc pthread_attr_getschedparam;
ma_proc pthread_attr_setschedparam;
} posix;
#endif
int _unused;
};
};
struct ma_device
{
ma_context* pContext;
ma_device_type type;
ma_uint32 sampleRate;
MA_ATOMIC ma_uint32 state; /* The state of the device is variable and can change at any time on any thread. Must be used atomically. */
ma_device_callback_proc onData; /* Set once at initialization time and should not be changed after. */
ma_stop_proc onStop; /* Set once at initialization time and should not be changed after. */
void* pUserData; /* Application defined data. */
ma_mutex lock;
ma_event wakeupEvent;
ma_event startEvent;
ma_event stopEvent;
ma_thread thread;
ma_result workResult; /* This is set by the worker thread after it's finished doing a job. */
ma_bool8 usingDefaultSampleRate;
ma_bool8 usingDefaultBufferSize;
ma_bool8 usingDefaultPeriods;
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(). */
ma_bool8 noPreZeroedOutputBuffer;
ma_bool8 noClip;
MA_ATOMIC float masterVolumeFactor; /* Linear 0..1. Can be read and written simultaneously by different threads. Must be used atomically. */
ma_duplex_rb duplexRB; /* Intermediary buffer for duplex device on asynchronous backends. */
struct
{
ma_resample_algorithm algorithm;
struct
{
ma_uint32 lpfOrder;
} linear;
struct
{
int quality;
} speex;
} resampling;
struct
{
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. */
char name[256]; /* Maybe temporary. Likely to be replaced with a query API. */
ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */
ma_format format;
ma_uint32 channels;
ma_channel channelMap[MA_MAX_CHANNELS];
ma_format internalFormat;
ma_uint32 internalChannels;
ma_uint32 internalSampleRate;
ma_channel internalChannelMap[MA_MAX_CHANNELS];
ma_uint32 internalPeriodSizeInFrames;
ma_uint32 internalPeriods;
ma_channel_mix_mode channelMixMode;
ma_data_converter converter;
ma_bool8 usingDefaultFormat;
ma_bool8 usingDefaultChannels;
ma_bool8 usingDefaultChannelMap;
} playback;
struct
{
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. */
char name[256]; /* Maybe temporary. Likely to be replaced with a query API. */
ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */
ma_format format;
ma_uint32 channels;
ma_channel channelMap[MA_MAX_CHANNELS];
ma_format internalFormat;
ma_uint32 internalChannels;
ma_uint32 internalSampleRate;
ma_channel internalChannelMap[MA_MAX_CHANNELS];
ma_uint32 internalPeriodSizeInFrames;
ma_uint32 internalPeriods;
ma_channel_mix_mode channelMixMode;
ma_data_converter converter;
ma_bool8 usingDefaultFormat;
ma_bool8 usingDefaultChannels;
ma_bool8 usingDefaultChannelMap;
} capture;
union
{
#ifdef MA_SUPPORT_WASAPI
struct
{
/*IAudioClient**/ ma_ptr pAudioClientPlayback;
/*IAudioClient**/ ma_ptr pAudioClientCapture;
/*IAudioRenderClient**/ ma_ptr pRenderClient;
/*IAudioCaptureClient**/ ma_ptr pCaptureClient;
/*IMMDeviceEnumerator**/ ma_ptr pDeviceEnumerator; /* Used for IMMNotificationClient notifications. Required for detecting default device changes. */
ma_IMMNotificationClient notificationClient;
/*HANDLE*/ ma_handle hEventPlayback; /* Auto reset. Initialized to signaled. */
/*HANDLE*/ ma_handle hEventCapture; /* Auto reset. Initialized to unsignaled. */
ma_uint32 actualPeriodSizeInFramesPlayback; /* 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. */
ma_uint32 actualPeriodSizeInFramesCapture;
ma_uint32 originalPeriodSizeInFrames;
ma_uint32 originalPeriodSizeInMilliseconds;
ma_uint32 originalPeriods;
ma_performance_profile originalPerformanceProfile;
ma_uint32 periodSizeInFramesPlayback;
ma_uint32 periodSizeInFramesCapture;
MA_ATOMIC ma_bool8 hasDefaultPlaybackDeviceChanged; /* Can be read and written simultaneously across different threads. Must be used atomically. */
MA_ATOMIC ma_bool8 hasDefaultCaptureDeviceChanged; /* Can be read and written simultaneously across different threads. Must be used atomically. */
MA_ATOMIC ma_bool8 isStartedCapture; /* Can be read and written simultaneously across different threads. Must be used atomically. */
MA_ATOMIC ma_bool8 isStartedPlayback; /* Can be read and written simultaneously across different threads. Must be used atomically. */
ma_bool8 noAutoConvertSRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */
ma_bool8 noDefaultQualitySRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */
ma_bool8 noHardwareOffloading;
ma_bool8 allowCaptureAutoStreamRouting;
ma_bool8 allowPlaybackAutoStreamRouting;
} wasapi;
#endif
#ifdef MA_SUPPORT_DSOUND
struct
{
/*LPDIRECTSOUND*/ ma_ptr pPlayback;
/*LPDIRECTSOUNDBUFFER*/ ma_ptr pPlaybackPrimaryBuffer;
/*LPDIRECTSOUNDBUFFER*/ ma_ptr pPlaybackBuffer;
/*LPDIRECTSOUNDCAPTURE*/ ma_ptr pCapture;
/*LPDIRECTSOUNDCAPTUREBUFFER*/ ma_ptr pCaptureBuffer;
} dsound;
#endif
#ifdef MA_SUPPORT_WINMM
struct
{
/*HWAVEOUT*/ ma_handle hDevicePlayback;
/*HWAVEIN*/ ma_handle hDeviceCapture;
/*HANDLE*/ ma_handle hEventPlayback;
/*HANDLE*/ ma_handle hEventCapture;
ma_uint32 fragmentSizeInFrames;
ma_uint32 iNextHeaderPlayback; /* [0,periods). Used as an index into pWAVEHDRPlayback. */
ma_uint32 iNextHeaderCapture; /* [0,periods). Used as an index into pWAVEHDRCapture. */
ma_uint32 headerFramesConsumedPlayback; /* The number of PCM frames consumed in the buffer in pWAVEHEADER[iNextHeader]. */
ma_uint32 headerFramesConsumedCapture; /* ^^^ */
/*WAVEHDR**/ ma_uint8* pWAVEHDRPlayback; /* One instantiation for each period. */
/*WAVEHDR**/ ma_uint8* pWAVEHDRCapture; /* One instantiation for each period. */
ma_uint8* pIntermediaryBufferPlayback;
ma_uint8* pIntermediaryBufferCapture;
ma_uint8* _pHeapData; /* Used internally and is used for the heap allocated data for the intermediary buffer and the WAVEHDR structures. */
} winmm;
#endif
#ifdef MA_SUPPORT_ALSA
struct
{
/*snd_pcm_t**/ ma_ptr pPCMPlayback;
/*snd_pcm_t**/ ma_ptr pPCMCapture;
ma_bool8 isUsingMMapPlayback;
ma_bool8 isUsingMMapCapture;
} alsa;
#endif
#ifdef MA_SUPPORT_PULSEAUDIO
struct
{
/*pa_stream**/ ma_ptr pStreamPlayback;
/*pa_stream**/ ma_ptr pStreamCapture;
ma_pcm_rb duplexRB;
} pulse;
#endif
#ifdef MA_SUPPORT_JACK
struct
{
/*jack_client_t**/ ma_ptr pClient;
/*jack_port_t**/ ma_ptr pPortsPlayback[MA_MAX_CHANNELS];
/*jack_port_t**/ ma_ptr pPortsCapture[MA_MAX_CHANNELS];
float* pIntermediaryBufferPlayback; /* Typed as a float because JACK is always floating point. */
float* pIntermediaryBufferCapture;
} jack;
#endif
#ifdef MA_SUPPORT_COREAUDIO
struct
{
ma_uint32 deviceObjectIDPlayback;
ma_uint32 deviceObjectIDCapture;
/*AudioUnit*/ ma_ptr audioUnitPlayback;
/*AudioUnit*/ ma_ptr audioUnitCapture;
/*AudioBufferList**/ ma_ptr pAudioBufferList; /* Only used for input devices. */
ma_uint32 audioBufferCapInFrames; /* Only used for input devices. The capacity in frames of each buffer in pAudioBufferList. */
ma_event stopEvent;
ma_uint32 originalPeriodSizeInFrames;
ma_uint32 originalPeriodSizeInMilliseconds;
ma_uint32 originalPeriods;
ma_bool32 isDefaultPlaybackDevice;
ma_bool32 isDefaultCaptureDevice;
ma_bool32 isSwitchingPlaybackDevice; /* <-- Set to true when the default device has changed and miniaudio is in the process of switching. */
ma_bool32 isSwitchingCaptureDevice; /* <-- Set to true when the default device has changed and miniaudio is in the process of switching. */
ma_pcm_rb duplexRB;
void* pRouteChangeHandler; /* Only used on mobile platforms. Obj-C object for handling route changes. */
} coreaudio;
#endif
#ifdef MA_SUPPORT_SNDIO
struct
{
ma_ptr handlePlayback;
ma_ptr handleCapture;
ma_bool32 isStartedPlayback;
ma_bool32 isStartedCapture;
} sndio;
#endif
#ifdef MA_SUPPORT_AUDIO4
struct
{
int fdPlayback;
int fdCapture;
} audio4;
#endif
#ifdef MA_SUPPORT_OSS
struct
{
int fdPlayback;
int fdCapture;
} oss;
#endif
#ifdef MA_SUPPORT_AAUDIO
struct
{
/*AAudioStream**/ ma_ptr pStreamPlayback;
/*AAudioStream**/ ma_ptr pStreamCapture;
ma_pcm_rb duplexRB;
} aaudio;
#endif
#ifdef MA_SUPPORT_OPENSL
struct
{
/*SLObjectItf*/ ma_ptr pOutputMixObj;
/*SLOutputMixItf*/ ma_ptr pOutputMix;
/*SLObjectItf*/ ma_ptr pAudioPlayerObj;
/*SLPlayItf*/ ma_ptr pAudioPlayer;
/*SLObjectItf*/ ma_ptr pAudioRecorderObj;
/*SLRecordItf*/ ma_ptr pAudioRecorder;
/*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueuePlayback;
/*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueueCapture;
ma_bool32 isDrainingCapture;
ma_bool32 isDrainingPlayback;
ma_uint32 currentBufferIndexPlayback;
ma_uint32 currentBufferIndexCapture;
ma_uint8* pBufferPlayback; /* This is malloc()'d and is used for storing audio data. Typed as ma_uint8 for easy offsetting. */
ma_uint8* pBufferCapture;
ma_pcm_rb duplexRB;
} opensl;
#endif
#ifdef MA_SUPPORT_WEBAUDIO
struct
{
int indexPlayback; /* We use a factory on the JavaScript side to manage devices and use an index for JS/C interop. */
int indexCapture;
} webaudio;
#endif
#ifdef MA_SUPPORT_NULL
struct
{
ma_thread deviceThread;
ma_event operationEvent;
ma_event operationCompletionEvent;
ma_semaphore operationSemaphore;
ma_uint32 operation;
ma_result operationResult;
ma_timer timer;
double priorRunTime;
ma_uint32 currentPeriodFramesRemainingPlayback;
ma_uint32 currentPeriodFramesRemainingCapture;
ma_uint64 lastProcessedFramePlayback;
ma_uint64 lastProcessedFrameCapture;
MA_ATOMIC ma_bool8 isStarted; /* Read and written by multiple threads. Must be used atomically. */
} null_device;
#endif
};
};
#if defined(_MSC_VER) && !defined(__clang__)
#pragma warning(pop)
#elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
#pragma GCC diagnostic pop /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
#endif
/*
Initializes a `ma_context_config` object.
Return Value
------------
A `ma_context_config` initialized to defaults.
Remarks
-------
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
is updated and new members are added to `ma_context_config`. It also sets logical defaults.
You can override members of the returned object by changing it's members directly.
See Also
--------
ma_context_init()
*/
MA_API ma_context_config ma_context_config_init(void);
/*
Initializes a context.
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
device. There is one context to many devices, and a device is created from a context. A context is required to enumerate devices.
Parameters
----------
backends (in, optional)
A list of backends to try initializing, in priority order. Can be NULL, in which case it uses default priority order.
backendCount (in, optional)
The number of items in `backend`. Ignored if `backend` is NULL.
pConfig (in, optional)
The context configuration.
pContext (in)
A pointer to the context object being initialized.
Return Value
------------
MA_SUCCESS if successful; any other error code otherwise.
Thread Safety
-------------
Unsafe. Do not call this function across multiple threads as some backends read and write to global state.
Remarks
-------
When `backends` is NULL, the default priority order will be used. Below is a list of backends in priority order:
|-------------|-----------------------|--------------------------------------------------------|
| Name | Enum Name | Supported Operating Systems |
|-------------|-----------------------|--------------------------------------------------------|
| WASAPI | ma_backend_wasapi | Windows Vista+ |
| DirectSound | ma_backend_dsound | Windows XP+ |
| WinMM | ma_backend_winmm | Windows XP+ (may work on older versions, but untested) |
| Core Audio | ma_backend_coreaudio | macOS, iOS |
| ALSA | ma_backend_alsa | Linux |
| PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) |
| JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) |
| sndio | ma_backend_sndio | OpenBSD |
| audio(4) | ma_backend_audio4 | NetBSD, OpenBSD |
| OSS | ma_backend_oss | FreeBSD |
| AAudio | ma_backend_aaudio | Android 8+ |
| OpenSL|ES | ma_backend_opensl | Android (API level 16+) |
| Web Audio | ma_backend_webaudio | Web (via Emscripten) |
| Null | ma_backend_null | Cross Platform (not used on Web) |
|-------------|-----------------------|--------------------------------------------------------|
The context can be configured via the `pConfig` argument. The config object is initialized with `ma_context_config_init()`. Individual configuration settings
can then be set directly on the structure. Below are the members of the `ma_context_config` object.
logCallback
Callback for handling log messages from miniaudio.
threadPriority
The desired priority to use for the audio thread. Allowable values include the following:
|--------------------------------------|
| Thread Priority |
|--------------------------------------|
| ma_thread_priority_idle |
| ma_thread_priority_lowest |
| ma_thread_priority_low |
| ma_thread_priority_normal |
| ma_thread_priority_high |
| ma_thread_priority_highest (default) |
| ma_thread_priority_realtime |
| ma_thread_priority_default |
|--------------------------------------|
pUserData
A pointer to application-defined data. This can be accessed from the context object directly such as `context.pUserData`.
allocationCallbacks
Structure containing custom allocation callbacks. Leaving this at defaults will cause it to use MA_MALLOC, MA_REALLOC and MA_FREE. These allocation
callbacks will be used for anything tied to the context, including devices.
alsa.useVerboseDeviceEnumeration
ALSA will typically enumerate many different devices which can be intrusive and not user-friendly. To combat this, miniaudio will enumerate only unique
card/device pairs by default. The problem with this is that you lose a bit of flexibility and control. Setting alsa.useVerboseDeviceEnumeration makes
it so the ALSA backend includes all devices. Defaults to false.
pulse.pApplicationName
PulseAudio only. The application name to use when initializing the PulseAudio context with `pa_context_new()`.
pulse.pServerName
PulseAudio only. The name of the server to connect to with `pa_context_connect()`.
pulse.tryAutoSpawn
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
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
intrusive for the end user.
coreaudio.sessionCategory
iOS only. The session category to use for the shared AudioSession instance. Below is a list of allowable values and their Core Audio equivalents.
|-----------------------------------------|-------------------------------------|
| miniaudio Token | Core Audio Token |
|-----------------------------------------|-------------------------------------|
| ma_ios_session_category_ambient | AVAudioSessionCategoryAmbient |
| ma_ios_session_category_solo_ambient | AVAudioSessionCategorySoloAmbient |
| ma_ios_session_category_playback | AVAudioSessionCategoryPlayback |
| ma_ios_session_category_record | AVAudioSessionCategoryRecord |
| ma_ios_session_category_play_and_record | AVAudioSessionCategoryPlayAndRecord |
| ma_ios_session_category_multi_route | AVAudioSessionCategoryMultiRoute |
| ma_ios_session_category_none | AVAudioSessionCategoryAmbient |
| ma_ios_session_category_default | AVAudioSessionCategoryAmbient |
|-----------------------------------------|-------------------------------------|
coreaudio.sessionCategoryOptions
iOS only. Session category options to use with the shared AudioSession instance. Below is a list of allowable values and their Core Audio equivalents.
|---------------------------------------------------------------------------|------------------------------------------------------------------|
| miniaudio Token | Core Audio Token |
|---------------------------------------------------------------------------|------------------------------------------------------------------|
| ma_ios_session_category_option_mix_with_others | AVAudioSessionCategoryOptionMixWithOthers |
| ma_ios_session_category_option_duck_others | AVAudioSessionCategoryOptionDuckOthers |
| ma_ios_session_category_option_allow_bluetooth | AVAudioSessionCategoryOptionAllowBluetooth |
| ma_ios_session_category_option_default_to_speaker | AVAudioSessionCategoryOptionDefaultToSpeaker |
| ma_ios_session_category_option_interrupt_spoken_audio_and_mix_with_others | AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers |
| ma_ios_session_category_option_allow_bluetooth_a2dp | AVAudioSessionCategoryOptionAllowBluetoothA2DP |
| ma_ios_session_category_option_allow_air_play | AVAudioSessionCategoryOptionAllowAirPlay |
|---------------------------------------------------------------------------|------------------------------------------------------------------|
jack.pClientName
The name of the client to pass to `jack_client_open()`.
jack.tryStartServer
Whether or not to try auto-starting the JACK server. Defaults to false.
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
relevant backends every time it's initialized.
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
reason for this is that a pointer to the context is stored in the `ma_device` structure.
Example 1 - Default Initialization
----------------------------------
The example below shows how to initialize the context using the default configuration.
```c
ma_context context;
ma_result result = ma_context_init(NULL, 0, NULL, &context);
if (result != MA_SUCCESS) {
// Error.
}
```
Example 2 - Custom Configuration
--------------------------------
The example below shows how to initialize the context using custom backend priorities and a custom configuration. In this hypothetical example, the program
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
want an error to be returned if no valid backend is available which they achieve by excluding the Null backend.
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.
```c
ma_backend backends[] = {
ma_backend_alsa,
ma_backend_pulseaudio,
ma_backend_wasapi,
ma_backend_dsound
};
ma_context_config config = ma_context_config_init();
config.logCallback = my_log_callback;
config.pUserData = pMyUserData;
ma_context context;
ma_result result = ma_context_init(backends, sizeof(backends)/sizeof(backends[0]), &config, &context);
if (result != MA_SUCCESS) {
// Error.
if (result == MA_NO_BACKEND) {
// Couldn't find an appropriate backend.
}
}
```
See Also
--------
ma_context_config_init()
ma_context_uninit()
*/
MA_API ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pConfig, ma_context* pContext);
/*
Uninitializes a context.
Return Value
------------
MA_SUCCESS if successful; any other error code otherwise.
Thread Safety
-------------
Unsafe. Do not call this function across multiple threads as some backends read and write to global state.
Remarks
-------
Results are undefined if you call this while any device created by this context is still active.
See Also
--------
ma_context_init()
*/
MA_API ma_result ma_context_uninit(ma_context* pContext);
/*
Retrieves the size of the ma_context object.
This is mainly for the purpose of bindings to know how much memory to allocate.
*/
MA_API size_t ma_context_sizeof(void);
/*
Enumerates over every device (both playback and capture).
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
an internal heap allocation, or it simply suits your code better.
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
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,
but don't call it from within the enumeration callback.
Returning false from the callback will stop enumeration. Returning true will continue enumeration.
Parameters
----------
pContext (in)
A pointer to the context performing the enumeration.
callback (in)
The callback to fire for each enumerated device.
pUserData (in)
A pointer to application-defined data passed to the callback.
Return Value
------------
MA_SUCCESS if successful; any other error code otherwise.
Thread Safety
-------------
Safe. This is guarded using a simple mutex lock.
Remarks
-------
Do _not_ assume the first enumerated device of a given type is the default device.
Some backends and platforms may only support default playback and capture devices.
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,
do not try to call `ma_context_get_device_info()` from within the callback.
Consider using `ma_context_get_devices()` for a simpler and safer API, albeit at the expense of an internal heap allocation.
Example 1 - Simple Enumeration
------------------------------
ma_bool32 ma_device_enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData)
{
printf("Device Name: %s\n", pInfo->name);
return MA_TRUE;
}
ma_result result = ma_context_enumerate_devices(&context, my_device_enum_callback, pMyUserData);
if (result != MA_SUCCESS) {
// Error.
}
See Also
--------
ma_context_get_devices()
*/
MA_API ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData);
/*
Retrieves basic information about every active playback and/or capture device.
This function will allocate memory internally for the device lists and return a pointer to them through the `ppPlaybackDeviceInfos` and `ppCaptureDeviceInfos`
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.
Parameters
----------
pContext (in)
A pointer to the context performing the enumeration.
ppPlaybackDeviceInfos (out)
A pointer to a pointer that will receive the address of a buffer containing the list of `ma_device_info` structures for playback devices.
pPlaybackDeviceCount (out)
A pointer to an unsigned integer that will receive the number of playback devices.
ppCaptureDeviceInfos (out)
A pointer to a pointer that will receive the address of a buffer containing the list of `ma_device_info` structures for capture devices.
pCaptureDeviceCount (out)
A pointer to an unsigned integer that will receive the number of capture devices.
Return Value
------------
MA_SUCCESS if successful; any other error code otherwise.
Thread Safety
-------------
Unsafe. Since each call to this function invalidates the pointers from the previous call, you should not be calling this simultaneously across multiple
threads. Instead, you need to make a copy of the returned data with your own higher level synchronization.
Remarks
-------
It is _not_ safe to assume the first device in the list is the default device.
You can pass in NULL for the playback or capture lists in which case they'll be ignored.
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.
See Also
--------
ma_context_get_devices()
*/
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);
/*
Retrieves information about a device of the given type, with the specified ID and share mode.
Parameters
----------
pContext (in)
A pointer to the context performing the query.
deviceType (in)
The type of the device being queried. Must be either `ma_device_type_playback` or `ma_device_type_capture`.
pDeviceID (in)
The ID of the device being queried.
shareMode (in)
The share mode to query for device capabilities. This should be set to whatever you're intending on using when initializing the device. If you're unsure,
set this to `ma_share_mode_shared`.
pDeviceInfo (out)
A pointer to the `ma_device_info` structure that will receive the device information.
Return Value
------------
MA_SUCCESS if successful; any other error code otherwise.
Thread Safety
-------------
Safe. This is guarded using a simple mutex lock.
Remarks
-------
Do _not_ call this from within the `ma_context_enumerate_devices()` callback.
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
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
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
the requested share mode is unsupported.
This leaves pDeviceInfo unmodified in the result of an error.
*/
MA_API ma_result ma_context_get_device_info(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo);
/*
Determines if the given context supports loopback mode.
Parameters
----------
pContext (in)
A pointer to the context getting queried.
Return Value
------------
MA_TRUE if the context supports loopback mode; MA_FALSE otherwise.
*/
MA_API ma_bool32 ma_context_is_loopback_supported(ma_context* pContext);
/*
Initializes a device config with default settings.
Parameters
----------
deviceType (in)
The type of the device this config is being initialized for. This must set to one of the following:
|-------------------------|
| Device Type |
|-------------------------|
| ma_device_type_playback |
| ma_device_type_capture |
| ma_device_type_duplex |
| ma_device_type_loopback |
|-------------------------|
Return Value
------------
A new device config object with default settings. You will typically want to adjust the config after this function returns. See remarks.
Thread Safety
-------------
Safe.
Callback Safety
---------------
Safe, but don't try initializing a device in a callback.
Remarks
-------
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
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
before initializing the device.
See `ma_device_init()` for details on specific configuration options.
Example 1 - Simple Configuration
--------------------------------
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
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
to the `ma_device_config` structure.
```c
ma_device_config config = ma_device_config_init(ma_device_type_playback);
config.playback.format = ma_format_f32;
config.playback.channels = 2;
config.sampleRate = 48000;
config.dataCallback = ma_data_callback;
config.pUserData = pMyUserData;
```
See Also
--------
ma_device_init()
ma_device_init_ex()
*/
MA_API ma_device_config ma_device_config_init(ma_device_type deviceType);
/*
Initializes a device.
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
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
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
device is done via a callback which is fired by miniaudio at periodic time intervals.
The frequency at which data is delivered to and from a device depends on the size of it's period. The size of the period can be defined in terms of PCM frames
or milliseconds, whichever is more convenient. Generally speaking, the smaller the period, the lower the latency at the expense of higher CPU usage and
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
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
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
backend is ultimately responsible for what it gives you. You cannot assume you will get exactly what you ask for.
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
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
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.
Parameters
----------
pContext (in, optional)
A pointer to the context that owns the device. This can be null, in which case it creates a default context internally.
pConfig (in)
A pointer to the device configuration. Cannot be null. See remarks for details.
pDevice (out)
A pointer to the device object being initialized.
Return Value
------------
MA_SUCCESS if successful; any other error code otherwise.
Thread Safety
-------------
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
calling this at the same time as `ma_device_uninit()`.
Callback Safety
---------------
Unsafe. It is not safe to call this inside any callback.
Remarks
-------
Setting `pContext` to NULL will result in miniaudio creating a default context internally and is equivalent to passing in a context initialized like so:
```c
ma_context_init(NULL, 0, NULL, &context);
```
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
device.pContext for the initialization of other devices.
The device can be configured via the `pConfig` argument. The config object is initialized with `ma_device_config_init()`. Individual configuration settings can
then be set directly on the structure. Below are the members of the `ma_device_config` object.
deviceType
Must be `ma_device_type_playback`, `ma_device_type_capture`, `ma_device_type_duplex` of `ma_device_type_loopback`.
sampleRate
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.
periodSizeInFrames
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
be used depending on the selected performance profile. This value affects latency. See below for details.
periodSizeInMilliseconds
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
used depending on the selected performance profile. The value affects latency. See below for details.
periods
The number of periods making up the device's entire buffer. The total buffer size is `periodSizeInFrames` or `periodSizeInMilliseconds` multiplied by
this value. This is just a hint as backends will be the ones who ultimately decide how your periods will be configured.
performanceProfile
A hint to miniaudio as to the performance requirements of your program. Can be either `ma_performance_profile_low_latency` (default) or
`ma_performance_profile_conservative`. This mainly affects the size of default buffers and can usually be left at it's default value.
noPreZeroedOutputBuffer
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
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
callback will write to every sample in the output buffer, or if you are doing your own clearing.
noClip
When set to true, the contents of the output buffer passed into the data callback will be clipped after returning. When set to false (default), 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 not the clip. This only
applies when the playback sample format is f32.
dataCallback
The callback to fire whenever data is ready to be delivered to or from the device.
stopCallback
The callback to fire whenever the device has stopped, either explicitly via `ma_device_stop()`, or implicitly due to things like the device being
disconnected.
pUserData
The user data pointer to use with the device. You can access this directly from the device object like `device.pUserData`.
resampling.algorithm
The resampling algorithm to use when miniaudio needs to perform resampling between the rate specified by `sampleRate` and the device's native rate. The
default value is `ma_resample_algorithm_linear`, and the quality can be configured with `resampling.linear.lpfOrder`.
resampling.linear.lpfOrder
The linear resampler applies a low-pass filter as part of it's procesing for anti-aliasing. This setting controls the order of the filter. The higher
the value, the better the quality, in general. Setting this to 0 will disable low-pass filtering altogether. The maximum value is
`MA_MAX_FILTER_ORDER`. The default value is `min(4, MA_MAX_FILTER_ORDER)`.
playback.pDeviceID
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
default playback device. Retrieve the device ID from the `ma_device_info` structure, which can be retrieved using device enumeration.
playback.format
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
initialization from the device object directly with `device.playback.format`.
playback.channels
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
from the device object directly with `device.playback.channels`.
playback.channelMap
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
device object direct with `device.playback.channelMap`.
playback.shareMode
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
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
ma_share_mode_shared and reinitializing.
capture.pDeviceID
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
default capture device. Retrieve the device ID from the `ma_device_info` structure, which can be retrieved using device enumeration.
capture.format
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
initialization from the device object directly with `device.capture.format`.
capture.channels
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
from the device object directly with `device.capture.channels`.
capture.channelMap
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
device object direct with `device.capture.channelMap`.
capture.shareMode
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
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
ma_share_mode_shared and reinitializing.
wasapi.noAutoConvertSRC
WASAPI only. When set to true, disables WASAPI's automatic resampling and forces the use of miniaudio's resampler. Defaults to false.
wasapi.noDefaultQualitySRC
WASAPI only. Only used when `wasapi.noAutoConvertSRC` is set to false. When set to true, disables the use of `AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY`.
You should usually leave this set to false, which is the default.
wasapi.noAutoStreamRouting
WASAPI only. When set to true, disables automatic stream routing on the WASAPI backend. Defaults to false.
wasapi.noHardwareOffloading
WASAPI only. When set to true, disables the use of WASAPI's hardware offloading feature. Defaults to false.
alsa.noMMap
ALSA only. When set to true, disables MMap mode. Defaults to false.
alsa.noAutoFormat
ALSA only. When set to true, disables ALSA's automatic format conversion by including the SND_PCM_NO_AUTO_FORMAT flag. Defaults to false.
alsa.noAutoChannels
ALSA only. When set to true, disables ALSA's automatic channel conversion by including the SND_PCM_NO_AUTO_CHANNELS flag. Defaults to false.
alsa.noAutoResample
ALSA only. When set to true, disables ALSA's automatic resampling by including the SND_PCM_NO_AUTO_RESAMPLE flag. Defaults to false.
pulse.pStreamNamePlayback
PulseAudio only. Sets the stream name for playback.
pulse.pStreamNameCapture
PulseAudio only. Sets the stream name for capture.
coreaudio.allowNominalSampleRateChange
Core Audio only. Desktop only. When enabled, allows the sample rate of the device to be changed at the operating system level. This
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
that is known to be natively supported by the hardware thereby avoiding the cost of resampling. When set to true, miniaudio will
find the closest match between the sample rate requested in the device config and the sample rates natively supported by the
hardware. When set to false, the sample rate currently set by the operating system will always be used.
Once initialized, the device's config is immutable. If you need to change the config you will need to initialize a new device.
After initializing the device it will be in a stopped state. To start it, use `ma_device_start()`.
If both `periodSizeInFrames` and `periodSizeInMilliseconds` are set to zero, it will default to `MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY` or
`MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE`, depending on whether or not `performanceProfile` is set to `ma_performance_profile_low_latency` or
`ma_performance_profile_conservative`.
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
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
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,
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.
Starting with Windows 10, miniaudio will use low-latency shared mode where possible which may make exclusive mode unnecessary.
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
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
on an optimized pass-through fast path. You can retrieve the format, channel count and sample rate by inspecting the `playback/capture.format`,
`playback/capture.channels` and `sampleRate` members of the device object.
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
asking for permissions. Please refer to the official documentation for ActivateAudioInterfaceAsync() for more information.
ALSA Specific: When initializing the default device, requesting shared mode will try using the "dmix" device for playback and the "dsnoop" device for capture.
If these fail it will try falling back to the "hw" device.
Example 1 - Simple Initialization
---------------------------------
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
playback device this is usually all you need.
```c
ma_device_config config = ma_device_config_init(ma_device_type_playback);
config.playback.format = ma_format_f32;
config.playback.channels = 2;
config.sampleRate = 48000;
config.dataCallback = ma_data_callback;
config.pMyUserData = pMyUserData;
ma_device device;
ma_result result = ma_device_init(NULL, &config, &device);
if (result != MA_SUCCESS) {
// Error
}
```
Example 2 - Advanced Initialization
-----------------------------------
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
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
enumeration.
```c
ma_context context;
ma_result result = ma_context_init(NULL, 0, NULL, &context);
if (result != MA_SUCCESS) {
// Error
}
ma_device_info* pPlaybackDeviceInfos;
ma_uint32 playbackDeviceCount;
result = ma_context_get_devices(&context, &pPlaybackDeviceInfos, &playbackDeviceCount, NULL, NULL);
if (result != MA_SUCCESS) {
// Error
}
// ... choose a device from pPlaybackDeviceInfos ...
ma_device_config config = ma_device_config_init(ma_device_type_playback);
config.playback.pDeviceID = pMyChosenDeviceID; // <-- Get this from the `id` member of one of the `ma_device_info` objects returned by ma_context_get_devices().
config.playback.format = ma_format_f32;
config.playback.channels = 2;
config.sampleRate = 48000;
config.dataCallback = ma_data_callback;
config.pUserData = pMyUserData;
config.periodSizeInMilliseconds = 10;
config.periods = 3;
ma_device device;
result = ma_device_init(&context, &config, &device);
if (result != MA_SUCCESS) {
// Error
}
```
See Also
--------
ma_device_config_init()
ma_device_uninit()
ma_device_start()
ma_context_init()
ma_context_get_devices()
ma_context_enumerate_devices()
*/
MA_API ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice);
/*
Initializes a device without a context, with extra parameters for controlling the configuration of the internal self-managed context.
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
allows you to configure the internally created context.
Parameters
----------
backends (in, optional)
A list of backends to try initializing, in priority order. Can be NULL, in which case it uses default priority order.
backendCount (in, optional)
The number of items in `backend`. Ignored if `backend` is NULL.
pContextConfig (in, optional)
The context configuration.
pConfig (in)
A pointer to the device configuration. Cannot be null. See remarks for details.
pDevice (out)
A pointer to the device object being initialized.
Return Value
------------
MA_SUCCESS if successful; any other error code otherwise.
Thread Safety
-------------
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
calling this at the same time as `ma_device_uninit()`.
Callback Safety
---------------
Unsafe. It is not safe to call this inside any callback.
Remarks
-------
You only need to use this function if you want to configure the context differently to it's defaults. You should never use this function if you want to manage
your own context.
See the documentation for `ma_context_init()` for information on the different context configuration options.
See Also
--------
ma_device_init()
ma_device_uninit()
ma_device_config_init()
ma_context_init()
*/
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);
/*
Uninitializes a device.
This will explicitly stop the device. You do not need to call `ma_device_stop()` beforehand, but it's harmless if you do.
Parameters
----------
pDevice (in)
A pointer to the device to stop.
Return Value
------------
MA_SUCCESS if successful; any other error code otherwise.
Thread Safety
-------------
Unsafe. As soon as this API is called the device should be considered undefined.
Callback Safety
---------------
Unsafe. It is not safe to call this inside any callback. Doing this will result in a deadlock.
See Also
--------
ma_device_init()
ma_device_stop()
*/
MA_API void ma_device_uninit(ma_device* pDevice);
/*
Starts the device. For playback devices this begins playback. For capture devices it begins recording.
Use `ma_device_stop()` to stop the device.
Parameters
----------
pDevice (in)
A pointer to the device to start.
Return Value
------------
MA_SUCCESS if successful; any other error code otherwise.
Thread Safety
-------------
Safe. It's safe to call this from any thread with the exception of the callback thread.
Callback Safety
---------------
Unsafe. It is not safe to call this inside any callback.
Remarks
-------
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
audio data in the buffer, which needs to be done before the device begins playback.
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.
Do not call this in any callback.
See Also
--------
ma_device_stop()
*/
MA_API ma_result ma_device_start(ma_device* pDevice);
/*
Stops the device. For playback devices this stops playback. For capture devices it stops recording.
Use `ma_device_start()` to start the device again.
Parameters
----------
pDevice (in)
A pointer to the device to stop.
Return Value
------------
MA_SUCCESS if successful; any other error code otherwise.
Thread Safety
-------------
Safe. It's safe to call this from any thread with the exception of the callback thread.
Callback Safety
---------------
Unsafe. It is not safe to call this inside any callback. Doing this will result in a deadlock.
Remarks
-------
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
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
that was specified at initialization time).
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
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
speakers or received from the microphone which can in turn result in de-syncs.
Do not call this in any callback.
This will be called implicitly by `ma_device_uninit()`.
See Also
--------
ma_device_start()
*/
MA_API ma_result ma_device_stop(ma_device* pDevice);
/*
Determines whether or not the device is started.
Parameters
----------
pDevice (in)
A pointer to the device whose start state is being retrieved.
Return Value
------------
True if the device is started, false otherwise.
Thread Safety
-------------
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
value will be out of sync.
Callback Safety
---------------
Safe. This is implemented as a simple accessor.
See Also
--------
ma_device_start()
ma_device_stop()
*/
MA_API ma_bool32 ma_device_is_started(const ma_device* pDevice);
/*
Retrieves the state of the device.
Parameters
----------
pDevice (in)
A pointer to the device whose state is being retrieved.
Return Value
------------
The current state of the device. The return value will be one of the following:
+------------------------+------------------------------------------------------------------------------+
| MA_STATE_UNINITIALIZED | Will only be returned if the device is in the middle of initialization. |
+------------------------+------------------------------------------------------------------------------+
| MA_STATE_STOPPED | The device is stopped. The initial state of the device after initialization. |
+------------------------+------------------------------------------------------------------------------+
| MA_STATE_STARTED | The device started and requesting and/or delivering audio data. |
+------------------------+------------------------------------------------------------------------------+
| MA_STATE_STARTING | The device is in the process of starting. |
+------------------------+------------------------------------------------------------------------------+
| MA_STATE_STOPPING | The device is in the process of stopping. |
+------------------------+------------------------------------------------------------------------------+
Thread Safety
-------------
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,
there's a possibility the return value could be out of sync. See remarks.
Callback Safety
---------------
Safe. This is implemented as a simple accessor.
Remarks
-------
The general flow of a devices state goes like this:
```
ma_device_init() -> MA_STATE_UNINITIALIZED -> MA_STATE_STOPPED
ma_device_start() -> MA_STATE_STARTING -> MA_STATE_STARTED
ma_device_stop() -> MA_STATE_STOPPING -> MA_STATE_STOPPED
```
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
value returned by this function could potentially be out of sync. If this is significant to your program you need to implement your own
synchronization.
*/
MA_API ma_uint32 ma_device_get_state(const ma_device* pDevice);
/*
Sets the master volume factor for the device.
The volume factor must be between 0 (silence) and 1 (full volume). Use `ma_device_set_master_gain_db()` to use decibel notation, where 0 is full volume and
values less than 0 decreases the volume.
Parameters
----------
pDevice (in)
A pointer to the device whose volume is being set.
volume (in)
The new volume factor. Must be within the range of [0, 1].
Return Value
------------
MA_SUCCESS if the volume was set successfully.
MA_INVALID_ARGS if pDevice is NULL.
MA_INVALID_ARGS if the volume factor is not within the range of [0, 1].
Thread Safety
-------------
Safe. This just sets a local member of the device object.
Callback Safety
---------------
Safe. If you set the volume in the data callback, that data written to the output buffer will have the new volume applied.
Remarks
-------
This applies the volume factor across all channels.
This does not change the operating system's volume. It only affects the volume for the given `ma_device` object's audio stream.
See Also
--------
ma_device_get_master_volume()
ma_device_set_master_volume_gain_db()
ma_device_get_master_volume_gain_db()
*/
MA_API ma_result ma_device_set_master_volume(ma_device* pDevice, float volume);
/*
Retrieves the master volume factor for the device.
Parameters
----------
pDevice (in)
A pointer to the device whose volume factor is being retrieved.
pVolume (in)
A pointer to the variable that will receive the volume factor. The returned value will be in the range of [0, 1].
Return Value
------------
MA_SUCCESS if successful.
MA_INVALID_ARGS if pDevice is NULL.
MA_INVALID_ARGS if pVolume is NULL.
Thread Safety
-------------
Safe. This just a simple member retrieval.
Callback Safety
---------------
Safe.
Remarks
-------
If an error occurs, `*pVolume` will be set to 0.
See Also
--------
ma_device_set_master_volume()
ma_device_set_master_volume_gain_db()
ma_device_get_master_volume_gain_db()
*/
MA_API ma_result ma_device_get_master_volume(ma_device* pDevice, float* pVolume);
/*
Sets the master volume for the device as gain in decibels.
A gain of 0 is full volume, whereas a gain of < 0 will decrease the volume.
Parameters
----------
pDevice (in)
A pointer to the device whose gain is being set.
gainDB (in)
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.
Return Value
------------
MA_SUCCESS if the volume was set successfully.
MA_INVALID_ARGS if pDevice is NULL.
MA_INVALID_ARGS if the gain is > 0.
Thread Safety
-------------
Safe. This just sets a local member of the device object.
Callback Safety
---------------
Safe. If you set the volume in the data callback, that data written to the output buffer will have the new volume applied.
Remarks
-------
This applies the gain across all channels.
This does not change the operating system's volume. It only affects the volume for the given `ma_device` object's audio stream.
See Also
--------
ma_device_get_master_volume_gain_db()
ma_device_set_master_volume()
ma_device_get_master_volume()
*/
MA_API ma_result ma_device_set_master_gain_db(ma_device* pDevice, float gainDB);
/*
Retrieves the master gain in decibels.
Parameters
----------
pDevice (in)
A pointer to the device whose gain is being retrieved.
pGainDB (in)
A pointer to the variable that will receive the gain in decibels. The returned value will be <= 0.
Return Value
------------
MA_SUCCESS if successful.
MA_INVALID_ARGS if pDevice is NULL.
MA_INVALID_ARGS if pGainDB is NULL.
Thread Safety
-------------
Safe. This just a simple member retrieval.
Callback Safety
---------------
Safe.
Remarks
-------
If an error occurs, `*pGainDB` will be set to 0.
See Also
--------
ma_device_set_master_volume_gain_db()
ma_device_set_master_volume()
ma_device_get_master_volume()
*/
MA_API ma_result ma_device_get_master_gain_db(ma_device* pDevice, float* pGainDB);
/*
Called from the data callback of asynchronous backends to allow miniaudio to process the data and fire the miniaudio data callback.
Parameters
----------
pDevice (in)
A pointer to device whose processing the data callback.
pOutput (out)
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
this can be NULL, in which case pInput must not be NULL.
pInput (in)
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
NULL, in which case `pOutput` must not be NULL.
frameCount (in)
The number of frames being processed.
Return Value
------------
MA_SUCCESS if successful; any other result code otherwise.
Thread Safety
-------------
This function should only ever be called from the internal data callback of the backend. It is safe to call this simultaneously between a
playback and capture device in duplex setups.
Callback Safety
---------------
Do not call this from the miniaudio data callback. It should only ever be called from the internal data callback of the backend.
Remarks
-------
If both `pOutput` and `pInput` are NULL, and error will be returned. In duplex scenarios, both `pOutput` and `pInput` can be non-NULL, in
which case `pInput` will be processed first, followed by `pOutput`.
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
callback.
*/
MA_API ma_result ma_device_handle_backend_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount);
/*
Retrieves a friendly name for a backend.
*/
MA_API const char* ma_get_backend_name(ma_backend backend);
/*
Determines whether or not the given backend is available by the compilation environment.
*/
MA_API ma_bool32 ma_is_backend_enabled(ma_backend backend);
/*
Retrieves compile-time enabled backends.
Parameters
----------
pBackends (out, optional)
A pointer to the buffer that will receive the enabled backends. Set to NULL to retrieve the backend count. Setting
the capacity of the buffer to `MA_BUFFER_COUNT` will guarantee it's large enough for all backends.
backendCap (in)
The capacity of the `pBackends` buffer.
pBackendCount (out)
A pointer to the variable that will receive the enabled backend count.
Return Value
------------
MA_SUCCESS if successful.
MA_INVALID_ARGS if `pBackendCount` is NULL.
MA_NO_SPACE if the capacity of `pBackends` is not large enough.
If `MA_NO_SPACE` is returned, the `pBackends` buffer will be filled with `*pBackendCount` values.
Thread Safety
-------------
Safe.
Callback Safety
---------------
Safe.
Remarks
-------
If you want to retrieve the number of backends so you can determine the capacity of `pBackends` buffer, you can call
this function with `pBackends` set to NULL.
This will also enumerate the null backend. If you don't want to include this you need to check for `ma_backend_null`
when you enumerate over the returned backends and handle it appropriately. Alternatively, you can disable it at
compile time with `MA_NO_NULL`.
The returned backends are determined based on compile time settings, not the platform it's currently running on. For
example, PulseAudio will be returned if it was enabled at compile time, even when the user doesn't actually have
PulseAudio installed.
Example 1
---------
The example below retrieves the enabled backend count using a fixed sized buffer allocated on the stack. The buffer is
given a capacity of `MA_BACKEND_COUNT` which will guarantee it'll be large enough to store all available backends.
Since `MA_BACKEND_COUNT` is always a relatively small value, this should be suitable for most scenarios.
```
ma_backend enabledBackends[MA_BACKEND_COUNT];
size_t enabledBackendCount;
result = ma_get_enabled_backends(enabledBackends, MA_BACKEND_COUNT, &enabledBackendCount);
if (result != MA_SUCCESS) {
// Failed to retrieve enabled backends. Should never happen in this example since all inputs are valid.
}
```
See Also
--------
ma_is_backend_enabled()
*/
MA_API ma_result ma_get_enabled_backends(ma_backend* pBackends, size_t backendCap, size_t* pBackendCount);
/*
Determines whether or not loopback mode is support by a backend.
*/
MA_API ma_bool32 ma_is_loopback_supported(ma_backend backend);
#endif /* MA_NO_DEVICE_IO */
#ifndef MA_NO_THREADING
/*
Locks a spinlock.
*/
MA_API ma_result ma_spinlock_lock(volatile ma_spinlock* pSpinlock);
/*
Locks a spinlock, but does not yield() when looping.
*/
MA_API ma_result ma_spinlock_lock_noyield(volatile ma_spinlock* pSpinlock);
/*
Unlocks a spinlock.
*/
MA_API ma_result ma_spinlock_unlock(volatile ma_spinlock* pSpinlock);
/*
Creates a mutex.
A mutex must be created from a valid context. A mutex is initially unlocked.
*/
MA_API ma_result ma_mutex_init(ma_mutex* pMutex);
/*
Deletes a mutex.
*/
MA_API void ma_mutex_uninit(ma_mutex* pMutex);
/*
Locks a mutex with an infinite timeout.
*/
MA_API void ma_mutex_lock(ma_mutex* pMutex);
/*
Unlocks a mutex.
*/
MA_API void ma_mutex_unlock(ma_mutex* pMutex);
/*
Initializes an auto-reset event.
*/
MA_API ma_result ma_event_init(ma_event* pEvent);
/*
Uninitializes an auto-reset event.
*/
MA_API void ma_event_uninit(ma_event* pEvent);
/*
Waits for the specified auto-reset event to become signalled.
*/
MA_API ma_result ma_event_wait(ma_event* pEvent);
/*
Signals the specified auto-reset event.
*/
MA_API ma_result ma_event_signal(ma_event* pEvent);
#endif /* MA_NO_THREADING */
/************************************************************************************************************************************************************
Utiltities
************************************************************************************************************************************************************/
/*
Adjust buffer size based on a scaling factor.
This just multiplies the base size by the scaling factor, making sure it's a size of at least 1.
*/
MA_API ma_uint32 ma_scale_buffer_size(ma_uint32 baseBufferSize, float scale);
/*
Calculates a buffer size in milliseconds from the specified number of frames and sample rate.
*/
MA_API ma_uint32 ma_calculate_buffer_size_in_milliseconds_from_frames(ma_uint32 bufferSizeInFrames, ma_uint32 sampleRate);
/*
Calculates a buffer size in frames from the specified number of milliseconds and sample rate.
*/
MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate);
/*
Copies PCM frames from one buffer to another.
*/
MA_API void ma_copy_pcm_frames(void* dst, const void* src, ma_uint64 frameCount, ma_format format, ma_uint32 channels);
/*
Copies silent frames into the given buffer.
Remarks
-------
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
makes more sense for the purpose of mixing to initialize it to the center point.
*/
MA_API void ma_silence_pcm_frames(void* p, ma_uint64 frameCount, ma_format format, ma_uint32 channels);
static MA_INLINE void ma_zero_pcm_frames(void* p, ma_uint64 frameCount, ma_format format, ma_uint32 channels) { ma_silence_pcm_frames(p, frameCount, format, channels); }
/*
Offsets a pointer by the specified number of PCM frames.
*/
MA_API void* ma_offset_pcm_frames_ptr(void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels);
MA_API const void* ma_offset_pcm_frames_const_ptr(const void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels);
static MA_INLINE float* ma_offset_pcm_frames_ptr_f32(float* p, ma_uint64 offsetInFrames, ma_uint32 channels) { return (float*)ma_offset_pcm_frames_const_ptr((void*)p, offsetInFrames, ma_format_f32, channels); }
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); }
/*
Clips f32 samples.
*/
MA_API void ma_clip_samples_f32(float* p, ma_uint64 sampleCount);
static MA_INLINE void ma_clip_pcm_frames_f32(float* p, ma_uint64 frameCount, ma_uint32 channels) { ma_clip_samples_f32(p, frameCount*channels); }
/*
Helper for applying a volume factor to samples.
Note that the source and destination buffers can be the same, in which case it'll perform the operation in-place.
*/
MA_API void ma_copy_and_apply_volume_factor_u8(ma_uint8* pSamplesOut, const ma_uint8* pSamplesIn, ma_uint64 sampleCount, float factor);
MA_API void ma_copy_and_apply_volume_factor_s16(ma_int16* pSamplesOut, const ma_int16* pSamplesIn, ma_uint64 sampleCount, float factor);
MA_API void ma_copy_and_apply_volume_factor_s24(void* pSamplesOut, const void* pSamplesIn, ma_uint64 sampleCount, float factor);
MA_API void ma_copy_and_apply_volume_factor_s32(ma_int32* pSamplesOut, const ma_int32* pSamplesIn, ma_uint64 sampleCount, float factor);
MA_API void ma_copy_and_apply_volume_factor_f32(float* pSamplesOut, const float* pSamplesIn, ma_uint64 sampleCount, float factor);
MA_API void ma_apply_volume_factor_u8(ma_uint8* pSamples, ma_uint64 sampleCount, float factor);
MA_API void ma_apply_volume_factor_s16(ma_int16* pSamples, ma_uint64 sampleCount, float factor);
MA_API void ma_apply_volume_factor_s24(void* pSamples, ma_uint64 sampleCount, float factor);
MA_API void ma_apply_volume_factor_s32(ma_int32* pSamples, ma_uint64 sampleCount, float factor);
MA_API void ma_apply_volume_factor_f32(float* pSamples, ma_uint64 sampleCount, float factor);
MA_API void ma_copy_and_apply_volume_factor_pcm_frames_u8(ma_uint8* pPCMFramesOut, const ma_uint8* pPCMFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor);
MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s16(ma_int16* pPCMFramesOut, const ma_int16* pPCMFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor);
MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s24(void* pPCMFramesOut, const void* pPCMFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor);
MA_API void ma_copy_and_apply_volume_factor_pcm_frames_s32(ma_int32* pPCMFramesOut, const ma_int32* pPCMFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor);
MA_API void ma_copy_and_apply_volume_factor_pcm_frames_f32(float* pPCMFramesOut, const float* pPCMFramesIn, ma_uint64 frameCount, ma_uint32 channels, float factor);
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);
MA_API void ma_apply_volume_factor_pcm_frames_u8(ma_uint8* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
MA_API void ma_apply_volume_factor_pcm_frames_s16(ma_int16* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
MA_API void ma_apply_volume_factor_pcm_frames_s24(void* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
MA_API void ma_apply_volume_factor_pcm_frames_s32(ma_int32* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
MA_API void ma_apply_volume_factor_pcm_frames_f32(float* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
MA_API void ma_apply_volume_factor_pcm_frames(void* pFrames, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor);
/*
Helper for converting a linear factor to gain in decibels.
*/
MA_API float ma_factor_to_gain_db(float factor);
/*
Helper for converting gain in decibels to a linear factor.
*/
MA_API float ma_gain_db_to_factor(float gain);
typedef void ma_data_source;
typedef struct
{
ma_result (* onRead)(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
ma_result (* onSeek)(ma_data_source* pDataSource, ma_uint64 frameIndex);
ma_result (* onMap)(ma_data_source* pDataSource, void** ppFramesOut, ma_uint64* pFrameCount); /* Returns MA_AT_END if the end has been reached. This should be considered successful. */
ma_result (* onUnmap)(ma_data_source* pDataSource, ma_uint64 frameCount);
ma_result (* onGetDataFormat)(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate);
ma_result (* onGetCursor)(ma_data_source* pDataSource, ma_uint64* pCursor);
ma_result (* onGetLength)(ma_data_source* pDataSource, ma_uint64* pLength);
} ma_data_source_callbacks;
MA_API ma_result ma_data_source_read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead, ma_bool32 loop); /* Must support pFramesOut = NULL in which case a forward seek should be performed. */
MA_API ma_result ma_data_source_seek_pcm_frames(ma_data_source* pDataSource, ma_uint64 frameCount, ma_uint64* pFramesSeeked, ma_bool32 loop); /* Can only seek forward. Equivalent to ma_data_source_read_pcm_frames(pDataSource, NULL, frameCount); */
MA_API ma_result ma_data_source_seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex);
MA_API ma_result ma_data_source_map(ma_data_source* pDataSource, void** ppFramesOut, ma_uint64* pFrameCount);
MA_API ma_result ma_data_source_unmap(ma_data_source* pDataSource, ma_uint64 frameCount); /* Returns MA_AT_END if the end has been reached. This should be considered successful. */
MA_API ma_result ma_data_source_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate);
MA_API ma_result ma_data_source_get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor);
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. */
typedef struct
{
ma_data_source_callbacks ds;
ma_format format;
ma_uint32 channels;
ma_uint64 cursor;
ma_uint64 sizeInFrames;
const void* pData;
} ma_audio_buffer_ref;
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);
MA_API ma_result ma_audio_buffer_ref_set_data(ma_audio_buffer_ref* pAudioBufferRef, const void* pData, ma_uint64 sizeInFrames);
MA_API ma_uint64 ma_audio_buffer_ref_read_pcm_frames(ma_audio_buffer_ref* pAudioBufferRef, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop);
MA_API ma_result ma_audio_buffer_ref_seek_to_pcm_frame(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameIndex);
MA_API ma_result ma_audio_buffer_ref_map(ma_audio_buffer_ref* pAudioBufferRef, void** ppFramesOut, ma_uint64* pFrameCount);
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. */
MA_API ma_result ma_audio_buffer_ref_at_end(ma_audio_buffer_ref* pAudioBufferRef);
MA_API ma_result ma_audio_buffer_ref_get_available_frames(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pAvailableFrames);
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint64 sizeInFrames;
const void* pData; /* If set to NULL, will allocate a block of memory for you. */
ma_allocation_callbacks allocationCallbacks;
} ma_audio_buffer_config;
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);
typedef struct
{
ma_audio_buffer_ref ref;
ma_allocation_callbacks allocationCallbacks;
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(). */
ma_uint8 _pExtraData[1]; /* For allocating a buffer with the memory located directly after the other memory of the structure. */
} ma_audio_buffer;
MA_API ma_result ma_audio_buffer_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer);
MA_API ma_result ma_audio_buffer_init_copy(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer);
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. */
MA_API void ma_audio_buffer_uninit(ma_audio_buffer* pAudioBuffer);
MA_API void ma_audio_buffer_uninit_and_free(ma_audio_buffer* pAudioBuffer);
MA_API ma_uint64 ma_audio_buffer_read_pcm_frames(ma_audio_buffer* pAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop);
MA_API ma_result ma_audio_buffer_seek_to_pcm_frame(ma_audio_buffer* pAudioBuffer, ma_uint64 frameIndex);
MA_API ma_result ma_audio_buffer_map(ma_audio_buffer* pAudioBuffer, void** ppFramesOut, ma_uint64* pFrameCount);
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. */
MA_API ma_result ma_audio_buffer_at_end(ma_audio_buffer* pAudioBuffer);
MA_API ma_result ma_audio_buffer_get_available_frames(ma_audio_buffer* pAudioBuffer, ma_uint64* pAvailableFrames);
/************************************************************************************************************************************************************
VFS
===
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
appropriate for a given situation.
************************************************************************************************************************************************************/
typedef void ma_vfs;
typedef ma_handle ma_vfs_file;
#define MA_OPEN_MODE_READ 0x00000001
#define MA_OPEN_MODE_WRITE 0x00000002
typedef enum
{
ma_seek_origin_start,
ma_seek_origin_current,
ma_seek_origin_end /* Not used by decoders. */
} ma_seek_origin;
typedef struct
{
ma_uint64 sizeInBytes;
} ma_file_info;
typedef struct
{
ma_result (* onOpen) (ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
ma_result (* onOpenW)(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
ma_result (* onClose)(ma_vfs* pVFS, ma_vfs_file file);
ma_result (* onRead) (ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead);
ma_result (* onWrite)(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten);
ma_result (* onSeek) (ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin);
ma_result (* onTell) (ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor);
ma_result (* onInfo) (ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo);
} ma_vfs_callbacks;
MA_API ma_result ma_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
MA_API ma_result ma_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
MA_API ma_result ma_vfs_close(ma_vfs* pVFS, ma_vfs_file file);
MA_API ma_result ma_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead);
MA_API ma_result ma_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten);
MA_API ma_result ma_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin);
MA_API ma_result ma_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor);
MA_API ma_result ma_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo);
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);
typedef struct
{
ma_vfs_callbacks cb;
ma_allocation_callbacks allocationCallbacks; /* Only used for the wchar_t version of open() on non-Windows platforms. */
} ma_default_vfs;
MA_API ma_result ma_default_vfs_init(ma_default_vfs* pVFS, const ma_allocation_callbacks* pAllocationCallbacks);
#if !defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING)
typedef enum
{
ma_resource_format_wav
} ma_resource_format;
#endif
/************************************************************************************************************************************************************
Decoding
========
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
you do your own synchronization.
************************************************************************************************************************************************************/
#ifndef MA_NO_DECODING
typedef struct ma_decoder ma_decoder;
typedef size_t (* ma_decoder_read_proc) (ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead); /* Returns the number of bytes read. */
typedef ma_bool32 (* ma_decoder_seek_proc) (ma_decoder* pDecoder, int byteOffset, ma_seek_origin origin); /* Origin will never be ma_seek_origin_end. */
typedef ma_uint64 (* ma_decoder_read_pcm_frames_proc) (ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount); /* Returns the number of frames read. Output data is in internal format. */
typedef ma_result (* ma_decoder_seek_to_pcm_frame_proc) (ma_decoder* pDecoder, ma_uint64 frameIndex);
typedef ma_result (* ma_decoder_uninit_proc) (ma_decoder* pDecoder);
typedef ma_uint64 (* ma_decoder_get_length_in_pcm_frames_proc)(ma_decoder* pDecoder);
typedef struct
{
ma_format format; /* Set to 0 or ma_format_unknown to use the stream's internal format. */
ma_uint32 channels; /* Set to 0 to use the stream's internal channels. */
ma_uint32 sampleRate; /* Set to 0 to use the stream's internal sample rate. */
ma_channel channelMap[MA_MAX_CHANNELS];
ma_channel_mix_mode channelMixMode;
ma_dither_mode ditherMode;
struct
{
ma_resample_algorithm algorithm;
struct
{
ma_uint32 lpfOrder;
} linear;
struct
{
int quality;
} speex;
} resampling;
ma_allocation_callbacks allocationCallbacks;
} ma_decoder_config;
struct ma_decoder
{
ma_data_source_callbacks ds;
ma_decoder_read_proc onRead;
ma_decoder_seek_proc onSeek;
void* pUserData;
ma_uint64 readPointerInBytes; /* In internal encoded data. */
ma_uint64 readPointerInPCMFrames; /* In output sample rate. Used for keeping track of how many frames are available for decoding. */
ma_format internalFormat;
ma_uint32 internalChannels;
ma_uint32 internalSampleRate;
ma_channel internalChannelMap[MA_MAX_CHANNELS];
ma_format outputFormat;
ma_uint32 outputChannels;
ma_uint32 outputSampleRate;
ma_channel outputChannelMap[MA_MAX_CHANNELS];
ma_data_converter converter; /* <-- Data conversion is achieved by running frames through this. */
ma_allocation_callbacks allocationCallbacks;
ma_decoder_read_pcm_frames_proc onReadPCMFrames;
ma_decoder_seek_to_pcm_frame_proc onSeekToPCMFrame;
ma_decoder_uninit_proc onUninit;
ma_decoder_get_length_in_pcm_frames_proc onGetLengthInPCMFrames;
void* pInternalDecoder; /* <-- The drwav/drflac/stb_vorbis/etc. objects. */
union
{
struct
{
ma_vfs* pVFS;
ma_vfs_file file;
} vfs;
struct
{
const ma_uint8* pData;
size_t dataSize;
size_t currentReadPos;
} memory; /* Only used for decoders that were opened against a block of memory. */
} backend;
};
MA_API ma_decoder_config ma_decoder_config_init(ma_format outputFormat, ma_uint32 outputChannels, ma_uint32 outputSampleRate);
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);
MA_API ma_result ma_decoder_init_wav(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_flac(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_mp3(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_vorbis(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_raw(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfigIn, const ma_decoder_config* pConfigOut, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_memory_wav(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_memory_flac(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_memory_mp3(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_memory_vorbis(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_memory_raw(const void* pData, size_t dataSize, const ma_decoder_config* pConfigIn, const ma_decoder_config* pConfigOut, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_vfs_wav(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_vfs_flac(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_vfs_mp3(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_vfs_vorbis(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_vfs_wav_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_vfs_flac_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_vfs_mp3_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_vfs_vorbis_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_file_wav(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_file_flac(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_file_mp3(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_file_vorbis(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_file_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_file_wav_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_file_flac_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_file_mp3_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_init_file_vorbis_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
MA_API ma_result ma_decoder_uninit(ma_decoder* pDecoder);
/*
Retrieves the current position of the read cursor in PCM frames.
*/
MA_API ma_result ma_decoder_get_cursor_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pCursor);
/*
Retrieves the length of the decoder in PCM frames.
Do not call this on streams of an undefined length, such as internet radio.
If the length is unknown or an error occurs, 0 will be returned.
This will always return 0 for Vorbis decoders. This is due to a limitation with stb_vorbis in push mode which is what miniaudio
uses internally.
For MP3's, this will decode the entire file. Do not call this in time critical scenarios.
This function is not thread safe without your own synchronization.
*/
MA_API ma_uint64 ma_decoder_get_length_in_pcm_frames(ma_decoder* pDecoder);
/*
Reads PCM frames from the given decoder.
This is not thread safe without your own synchronization.
*/
MA_API ma_uint64 ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount);
/*
Seeks to a PCM frame based on it's absolute index.
This is not thread safe without your own synchronization.
*/
MA_API ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex);
/*
Retrieves the number of frames that can be read before reaching the end.
This calls `ma_decoder_get_length_in_pcm_frames()` so you need to be aware of the rules for that function, in
particular ensuring you do not call it on streams of an undefined length, such as internet radio.
If the total length of the decoder cannot be retrieved, such as with Vorbis decoders, `MA_NOT_IMPLEMENTED` will be
returned.
*/
MA_API ma_result ma_decoder_get_available_frames(ma_decoder* pDecoder, ma_uint64* pAvailableFrames);
/*
Helper for opening and decoding a file into a heap allocated block of memory. Free the returned pointer with ma_free(). On input,
pConfig should be set to what you want. On output it will be set to what you got.
*/
MA_API ma_result ma_decode_from_vfs(ma_vfs* pVFS, const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut);
MA_API ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut);
MA_API ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut);
#endif /* MA_NO_DECODING */
/************************************************************************************************************************************************************
Encoding
========
Encoders do not perform any format conversion for you. If your target format does not support the format, and error will be returned.
************************************************************************************************************************************************************/
#ifndef MA_NO_ENCODING
typedef struct ma_encoder ma_encoder;
typedef size_t (* ma_encoder_write_proc) (ma_encoder* pEncoder, const void* pBufferIn, size_t bytesToWrite); /* Returns the number of bytes written. */
typedef ma_bool32 (* ma_encoder_seek_proc) (ma_encoder* pEncoder, int byteOffset, ma_seek_origin origin);
typedef ma_result (* ma_encoder_init_proc) (ma_encoder* pEncoder);
typedef void (* ma_encoder_uninit_proc) (ma_encoder* pEncoder);
typedef ma_uint64 (* ma_encoder_write_pcm_frames_proc)(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount);
typedef struct
{
ma_resource_format resourceFormat;
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
ma_allocation_callbacks allocationCallbacks;
} ma_encoder_config;
MA_API ma_encoder_config ma_encoder_config_init(ma_resource_format resourceFormat, ma_format format, ma_uint32 channels, ma_uint32 sampleRate);
struct ma_encoder
{
ma_encoder_config config;
ma_encoder_write_proc onWrite;
ma_encoder_seek_proc onSeek;
ma_encoder_init_proc onInit;
ma_encoder_uninit_proc onUninit;
ma_encoder_write_pcm_frames_proc onWritePCMFrames;
void* pUserData;
void* pInternalEncoder; /* <-- The drwav/drflac/stb_vorbis/etc. objects. */
void* pFile; /* FILE*. Only used when initialized with ma_encoder_init_file(). */
};
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);
MA_API ma_result ma_encoder_init_file(const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
MA_API ma_result ma_encoder_init_file_w(const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
MA_API void ma_encoder_uninit(ma_encoder* pEncoder);
MA_API ma_uint64 ma_encoder_write_pcm_frames(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount);
#endif /* MA_NO_ENCODING */
/************************************************************************************************************************************************************
Generation
************************************************************************************************************************************************************/
#ifndef MA_NO_GENERATION
typedef enum
{
ma_waveform_type_sine,
ma_waveform_type_square,
ma_waveform_type_triangle,
ma_waveform_type_sawtooth
} ma_waveform_type;
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
ma_waveform_type type;
double amplitude;
double frequency;
} ma_waveform_config;
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);
typedef struct
{
ma_data_source_callbacks ds;
ma_waveform_config config;
double advance;
double time;
} ma_waveform;
MA_API ma_result ma_waveform_init(const ma_waveform_config* pConfig, ma_waveform* pWaveform);
MA_API ma_uint64 ma_waveform_read_pcm_frames(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount);
MA_API ma_result ma_waveform_seek_to_pcm_frame(ma_waveform* pWaveform, ma_uint64 frameIndex);
MA_API ma_result ma_waveform_set_amplitude(ma_waveform* pWaveform, double amplitude);
MA_API ma_result ma_waveform_set_frequency(ma_waveform* pWaveform, double frequency);
MA_API ma_result ma_waveform_set_type(ma_waveform* pWaveform, ma_waveform_type type);
MA_API ma_result ma_waveform_set_sample_rate(ma_waveform* pWaveform, ma_uint32 sampleRate);
typedef enum
{
ma_noise_type_white,
ma_noise_type_pink,
ma_noise_type_brownian
} ma_noise_type;
typedef struct
{
ma_format format;
ma_uint32 channels;
ma_noise_type type;
ma_int32 seed;
double amplitude;
ma_bool32 duplicateChannels;
} ma_noise_config;
MA_API ma_noise_config ma_noise_config_init(ma_format format, ma_uint32 channels, ma_noise_type type, ma_int32 seed, double amplitude);
typedef struct
{
ma_data_source_callbacks ds;
ma_noise_config config;
ma_lcg lcg;
union
{
struct
{
double bin[MA_MAX_CHANNELS][16];
double accumulation[MA_MAX_CHANNELS];
ma_uint32 counter[MA_MAX_CHANNELS];
} pink;
struct
{
double accumulation[MA_MAX_CHANNELS];
} brownian;
} state;
} ma_noise;
MA_API ma_result ma_noise_init(const ma_noise_config* pConfig, ma_noise* pNoise);
MA_API ma_uint64 ma_noise_read_pcm_frames(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount);
MA_API ma_result ma_noise_set_amplitude(ma_noise* pNoise, double amplitude);
MA_API ma_result ma_noise_set_seed(ma_noise* pNoise, ma_int32 seed);
MA_API ma_result ma_noise_set_type(ma_noise* pNoise, ma_noise_type type);
#endif /* MA_NO_GENERATION */
#ifdef __cplusplus
}
#endif
#endif /* miniaudio_h */
/************************************************************************************************************************************************************
*************************************************************************************************************************************************************
IMPLEMENTATION
*************************************************************************************************************************************************************
************************************************************************************************************************************************************/
#if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION)
#ifndef miniaudio_c
#define miniaudio_c
#include
#include /* For INT_MAX */
#include /* sin(), etc. */
#include
#include
#if !defined(_MSC_VER) && !defined(__DMC__)
#include /* For strcasecmp(). */
#include /* For wcslen(), wcsrtombs() */
#endif
#ifdef MA_WIN32
#include
#else
#include /* For malloc(), free(), wcstombs(). */
#include /* For memset() */
#include
#include /* select() (used for ma_sleep()). */
#endif
#include /* For fstat(), etc. */
#ifdef MA_EMSCRIPTEN
#include
#endif
#if !defined(MA_64BIT) && !defined(MA_32BIT)
#ifdef _WIN32
#ifdef _WIN64
#define MA_64BIT
#else
#define MA_32BIT
#endif
#endif
#endif
#if !defined(MA_64BIT) && !defined(MA_32BIT)
#ifdef __GNUC__
#ifdef __LP64__
#define MA_64BIT
#else
#define MA_32BIT
#endif
#endif
#endif
#if !defined(MA_64BIT) && !defined(MA_32BIT)
#include
#if INTPTR_MAX == INT64_MAX
#define MA_64BIT
#else
#define MA_32BIT
#endif
#endif
/* Architecture Detection */
#if defined(__x86_64__) || defined(_M_X64)
#define MA_X64
#elif defined(__i386) || defined(_M_IX86)
#define MA_X86
#elif defined(__arm__) || defined(_M_ARM)
#define MA_ARM
#endif
/* Cannot currently support AVX-512 if AVX is disabled. */
#if !defined(MA_NO_AVX512) && defined(MA_NO_AVX2)
#define MA_NO_AVX512
#endif
/* Intrinsics Support */
#if defined(MA_X64) || defined(MA_X86)
#if defined(_MSC_VER) && !defined(__clang__)
/* MSVC. */
#if _MSC_VER >= 1400 && !defined(MA_NO_SSE2) /* 2005 */
#define MA_SUPPORT_SSE2
#endif
/*#if _MSC_VER >= 1600 && !defined(MA_NO_AVX)*/ /* 2010 */
/* #define MA_SUPPORT_AVX*/
/*#endif*/
#if _MSC_VER >= 1700 && !defined(MA_NO_AVX2) /* 2012 */
#define MA_SUPPORT_AVX2
#endif
#if _MSC_VER >= 1910 && !defined(MA_NO_AVX512) /* 2017 */
#define MA_SUPPORT_AVX512
#endif
#else
/* Assume GNUC-style. */
#if defined(__SSE2__) && !defined(MA_NO_SSE2)
#define MA_SUPPORT_SSE2
#endif
/*#if defined(__AVX__) && !defined(MA_NO_AVX)*/
/* #define MA_SUPPORT_AVX*/
/*#endif*/
#if defined(__AVX2__) && !defined(MA_NO_AVX2)
#define MA_SUPPORT_AVX2
#endif
#if defined(__AVX512F__) && !defined(MA_NO_AVX512)
#define MA_SUPPORT_AVX512
#endif
#endif
/* If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. */
#if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
#if !defined(MA_SUPPORT_SSE2) && !defined(MA_NO_SSE2) && __has_include()
#define MA_SUPPORT_SSE2
#endif
/*#if !defined(MA_SUPPORT_AVX) && !defined(MA_NO_AVX) && __has_include()*/
/* #define MA_SUPPORT_AVX*/
/*#endif*/
#if !defined(MA_SUPPORT_AVX2) && !defined(MA_NO_AVX2) && __has_include()
#define MA_SUPPORT_AVX2
#endif
#if !defined(MA_SUPPORT_AVX512) && !defined(MA_NO_AVX512) && __has_include()
#define MA_SUPPORT_AVX512
#endif
#endif
#if defined(MA_SUPPORT_AVX512)
#include /* Not a mistake. Intentionally including instead of because otherwise the compiler will complain. */
#elif defined(MA_SUPPORT_AVX2) || defined(MA_SUPPORT_AVX)
#include
#elif defined(MA_SUPPORT_SSE2)
#include
#endif
#endif
#if defined(MA_ARM)
#if !defined(MA_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
#define MA_SUPPORT_NEON
#endif
/* Fall back to looking for the #include file. */
#if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
#if !defined(MA_SUPPORT_NEON) && !defined(MA_NO_NEON) && __has_include()
#define MA_SUPPORT_NEON
#endif
#endif
#if defined(MA_SUPPORT_NEON)
#include
#endif
#endif
/* Begin globally disabled warnings. */
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4752) /* found Intel(R) Advanced Vector Extensions; consider using /arch:AVX */
#endif
#if defined(MA_X64) || defined(MA_X86)
#if defined(_MSC_VER) && !defined(__clang__)
#if _MSC_VER >= 1400
#include
static MA_INLINE void ma_cpuid(int info[4], int fid)
{
__cpuid(info, fid);
}
#else
#define MA_NO_CPUID
#endif
#if _MSC_VER >= 1600 && (defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 160040219)
static MA_INLINE unsigned __int64 ma_xgetbv(int reg)
{
return _xgetbv(reg);
}
#else
#define MA_NO_XGETBV
#endif
#elif (defined(__GNUC__) || defined(__clang__)) && !defined(MA_ANDROID)
static MA_INLINE void ma_cpuid(int info[4], int fid)
{
/*
It looks like the -fPIC option uses the ebx register which GCC complains about. We can work around this by just using a different register, the
specific register of which I'm letting the compiler decide on. The "k" prefix is used to specify a 32-bit register. The {...} syntax is for
supporting different assembly dialects.
What's basically happening is that we're saving and restoring the ebx register manually.
*/
#if defined(DRFLAC_X86) && defined(__PIC__)
__asm__ __volatile__ (
"xchg{l} {%%}ebx, %k1;"
"cpuid;"
"xchg{l} {%%}ebx, %k1;"
: "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
);
#else
__asm__ __volatile__ (
"cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
);
#endif
}
static MA_INLINE ma_uint64 ma_xgetbv(int reg)
{
unsigned int hi;
unsigned int lo;
__asm__ __volatile__ (
"xgetbv" : "=a"(lo), "=d"(hi) : "c"(reg)
);
return ((ma_uint64)hi << 32) | (ma_uint64)lo;
}
#else
#define MA_NO_CPUID
#define MA_NO_XGETBV
#endif
#else
#define MA_NO_CPUID
#define MA_NO_XGETBV
#endif
static MA_INLINE ma_bool32 ma_has_sse2(void)
{
#if defined(MA_SUPPORT_SSE2)
#if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_SSE2)
#if defined(MA_X64)
return MA_TRUE; /* 64-bit targets always support SSE2. */
#elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)
return MA_TRUE; /* If the compiler is allowed to freely generate SSE2 code we can assume support. */
#else
#if defined(MA_NO_CPUID)
return MA_FALSE;
#else
int info[4];
ma_cpuid(info, 1);
return (info[3] & (1 << 26)) != 0;
#endif
#endif
#else
return MA_FALSE; /* SSE2 is only supported on x86 and x64 architectures. */
#endif
#else
return MA_FALSE; /* No compiler support. */
#endif
}
#if 0
static MA_INLINE ma_bool32 ma_has_avx()
{
#if defined(MA_SUPPORT_AVX)
#if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX)
#if defined(_AVX_) || defined(__AVX__)
return MA_TRUE; /* If the compiler is allowed to freely generate AVX code we can assume support. */
#else
/* AVX requires both CPU and OS support. */
#if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV)
return MA_FALSE;
#else
int info[4];
ma_cpuid(info, 1);
if (((info[2] & (1 << 27)) != 0) && ((info[2] & (1 << 28)) != 0)) {
ma_uint64 xrc = ma_xgetbv(0);
if ((xrc & 0x06) == 0x06) {
return MA_TRUE;
} else {
return MA_FALSE;
}
} else {
return MA_FALSE;
}
#endif
#endif
#else
return MA_FALSE; /* AVX is only supported on x86 and x64 architectures. */
#endif
#else
return MA_FALSE; /* No compiler support. */
#endif
}
#endif
static MA_INLINE ma_bool32 ma_has_avx2(void)
{
#if defined(MA_SUPPORT_AVX2)
#if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX2)
#if defined(_AVX2_) || defined(__AVX2__)
return MA_TRUE; /* If the compiler is allowed to freely generate AVX2 code we can assume support. */
#else
/* AVX2 requires both CPU and OS support. */
#if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV)
return MA_FALSE;
#else
int info1[4];
int info7[4];
ma_cpuid(info1, 1);
ma_cpuid(info7, 7);
if (((info1[2] & (1 << 27)) != 0) && ((info7[1] & (1 << 5)) != 0)) {
ma_uint64 xrc = ma_xgetbv(0);
if ((xrc & 0x06) == 0x06) {
return MA_TRUE;
} else {
return MA_FALSE;
}
} else {
return MA_FALSE;
}
#endif
#endif
#else
return MA_FALSE; /* AVX2 is only supported on x86 and x64 architectures. */
#endif
#else
return MA_FALSE; /* No compiler support. */
#endif
}
static MA_INLINE ma_bool32 ma_has_avx512f(void)
{
#if defined(MA_SUPPORT_AVX512)
#if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX512)
#if defined(__AVX512F__)
return MA_TRUE; /* If the compiler is allowed to freely generate AVX-512F code we can assume support. */
#else
/* AVX-512 requires both CPU and OS support. */
#if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV)
return MA_FALSE;
#else
int info1[4];
int info7[4];
ma_cpuid(info1, 1);
ma_cpuid(info7, 7);
if (((info1[2] & (1 << 27)) != 0) && ((info7[1] & (1 << 16)) != 0)) {
ma_uint64 xrc = ma_xgetbv(0);
if ((xrc & 0xE6) == 0xE6) {
return MA_TRUE;
} else {
return MA_FALSE;
}
} else {
return MA_FALSE;
}
#endif
#endif
#else
return MA_FALSE; /* AVX-512F is only supported on x86 and x64 architectures. */
#endif
#else
return MA_FALSE; /* No compiler support. */
#endif
}
static MA_INLINE ma_bool32 ma_has_neon(void)
{
#if defined(MA_SUPPORT_NEON)
#if defined(MA_ARM) && !defined(MA_NO_NEON)
#if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
return MA_TRUE; /* If the compiler is allowed to freely generate NEON code we can assume support. */
#else
/* TODO: Runtime check. */
return MA_FALSE;
#endif
#else
return MA_FALSE; /* NEON is only supported on ARM architectures. */
#endif
#else
return MA_FALSE; /* No compiler support. */
#endif
}
#define MA_SIMD_NONE 0
#define MA_SIMD_SSE2 1
#define MA_SIMD_AVX2 2
#define MA_SIMD_NEON 3
#ifndef MA_PREFERRED_SIMD
# if defined(MA_SUPPORT_SSE2) && defined(MA_PREFER_SSE2)
#define MA_PREFERRED_SIMD MA_SIMD_SSE2
#elif defined(MA_SUPPORT_AVX2) && defined(MA_PREFER_AVX2)
#define MA_PREFERRED_SIMD MA_SIMD_AVX2
#elif defined(MA_SUPPORT_NEON) && defined(MA_PREFER_NEON)
#define MA_PREFERRED_SIMD MA_SIMD_NEON
#else
#define MA_PREFERRED_SIMD MA_SIMD_NONE
#endif
#endif
#if defined(_MSC_VER) && _MSC_VER >= 1400
#define MA_HAS_BYTESWAP16_INTRINSIC
#define MA_HAS_BYTESWAP32_INTRINSIC
#define MA_HAS_BYTESWAP64_INTRINSIC
#elif defined(__clang__)
#if defined(__has_builtin)
#if __has_builtin(__builtin_bswap16)
#define MA_HAS_BYTESWAP16_INTRINSIC
#endif
#if __has_builtin(__builtin_bswap32)
#define MA_HAS_BYTESWAP32_INTRINSIC
#endif
#if __has_builtin(__builtin_bswap64)
#define MA_HAS_BYTESWAP64_INTRINSIC
#endif
#endif
#elif defined(__GNUC__)
#if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
#define MA_HAS_BYTESWAP32_INTRINSIC
#define MA_HAS_BYTESWAP64_INTRINSIC
#endif
#if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
#define MA_HAS_BYTESWAP16_INTRINSIC
#endif
#endif
static MA_INLINE ma_bool32 ma_is_little_endian(void)
{
#if defined(MA_X86) || defined(MA_X64)
return MA_TRUE;
#else
int n = 1;
return (*(char*)&n) == 1;
#endif
}
static MA_INLINE ma_bool32 ma_is_big_endian(void)
{
return !ma_is_little_endian();
}
static MA_INLINE ma_uint32 ma_swap_endian_uint32(ma_uint32 n)
{
#ifdef MA_HAS_BYTESWAP32_INTRINSIC
#if defined(_MSC_VER)
return _byteswap_ulong(n);
#elif defined(__GNUC__) || defined(__clang__)
#if defined(MA_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(MA_64BIT) /* <-- 64-bit inline assembly has not been tested, so disabling for now. */
/* Inline assembly optimized implementation for ARM. In my testing, GCC does not generate optimized code with __builtin_bswap32(). */
ma_uint32 r;
__asm__ __volatile__ (
#if defined(MA_64BIT)
"rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n) /* <-- This is untested. If someone in the community could test this, that would be appreciated! */
#else
"rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
#endif
);
return r;
#else
return __builtin_bswap32(n);
#endif
#else
#error "This compiler does not support the byte swap intrinsic."
#endif
#else
return ((n & 0xFF000000) >> 24) |
((n & 0x00FF0000) >> 8) |
((n & 0x0000FF00) << 8) |
((n & 0x000000FF) << 24);
#endif
}
#if !defined(MA_EMSCRIPTEN)
#ifdef MA_WIN32
static void ma_sleep__win32(ma_uint32 milliseconds)
{
Sleep((DWORD)milliseconds);
}
#endif
#ifdef MA_POSIX
static void ma_sleep__posix(ma_uint32 milliseconds)
{
#ifdef MA_EMSCRIPTEN
(void)milliseconds;
MA_ASSERT(MA_FALSE); /* The Emscripten build should never sleep. */
#else
#if _POSIX_C_SOURCE >= 199309L
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = milliseconds % 1000 * 1000000;
nanosleep(&ts, NULL);
#else
struct timeval tv;
tv.tv_sec = milliseconds / 1000;
tv.tv_usec = milliseconds % 1000 * 1000;
select(0, NULL, NULL, NULL, &tv);
#endif
#endif
}
#endif
static void ma_sleep(ma_uint32 milliseconds)
{
#ifdef MA_WIN32
ma_sleep__win32(milliseconds);
#endif
#ifdef MA_POSIX
ma_sleep__posix(milliseconds);
#endif
}
#endif
static MA_INLINE void ma_yield()
{
#if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)
/* x86/x64 */
#if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__DMC__)) && !defined(__clang__)
#if _MSC_VER >= 1400
_mm_pause();
#else
#if defined(__DMC__)
/* Digital Mars does not recognize the PAUSE opcode. Fall back to NOP. */
__asm nop;
#else
__asm pause;
#endif
#endif
#else
__asm__ __volatile__ ("pause");
#endif
#elif (defined(__arm__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7) || (defined(_M_ARM) && _M_ARM >= 7) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__)
/* ARM */
#if defined(_MSC_VER)
/* Apparently there is a __yield() intrinsic that's compatible with ARM, but I cannot find documentation for it nor can I find where it's declared. */
__yield();
#else
__asm__ __volatile__ ("yield"); /* ARMv6K/ARMv6T2 and above. */
#endif
#else
/* Unknown or unsupported architecture. No-op. */
#endif
}
#ifndef MA_COINIT_VALUE
#define MA_COINIT_VALUE 0 /* 0 = COINIT_MULTITHREADED */
#endif
#ifndef MA_PI
#define MA_PI 3.14159265358979323846264f
#endif
#ifndef MA_PI_D
#define MA_PI_D 3.14159265358979323846264
#endif
#ifndef MA_TAU
#define MA_TAU 6.28318530717958647693f
#endif
#ifndef MA_TAU_D
#define MA_TAU_D 6.28318530717958647693
#endif
/* The default format when ma_format_unknown (0) is requested when initializing a device. */
#ifndef MA_DEFAULT_FORMAT
#define MA_DEFAULT_FORMAT ma_format_f32
#endif
/* The default channel count to use when 0 is used when initializing a device. */
#ifndef MA_DEFAULT_CHANNELS
#define MA_DEFAULT_CHANNELS 2
#endif
/* The default sample rate to use when 0 is used when initializing a device. */
#ifndef MA_DEFAULT_SAMPLE_RATE
#define MA_DEFAULT_SAMPLE_RATE 48000
#endif
/* Default periods when none is specified in ma_device_init(). More periods means more work on the CPU. */
#ifndef MA_DEFAULT_PERIODS
#define MA_DEFAULT_PERIODS 3
#endif
/* The default period size in milliseconds for low latency mode. */
#ifndef MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY
#define MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY 10
#endif
/* The default buffer size in milliseconds for conservative mode. */
#ifndef MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE
#define MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE 100
#endif
/* The default LPF filter order for linear resampling. Note that this is clamped to MA_MAX_FILTER_ORDER. */
#ifndef MA_DEFAULT_RESAMPLER_LPF_ORDER
#if MA_MAX_FILTER_ORDER >= 4
#define MA_DEFAULT_RESAMPLER_LPF_ORDER 4
#else
#define MA_DEFAULT_RESAMPLER_LPF_ORDER MA_MAX_FILTER_ORDER
#endif
#endif
#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif
/* Standard sample rates, in order of priority. */
static ma_uint32 g_maStandardSampleRatePriorities[] = {
MA_SAMPLE_RATE_48000, /* Most common */
MA_SAMPLE_RATE_44100,
MA_SAMPLE_RATE_32000, /* Lows */
MA_SAMPLE_RATE_24000,
MA_SAMPLE_RATE_22050,
MA_SAMPLE_RATE_88200, /* Highs */
MA_SAMPLE_RATE_96000,
MA_SAMPLE_RATE_176400,
MA_SAMPLE_RATE_192000,
MA_SAMPLE_RATE_16000, /* Extreme lows */
MA_SAMPLE_RATE_11025,
MA_SAMPLE_RATE_8000,
MA_SAMPLE_RATE_352800, /* Extreme highs */
MA_SAMPLE_RATE_384000
};
static ma_format g_maFormatPriorities[] = {
ma_format_s16, /* Most common */
ma_format_f32,
/*ma_format_s24_32,*/ /* Clean alignment */
ma_format_s32,
ma_format_s24, /* Unclean alignment */
ma_format_u8 /* Low quality */
};
#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
#pragma GCC diagnostic pop
#endif
MA_API void ma_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision)
{
if (pMajor) {
*pMajor = MA_VERSION_MAJOR;
}
if (pMinor) {
*pMinor = MA_VERSION_MINOR;
}
if (pRevision) {
*pRevision = MA_VERSION_REVISION;
}
}
MA_API const char* ma_version_string(void)
{
return MA_VERSION_STRING;
}
/******************************************************************************
Standard Library Stuff
******************************************************************************/
#ifndef MA_MALLOC
#ifdef MA_WIN32
#define MA_MALLOC(sz) HeapAlloc(GetProcessHeap(), 0, (sz))
#else
#define MA_MALLOC(sz) malloc((sz))
#endif
#endif
#ifndef MA_REALLOC
#ifdef MA_WIN32
#define MA_REALLOC(p, sz) (((sz) > 0) ? ((p) ? HeapReAlloc(GetProcessHeap(), 0, (p), (sz)) : HeapAlloc(GetProcessHeap(), 0, (sz))) : ((VOID*)(size_t)(HeapFree(GetProcessHeap(), 0, (p)) & 0)))
#else
#define MA_REALLOC(p, sz) realloc((p), (sz))
#endif
#endif
#ifndef MA_FREE
#ifdef MA_WIN32
#define MA_FREE(p) HeapFree(GetProcessHeap(), 0, (p))
#else
#define MA_FREE(p) free((p))
#endif
#endif
#ifndef MA_ZERO_MEMORY
#ifdef MA_WIN32
#define MA_ZERO_MEMORY(p, sz) ZeroMemory((p), (sz))
#else
#define MA_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
#endif
#endif
#ifndef MA_COPY_MEMORY
#ifdef MA_WIN32
#define MA_COPY_MEMORY(dst, src, sz) CopyMemory((dst), (src), (sz))
#else
#define MA_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
#endif
#endif
#ifndef MA_ASSERT
#ifdef MA_WIN32
#define MA_ASSERT(condition) assert(condition)
#else
#define MA_ASSERT(condition) assert(condition)
#endif
#endif
#define MA_ZERO_OBJECT(p) MA_ZERO_MEMORY((p), sizeof(*(p)))
#define ma_countof(x) (sizeof(x) / sizeof(x[0]))
#define ma_max(x, y) (((x) > (y)) ? (x) : (y))
#define ma_min(x, y) (((x) < (y)) ? (x) : (y))
#define ma_abs(x) (((x) > 0) ? (x) : -(x))
#define ma_clamp(x, lo, hi) (ma_max(lo, ma_min(x, hi)))
#define ma_offset_ptr(p, offset) (((ma_uint8*)(p)) + (offset))
#define ma_buffer_frame_capacity(buffer, channels, format) (sizeof(buffer) / ma_get_bytes_per_sample(format) / (channels))
static MA_INLINE double ma_sin(double x)
{
/* TODO: Implement custom sin(x). */
return sin(x);
}
static MA_INLINE double ma_exp(double x)
{
/* TODO: Implement custom exp(x). */
return exp(x);
}
static MA_INLINE double ma_log(double x)
{
/* TODO: Implement custom log(x). */
return log(x);
}
static MA_INLINE double ma_pow(double x, double y)
{
/* TODO: Implement custom pow(x, y). */
return pow(x, y);
}
static MA_INLINE double ma_sqrt(double x)
{
/* TODO: Implement custom sqrt(x). */
return sqrt(x);
}
static MA_INLINE double ma_cos(double x)
{
return ma_sin((MA_PI_D*0.5) - x);
}
static MA_INLINE double ma_log10(double x)
{
return ma_log(x) * 0.43429448190325182765;
}
static MA_INLINE float ma_powf(float x, float y)
{
return (float)ma_pow((double)x, (double)y);
}
static MA_INLINE float ma_log10f(float x)
{
return (float)ma_log10((double)x);
}
/*
Return Values:
0: Success
22: EINVAL
34: ERANGE
Not using symbolic constants for errors because I want to avoid #including errno.h
*/
MA_API int ma_strcpy_s(char* dst, size_t dstSizeInBytes, const char* src)
{
size_t i;
if (dst == 0) {
return 22;
}
if (dstSizeInBytes == 0) {
return 34;
}
if (src == 0) {
dst[0] = '\0';
return 22;
}
for (i = 0; i < dstSizeInBytes && src[i] != '\0'; ++i) {
dst[i] = src[i];
}
if (i < dstSizeInBytes) {
dst[i] = '\0';
return 0;
}
dst[0] = '\0';
return 34;
}
MA_API int ma_wcscpy_s(wchar_t* dst, size_t dstSizeInBytes, const wchar_t* src)
{
size_t i;
if (dst == 0) {
return 22;
}
if (dstSizeInBytes == 0) {
return 34;
}
if (src == 0) {
dst[0] = '\0';
return 22;
}
for (i = 0; i < dstSizeInBytes && src[i] != '\0'; ++i) {
dst[i] = src[i];
}
if (i < dstSizeInBytes) {
dst[i] = '\0';
return 0;
}
dst[0] = '\0';
return 34;
}
MA_API int ma_strncpy_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count)
{
size_t maxcount;
size_t i;
if (dst == 0) {
return 22;
}
if (dstSizeInBytes == 0) {
return 34;
}
if (src == 0) {
dst[0] = '\0';
return 22;
}
maxcount = count;
if (count == ((size_t)-1) || count >= dstSizeInBytes) { /* -1 = _TRUNCATE */
maxcount = dstSizeInBytes - 1;
}
for (i = 0; i < maxcount && src[i] != '\0'; ++i) {
dst[i] = src[i];
}
if (src[i] == '\0' || i == count || count == ((size_t)-1)) {
dst[i] = '\0';
return 0;
}
dst[0] = '\0';
return 34;
}
MA_API int ma_strcat_s(char* dst, size_t dstSizeInBytes, const char* src)
{
char* dstorig;
if (dst == 0) {
return 22;
}
if (dstSizeInBytes == 0) {
return 34;
}
if (src == 0) {
dst[0] = '\0';
return 22;
}
dstorig = dst;
while (dstSizeInBytes > 0 && dst[0] != '\0') {
dst += 1;
dstSizeInBytes -= 1;
}
if (dstSizeInBytes == 0) {
return 22; /* Unterminated. */
}
while (dstSizeInBytes > 0 && src[0] != '\0') {
*dst++ = *src++;
dstSizeInBytes -= 1;
}
if (dstSizeInBytes > 0) {
dst[0] = '\0';
} else {
dstorig[0] = '\0';
return 34;
}
return 0;
}
MA_API int ma_strncat_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count)
{
char* dstorig;
if (dst == 0) {
return 22;
}
if (dstSizeInBytes == 0) {
return 34;
}
if (src == 0) {
return 22;
}
dstorig = dst;
while (dstSizeInBytes > 0 && dst[0] != '\0') {
dst += 1;
dstSizeInBytes -= 1;
}
if (dstSizeInBytes == 0) {
return 22; /* Unterminated. */
}
if (count == ((size_t)-1)) { /* _TRUNCATE */
count = dstSizeInBytes - 1;
}
while (dstSizeInBytes > 0 && src[0] != '\0' && count > 0) {
*dst++ = *src++;
dstSizeInBytes -= 1;
count -= 1;
}
if (dstSizeInBytes > 0) {
dst[0] = '\0';
} else {
dstorig[0] = '\0';
return 34;
}
return 0;
}
MA_API int ma_itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix)
{
int sign;
unsigned int valueU;
char* dstEnd;
if (dst == NULL || dstSizeInBytes == 0) {
return 22;
}
if (radix < 2 || radix > 36) {
dst[0] = '\0';
return 22;
}
sign = (value < 0 && radix == 10) ? -1 : 1; /* The negative sign is only used when the base is 10. */
if (value < 0) {
valueU = -value;
} else {
valueU = value;
}
dstEnd = dst;
do
{
int remainder = valueU % radix;
if (remainder > 9) {
*dstEnd = (char)((remainder - 10) + 'a');
} else {
*dstEnd = (char)(remainder + '0');
}
dstEnd += 1;
dstSizeInBytes -= 1;
valueU /= radix;
} while (dstSizeInBytes > 0 && valueU > 0);
if (dstSizeInBytes == 0) {
dst[0] = '\0';
return 22; /* Ran out of room in the output buffer. */
}
if (sign < 0) {
*dstEnd++ = '-';
dstSizeInBytes -= 1;
}
if (dstSizeInBytes == 0) {
dst[0] = '\0';
return 22; /* Ran out of room in the output buffer. */
}
*dstEnd = '\0';
/* At this point the string will be reversed. */
dstEnd -= 1;
while (dst < dstEnd) {
char temp = *dst;
*dst = *dstEnd;
*dstEnd = temp;
dst += 1;
dstEnd -= 1;
}
return 0;
}
MA_API int ma_strcmp(const char* str1, const char* str2)
{
if (str1 == str2) return 0;
/* These checks differ from the standard implementation. It's not important, but I prefer it just for sanity. */
if (str1 == NULL) return -1;
if (str2 == NULL) return 1;
for (;;) {
if (str1[0] == '\0') {
break;
}
if (str1[0] != str2[0]) {
break;
}
str1 += 1;
str2 += 1;
}
return ((unsigned char*)str1)[0] - ((unsigned char*)str2)[0];
}
MA_API int ma_strappend(char* dst, size_t dstSize, const char* srcA, const char* srcB)
{
int result;
result = ma_strncpy_s(dst, dstSize, srcA, (size_t)-1);
if (result != 0) {
return result;
}
result = ma_strncat_s(dst, dstSize, srcB, (size_t)-1);
if (result != 0) {
return result;
}
return result;
}
MA_API char* ma_copy_string(const char* src, const ma_allocation_callbacks* pAllocationCallbacks)
{
size_t sz = strlen(src)+1;
char* dst = (char*)ma_malloc(sz, pAllocationCallbacks);
if (dst == NULL) {
return NULL;
}
ma_strcpy_s(dst, sz, src);
return dst;
}
MA_API wchar_t* ma_copy_string_w(const wchar_t* src, const ma_allocation_callbacks* pAllocationCallbacks)
{
size_t sz = wcslen(src)+1;
wchar_t* dst = (wchar_t*)ma_malloc(sz * sizeof(*dst), pAllocationCallbacks);
if (dst == NULL) {
return NULL;
}
ma_wcscpy_s(dst, sz, src);
return dst;
}
#include
static ma_result ma_result_from_errno(int e)
{
switch (e)
{
case 0: return MA_SUCCESS;
#ifdef EPERM
case EPERM: return MA_INVALID_OPERATION;
#endif
#ifdef ENOENT
case ENOENT: return MA_DOES_NOT_EXIST;
#endif
#ifdef ESRCH
case ESRCH: return MA_DOES_NOT_EXIST;
#endif
#ifdef EINTR
case EINTR: return MA_INTERRUPT;
#endif
#ifdef EIO
case EIO: return MA_IO_ERROR;
#endif
#ifdef ENXIO
case ENXIO: return MA_DOES_NOT_EXIST;
#endif
#ifdef E2BIG
case E2BIG: return MA_INVALID_ARGS;
#endif
#ifdef ENOEXEC
case ENOEXEC: return MA_INVALID_FILE;
#endif
#ifdef EBADF
case EBADF: return MA_INVALID_FILE;
#endif
#ifdef ECHILD
case ECHILD: return MA_ERROR;
#endif
#ifdef EAGAIN
case EAGAIN: return MA_UNAVAILABLE;
#endif
#ifdef ENOMEM
case ENOMEM: return MA_OUT_OF_MEMORY;
#endif
#ifdef EACCES
case EACCES: return MA_ACCESS_DENIED;
#endif
#ifdef EFAULT
case EFAULT: return MA_BAD_ADDRESS;
#endif
#ifdef ENOTBLK
case ENOTBLK: return MA_ERROR;
#endif
#ifdef EBUSY
case EBUSY: return MA_BUSY;
#endif
#ifdef EEXIST
case EEXIST: return MA_ALREADY_EXISTS;
#endif
#ifdef EXDEV
case EXDEV: return MA_ERROR;
#endif
#ifdef ENODEV
case ENODEV: return MA_DOES_NOT_EXIST;
#endif
#ifdef ENOTDIR
case ENOTDIR: return MA_NOT_DIRECTORY;
#endif
#ifdef EISDIR
case EISDIR: return MA_IS_DIRECTORY;
#endif
#ifdef EINVAL
case EINVAL: return MA_INVALID_ARGS;
#endif
#ifdef ENFILE
case ENFILE: return MA_TOO_MANY_OPEN_FILES;
#endif
#ifdef EMFILE
case EMFILE: return MA_TOO_MANY_OPEN_FILES;
#endif
#ifdef ENOTTY
case ENOTTY: return MA_INVALID_OPERATION;
#endif
#ifdef ETXTBSY
case ETXTBSY: return MA_BUSY;
#endif
#ifdef EFBIG
case EFBIG: return MA_TOO_BIG;
#endif
#ifdef ENOSPC
case ENOSPC: return MA_NO_SPACE;
#endif
#ifdef ESPIPE
case ESPIPE: return MA_BAD_SEEK;
#endif
#ifdef EROFS
case EROFS: return MA_ACCESS_DENIED;
#endif
#ifdef EMLINK
case EMLINK: return MA_TOO_MANY_LINKS;
#endif
#ifdef EPIPE
case EPIPE: return MA_BAD_PIPE;
#endif
#ifdef EDOM
case EDOM: return MA_OUT_OF_RANGE;
#endif
#ifdef ERANGE
case ERANGE: return MA_OUT_OF_RANGE;
#endif
#ifdef EDEADLK
case EDEADLK: return MA_DEADLOCK;
#endif
#ifdef ENAMETOOLONG
case ENAMETOOLONG: return MA_PATH_TOO_LONG;
#endif
#ifdef ENOLCK
case ENOLCK: return MA_ERROR;
#endif
#ifdef ENOSYS
case ENOSYS: return MA_NOT_IMPLEMENTED;
#endif
#ifdef ENOTEMPTY
case ENOTEMPTY: return MA_DIRECTORY_NOT_EMPTY;
#endif
#ifdef ELOOP
case ELOOP: return MA_TOO_MANY_LINKS;
#endif
#ifdef ENOMSG
case ENOMSG: return MA_NO_MESSAGE;
#endif
#ifdef EIDRM
case EIDRM: return MA_ERROR;
#endif
#ifdef ECHRNG
case ECHRNG: return MA_ERROR;
#endif
#ifdef EL2NSYNC
case EL2NSYNC: return MA_ERROR;
#endif
#ifdef EL3HLT
case EL3HLT: return MA_ERROR;
#endif
#ifdef EL3RST
case EL3RST: return MA_ERROR;
#endif
#ifdef ELNRNG
case ELNRNG: return MA_OUT_OF_RANGE;
#endif
#ifdef EUNATCH
case EUNATCH: return MA_ERROR;
#endif
#ifdef ENOCSI
case ENOCSI: return MA_ERROR;
#endif
#ifdef EL2HLT
case EL2HLT: return MA_ERROR;
#endif
#ifdef EBADE
case EBADE: return MA_ERROR;
#endif
#ifdef EBADR
case EBADR: return MA_ERROR;
#endif
#ifdef EXFULL
case EXFULL: return MA_ERROR;
#endif
#ifdef ENOANO
case ENOANO: return MA_ERROR;
#endif
#ifdef EBADRQC
case EBADRQC: return MA_ERROR;
#endif
#ifdef EBADSLT
case EBADSLT: return MA_ERROR;
#endif
#ifdef EBFONT
case EBFONT: return MA_INVALID_FILE;
#endif
#ifdef ENOSTR
case ENOSTR: return MA_ERROR;
#endif
#ifdef ENODATA
case ENODATA: return MA_NO_DATA_AVAILABLE;
#endif
#ifdef ETIME
case ETIME: return MA_TIMEOUT;
#endif
#ifdef ENOSR
case ENOSR: return MA_NO_DATA_AVAILABLE;
#endif
#ifdef ENONET
case ENONET: return MA_NO_NETWORK;
#endif
#ifdef ENOPKG
case ENOPKG: return MA_ERROR;
#endif
#ifdef EREMOTE
case EREMOTE: return MA_ERROR;
#endif
#ifdef ENOLINK
case ENOLINK: return MA_ERROR;
#endif
#ifdef EADV
case EADV: return MA_ERROR;
#endif
#ifdef ESRMNT
case ESRMNT: return MA_ERROR;
#endif
#ifdef ECOMM
case ECOMM: return MA_ERROR;
#endif
#ifdef EPROTO
case EPROTO: return MA_ERROR;
#endif
#ifdef EMULTIHOP
case EMULTIHOP: return MA_ERROR;
#endif
#ifdef EDOTDOT
case EDOTDOT: return MA_ERROR;
#endif
#ifdef EBADMSG
case EBADMSG: return MA_BAD_MESSAGE;
#endif
#ifdef EOVERFLOW
case EOVERFLOW: return MA_TOO_BIG;
#endif
#ifdef ENOTUNIQ
case ENOTUNIQ: return MA_NOT_UNIQUE;
#endif
#ifdef EBADFD
case EBADFD: return MA_ERROR;
#endif
#ifdef EREMCHG
case EREMCHG: return MA_ERROR;
#endif
#ifdef ELIBACC
case ELIBACC: return MA_ACCESS_DENIED;
#endif
#ifdef ELIBBAD
case ELIBBAD: return MA_INVALID_FILE;
#endif
#ifdef ELIBSCN
case ELIBSCN: return MA_INVALID_FILE;
#endif
#ifdef ELIBMAX
case ELIBMAX: return MA_ERROR;
#endif
#ifdef ELIBEXEC
case ELIBEXEC: return MA_ERROR;
#endif
#ifdef EILSEQ
case EILSEQ: return MA_INVALID_DATA;
#endif
#ifdef ERESTART
case ERESTART: return MA_ERROR;
#endif
#ifdef ESTRPIPE
case ESTRPIPE: return MA_ERROR;
#endif
#ifdef EUSERS
case EUSERS: return MA_ERROR;
#endif
#ifdef ENOTSOCK
case ENOTSOCK: return MA_NOT_SOCKET;
#endif
#ifdef EDESTADDRREQ
case EDESTADDRREQ: return MA_NO_ADDRESS;
#endif
#ifdef EMSGSIZE
case EMSGSIZE: return MA_TOO_BIG;
#endif
#ifdef EPROTOTYPE
case EPROTOTYPE: return MA_BAD_PROTOCOL;
#endif
#ifdef ENOPROTOOPT
case ENOPROTOOPT: return MA_PROTOCOL_UNAVAILABLE;
#endif
#ifdef EPROTONOSUPPORT
case EPROTONOSUPPORT: return MA_PROTOCOL_NOT_SUPPORTED;
#endif
#ifdef ESOCKTNOSUPPORT
case ESOCKTNOSUPPORT: return MA_SOCKET_NOT_SUPPORTED;
#endif
#ifdef EOPNOTSUPP
case EOPNOTSUPP: return MA_INVALID_OPERATION;
#endif
#ifdef EPFNOSUPPORT
case EPFNOSUPPORT: return MA_PROTOCOL_FAMILY_NOT_SUPPORTED;
#endif
#ifdef EAFNOSUPPORT
case EAFNOSUPPORT: return MA_ADDRESS_FAMILY_NOT_SUPPORTED;
#endif
#ifdef EADDRINUSE
case EADDRINUSE: return MA_ALREADY_IN_USE;
#endif
#ifdef EADDRNOTAVAIL
case EADDRNOTAVAIL: return MA_ERROR;
#endif
#ifdef ENETDOWN
case ENETDOWN: return MA_NO_NETWORK;
#endif
#ifdef ENETUNREACH
case ENETUNREACH: return MA_NO_NETWORK;
#endif
#ifdef ENETRESET
case ENETRESET: return MA_NO_NETWORK;
#endif
#ifdef ECONNABORTED
case ECONNABORTED: return MA_NO_NETWORK;
#endif
#ifdef ECONNRESET
case ECONNRESET: return MA_CONNECTION_RESET;
#endif
#ifdef ENOBUFS
case ENOBUFS: return MA_NO_SPACE;
#endif
#ifdef EISCONN
case EISCONN: return MA_ALREADY_CONNECTED;
#endif
#ifdef ENOTCONN
case ENOTCONN: return MA_NOT_CONNECTED;
#endif
#ifdef ESHUTDOWN
case ESHUTDOWN: return MA_ERROR;
#endif
#ifdef ETOOMANYREFS
case ETOOMANYREFS: return MA_ERROR;
#endif
#ifdef ETIMEDOUT
case ETIMEDOUT: return MA_TIMEOUT;
#endif
#ifdef ECONNREFUSED
case ECONNREFUSED: return MA_CONNECTION_REFUSED;
#endif
#ifdef EHOSTDOWN
case EHOSTDOWN: return MA_NO_HOST;
#endif
#ifdef EHOSTUNREACH
case EHOSTUNREACH: return MA_NO_HOST;
#endif
#ifdef EALREADY
case EALREADY: return MA_IN_PROGRESS;
#endif
#ifdef EINPROGRESS
case EINPROGRESS: return MA_IN_PROGRESS;
#endif
#ifdef ESTALE
case ESTALE: return MA_INVALID_FILE;
#endif
#ifdef EUCLEAN
case EUCLEAN: return MA_ERROR;
#endif
#ifdef ENOTNAM
case ENOTNAM: return MA_ERROR;
#endif
#ifdef ENAVAIL
case ENAVAIL: return MA_ERROR;
#endif
#ifdef EISNAM
case EISNAM: return MA_ERROR;
#endif
#ifdef EREMOTEIO
case EREMOTEIO: return MA_IO_ERROR;
#endif
#ifdef EDQUOT
case EDQUOT: return MA_NO_SPACE;
#endif
#ifdef ENOMEDIUM
case ENOMEDIUM: return MA_DOES_NOT_EXIST;
#endif
#ifdef EMEDIUMTYPE
case EMEDIUMTYPE: return MA_ERROR;
#endif
#ifdef ECANCELED
case ECANCELED: return MA_CANCELLED;
#endif
#ifdef ENOKEY
case ENOKEY: return MA_ERROR;
#endif
#ifdef EKEYEXPIRED
case EKEYEXPIRED: return MA_ERROR;
#endif
#ifdef EKEYREVOKED
case EKEYREVOKED: return MA_ERROR;
#endif
#ifdef EKEYREJECTED
case EKEYREJECTED: return MA_ERROR;
#endif
#ifdef EOWNERDEAD
case EOWNERDEAD: return MA_ERROR;
#endif
#ifdef ENOTRECOVERABLE
case ENOTRECOVERABLE: return MA_ERROR;
#endif
#ifdef ERFKILL
case ERFKILL: return MA_ERROR;
#endif
#ifdef EHWPOISON
case EHWPOISON: return MA_ERROR;
#endif
default: return MA_ERROR;
}
}
MA_API ma_result ma_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
{
#if _MSC_VER && _MSC_VER >= 1400
errno_t err;
#endif
if (ppFile != NULL) {
*ppFile = NULL; /* Safety. */
}
if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
return MA_INVALID_ARGS;
}
#if _MSC_VER && _MSC_VER >= 1400
err = fopen_s(ppFile, pFilePath, pOpenMode);
if (err != 0) {
return ma_result_from_errno(err);
}
#else
#if defined(_WIN32) || defined(__APPLE__)
*ppFile = fopen(pFilePath, pOpenMode);
#else
#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
*ppFile = fopen64(pFilePath, pOpenMode);
#else
*ppFile = fopen(pFilePath, pOpenMode);
#endif
#endif
if (*ppFile == NULL) {
ma_result result = ma_result_from_errno(errno);
if (result == MA_SUCCESS) {
result = MA_ERROR; /* Just a safety check to make sure we never ever return success when pFile == NULL. */
}
return result;
}
#endif
return MA_SUCCESS;
}
/*
_wfopen() isn't always available in all compilation environments.
* Windows only.
* MSVC seems to support it universally as far back as VC6 from what I can tell (haven't checked further back).
* MinGW-64 (both 32- and 64-bit) seems to support it.
* MinGW wraps it in !defined(__STRICT_ANSI__).
* OpenWatcom wraps it in !defined(_NO_EXT_KEYS).
This can be reviewed as compatibility issues arise. The preference is to use _wfopen_s() and _wfopen() as opposed to the wcsrtombs()
fallback, so if you notice your compiler not detecting this properly I'm happy to look at adding support.
*/
#if defined(_WIN32)
#if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
#define MA_HAS_WFOPEN
#endif
#endif
MA_API ma_result ma_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const ma_allocation_callbacks* pAllocationCallbacks)
{
if (ppFile != NULL) {
*ppFile = NULL; /* Safety. */
}
if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
return MA_INVALID_ARGS;
}
#if defined(MA_HAS_WFOPEN)
{
/* Use _wfopen() on Windows. */
#if defined(_MSC_VER) && _MSC_VER >= 1400
errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
if (err != 0) {
return ma_result_from_errno(err);
}
#else
*ppFile = _wfopen(pFilePath, pOpenMode);
if (*ppFile == NULL) {
return ma_result_from_errno(errno);
}
#endif
(void)pAllocationCallbacks;
}
#else
/*
Use fopen() on anything other than Windows. Requires a conversion. This is annoying because fopen() is locale specific. The only real way I can
think of to do this is with wcsrtombs(). Note that wcstombs() is apparently not thread-safe because it uses a static global mbstate_t object for
maintaining state. I've checked this with -std=c89 and it works, but if somebody get's a compiler error I'll look into improving compatibility.
*/
{
mbstate_t mbs;
size_t lenMB;
const wchar_t* pFilePathTemp = pFilePath;
char* pFilePathMB = NULL;
char pOpenModeMB[32] = {0};
/* Get the length first. */
MA_ZERO_OBJECT(&mbs);
lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
if (lenMB == (size_t)-1) {
return ma_result_from_errno(errno);
}
pFilePathMB = (char*)ma_malloc(lenMB + 1, pAllocationCallbacks);
if (pFilePathMB == NULL) {
return MA_OUT_OF_MEMORY;
}
pFilePathTemp = pFilePath;
MA_ZERO_OBJECT(&mbs);
wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
/* The open mode should always consist of ASCII characters so we should be able to do a trivial conversion. */
{
size_t i = 0;
for (;;) {
if (pOpenMode[i] == 0) {
pOpenModeMB[i] = '\0';
break;
}
pOpenModeMB[i] = (char)pOpenMode[i];
i += 1;
}
}
*ppFile = fopen(pFilePathMB, pOpenModeMB);
ma_free(pFilePathMB, pAllocationCallbacks);
}
if (*ppFile == NULL) {
return MA_ERROR;
}
#endif
return MA_SUCCESS;
}
static MA_INLINE void ma_copy_memory_64(void* dst, const void* src, ma_uint64 sizeInBytes)
{
#if 0xFFFFFFFFFFFFFFFF <= MA_SIZE_MAX
MA_COPY_MEMORY(dst, src, (size_t)sizeInBytes);
#else
while (sizeInBytes > 0) {
ma_uint64 bytesToCopyNow = sizeInBytes;
if (bytesToCopyNow > MA_SIZE_MAX) {
bytesToCopyNow = MA_SIZE_MAX;
}
MA_COPY_MEMORY(dst, src, (size_t)bytesToCopyNow); /* Safe cast to size_t. */
sizeInBytes -= bytesToCopyNow;
dst = ( void*)(( ma_uint8*)dst + bytesToCopyNow);
src = (const void*)((const ma_uint8*)src + bytesToCopyNow);
}
#endif
}
static MA_INLINE void ma_zero_memory_64(void* dst, ma_uint64 sizeInBytes)
{
#if 0xFFFFFFFFFFFFFFFF <= MA_SIZE_MAX
MA_ZERO_MEMORY(dst, (size_t)sizeInBytes);
#else
while (sizeInBytes > 0) {
ma_uint64 bytesToZeroNow = sizeInBytes;
if (bytesToZeroNow > MA_SIZE_MAX) {
bytesToZeroNow = MA_SIZE_MAX;
}
MA_ZERO_MEMORY(dst, (size_t)bytesToZeroNow); /* Safe cast to size_t. */
sizeInBytes -= bytesToZeroNow;
dst = (void*)((ma_uint8*)dst + bytesToZeroNow);
}
#endif
}
/* Thanks to good old Bit Twiddling Hacks for this one: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 */
static MA_INLINE unsigned int ma_next_power_of_2(unsigned int x)
{
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
}
static MA_INLINE unsigned int ma_prev_power_of_2(unsigned int x)
{
return ma_next_power_of_2(x) >> 1;
}
static MA_INLINE unsigned int ma_round_to_power_of_2(unsigned int x)
{
unsigned int prev = ma_prev_power_of_2(x);
unsigned int next = ma_next_power_of_2(x);
if ((next - x) > (x - prev)) {
return prev;
} else {
return next;
}
}
static MA_INLINE unsigned int ma_count_set_bits(unsigned int x)
{
unsigned int count = 0;
while (x != 0) {
if (x & 1) {
count += 1;
}
x = x >> 1;
}
return count;
}
/* Clamps an f32 sample to -1..1 */
static MA_INLINE float ma_clip_f32(float x)
{
if (x < -1) return -1;
if (x > +1) return +1;
return x;
}
static MA_INLINE float ma_mix_f32(float x, float y, float a)
{
return x*(1-a) + y*a;
}
static MA_INLINE float ma_mix_f32_fast(float x, float y, float a)
{
float r0 = (y - x);
float r1 = r0*a;
return x + r1;
/*return x + (y - x)*a;*/
}
#if defined(MA_SUPPORT_SSE2)
static MA_INLINE __m128 ma_mix_f32_fast__sse2(__m128 x, __m128 y, __m128 a)
{
return _mm_add_ps(x, _mm_mul_ps(_mm_sub_ps(y, x), a));
}
#endif
#if defined(MA_SUPPORT_AVX2)
static MA_INLINE __m256 ma_mix_f32_fast__avx2(__m256 x, __m256 y, __m256 a)
{
return _mm256_add_ps(x, _mm256_mul_ps(_mm256_sub_ps(y, x), a));
}
#endif
#if defined(MA_SUPPORT_AVX512)
static MA_INLINE __m512 ma_mix_f32_fast__avx512(__m512 x, __m512 y, __m512 a)
{
return _mm512_add_ps(x, _mm512_mul_ps(_mm512_sub_ps(y, x), a));
}
#endif
#if defined(MA_SUPPORT_NEON)
static MA_INLINE float32x4_t ma_mix_f32_fast__neon(float32x4_t x, float32x4_t y, float32x4_t a)
{
return vaddq_f32(x, vmulq_f32(vsubq_f32(y, x), a));
}
#endif
static MA_INLINE double ma_mix_f64(double x, double y, double a)
{
return x*(1-a) + y*a;
}
static MA_INLINE double ma_mix_f64_fast(double x, double y, double a)
{
return x + (y - x)*a;
}
static MA_INLINE float ma_scale_to_range_f32(float x, float lo, float hi)
{
return lo + x*(hi-lo);
}
/*
Greatest common factor using Euclid's algorithm iteratively.
*/
static MA_INLINE ma_uint32 ma_gcf_u32(ma_uint32 a, ma_uint32 b)
{
for (;;) {
if (b == 0) {
break;
} else {
ma_uint32 t = a;
a = b;
b = t % a;
}
}
return a;
}
/*
Random Number Generation
miniaudio uses the LCG random number generation algorithm. This is good enough for audio.
Note that miniaudio's global LCG implementation uses global state which is _not_ thread-local. When this is called across
multiple threads, results will be unpredictable. However, it won't crash and results will still be random enough for
miniaudio's purposes.
*/
#ifndef MA_DEFAULT_LCG_SEED
#define MA_DEFAULT_LCG_SEED 4321
#endif
#define MA_LCG_M 2147483647
#define MA_LCG_A 48271
#define MA_LCG_C 0
static ma_lcg g_maLCG = {MA_DEFAULT_LCG_SEED}; /* Non-zero initial seed. Use ma_seed() to use an explicit seed. */
static MA_INLINE void ma_lcg_seed(ma_lcg* pLCG, ma_int32 seed)
{
MA_ASSERT(pLCG != NULL);
pLCG->state = seed;
}
static MA_INLINE ma_int32 ma_lcg_rand_s32(ma_lcg* pLCG)
{
pLCG->state = (MA_LCG_A * pLCG->state + MA_LCG_C) % MA_LCG_M;
return pLCG->state;
}
static MA_INLINE ma_uint32 ma_lcg_rand_u32(ma_lcg* pLCG)
{
return (ma_uint32)ma_lcg_rand_s32(pLCG);
}
static MA_INLINE ma_int16 ma_lcg_rand_s16(ma_lcg* pLCG)
{
return (ma_int16)(ma_lcg_rand_s32(pLCG) & 0xFFFF);
}
static MA_INLINE double ma_lcg_rand_f64(ma_lcg* pLCG)
{
return ma_lcg_rand_s32(pLCG) / (double)0x7FFFFFFF;
}
static MA_INLINE float ma_lcg_rand_f32(ma_lcg* pLCG)
{
return (float)ma_lcg_rand_f64(pLCG);
}
static MA_INLINE float ma_lcg_rand_range_f32(ma_lcg* pLCG, float lo, float hi)
{
return ma_scale_to_range_f32(ma_lcg_rand_f32(pLCG), lo, hi);
}
static MA_INLINE ma_int32 ma_lcg_rand_range_s32(ma_lcg* pLCG, ma_int32 lo, ma_int32 hi)
{
if (lo == hi) {
return lo;
}
return lo + ma_lcg_rand_u32(pLCG) / (0xFFFFFFFF / (hi - lo + 1) + 1);
}
static MA_INLINE void ma_seed(ma_int32 seed)
{
ma_lcg_seed(&g_maLCG, seed);
}
static MA_INLINE ma_int32 ma_rand_s32(void)
{
return ma_lcg_rand_s32(&g_maLCG);
}
static MA_INLINE ma_uint32 ma_rand_u32(void)
{
return ma_lcg_rand_u32(&g_maLCG);
}
static MA_INLINE double ma_rand_f64(void)
{
return ma_lcg_rand_f64(&g_maLCG);
}
static MA_INLINE float ma_rand_f32(void)
{
return ma_lcg_rand_f32(&g_maLCG);
}
static MA_INLINE float ma_rand_range_f32(float lo, float hi)
{
return ma_lcg_rand_range_f32(&g_maLCG, lo, hi);
}
static MA_INLINE ma_int32 ma_rand_range_s32(ma_int32 lo, ma_int32 hi)
{
return ma_lcg_rand_range_s32(&g_maLCG, lo, hi);
}
static MA_INLINE float ma_dither_f32_rectangle(float ditherMin, float ditherMax)
{
return ma_rand_range_f32(ditherMin, ditherMax);
}
static MA_INLINE float ma_dither_f32_triangle(float ditherMin, float ditherMax)
{
float a = ma_rand_range_f32(ditherMin, 0);
float b = ma_rand_range_f32(0, ditherMax);
return a + b;
}
static MA_INLINE float ma_dither_f32(ma_dither_mode ditherMode, float ditherMin, float ditherMax)
{
if (ditherMode == ma_dither_mode_rectangle) {
return ma_dither_f32_rectangle(ditherMin, ditherMax);
}
if (ditherMode == ma_dither_mode_triangle) {
return ma_dither_f32_triangle(ditherMin, ditherMax);
}
return 0;
}
static MA_INLINE ma_int32 ma_dither_s32(ma_dither_mode ditherMode, ma_int32 ditherMin, ma_int32 ditherMax)
{
if (ditherMode == ma_dither_mode_rectangle) {
ma_int32 a = ma_rand_range_s32(ditherMin, ditherMax);
return a;
}
if (ditherMode == ma_dither_mode_triangle) {
ma_int32 a = ma_rand_range_s32(ditherMin, 0);
ma_int32 b = ma_rand_range_s32(0, ditherMax);
return a + b;
}
return 0;
}
/**************************************************************************************************************************************************************
Atomics
**************************************************************************************************************************************************************/
/* c89atomic.h begin */
#ifndef c89atomic_h
#define c89atomic_h
#if defined(__cplusplus)
extern "C" {
#endif
typedef signed char c89atomic_int8;
typedef unsigned char c89atomic_uint8;
typedef signed short c89atomic_int16;
typedef unsigned short c89atomic_uint16;
typedef signed int c89atomic_int32;
typedef unsigned int c89atomic_uint32;
#if defined(_MSC_VER)
typedef signed __int64 c89atomic_int64;
typedef unsigned __int64 c89atomic_uint64;
#else
#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlong-long"
#if defined(__clang__)
#pragma GCC diagnostic ignored "-Wc++11-long-long"
#endif
#endif
typedef signed long long c89atomic_int64;
typedef unsigned long long c89atomic_uint64;
#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
#pragma GCC diagnostic pop
#endif
#endif
typedef int c89atomic_memory_order;
typedef unsigned char c89atomic_bool;
typedef unsigned char c89atomic_flag;
#if !defined(C89ATOMIC_64BIT) && !defined(C89ATOMIC_32BIT)
#ifdef _WIN32
#ifdef _WIN64
#define C89ATOMIC_64BIT
#else
#define C89ATOMIC_32BIT
#endif
#endif
#endif
#if !defined(C89ATOMIC_64BIT) && !defined(C89ATOMIC_32BIT)
#ifdef __GNUC__
#ifdef __LP64__
#define C89ATOMIC_64BIT
#else
#define C89ATOMIC_32BIT
#endif
#endif
#endif
#if !defined(C89ATOMIC_64BIT) && !defined(C89ATOMIC_32BIT)
#include
#if INTPTR_MAX == INT64_MAX
#define C89ATOMIC_64BIT
#else
#define C89ATOMIC_32BIT
#endif
#endif
#if defined(__x86_64__) || defined(_M_X64)
#define C89ATOMIC_X64
#elif defined(__i386) || defined(_M_IX86)
#define C89ATOMIC_X86
#elif defined(__arm__) || defined(_M_ARM)
#define C89ATOMIC_ARM
#endif
#if defined(_MSC_VER)
#define C89ATOMIC_INLINE __forceinline
#elif defined(__GNUC__)
#if defined(__STRICT_ANSI__)
#define C89ATOMIC_INLINE __inline__ __attribute__((always_inline))
#else
#define C89ATOMIC_INLINE inline __attribute__((always_inline))
#endif
#elif defined(__WATCOMC__) || defined(__DMC__)
#define C89ATOMIC_INLINE __inline
#else
#define C89ATOMIC_INLINE
#endif
#if (defined(_MSC_VER) ) || defined(__WATCOMC__) || defined(__DMC__)
#define c89atomic_memory_order_relaxed 0
#define c89atomic_memory_order_consume 1
#define c89atomic_memory_order_acquire 2
#define c89atomic_memory_order_release 3
#define c89atomic_memory_order_acq_rel 4
#define c89atomic_memory_order_seq_cst 5
#if _MSC_VER >= 1400
#include
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
(void)order;
return (c89atomic_uint8)_InterlockedExchange8((volatile char*)dst, (char)src);
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
(void)order;
return (c89atomic_uint16)_InterlockedExchange16((volatile short*)dst, (short)src);
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
(void)order;
return (c89atomic_uint32)_InterlockedExchange((volatile long*)dst, (long)src);
}
#if defined(C89ATOMIC_64BIT)
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
(void)order;
return (c89atomic_uint64)_InterlockedExchange64((volatile long long*)dst, (long long)src);
}
#endif
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
(void)order;
return (c89atomic_uint8)_InterlockedExchangeAdd8((volatile char*)dst, (char)src);
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
(void)order;
return (c89atomic_uint16)_InterlockedExchangeAdd16((volatile short*)dst, (short)src);
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
(void)order;
return (c89atomic_uint32)_InterlockedExchangeAdd((volatile long*)dst, (long)src);
}
#if defined(C89ATOMIC_64BIT)
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
(void)order;
return (c89atomic_uint64)_InterlockedExchangeAdd64((volatile long long*)dst, (long long)src);
}
#endif
#define c89atomic_compare_and_swap_8( dst, expected, desired) (c89atomic_uint8 )_InterlockedCompareExchange8 ((volatile char* )dst, (char )desired, (char )expected)
#define c89atomic_compare_and_swap_16(dst, expected, desired) (c89atomic_uint16)_InterlockedCompareExchange16((volatile short* )dst, (short )desired, (short )expected)
#define c89atomic_compare_and_swap_32(dst, expected, desired) (c89atomic_uint32)_InterlockedCompareExchange ((volatile long* )dst, (long )desired, (long )expected)
#define c89atomic_compare_and_swap_64(dst, expected, desired) (c89atomic_uint64)_InterlockedCompareExchange64((volatile long long*)dst, (long long)desired, (long long)expected)
#if defined(C89ATOMIC_X64)
#define c89atomic_thread_fence(order) __faststorefence(), (void)order
#else
static C89ATOMIC_INLINE void c89atomic_thread_fence(c89atomic_memory_order order)
{
volatile c89atomic_uint32 barrier = 0;
(void)order;
c89atomic_fetch_add_explicit_32(&barrier, 0, order);
}
#endif
#else
#if defined(C89ATOMIC_X86)
static C89ATOMIC_INLINE void __stdcall c89atomic_thread_fence(c89atomic_memory_order order)
{
(void)order;
__asm {
lock add [esp], 0
}
}
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
c89atomic_uint8 result = 0;
(void)order;
__asm {
mov ecx, dst
mov al, src
lock xchg [ecx], al
mov result, al
}
return result;
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
c89atomic_uint16 result = 0;
(void)order;
__asm {
mov ecx, dst
mov ax, src
lock xchg [ecx], ax
mov result, ax
}
return result;
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
c89atomic_uint32 result = 0;
(void)order;
__asm {
mov ecx, dst
mov eax, src
lock xchg [ecx], eax
mov result, eax
}
return result;
}
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
c89atomic_uint8 result = 0;
(void)order;
__asm {
mov ecx, dst
mov al, src
lock xadd [ecx], al
mov result, al
}
return result;
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
c89atomic_uint16 result = 0;
(void)order;
__asm {
mov ecx, dst
mov ax, src
lock xadd [ecx], ax
mov result, ax
}
return result;
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
c89atomic_uint32 result = 0;
(void)order;
__asm {
mov ecx, dst
mov eax, src
lock xadd [ecx], eax
mov result, eax
}
return result;
}
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_compare_and_swap_8(volatile c89atomic_uint8* dst, c89atomic_uint8 expected, c89atomic_uint8 desired)
{
c89atomic_uint8 result = 0;
__asm {
mov ecx, dst
mov al, expected
mov dl, desired
lock cmpxchg [ecx], dl
mov result, al
}
return result;
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_compare_and_swap_16(volatile c89atomic_uint16* dst, c89atomic_uint16 expected, c89atomic_uint16 desired)
{
c89atomic_uint16 result = 0;
__asm {
mov ecx, dst
mov ax, expected
mov dx, desired
lock cmpxchg [ecx], dx
mov result, ax
}
return result;
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_compare_and_swap_32(volatile c89atomic_uint32* dst, c89atomic_uint32 expected, c89atomic_uint32 desired)
{
c89atomic_uint32 result = 0;
__asm {
mov ecx, dst
mov eax, expected
mov edx, desired
lock cmpxchg [ecx], edx
mov result, eax
}
return result;
}
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_compare_and_swap_64(volatile c89atomic_uint64* dst, c89atomic_uint64 expected, c89atomic_uint64 desired)
{
c89atomic_uint32 resultEAX = 0;
c89atomic_uint32 resultEDX = 0;
__asm {
mov esi, dst
mov eax, dword ptr expected
mov edx, dword ptr expected + 4
mov ebx, dword ptr desired
mov ecx, dword ptr desired + 4
lock cmpxchg8b qword ptr [esi]
mov resultEAX, eax
mov resultEDX, edx
}
return ((c89atomic_uint64)resultEDX << 32) | resultEAX;
}
#else
#error Unsupported architecture.
#endif
#endif
#define c89atomic_compiler_fence() c89atomic_thread_fence(c89atomic_memory_order_seq_cst)
#define c89atomic_signal_fence(order) c89atomic_thread_fence(order)
static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_load_explicit_8(volatile c89atomic_uint8* ptr, c89atomic_memory_order order)
{
(void)order;
return c89atomic_compare_and_swap_8(ptr, 0, 0);
}
static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_load_explicit_16(volatile c89atomic_uint16* ptr, c89atomic_memory_order order)
{
(void)order;
return c89atomic_compare_and_swap_16(ptr, 0, 0);
}
static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_load_explicit_32(volatile c89atomic_uint32* ptr, c89atomic_memory_order order)
{
(void)order;
return c89atomic_compare_and_swap_32(ptr, 0, 0);
}
static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_load_explicit_64(volatile c89atomic_uint64* ptr, c89atomic_memory_order order)
{
(void)order;
return c89atomic_compare_and_swap_64(ptr, 0, 0);
}
#define c89atomic_store_explicit_8( dst, src, order) (void)c89atomic_exchange_explicit_8 (dst, src, order)
#define c89atomic_store_explicit_16(dst, src, order) (void)c89atomic_exchange_explicit_16(dst, src, order)
#define c89atomic_store_explicit_32(dst, src, order) (void)c89atomic_exchange_explicit_32(dst, src, order)
#define c89atomic_store_explicit_64(dst, src, order) (void)c89atomic_exchange_explicit_64(dst, src, order)
#if defined(C89ATOMIC_32BIT)
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
volatile c89atomic_uint64 oldValue;
do {
oldValue = *dst;
} while (c89atomic_compare_and_swap_64(dst, oldValue, src) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
volatile c89atomic_uint64 oldValue;
volatile c89atomic_uint64 newValue;
do {
oldValue = *dst;
newValue = oldValue + src;
} while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
#endif
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_sub_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
volatile c89atomic_uint8 oldValue;
volatile c89atomic_uint8 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint8)(oldValue - src);
} while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_sub_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
volatile c89atomic_uint16 oldValue;
volatile c89atomic_uint16 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint16)(oldValue - src);
} while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_sub_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
volatile c89atomic_uint32 oldValue;
volatile c89atomic_uint32 newValue;
do {
oldValue = *dst;
newValue = oldValue - src;
} while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_sub_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
volatile c89atomic_uint64 oldValue;
volatile c89atomic_uint64 newValue;
do {
oldValue = *dst;
newValue = oldValue - src;
} while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_and_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
volatile c89atomic_uint8 oldValue;
volatile c89atomic_uint8 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint8)(oldValue & src);
} while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_and_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
volatile c89atomic_uint16 oldValue;
volatile c89atomic_uint16 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint16)(oldValue & src);
} while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_and_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
volatile c89atomic_uint32 oldValue;
volatile c89atomic_uint32 newValue;
do {
oldValue = *dst;
newValue = oldValue & src;
} while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_and_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
volatile c89atomic_uint64 oldValue;
volatile c89atomic_uint64 newValue;
do {
oldValue = *dst;
newValue = oldValue & src;
} while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_xor_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
volatile c89atomic_uint8 oldValue;
volatile c89atomic_uint8 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint8)(oldValue ^ src);
} while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_xor_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
volatile c89atomic_uint16 oldValue;
volatile c89atomic_uint16 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint16)(oldValue ^ src);
} while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_xor_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
volatile c89atomic_uint32 oldValue;
volatile c89atomic_uint32 newValue;
do {
oldValue = *dst;
newValue = oldValue ^ src;
} while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_xor_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
volatile c89atomic_uint64 oldValue;
volatile c89atomic_uint64 newValue;
do {
oldValue = *dst;
newValue = oldValue ^ src;
} while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_or_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
volatile c89atomic_uint8 oldValue;
volatile c89atomic_uint8 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint8)(oldValue | src);
} while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_or_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
volatile c89atomic_uint16 oldValue;
volatile c89atomic_uint16 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint16)(oldValue | src);
} while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_or_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
volatile c89atomic_uint32 oldValue;
volatile c89atomic_uint32 newValue;
do {
oldValue = *dst;
newValue = oldValue | src;
} while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_or_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
volatile c89atomic_uint64 oldValue;
volatile c89atomic_uint64 newValue;
do {
oldValue = *dst;
newValue = oldValue | src;
} while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
#define c89atomic_test_and_set_explicit_8( dst, order) c89atomic_exchange_explicit_8 (dst, 1, order)
#define c89atomic_test_and_set_explicit_16(dst, order) c89atomic_exchange_explicit_16(dst, 1, order)
#define c89atomic_test_and_set_explicit_32(dst, order) c89atomic_exchange_explicit_32(dst, 1, order)
#define c89atomic_test_and_set_explicit_64(dst, order) c89atomic_exchange_explicit_64(dst, 1, order)
#define c89atomic_clear_explicit_8( dst, order) c89atomic_store_explicit_8 (dst, 0, order)
#define c89atomic_clear_explicit_16(dst, order) c89atomic_store_explicit_16(dst, 0, order)
#define c89atomic_clear_explicit_32(dst, order) c89atomic_store_explicit_32(dst, 0, order)
#define c89atomic_clear_explicit_64(dst, order) c89atomic_store_explicit_64(dst, 0, order)
#define c89atomic_flag_test_and_set_explicit(ptr, order) (c89atomic_flag)c89atomic_test_and_set_explicit_8(ptr, order)
#define c89atomic_flag_clear_explicit(ptr, order) c89atomic_clear_explicit_8(ptr, order)
#elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
#define C89ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE
#define C89ATOMIC_HAS_NATIVE_IS_LOCK_FREE
#define c89atomic_memory_order_relaxed __ATOMIC_RELAXED
#define c89atomic_memory_order_consume __ATOMIC_CONSUME
#define c89atomic_memory_order_acquire __ATOMIC_ACQUIRE
#define c89atomic_memory_order_release __ATOMIC_RELEASE
#define c89atomic_memory_order_acq_rel __ATOMIC_ACQ_REL
#define c89atomic_memory_order_seq_cst __ATOMIC_SEQ_CST
#define c89atomic_compiler_fence() __asm__ __volatile__("":::"memory")
#define c89atomic_thread_fence(order) __atomic_thread_fence(order)
#define c89atomic_signal_fence(order) __atomic_signal_fence(order)
#define c89atomic_is_lock_free_8(ptr) __atomic_is_lock_free(1, ptr)
#define c89atomic_is_lock_free_16(ptr) __atomic_is_lock_free(2, ptr)
#define c89atomic_is_lock_free_32(ptr) __atomic_is_lock_free(4, ptr)
#define c89atomic_is_lock_free_64(ptr) __atomic_is_lock_free(8, ptr)
#define c89atomic_flag_test_and_set_explicit(dst, order) (c89atomic_flag)__atomic_test_and_set(dst, order)
#define c89atomic_flag_clear_explicit(dst, order) __atomic_clear(dst, order)
#define c89atomic_test_and_set_explicit_8( dst, order) __atomic_exchange_n(dst, 1, order)
#define c89atomic_test_and_set_explicit_16(dst, order) __atomic_exchange_n(dst, 1, order)
#define c89atomic_test_and_set_explicit_32(dst, order) __atomic_exchange_n(dst, 1, order)
#define c89atomic_test_and_set_explicit_64(dst, order) __atomic_exchange_n(dst, 1, order)
#define c89atomic_clear_explicit_8( dst, order) __atomic_store_n(dst, 0, order)
#define c89atomic_clear_explicit_16(dst, order) __atomic_store_n(dst, 0, order)
#define c89atomic_clear_explicit_32(dst, order) __atomic_store_n(dst, 0, order)
#define c89atomic_clear_explicit_64(dst, order) __atomic_store_n(dst, 0, order)
#define c89atomic_store_explicit_8( dst, src, order) __atomic_store_n(dst, src, order)
#define c89atomic_store_explicit_16(dst, src, order) __atomic_store_n(dst, src, order)
#define c89atomic_store_explicit_32(dst, src, order) __atomic_store_n(dst, src, order)
#define c89atomic_store_explicit_64(dst, src, order) __atomic_store_n(dst, src, order)
#define c89atomic_load_explicit_8( dst, order) __atomic_load_n(dst, order)
#define c89atomic_load_explicit_16(dst, order) __atomic_load_n(dst, order)
#define c89atomic_load_explicit_32(dst, order) __atomic_load_n(dst, order)
#define c89atomic_load_explicit_64(dst, order) __atomic_load_n(dst, order)
#define c89atomic_exchange_explicit_8( dst, src, order) __atomic_exchange_n(dst, src, order)
#define c89atomic_exchange_explicit_16(dst, src, order) __atomic_exchange_n(dst, src, order)
#define c89atomic_exchange_explicit_32(dst, src, order) __atomic_exchange_n(dst, src, order)
#define c89atomic_exchange_explicit_64(dst, src, order) __atomic_exchange_n(dst, src, order)
#define c89atomic_compare_exchange_strong_explicit_8( dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
#define c89atomic_compare_exchange_strong_explicit_16(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
#define c89atomic_compare_exchange_strong_explicit_32(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
#define c89atomic_compare_exchange_strong_explicit_64(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
#define c89atomic_compare_exchange_weak_explicit_8( dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
#define c89atomic_compare_exchange_weak_explicit_16(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
#define c89atomic_compare_exchange_weak_explicit_32(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
#define c89atomic_compare_exchange_weak_explicit_64(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
#define c89atomic_fetch_add_explicit_8( dst, src, order) __atomic_fetch_add(dst, src, order)
#define c89atomic_fetch_add_explicit_16(dst, src, order) __atomic_fetch_add(dst, src, order)
#define c89atomic_fetch_add_explicit_32(dst, src, order) __atomic_fetch_add(dst, src, order)
#define c89atomic_fetch_add_explicit_64(dst, src, order) __atomic_fetch_add(dst, src, order)
#define c89atomic_fetch_sub_explicit_8( dst, src, order) __atomic_fetch_sub(dst, src, order)
#define c89atomic_fetch_sub_explicit_16(dst, src, order) __atomic_fetch_sub(dst, src, order)
#define c89atomic_fetch_sub_explicit_32(dst, src, order) __atomic_fetch_sub(dst, src, order)
#define c89atomic_fetch_sub_explicit_64(dst, src, order) __atomic_fetch_sub(dst, src, order)
#define c89atomic_fetch_or_explicit_8( dst, src, order) __atomic_fetch_or(dst, src, order)
#define c89atomic_fetch_or_explicit_16(dst, src, order) __atomic_fetch_or(dst, src, order)
#define c89atomic_fetch_or_explicit_32(dst, src, order) __atomic_fetch_or(dst, src, order)
#define c89atomic_fetch_or_explicit_64(dst, src, order) __atomic_fetch_or(dst, src, order)
#define c89atomic_fetch_xor_explicit_8( dst, src, order) __atomic_fetch_xor(dst, src, order)
#define c89atomic_fetch_xor_explicit_16(dst, src, order) __atomic_fetch_xor(dst, src, order)
#define c89atomic_fetch_xor_explicit_32(dst, src, order) __atomic_fetch_xor(dst, src, order)
#define c89atomic_fetch_xor_explicit_64(dst, src, order) __atomic_fetch_xor(dst, src, order)
#define c89atomic_fetch_and_explicit_8( dst, src, order) __atomic_fetch_and(dst, src, order)
#define c89atomic_fetch_and_explicit_16(dst, src, order) __atomic_fetch_and(dst, src, order)
#define c89atomic_fetch_and_explicit_32(dst, src, order) __atomic_fetch_and(dst, src, order)
#define c89atomic_fetch_and_explicit_64(dst, src, order) __atomic_fetch_and(dst, src, order)
#define c89atomic_compare_and_swap_8 (dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
#define c89atomic_compare_and_swap_16(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
#define c89atomic_compare_and_swap_32(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
#define c89atomic_compare_and_swap_64(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
#else
#define c89atomic_memory_order_relaxed 1
#define c89atomic_memory_order_consume 2
#define c89atomic_memory_order_acquire 3
#define c89atomic_memory_order_release 4
#define c89atomic_memory_order_acq_rel 5
#define c89atomic_memory_order_seq_cst 6
#define c89atomic_compiler_fence() __asm__ __volatile__("":::"memory")
#if defined(__GNUC__)
#define c89atomic_thread_fence(order) __sync_synchronize(), (void)order
static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
if (order > c89atomic_memory_order_acquire) {
__sync_synchronize();
}
return __sync_lock_test_and_set(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
volatile c89atomic_uint16 oldValue;
do {
oldValue = *dst;
} while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
volatile c89atomic_uint32 oldValue;
do {
oldValue = *dst;
} while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
volatile c89atomic_uint64 oldValue;
do {
oldValue = *dst;
} while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_add(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_add(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_add(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_add(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_sub_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_sub(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_sub_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_sub(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_sub_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_sub(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_sub_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_sub(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_or_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_or(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_or_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_or(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_or_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_or(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_or_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_or(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_xor_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_xor(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_xor_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_xor(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_xor_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_xor(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_xor_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_xor(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_and_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_and(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_and_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_and(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_and_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_and(dst, src);
}
static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_and_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
(void)order;
return __sync_fetch_and_and(dst, src);
}
#define c89atomic_compare_and_swap_8( dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
#define c89atomic_compare_and_swap_16(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
#define c89atomic_compare_and_swap_32(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
#define c89atomic_compare_and_swap_64(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
#else
#if defined(C89ATOMIC_X86)
#define c89atomic_thread_fence(order) __asm__ __volatile__("lock; addl $0, (%%esp)" ::: "memory", "cc")
#elif defined(C89ATOMIC_X64)
#define c89atomic_thread_fence(order) __asm__ __volatile__("lock; addq $0, (%%rsp)" ::: "memory", "cc")
#else
#error Unsupported architecture. Please submit a feature request.
#endif
static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_compare_and_swap_8(volatile c89atomic_uint8* dst, c89atomic_uint8 expected, c89atomic_uint8 desired)
{
volatile c89atomic_uint8 result;
#if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
__asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
#else
#error Unsupported architecture. Please submit a feature request.
#endif
return result;
}
static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_compare_and_swap_16(volatile c89atomic_uint16* dst, c89atomic_uint16 expected, c89atomic_uint16 desired)
{
volatile c89atomic_uint16 result;
#if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
__asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
#else
#error Unsupported architecture. Please submit a feature request.
#endif
return result;
}
static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_compare_and_swap_32(volatile c89atomic_uint32* dst, c89atomic_uint32 expected, c89atomic_uint32 desired)
{
volatile c89atomic_uint32 result;
#if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
__asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
#else
#error Unsupported architecture. Please submit a feature request.
#endif
return result;
}
static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_compare_and_swap_64(volatile c89atomic_uint64* dst, c89atomic_uint64 expected, c89atomic_uint64 desired)
{
volatile c89atomic_uint64 result;
#if defined(C89ATOMIC_X86)
volatile c89atomic_uint32 resultEAX;
volatile c89atomic_uint32 resultEDX;
__asm__ __volatile__("push %%ebx; xchg %5, %%ebx; lock; cmpxchg8b %0; pop %%ebx" : "+m"(*dst), "=a"(resultEAX), "=d"(resultEDX) : "a"(expected & 0xFFFFFFFF), "d"(expected >> 32), "r"(desired & 0xFFFFFFFF), "c"(desired >> 32) : "cc");
result = ((c89atomic_uint64)resultEDX << 32) | resultEAX;
#elif defined(C89ATOMIC_X64)
__asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
#else
#error Unsupported architecture. Please submit a feature request.
#endif
return result;
}
static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
volatile c89atomic_uint8 result = 0;
(void)order;
#if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
__asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
#else
#error Unsupported architecture. Please submit a feature request.
#endif
return result;
}
static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
volatile c89atomic_uint16 result = 0;
(void)order;
#if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
__asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
#else
#error Unsupported architecture. Please submit a feature request.
#endif
return result;
}
static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
volatile c89atomic_uint32 result;
(void)order;
#if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
__asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
#else
#error Unsupported architecture. Please submit a feature request.
#endif
return result;
}
static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
volatile c89atomic_uint64 result;
(void)order;
#if defined(C89ATOMIC_X86)
do {
result = *dst;
} while (c89atomic_compare_and_swap_64(dst, result, src) != result);
#elif defined(C89ATOMIC_X64)
__asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
#else
#error Unsupported architecture. Please submit a feature request.
#endif
return result;
}
static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
c89atomic_uint8 result;
(void)order;
#if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
__asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
#else
#error Unsupported architecture. Please submit a feature request.
#endif
return result;
}
static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
c89atomic_uint16 result;
(void)order;
#if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
__asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
#else
#error Unsupported architecture. Please submit a feature request.
#endif
return result;
}
static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
c89atomic_uint32 result;
(void)order;
#if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
__asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
#else
#error Unsupported architecture. Please submit a feature request.
#endif
return result;
}
static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
#if defined(C89ATOMIC_X86)
volatile c89atomic_uint64 oldValue;
volatile c89atomic_uint64 newValue;
(void)order;
do {
oldValue = *dst;
newValue = oldValue + src;
} while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
return oldValue;
#elif defined(C89ATOMIC_X64)
volatile c89atomic_uint64 result;
(void)order;
__asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
return result;
#endif
}
static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_sub_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
volatile c89atomic_uint8 oldValue;
volatile c89atomic_uint8 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint8)(oldValue - src);
} while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_sub_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
volatile c89atomic_uint16 oldValue;
volatile c89atomic_uint16 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint16)(oldValue - src);
} while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_sub_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
volatile c89atomic_uint32 oldValue;
volatile c89atomic_uint32 newValue;
do {
oldValue = *dst;
newValue = oldValue - src;
} while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_sub_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
volatile c89atomic_uint64 oldValue;
volatile c89atomic_uint64 newValue;
do {
oldValue = *dst;
newValue = oldValue - src;
} while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_and_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
volatile c89atomic_uint8 oldValue;
volatile c89atomic_uint8 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint8)(oldValue & src);
} while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_and_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
volatile c89atomic_uint16 oldValue;
volatile c89atomic_uint16 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint16)(oldValue & src);
} while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_and_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
volatile c89atomic_uint32 oldValue;
volatile c89atomic_uint32 newValue;
do {
oldValue = *dst;
newValue = oldValue & src;
} while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_and_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
volatile c89atomic_uint64 oldValue;
volatile c89atomic_uint64 newValue;
do {
oldValue = *dst;
newValue = oldValue & src;
} while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_xor_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
volatile c89atomic_uint8 oldValue;
volatile c89atomic_uint8 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint8)(oldValue ^ src);
} while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_xor_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
volatile c89atomic_uint16 oldValue;
volatile c89atomic_uint16 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint16)(oldValue ^ src);
} while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_xor_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
volatile c89atomic_uint32 oldValue;
volatile c89atomic_uint32 newValue;
do {
oldValue = *dst;
newValue = oldValue ^ src;
} while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_xor_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
volatile c89atomic_uint64 oldValue;
volatile c89atomic_uint64 newValue;
do {
oldValue = *dst;
newValue = oldValue ^ src;
} while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_or_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
{
volatile c89atomic_uint8 oldValue;
volatile c89atomic_uint8 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint8)(oldValue | src);
} while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_or_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
{
volatile c89atomic_uint16 oldValue;
volatile c89atomic_uint16 newValue;
do {
oldValue = *dst;
newValue = (c89atomic_uint16)(oldValue | src);
} while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_or_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
{
volatile c89atomic_uint32 oldValue;
volatile c89atomic_uint32 newValue;
do {
oldValue = *dst;
newValue = oldValue | src;
} while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_or_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
{
volatile c89atomic_uint64 oldValue;
volatile c89atomic_uint64 newValue;
do {
oldValue = *dst;
newValue = oldValue | src;
} while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
(void)order;
return oldValue;
}
#endif
#define c89atomic_signal_fence(order) c89atomic_thread_fence(order)
static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_load_explicit_8(volatile c89atomic_uint8* ptr, c89atomic_memory_order order)
{
(void)order;
return c89atomic_compare_and_swap_8(ptr, 0, 0);
}
static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_load_explicit_16(volatile c89atomic_uint16* ptr, c89atomic_memory_order order)
{
(void)order;
return c89atomic_compare_and_swap_16(ptr, 0, 0);
}
static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_load_explicit_32(volatile c89atomic_uint32* ptr, c89atomic_memory_order order)
{
(void)order;
return c89atomic_compare_and_swap_32(ptr, 0, 0);
}
static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_load_explicit_64(volatile c89atomic_uint64* ptr, c89atomic_memory_order order)
{
(void)order;
return c89atomic_compare_and_swap_64(ptr, 0, 0);
}
#define c89atomic_store_explicit_8( dst, src, order) (void)c89atomic_exchange_explicit_8 (dst, src, order)
#define c89atomic_store_explicit_16(dst, src, order) (void)c89atomic_exchange_explicit_16(dst, src, order)
#define c89atomic_store_explicit_32(dst, src, order) (void)c89atomic_exchange_explicit_32(dst, src, order)
#define c89atomic_store_explicit_64(dst, src, order) (void)c89atomic_exchange_explicit_64(dst, src, order)
#define c89atomic_test_and_set_explicit_8( dst, order) c89atomic_exchange_explicit_8 (dst, 1, order)
#define c89atomic_test_and_set_explicit_16(dst, order) c89atomic_exchange_explicit_16(dst, 1, order)
#define c89atomic_test_and_set_explicit_32(dst, order) c89atomic_exchange_explicit_32(dst, 1, order)
#define c89atomic_test_and_set_explicit_64(dst, order) c89atomic_exchange_explicit_64(dst, 1, order)
#define c89atomic_clear_explicit_8( dst, order) c89atomic_store_explicit_8 (dst, 0, order)
#define c89atomic_clear_explicit_16(dst, order) c89atomic_store_explicit_16(dst, 0, order)
#define c89atomic_clear_explicit_32(dst, order) c89atomic_store_explicit_32(dst, 0, order)
#define c89atomic_clear_explicit_64(dst, order) c89atomic_store_explicit_64(dst, 0, order)
#define c89atomic_flag_test_and_set_explicit(ptr, order) (c89atomic_flag)c89atomic_test_and_set_explicit_8(ptr, order)
#define c89atomic_flag_clear_explicit(ptr, order) c89atomic_clear_explicit_8(ptr, order)
#endif
#if !defined(C89ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE)
c89atomic_bool c89atomic_compare_exchange_strong_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8* expected, c89atomic_uint8 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
{
c89atomic_uint8 expectedValue;
c89atomic_uint8 result;
(void)successOrder;
(void)failureOrder;
expectedValue = c89atomic_load_explicit_8(expected, c89atomic_memory_order_seq_cst);
result = c89atomic_compare_and_swap_8(dst, expectedValue, desired);
if (result == expectedValue) {
return 1;
} else {
c89atomic_store_explicit_8(expected, result, failureOrder);
return 0;
}
}
c89atomic_bool c89atomic_compare_exchange_strong_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16* expected, c89atomic_uint16 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
{
c89atomic_uint16 expectedValue;
c89atomic_uint16 result;
(void)successOrder;
(void)failureOrder;
expectedValue = c89atomic_load_explicit_16(expected, c89atomic_memory_order_seq_cst);
result = c89atomic_compare_and_swap_16(dst, expectedValue, desired);
if (result == expectedValue) {
return 1;
} else {
c89atomic_store_explicit_16(expected, result, failureOrder);
return 0;
}
}
c89atomic_bool c89atomic_compare_exchange_strong_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32* expected, c89atomic_uint32 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
{
c89atomic_uint32 expectedValue;
c89atomic_uint32 result;
(void)successOrder;
(void)failureOrder;
expectedValue = c89atomic_load_explicit_32(expected, c89atomic_memory_order_seq_cst);
result = c89atomic_compare_and_swap_32(dst, expectedValue, desired);
if (result == expectedValue) {
return 1;
} else {
c89atomic_store_explicit_32(expected, result, failureOrder);
return 0;
}
}
c89atomic_bool c89atomic_compare_exchange_strong_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64* expected, c89atomic_uint64 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
{
c89atomic_uint64 expectedValue;
c89atomic_uint64 result;
(void)successOrder;
(void)failureOrder;
expectedValue = c89atomic_load_explicit_64(expected, c89atomic_memory_order_seq_cst);
result = c89atomic_compare_and_swap_64(dst, expectedValue, desired);
if (result == expectedValue) {
return 1;
} else {
c89atomic_store_explicit_64(expected, result, failureOrder);
return 0;
}
}
#define c89atomic_compare_exchange_weak_explicit_8( dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_8 (dst, expected, desired, successOrder, failureOrder)
#define c89atomic_compare_exchange_weak_explicit_16(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_16(dst, expected, desired, successOrder, failureOrder)
#define c89atomic_compare_exchange_weak_explicit_32(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_32(dst, expected, desired, successOrder, failureOrder)
#define c89atomic_compare_exchange_weak_explicit_64(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_64(dst, expected, desired, successOrder, failureOrder)
#endif
#if !defined(C89ATOMIC_HAS_NATIVE_IS_LOCK_FREE)
static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_8(volatile void* ptr)
{
(void)ptr;
return 1;
}
static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_16(volatile void* ptr)
{
(void)ptr;
return 1;
}
static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_32(volatile void* ptr)
{
(void)ptr;
return 1;
}
static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_64(volatile void* ptr)
{
(void)ptr;
#if defined(C89ATOMIC_64BIT)
return 1;
#else
#if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
return 1;
#else
return 0;
#endif
#endif
}
#endif
#if defined(C89ATOMIC_64BIT)
static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_ptr(volatile void** ptr)
{
return c89atomic_is_lock_free_64((volatile c89atomic_uint64*)ptr);
}
static C89ATOMIC_INLINE void* c89atomic_load_explicit_ptr(volatile void** ptr, c89atomic_memory_order order)
{
return (void*)c89atomic_load_explicit_64((volatile c89atomic_uint64*)ptr, order);
}
static C89ATOMIC_INLINE void c89atomic_store_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order)
{
c89atomic_store_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64)src, order);
}
static C89ATOMIC_INLINE void* c89atomic_exchange_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order)
{
return (void*)c89atomic_exchange_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64)src, order);
}
static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_ptr(volatile void** dst, void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
{
return c89atomic_compare_exchange_strong_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder);
}
static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_weak_explicit_ptr(volatile void** dst, volatile void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
{
return c89atomic_compare_exchange_weak_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder);
}
static C89ATOMIC_INLINE void* c89atomic_compare_and_swap_ptr(volatile void** dst, void* expected, void* desired)
{
return (void*)c89atomic_compare_and_swap_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64)expected, (c89atomic_uint64)desired);
}
#elif defined(C89ATOMIC_32BIT)
static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_ptr(volatile void** ptr)
{
return c89atomic_is_lock_free_32((volatile c89atomic_uint32*)ptr);
}
static C89ATOMIC_INLINE void* c89atomic_load_explicit_ptr(volatile void** ptr, c89atomic_memory_order order)
{
return (void*)c89atomic_load_explicit_32((volatile c89atomic_uint32*)ptr, order);
}
static C89ATOMIC_INLINE void c89atomic_store_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order)
{
c89atomic_store_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32)src, order);
}
static C89ATOMIC_INLINE void* c89atomic_exchange_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order)
{
return (void*)c89atomic_exchange_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32)src, order);
}
static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_ptr(volatile void** dst, void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
{
return c89atomic_compare_exchange_strong_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder);
}
static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_weak_explicit_ptr(volatile void** dst, volatile void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
{
return c89atomic_compare_exchange_weak_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder);
}
static C89ATOMIC_INLINE void* c89atomic_compare_and_swap_ptr(volatile void** dst, void* expected, void* desired)
{
return (void*)c89atomic_compare_and_swap_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32)expected, (c89atomic_uint32)desired);
}
#else
#error Unsupported architecture.
#endif
#define c89atomic_flag_test_and_set(ptr) c89atomic_flag_test_and_set_explicit(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_flag_clear(ptr) c89atomic_flag_clear_explicit(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_store_ptr(dst, src) c89atomic_store_explicit_ptr((volatile void**)dst, (void*)src, c89atomic_memory_order_seq_cst)
#define c89atomic_load_ptr(ptr) c89atomic_load_explicit_ptr((volatile void**)ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_exchange_ptr(dst, src) c89atomic_exchange_explicit_ptr((volatile void**)dst, (void*)src, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_strong_ptr(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_ptr((volatile void**)dst, (void*)expected, (void*)desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_weak_ptr(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_ptr((volatile void**)dst, (void*)expected, (void*)desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_test_and_set_8( ptr) c89atomic_test_and_set_explicit_8( ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_test_and_set_16(ptr) c89atomic_test_and_set_explicit_16(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_test_and_set_32(ptr) c89atomic_test_and_set_explicit_32(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_test_and_set_64(ptr) c89atomic_test_and_set_explicit_64(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_clear_8( ptr) c89atomic_clear_explicit_8( ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_clear_16(ptr) c89atomic_clear_explicit_16(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_clear_32(ptr) c89atomic_clear_explicit_32(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_clear_64(ptr) c89atomic_clear_explicit_64(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_store_8( dst, src) c89atomic_store_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_store_16(dst, src) c89atomic_store_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_store_32(dst, src) c89atomic_store_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_store_64(dst, src) c89atomic_store_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_load_8( ptr) c89atomic_load_explicit_8( ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_load_16(ptr) c89atomic_load_explicit_16(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_load_32(ptr) c89atomic_load_explicit_32(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_load_64(ptr) c89atomic_load_explicit_64(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_exchange_8( dst, src) c89atomic_exchange_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_exchange_16(dst, src) c89atomic_exchange_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_exchange_32(dst, src) c89atomic_exchange_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_exchange_64(dst, src) c89atomic_exchange_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_strong_8( dst, expected, desired) c89atomic_compare_exchange_strong_explicit_8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_strong_16(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_strong_32(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_strong_64(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_weak_8( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_weak_16( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_weak_32( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_weak_64( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_add_8( dst, src) c89atomic_fetch_add_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_add_16(dst, src) c89atomic_fetch_add_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_add_32(dst, src) c89atomic_fetch_add_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_add_64(dst, src) c89atomic_fetch_add_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_sub_8( dst, src) c89atomic_fetch_sub_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_sub_16(dst, src) c89atomic_fetch_sub_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_sub_32(dst, src) c89atomic_fetch_sub_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_sub_64(dst, src) c89atomic_fetch_sub_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_or_8( dst, src) c89atomic_fetch_or_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_or_16(dst, src) c89atomic_fetch_or_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_or_32(dst, src) c89atomic_fetch_or_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_or_64(dst, src) c89atomic_fetch_or_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_xor_8( dst, src) c89atomic_fetch_xor_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_xor_16(dst, src) c89atomic_fetch_xor_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_xor_32(dst, src) c89atomic_fetch_xor_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_xor_64(dst, src) c89atomic_fetch_xor_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_and_8( dst, src) c89atomic_fetch_and_explicit_8 (dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_and_16(dst, src) c89atomic_fetch_and_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_and_32(dst, src) c89atomic_fetch_and_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_and_64(dst, src) c89atomic_fetch_and_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_test_and_set_explicit_i8( ptr, order) c89atomic_test_and_set_explicit_8( (c89atomic_uint8* )ptr, order)
#define c89atomic_test_and_set_explicit_i16(ptr, order) c89atomic_test_and_set_explicit_16((c89atomic_uint16*)ptr, order)
#define c89atomic_test_and_set_explicit_i32(ptr, order) c89atomic_test_and_set_explicit_32((c89atomic_uint32*)ptr, order)
#define c89atomic_test_and_set_explicit_i64(ptr, order) c89atomic_test_and_set_explicit_64((c89atomic_uint64*)ptr, order)
#define c89atomic_clear_explicit_i8( ptr, order) c89atomic_clear_explicit_8( (c89atomic_uint8* )ptr, order)
#define c89atomic_clear_explicit_i16(ptr, order) c89atomic_clear_explicit_16((c89atomic_uint16*)ptr, order)
#define c89atomic_clear_explicit_i32(ptr, order) c89atomic_clear_explicit_32((c89atomic_uint32*)ptr, order)
#define c89atomic_clear_explicit_i64(ptr, order) c89atomic_clear_explicit_64((c89atomic_uint64*)ptr, order)
#define c89atomic_store_explicit_i8( dst, src, order) c89atomic_store_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
#define c89atomic_store_explicit_i16(dst, src, order) c89atomic_store_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
#define c89atomic_store_explicit_i32(dst, src, order) c89atomic_store_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
#define c89atomic_store_explicit_i64(dst, src, order) c89atomic_store_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
#define c89atomic_load_explicit_i8( ptr, order) c89atomic_load_explicit_8( (c89atomic_uint8* )ptr, order)
#define c89atomic_load_explicit_i16(ptr, order) c89atomic_load_explicit_16((c89atomic_uint16*)ptr, order)
#define c89atomic_load_explicit_i32(ptr, order) c89atomic_load_explicit_32((c89atomic_uint32*)ptr, order)
#define c89atomic_load_explicit_i64(ptr, order) c89atomic_load_explicit_64((c89atomic_uint64*)ptr, order)
#define c89atomic_exchange_explicit_i8( dst, src, order) c89atomic_exchange_explicit_8 ((c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
#define c89atomic_exchange_explicit_i16(dst, src, order) c89atomic_exchange_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
#define c89atomic_exchange_explicit_i32(dst, src, order) c89atomic_exchange_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
#define c89atomic_exchange_explicit_i64(dst, src, order) c89atomic_exchange_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
#define c89atomic_compare_exchange_strong_explicit_i8( dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8* )expected, (c89atomic_uint8 )desired, successOrder, failureOrder)
#define c89atomic_compare_exchange_strong_explicit_i16(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16*)expected, (c89atomic_uint16)desired, successOrder, failureOrder)
#define c89atomic_compare_exchange_strong_explicit_i32(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder)
#define c89atomic_compare_exchange_strong_explicit_i64(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder)
#define c89atomic_compare_exchange_weak_explicit_i8( dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8* )expected, (c89atomic_uint8 )desired, successOrder, failureOrder)
#define c89atomic_compare_exchange_weak_explicit_i16(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16*)expected, (c89atomic_uint16)desired, successOrder, failureOrder)
#define c89atomic_compare_exchange_weak_explicit_i32(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder)
#define c89atomic_compare_exchange_weak_explicit_i64(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder)
#define c89atomic_fetch_add_explicit_i8( dst, src, order) c89atomic_fetch_add_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
#define c89atomic_fetch_add_explicit_i16(dst, src, order) c89atomic_fetch_add_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
#define c89atomic_fetch_add_explicit_i32(dst, src, order) c89atomic_fetch_add_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
#define c89atomic_fetch_add_explicit_i64(dst, src, order) c89atomic_fetch_add_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
#define c89atomic_fetch_sub_explicit_i8( dst, src, order) c89atomic_fetch_sub_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
#define c89atomic_fetch_sub_explicit_i16(dst, src, order) c89atomic_fetch_sub_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
#define c89atomic_fetch_sub_explicit_i32(dst, src, order) c89atomic_fetch_sub_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
#define c89atomic_fetch_sub_explicit_i64(dst, src, order) c89atomic_fetch_sub_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
#define c89atomic_fetch_or_explicit_i8( dst, src, order) c89atomic_fetch_or_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
#define c89atomic_fetch_or_explicit_i16(dst, src, order) c89atomic_fetch_or_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
#define c89atomic_fetch_or_explicit_i32(dst, src, order) c89atomic_fetch_or_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
#define c89atomic_fetch_or_explicit_i64(dst, src, order) c89atomic_fetch_or_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
#define c89atomic_fetch_xor_explicit_i8( dst, src, order) c89atomic_fetch_xor_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
#define c89atomic_fetch_xor_explicit_i16(dst, src, order) c89atomic_fetch_xor_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
#define c89atomic_fetch_xor_explicit_i32(dst, src, order) c89atomic_fetch_xor_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
#define c89atomic_fetch_xor_explicit_i64(dst, src, order) c89atomic_fetch_xor_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
#define c89atomic_fetch_and_explicit_i8( dst, src, order) c89atomic_fetch_and_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
#define c89atomic_fetch_and_explicit_i16(dst, src, order) c89atomic_fetch_and_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
#define c89atomic_fetch_and_explicit_i32(dst, src, order) c89atomic_fetch_and_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
#define c89atomic_fetch_and_explicit_i64(dst, src, order) c89atomic_fetch_and_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
#define c89atomic_test_and_set_i8( ptr) c89atomic_test_and_set_explicit_i8( ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_test_and_set_i16(ptr) c89atomic_test_and_set_explicit_i16(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_test_and_set_i32(ptr) c89atomic_test_and_set_explicit_i32(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_test_and_set_i64(ptr) c89atomic_test_and_set_explicit_i64(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_clear_i8( ptr) c89atomic_clear_explicit_i8( ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_clear_i16(ptr) c89atomic_clear_explicit_i16(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_clear_i32(ptr) c89atomic_clear_explicit_i32(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_clear_i64(ptr) c89atomic_clear_explicit_i64(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_store_i8( dst, src) c89atomic_store_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_store_i16(dst, src) c89atomic_store_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_store_i32(dst, src) c89atomic_store_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_store_i64(dst, src) c89atomic_store_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_load_i8( ptr) c89atomic_load_explicit_i8( ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_load_i16(ptr) c89atomic_load_explicit_i16(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_load_i32(ptr) c89atomic_load_explicit_i32(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_load_i64(ptr) c89atomic_load_explicit_i64(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_exchange_i8( dst, src) c89atomic_exchange_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_exchange_i16(dst, src) c89atomic_exchange_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_exchange_i32(dst, src) c89atomic_exchange_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_exchange_i64(dst, src) c89atomic_exchange_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_strong_i8( dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_strong_i16(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_strong_i32(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_strong_i64(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_weak_i8( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_weak_i16(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_weak_i32(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_compare_exchange_weak_i64(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_add_i8( dst, src) c89atomic_fetch_add_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_add_i16(dst, src) c89atomic_fetch_add_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_add_i32(dst, src) c89atomic_fetch_add_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_add_i64(dst, src) c89atomic_fetch_add_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_sub_i8( dst, src) c89atomic_fetch_sub_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_sub_i16(dst, src) c89atomic_fetch_sub_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_sub_i32(dst, src) c89atomic_fetch_sub_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_sub_i64(dst, src) c89atomic_fetch_sub_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_or_i8( dst, src) c89atomic_fetch_or_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_or_i16(dst, src) c89atomic_fetch_or_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_or_i32(dst, src) c89atomic_fetch_or_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_or_i64(dst, src) c89atomic_fetch_or_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_xor_i8( dst, src) c89atomic_fetch_xor_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_xor_i16(dst, src) c89atomic_fetch_xor_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_xor_i32(dst, src) c89atomic_fetch_xor_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_xor_i64(dst, src) c89atomic_fetch_xor_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_and_i8( dst, src) c89atomic_fetch_and_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_and_i16(dst, src) c89atomic_fetch_and_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_and_i32(dst, src) c89atomic_fetch_and_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_fetch_and_i64(dst, src) c89atomic_fetch_and_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
typedef union
{
c89atomic_uint32 i;
float f;
} c89atomic_if32;
typedef union
{
c89atomic_uint64 i;
double f;
} c89atomic_if64;
#define c89atomic_clear_explicit_f32(ptr, order) c89atomic_clear_explicit_32((c89atomic_uint32*)ptr, order)
#define c89atomic_clear_explicit_f64(ptr, order) c89atomic_clear_explicit_64((c89atomic_uint64*)ptr, order)
static C89ATOMIC_INLINE void c89atomic_store_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order)
{
c89atomic_if32 x;
x.f = src;
c89atomic_store_explicit_32((volatile c89atomic_uint32*)dst, x.i, order);
}
static C89ATOMIC_INLINE void c89atomic_store_explicit_f64(volatile float* dst, float src, c89atomic_memory_order order)
{
c89atomic_if64 x;
x.f = src;
c89atomic_store_explicit_64((volatile c89atomic_uint64*)dst, x.i, order);
}
static C89ATOMIC_INLINE float c89atomic_load_explicit_f32(volatile float* ptr, c89atomic_memory_order order)
{
c89atomic_if32 r;
r.i = c89atomic_load_explicit_32((volatile c89atomic_uint32*)ptr, order);
return r.f;
}
static C89ATOMIC_INLINE double c89atomic_load_explicit_f64(volatile double* ptr, c89atomic_memory_order order)
{
c89atomic_if64 r;
r.i = c89atomic_load_explicit_64((volatile c89atomic_uint64*)ptr, order);
return r.f;
}
static C89ATOMIC_INLINE float c89atomic_exchange_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order)
{
c89atomic_if32 r;
c89atomic_if32 x;
x.f = src;
r.i = c89atomic_exchange_explicit_32((volatile c89atomic_uint32*)dst, x.i, order);
return r.f;
}
static C89ATOMIC_INLINE double c89atomic_exchange_explicit_f64(volatile double* dst, double src, c89atomic_memory_order order)
{
c89atomic_if64 r;
c89atomic_if64 x;
x.f = src;
r.i = c89atomic_exchange_explicit_64((volatile c89atomic_uint64*)dst, x.i, order);
return r.f;
}
#define c89atomic_clear_f32(ptr) c89atomic_clear_explicit_f32(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_clear_f64(ptr) c89atomic_clear_explicit_f64(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_store_f32(dst, src) c89atomic_store_explicit_f32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_store_f64(dst, src) c89atomic_store_explicit_f64(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_load_f32(ptr) c89atomic_load_explicit_f32(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_load_f64(ptr) c89atomic_load_explicit_f64(ptr, c89atomic_memory_order_seq_cst)
#define c89atomic_exchange_f32(dst, src) c89atomic_exchange_explicit_f32(dst, src, c89atomic_memory_order_seq_cst)
#define c89atomic_exchange_f64(dst, src) c89atomic_exchange_explicit_f64(dst, src, c89atomic_memory_order_seq_cst)
typedef c89atomic_flag c89atomic_spinlock;
static C89ATOMIC_INLINE void c89atomic_spinlock_lock(volatile c89atomic_spinlock* pSpinlock)
{
for (;;) {
if (c89atomic_flag_test_and_set_explicit(pSpinlock, c89atomic_memory_order_acquire) == 0) {
break;
}
while (c89atomic_load_explicit_8(pSpinlock, c89atomic_memory_order_relaxed) == 1) {
}
}
}
static C89ATOMIC_INLINE void c89atomic_spinlock_unlock(volatile c89atomic_spinlock* pSpinlock)
{
c89atomic_flag_clear_explicit(pSpinlock, c89atomic_memory_order_release);
}
#if defined(__cplusplus)
}
#endif
#endif
/* c89atomic.h end */
static void* ma__malloc_default(size_t sz, void* pUserData)
{
(void)pUserData;
return MA_MALLOC(sz);
}
static void* ma__realloc_default(void* p, size_t sz, void* pUserData)
{
(void)pUserData;
return MA_REALLOC(p, sz);
}
static void ma__free_default(void* p, void* pUserData)
{
(void)pUserData;
MA_FREE(p);
}
static void* ma__malloc_from_callbacks(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
{
if (pAllocationCallbacks == NULL) {
return NULL;
}
if (pAllocationCallbacks->onMalloc != NULL) {
return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
}
/* Try using realloc(). */
if (pAllocationCallbacks->onRealloc != NULL) {
return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
}
return NULL;
}
static void* ma__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const ma_allocation_callbacks* pAllocationCallbacks)
{
if (pAllocationCallbacks == NULL) {
return NULL;
}
if (pAllocationCallbacks->onRealloc != NULL) {
return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
}
/* Try emulating realloc() in terms of malloc()/free(). */
if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
void* p2;
p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
if (p2 == NULL) {
return NULL;
}
if (p != NULL) {
MA_COPY_MEMORY(p2, p, szOld);
pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
}
return p2;
}
return NULL;
}
static MA_INLINE void* ma__calloc_from_callbacks(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
{
void* p = ma__malloc_from_callbacks(sz, pAllocationCallbacks);
if (p != NULL) {
MA_ZERO_MEMORY(p, sz);
}
return p;
}
static void ma__free_from_callbacks(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
{
if (p == NULL || pAllocationCallbacks == NULL) {
return;
}
if (pAllocationCallbacks->onFree != NULL) {
pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
}
}
static ma_allocation_callbacks ma_allocation_callbacks_init_default(void)
{
ma_allocation_callbacks callbacks;
callbacks.pUserData = NULL;
callbacks.onMalloc = ma__malloc_default;
callbacks.onRealloc = ma__realloc_default;
callbacks.onFree = ma__free_default;
return callbacks;
}
static ma_result ma_allocation_callbacks_init_copy(ma_allocation_callbacks* pDst, const ma_allocation_callbacks* pSrc)
{
if (pDst == NULL) {
return MA_INVALID_ARGS;
}
if (pSrc == NULL) {
*pDst = ma_allocation_callbacks_init_default();
} else {
if (pSrc->pUserData == NULL && pSrc->onFree == NULL && pSrc->onMalloc == NULL && pSrc->onRealloc == NULL) {
*pDst = ma_allocation_callbacks_init_default();
} else {
if (pSrc->onFree == NULL || (pSrc->onMalloc == NULL && pSrc->onRealloc == NULL)) {
return MA_INVALID_ARGS; /* Invalid allocation callbacks. */
} else {
*pDst = *pSrc;
}
}
}
return MA_SUCCESS;
}
MA_API ma_uint64 ma_calculate_frame_count_after_resampling(ma_uint32 sampleRateOut, ma_uint32 sampleRateIn, ma_uint64 frameCountIn)
{
/* For robustness we're going to use a resampler object to calculate this since that already has a way of calculating this. */
ma_result result;
ma_uint64 frameCountOut;
ma_resampler_config config;
ma_resampler resampler;
if (sampleRateOut == sampleRateIn) {
return frameCountIn;
}
config = ma_resampler_config_init(ma_format_s16, 1, sampleRateIn, sampleRateOut, ma_resample_algorithm_linear);
result = ma_resampler_init(&config, &resampler);
if (result != MA_SUCCESS) {
return 0;
}
frameCountOut = ma_resampler_get_expected_output_frame_count(&resampler, frameCountIn);
ma_resampler_uninit(&resampler);
return frameCountOut;
}
#ifndef MA_DATA_CONVERTER_STACK_BUFFER_SIZE
#define MA_DATA_CONVERTER_STACK_BUFFER_SIZE 4096
#endif
#if defined(MA_WIN32)
static ma_result ma_result_from_GetLastError(DWORD error)
{
switch (error)
{
case ERROR_SUCCESS: return MA_SUCCESS;
case ERROR_PATH_NOT_FOUND: return MA_DOES_NOT_EXIST;
case ERROR_TOO_MANY_OPEN_FILES: return MA_TOO_MANY_OPEN_FILES;
case ERROR_NOT_ENOUGH_MEMORY: return MA_OUT_OF_MEMORY;
case ERROR_DISK_FULL: return MA_NO_SPACE;
case ERROR_HANDLE_EOF: return MA_END_OF_FILE;
case ERROR_NEGATIVE_SEEK: return MA_BAD_SEEK;
case ERROR_INVALID_PARAMETER: return MA_INVALID_ARGS;
case ERROR_ACCESS_DENIED: return MA_ACCESS_DENIED;
case ERROR_SEM_TIMEOUT: return MA_TIMEOUT;
case ERROR_FILE_NOT_FOUND: return MA_DOES_NOT_EXIST;
default: break;
}
return MA_ERROR;
}
#endif /* MA_WIN32 */
/*******************************************************************************
Threading
*******************************************************************************/
#ifndef MA_NO_THREADING
#ifdef MA_WIN32
#define MA_THREADCALL WINAPI
typedef unsigned long ma_thread_result;
#else
#define MA_THREADCALL
typedef void* ma_thread_result;
#endif
typedef ma_thread_result (MA_THREADCALL * ma_thread_entry_proc)(void* pData);
static MA_INLINE ma_result ma_spinlock_lock_ex(volatile ma_spinlock* pSpinlock, ma_bool32 yield)
{
if (pSpinlock == NULL) {
return MA_INVALID_ARGS;
}
for (;;) {
if (c89atomic_flag_test_and_set_explicit(pSpinlock, c89atomic_memory_order_acquire) == 0) {
break;
}
while (c89atomic_load_explicit_8(pSpinlock, c89atomic_memory_order_relaxed) == 1) {
if (yield) {
ma_yield();
}
}
}
return MA_SUCCESS;
}
MA_API ma_result ma_spinlock_lock(volatile ma_spinlock* pSpinlock)
{
return ma_spinlock_lock_ex(pSpinlock, MA_TRUE);
}
MA_API ma_result ma_spinlock_lock_noyield(volatile ma_spinlock* pSpinlock)
{
return ma_spinlock_lock_ex(pSpinlock, MA_FALSE);
}
MA_API ma_result ma_spinlock_unlock(volatile ma_spinlock* pSpinlock)
{
if (pSpinlock == NULL) {
return MA_INVALID_ARGS;
}
c89atomic_flag_clear_explicit(pSpinlock, c89atomic_memory_order_release);
return MA_SUCCESS;
}
#ifdef MA_WIN32
static int ma_thread_priority_to_win32(ma_thread_priority priority)
{
switch (priority) {
case ma_thread_priority_idle: return THREAD_PRIORITY_IDLE;
case ma_thread_priority_lowest: return THREAD_PRIORITY_LOWEST;
case ma_thread_priority_low: return THREAD_PRIORITY_BELOW_NORMAL;
case ma_thread_priority_normal: return THREAD_PRIORITY_NORMAL;
case ma_thread_priority_high: return THREAD_PRIORITY_ABOVE_NORMAL;
case ma_thread_priority_highest: return THREAD_PRIORITY_HIGHEST;
case ma_thread_priority_realtime: return THREAD_PRIORITY_TIME_CRITICAL;
default: return THREAD_PRIORITY_NORMAL;
}
}
static ma_result ma_thread_create__win32(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, ma_thread_entry_proc entryProc, void* pData)
{
*pThread = CreateThread(NULL, stackSize, entryProc, pData, 0, NULL);
if (*pThread == NULL) {
return ma_result_from_GetLastError(GetLastError());
}
SetThreadPriority((HANDLE)*pThread, ma_thread_priority_to_win32(priority));
return MA_SUCCESS;
}
static void ma_thread_wait__win32(ma_thread* pThread)
{
WaitForSingleObject((HANDLE)*pThread, INFINITE);
}
static ma_result ma_mutex_init__win32(ma_mutex* pMutex)
{
*pMutex = CreateEventW(NULL, FALSE, TRUE, NULL);
if (*pMutex == NULL) {
return ma_result_from_GetLastError(GetLastError());
}
return MA_SUCCESS;
}
static void ma_mutex_uninit__win32(ma_mutex* pMutex)
{
CloseHandle((HANDLE)*pMutex);
}
static void ma_mutex_lock__win32(ma_mutex* pMutex)
{
WaitForSingleObject((HANDLE)*pMutex, INFINITE);
}
static void ma_mutex_unlock__win32(ma_mutex* pMutex)
{
SetEvent((HANDLE)*pMutex);
}
static ma_result ma_event_init__win32(ma_event* pEvent)
{
*pEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
if (*pEvent == NULL) {
return ma_result_from_GetLastError(GetLastError());
}
return MA_SUCCESS;
}
static void ma_event_uninit__win32(ma_event* pEvent)
{
CloseHandle((HANDLE)*pEvent);
}
static ma_result ma_event_wait__win32(ma_event* pEvent)
{
DWORD result = WaitForSingleObject((HANDLE)*pEvent, INFINITE);
if (result == WAIT_OBJECT_0) {
return MA_SUCCESS;
}
if (result == WAIT_TIMEOUT) {
return MA_TIMEOUT;
}
return ma_result_from_GetLastError(GetLastError());
}
static ma_result ma_event_signal__win32(ma_event* pEvent)
{
BOOL result = SetEvent((HANDLE)*pEvent);
if (result == 0) {
return ma_result_from_GetLastError(GetLastError());
}
return MA_SUCCESS;
}
static ma_result ma_semaphore_init__win32(int initialValue, ma_semaphore* pSemaphore)
{
*pSemaphore = CreateSemaphoreW(NULL, (LONG)initialValue, LONG_MAX, NULL);
if (*pSemaphore == NULL) {
return ma_result_from_GetLastError(GetLastError());
}
return MA_SUCCESS;
}
static void ma_semaphore_uninit__win32(ma_semaphore* pSemaphore)
{
CloseHandle((HANDLE)*pSemaphore);
}
static ma_result ma_semaphore_wait__win32(ma_semaphore* pSemaphore)
{
DWORD result = WaitForSingleObject((HANDLE)*pSemaphore, INFINITE);
if (result == WAIT_OBJECT_0) {
return MA_SUCCESS;
}
if (result == WAIT_TIMEOUT) {
return MA_TIMEOUT;
}
return ma_result_from_GetLastError(GetLastError());
}
static ma_result ma_semaphore_release__win32(ma_semaphore* pSemaphore)
{
BOOL result = ReleaseSemaphore((HANDLE)*pSemaphore, 1, NULL);
if (result == 0) {
return ma_result_from_GetLastError(GetLastError());
}
return MA_SUCCESS;
}
#endif
#ifdef MA_POSIX
static ma_result ma_thread_create__posix(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, ma_thread_entry_proc entryProc, void* pData)
{
int result;
pthread_attr_t* pAttr = NULL;
#if !defined(__EMSCRIPTEN__)
/* Try setting the thread priority. It's not critical if anything fails here. */
pthread_attr_t attr;
if (pthread_attr_init(&attr) == 0) {
int scheduler = -1;
if (priority == ma_thread_priority_idle) {
#ifdef SCHED_IDLE
if (pthread_attr_setschedpolicy(&attr, SCHED_IDLE) == 0) {
scheduler = SCHED_IDLE;
}
#endif
} else if (priority == ma_thread_priority_realtime) {
#ifdef SCHED_FIFO
if (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) == 0) {
scheduler = SCHED_FIFO;
}
#endif
#ifdef MA_LINUX
} else {
scheduler = sched_getscheduler(0);
#endif
}
if (stackSize > 0) {
pthread_attr_setstacksize(&attr, stackSize);
}
if (scheduler != -1) {
int priorityMin = sched_get_priority_min(scheduler);
int priorityMax = sched_get_priority_max(scheduler);
int priorityStep = (priorityMax - priorityMin) / 7; /* 7 = number of priorities supported by miniaudio. */
struct sched_param sched;
if (pthread_attr_getschedparam(&attr, &sched) == 0) {
if (priority == ma_thread_priority_idle) {
sched.sched_priority = priorityMin;
} else if (priority == ma_thread_priority_realtime) {
sched.sched_priority = priorityMax;
} else {
sched.sched_priority += ((int)priority + 5) * priorityStep; /* +5 because the lowest priority is -5. */
if (sched.sched_priority < priorityMin) {
sched.sched_priority = priorityMin;
}
if (sched.sched_priority > priorityMax) {
sched.sched_priority = priorityMax;
}
}
if (pthread_attr_setschedparam(&attr, &sched) == 0) {
pAttr = &attr;
}
}
}
}
#else
/* It's the emscripten build. We'll have a few unused parameters. */
(void)priority;
(void)stackSize;
#endif
result = pthread_create(pThread, pAttr, entryProc, pData);
/* The thread attributes object is no longer required. */
if (pAttr != NULL) {
pthread_attr_destroy(pAttr);
}
if (result != 0) {
return ma_result_from_errno(result);
}
return MA_SUCCESS;
}
static void ma_thread_wait__posix(ma_thread* pThread)
{
pthread_join(*pThread, NULL);
}
static ma_result ma_mutex_init__posix(ma_mutex* pMutex)
{
int result = pthread_mutex_init((pthread_mutex_t*)pMutex, NULL);
if (result != 0) {
return ma_result_from_errno(result);
}
return MA_SUCCESS;
}
static void ma_mutex_uninit__posix(ma_mutex* pMutex)
{
pthread_mutex_destroy((pthread_mutex_t*)pMutex);
}
static void ma_mutex_lock__posix(ma_mutex* pMutex)
{
pthread_mutex_lock((pthread_mutex_t*)pMutex);
}
static void ma_mutex_unlock__posix(ma_mutex* pMutex)
{
pthread_mutex_unlock((pthread_mutex_t*)pMutex);
}
static ma_result ma_event_init__posix(ma_event* pEvent)
{
int result;
result = pthread_mutex_init(&pEvent->lock, NULL);
if (result != 0) {
return ma_result_from_errno(result);
}
result = pthread_cond_init(&pEvent->cond, NULL);
if (result != 0) {
pthread_mutex_destroy(&pEvent->lock);
return ma_result_from_errno(result);
}
pEvent->value = 0;
return MA_SUCCESS;
}
static void ma_event_uninit__posix(ma_event* pEvent)
{
pthread_cond_destroy(&pEvent->cond);
pthread_mutex_destroy(&pEvent->lock);
}
static ma_result ma_event_wait__posix(ma_event* pEvent)
{
pthread_mutex_lock(&pEvent->lock);
{
while (pEvent->value == 0) {
pthread_cond_wait(&pEvent->cond, &pEvent->lock);
}
pEvent->value = 0; /* Auto-reset. */
}
pthread_mutex_unlock(&pEvent->lock);
return MA_SUCCESS;
}
static ma_result ma_event_signal__posix(ma_event* pEvent)
{
pthread_mutex_lock(&pEvent->lock);
{
pEvent->value = 1;
pthread_cond_signal(&pEvent->cond);
}
pthread_mutex_unlock(&pEvent->lock);
return MA_SUCCESS;
}
static ma_result ma_semaphore_init__posix(int initialValue, ma_semaphore* pSemaphore)
{
int result;
if (pSemaphore == NULL) {
return MA_INVALID_ARGS;
}
pSemaphore->value = initialValue;
result = pthread_mutex_init(&pSemaphore->lock, NULL);
if (result != 0) {
return ma_result_from_errno(result); /* Failed to create mutex. */
}
result = pthread_cond_init(&pSemaphore->cond, NULL);
if (result != 0) {
pthread_mutex_destroy(&pSemaphore->lock);
return ma_result_from_errno(result); /* Failed to create condition variable. */
}
return MA_SUCCESS;
}
static void ma_semaphore_uninit__posix(ma_semaphore* pSemaphore)
{
if (pSemaphore == NULL) {
return;
}
pthread_cond_destroy(&pSemaphore->cond);
pthread_mutex_destroy(&pSemaphore->lock);
}
static ma_result ma_semaphore_wait__posix(ma_semaphore* pSemaphore)
{
if (pSemaphore == NULL) {
return MA_INVALID_ARGS;
}
pthread_mutex_lock(&pSemaphore->lock);
{
/* We need to wait on a condition variable before escaping. We can't return from this function until the semaphore has been signaled. */
while (pSemaphore->value == 0) {
pthread_cond_wait(&pSemaphore->cond, &pSemaphore->lock);
}
pSemaphore->value -= 1;
}
pthread_mutex_unlock(&pSemaphore->lock);
return MA_SUCCESS;
}
static ma_result ma_semaphore_release__posix(ma_semaphore* pSemaphore)
{
if (pSemaphore == NULL) {
return MA_INVALID_ARGS;
}
pthread_mutex_lock(&pSemaphore->lock);
{
pSemaphore->value += 1;
pthread_cond_signal(&pSemaphore->cond);
}
pthread_mutex_unlock(&pSemaphore->lock);
return MA_SUCCESS;
}
#endif
static ma_result ma_thread_create(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, ma_thread_entry_proc entryProc, void* pData)
{
if (pThread == NULL || entryProc == NULL) {
return MA_FALSE;
}
#ifdef MA_WIN32
return ma_thread_create__win32(pThread, priority, stackSize, entryProc, pData);
#endif
#ifdef MA_POSIX
return ma_thread_create__posix(pThread, priority, stackSize, entryProc, pData);
#endif
}
static void ma_thread_wait(ma_thread* pThread)
{
if (pThread == NULL) {
return;
}
#ifdef MA_WIN32
ma_thread_wait__win32(pThread);
#endif
#ifdef MA_POSIX
ma_thread_wait__posix(pThread);
#endif
}
MA_API ma_result ma_mutex_init(ma_mutex* pMutex)
{
if (pMutex == NULL) {
MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */
return MA_INVALID_ARGS;
}
#ifdef MA_WIN32
return ma_mutex_init__win32(pMutex);
#endif
#ifdef MA_POSIX
return ma_mutex_init__posix(pMutex);
#endif
}
MA_API void ma_mutex_uninit(ma_mutex* pMutex)
{
if (pMutex == NULL) {
return;
}
#ifdef MA_WIN32
ma_mutex_uninit__win32(pMutex);
#endif
#ifdef MA_POSIX
ma_mutex_uninit__posix(pMutex);
#endif
}
MA_API void ma_mutex_lock(ma_mutex* pMutex)
{
if (pMutex == NULL) {
MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */
return;
}
#ifdef MA_WIN32
ma_mutex_lock__win32(pMutex);
#endif
#ifdef MA_POSIX
ma_mutex_lock__posix(pMutex);
#endif
}
MA_API void ma_mutex_unlock(ma_mutex* pMutex)
{
if (pMutex == NULL) {
MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */
return;
}
#ifdef MA_WIN32
ma_mutex_unlock__win32(pMutex);
#endif
#ifdef MA_POSIX
ma_mutex_unlock__posix(pMutex);
#endif
}
MA_API ma_result ma_event_init(ma_event* pEvent)
{
if (pEvent == NULL) {
MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */
return MA_INVALID_ARGS;
}
#ifdef MA_WIN32
return ma_event_init__win32(pEvent);
#endif
#ifdef MA_POSIX
return ma_event_init__posix(pEvent);
#endif
}
#if 0
static ma_result ma_event_alloc_and_init(ma_event** ppEvent, ma_allocation_callbacks* pAllocationCallbacks)
{
ma_result result;
ma_event* pEvent;
if (ppEvent == NULL) {
return MA_INVALID_ARGS;
}
*ppEvent = NULL;
pEvent = ma_malloc(sizeof(*pEvent), pAllocationCallbacks/*, MA_ALLOCATION_TYPE_EVENT*/);
if (pEvent == NULL) {
return MA_OUT_OF_MEMORY;
}
result = ma_event_init(pEvent);
if (result != MA_SUCCESS) {
ma_free(pEvent, pAllocationCallbacks/*, MA_ALLOCATION_TYPE_EVENT*/);
return result;
}
*ppEvent = pEvent;
return result;
}
#endif
MA_API void ma_event_uninit(ma_event* pEvent)
{
if (pEvent == NULL) {
return;
}
#ifdef MA_WIN32
ma_event_uninit__win32(pEvent);
#endif
#ifdef MA_POSIX
ma_event_uninit__posix(pEvent);
#endif
}
#if 0
static void ma_event_uninit_and_free(ma_event* pEvent, ma_allocation_callbacks* pAllocationCallbacks)
{
if (pEvent == NULL) {
return;
}
ma_event_uninit(pEvent);
ma_free(pEvent, pAllocationCallbacks/*, MA_ALLOCATION_TYPE_EVENT*/);
}
#endif
MA_API ma_result ma_event_wait(ma_event* pEvent)
{
if (pEvent == NULL) {
MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */
return MA_INVALID_ARGS;
}
#ifdef MA_WIN32
return ma_event_wait__win32(pEvent);
#endif
#ifdef MA_POSIX
return ma_event_wait__posix(pEvent);
#endif
}
MA_API ma_result ma_event_signal(ma_event* pEvent)
{
if (pEvent == NULL) {
MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */
return MA_INVALID_ARGS;
}
#ifdef MA_WIN32
return ma_event_signal__win32(pEvent);
#endif
#ifdef MA_POSIX
return ma_event_signal__posix(pEvent);
#endif
}
MA_API ma_result ma_semaphore_init(int initialValue, ma_semaphore* pSemaphore)
{
if (pSemaphore == NULL) {
MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
return MA_INVALID_ARGS;
}
#ifdef MA_WIN32
return ma_semaphore_init__win32(initialValue, pSemaphore);
#endif
#ifdef MA_POSIX
return ma_semaphore_init__posix(initialValue, pSemaphore);
#endif
}
MA_API void ma_semaphore_uninit(ma_semaphore* pSemaphore)
{
if (pSemaphore == NULL) {
MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
return;
}
#ifdef MA_WIN32
ma_semaphore_uninit__win32(pSemaphore);
#endif
#ifdef MA_POSIX
ma_semaphore_uninit__posix(pSemaphore);
#endif
}
MA_API ma_result ma_semaphore_wait(ma_semaphore* pSemaphore)
{
if (pSemaphore == NULL) {
MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
return MA_INVALID_ARGS;
}
#ifdef MA_WIN32
return ma_semaphore_wait__win32(pSemaphore);
#endif
#ifdef MA_POSIX
return ma_semaphore_wait__posix(pSemaphore);
#endif
}
MA_API ma_result ma_semaphore_release(ma_semaphore* pSemaphore)
{
if (pSemaphore == NULL) {
MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
return MA_INVALID_ARGS;
}
#ifdef MA_WIN32
return ma_semaphore_release__win32(pSemaphore);
#endif
#ifdef MA_POSIX
return ma_semaphore_release__posix(pSemaphore);
#endif
}
#else
/* 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. */
#ifndef MA_NO_DEVICE_IO
#error "MA_NO_THREADING cannot be used without MA_NO_DEVICE_IO";
#endif
#endif /* MA_NO_THREADING */
/************************************************************************************************************************************************************
*************************************************************************************************************************************************************
DEVICE I/O
==========
*************************************************************************************************************************************************************
************************************************************************************************************************************************************/
#ifndef MA_NO_DEVICE_IO
#ifdef MA_WIN32
#include
#include
#include
#endif
#if defined(MA_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200)
#include /* For mach_absolute_time() */
#endif
#ifdef MA_POSIX
#include
#include
#include
#endif
/*
Unfortunately using runtime linking for pthreads causes problems. This has occurred for me when testing on FreeBSD. When
using runtime linking, deadlocks can occur (for me it happens when loading data from fread()). It turns out that doing
compile-time linking fixes this. I'm not sure why this happens, but the safest way I can think of to fix this is to simply
disable runtime linking by default. To enable runtime linking, #define this before the implementation of this file. I am
not officially supporting this, but I'm leaving it here in case it's useful for somebody, somewhere.
*/
/*#define MA_USE_RUNTIME_LINKING_FOR_PTHREAD*/
/* Disable run-time linking on certain backends. */
#ifndef MA_NO_RUNTIME_LINKING
#if defined(MA_EMSCRIPTEN)
#define MA_NO_RUNTIME_LINKING
#endif
#endif
MA_API const char* ma_get_backend_name(ma_backend backend)
{
switch (backend)
{
case ma_backend_wasapi: return "WASAPI";
case ma_backend_dsound: return "DirectSound";
case ma_backend_winmm: return "WinMM";
case ma_backend_coreaudio: return "Core Audio";
case ma_backend_sndio: return "sndio";
case ma_backend_audio4: return "audio(4)";
case ma_backend_oss: return "OSS";
case ma_backend_pulseaudio: return "PulseAudio";
case ma_backend_alsa: return "ALSA";
case ma_backend_jack: return "JACK";
case ma_backend_aaudio: return "AAudio";
case ma_backend_opensl: return "OpenSL|ES";
case ma_backend_webaudio: return "Web Audio";
case ma_backend_custom: return "Custom";
case ma_backend_null: return "Null";
default: return "Unknown";
}
}
MA_API ma_bool32 ma_is_backend_enabled(ma_backend backend)
{
/*
This looks a little bit gross, but we want all backends to be included in the switch to avoid warnings on some compilers
about some enums not being handled by the switch statement.
*/
switch (backend)
{
case ma_backend_wasapi:
#if defined(MA_HAS_WASAPI)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_dsound:
#if defined(MA_HAS_DSOUND)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_winmm:
#if defined(MA_HAS_WINMM)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_coreaudio:
#if defined(MA_HAS_COREAUDIO)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_sndio:
#if defined(MA_HAS_SNDIO)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_audio4:
#if defined(MA_HAS_AUDIO4)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_oss:
#if defined(MA_HAS_OSS)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_pulseaudio:
#if defined(MA_HAS_PULSEAUDIO)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_alsa:
#if defined(MA_HAS_ALSA)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_jack:
#if defined(MA_HAS_JACK)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_aaudio:
#if defined(MA_HAS_AAUDIO)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_opensl:
#if defined(MA_HAS_OPENSL)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_webaudio:
#if defined(MA_HAS_WEBAUDIO)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_custom:
#if defined(MA_HAS_CUSTOM)
return MA_TRUE;
#else
return MA_FALSE;
#endif
case ma_backend_null:
#if defined(MA_HAS_NULL)
return MA_TRUE;
#else
return MA_FALSE;
#endif
default: return MA_FALSE;
}
}
MA_API ma_result ma_get_enabled_backends(ma_backend* pBackends, size_t backendCap, size_t* pBackendCount)
{
size_t backendCount;
size_t iBackend;
ma_result result = MA_SUCCESS;
if (pBackendCount == NULL) {
return MA_INVALID_ARGS;
}
backendCount = 0;
for (iBackend = 0; iBackend <= ma_backend_null; iBackend += 1) {
ma_backend backend = (ma_backend)iBackend;
if (ma_is_backend_enabled(backend)) {
/* The backend is enabled. Try adding it to the list. If there's no room, MA_NO_SPACE needs to be returned. */
if (backendCount == backendCap) {
result = MA_NO_SPACE;
break;
} else {
pBackends[backendCount] = backend;
backendCount += 1;
}
}
}
if (pBackendCount != NULL) {
*pBackendCount = backendCount;
}
return result;
}
MA_API ma_bool32 ma_is_loopback_supported(ma_backend backend)
{
switch (backend)
{
case ma_backend_wasapi: return MA_TRUE;
case ma_backend_dsound: return MA_FALSE;
case ma_backend_winmm: return MA_FALSE;
case ma_backend_coreaudio: return MA_FALSE;
case ma_backend_sndio: return MA_FALSE;
case ma_backend_audio4: return MA_FALSE;
case ma_backend_oss: return MA_FALSE;
case ma_backend_pulseaudio: return MA_FALSE;
case ma_backend_alsa: return MA_FALSE;
case ma_backend_jack: return MA_FALSE;
case ma_backend_aaudio: return MA_FALSE;
case ma_backend_opensl: return MA_FALSE;
case ma_backend_webaudio: return MA_FALSE;
case ma_backend_custom: return MA_FALSE; /* <-- Will depend on the implementation of the backend. */
case ma_backend_null: return MA_FALSE;
default: return MA_FALSE;
}
}
#ifdef MA_WIN32
/* WASAPI error codes. */
#define MA_AUDCLNT_E_NOT_INITIALIZED ((HRESULT)0x88890001)
#define MA_AUDCLNT_E_ALREADY_INITIALIZED ((HRESULT)0x88890002)
#define MA_AUDCLNT_E_WRONG_ENDPOINT_TYPE ((HRESULT)0x88890003)
#define MA_AUDCLNT_E_DEVICE_INVALIDATED ((HRESULT)0x88890004)
#define MA_AUDCLNT_E_NOT_STOPPED ((HRESULT)0x88890005)
#define MA_AUDCLNT_E_BUFFER_TOO_LARGE ((HRESULT)0x88890006)
#define MA_AUDCLNT_E_OUT_OF_ORDER ((HRESULT)0x88890007)
#define MA_AUDCLNT_E_UNSUPPORTED_FORMAT ((HRESULT)0x88890008)
#define MA_AUDCLNT_E_INVALID_SIZE ((HRESULT)0x88890009)
#define MA_AUDCLNT_E_DEVICE_IN_USE ((HRESULT)0x8889000A)
#define MA_AUDCLNT_E_BUFFER_OPERATION_PENDING ((HRESULT)0x8889000B)
#define MA_AUDCLNT_E_THREAD_NOT_REGISTERED ((HRESULT)0x8889000C)
#define MA_AUDCLNT_E_NO_SINGLE_PROCESS ((HRESULT)0x8889000D)
#define MA_AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED ((HRESULT)0x8889000E)
#define MA_AUDCLNT_E_ENDPOINT_CREATE_FAILED ((HRESULT)0x8889000F)
#define MA_AUDCLNT_E_SERVICE_NOT_RUNNING ((HRESULT)0x88890010)
#define MA_AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED ((HRESULT)0x88890011)
#define MA_AUDCLNT_E_EXCLUSIVE_MODE_ONLY ((HRESULT)0x88890012)
#define MA_AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL ((HRESULT)0x88890013)
#define MA_AUDCLNT_E_EVENTHANDLE_NOT_SET ((HRESULT)0x88890014)
#define MA_AUDCLNT_E_INCORRECT_BUFFER_SIZE ((HRESULT)0x88890015)
#define MA_AUDCLNT_E_BUFFER_SIZE_ERROR ((HRESULT)0x88890016)
#define MA_AUDCLNT_E_CPUUSAGE_EXCEEDED ((HRESULT)0x88890017)
#define MA_AUDCLNT_E_BUFFER_ERROR ((HRESULT)0x88890018)
#define MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED ((HRESULT)0x88890019)
#define MA_AUDCLNT_E_INVALID_DEVICE_PERIOD ((HRESULT)0x88890020)
#define MA_AUDCLNT_E_INVALID_STREAM_FLAG ((HRESULT)0x88890021)
#define MA_AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE ((HRESULT)0x88890022)
#define MA_AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES ((HRESULT)0x88890023)
#define MA_AUDCLNT_E_OFFLOAD_MODE_ONLY ((HRESULT)0x88890024)
#define MA_AUDCLNT_E_NONOFFLOAD_MODE_ONLY ((HRESULT)0x88890025)
#define MA_AUDCLNT_E_RESOURCES_INVALIDATED ((HRESULT)0x88890026)
#define MA_AUDCLNT_E_RAW_MODE_UNSUPPORTED ((HRESULT)0x88890027)
#define MA_AUDCLNT_E_ENGINE_PERIODICITY_LOCKED ((HRESULT)0x88890028)
#define MA_AUDCLNT_E_ENGINE_FORMAT_LOCKED ((HRESULT)0x88890029)
#define MA_AUDCLNT_E_HEADTRACKING_ENABLED ((HRESULT)0x88890030)
#define MA_AUDCLNT_E_HEADTRACKING_UNSUPPORTED ((HRESULT)0x88890040)
#define MA_AUDCLNT_S_BUFFER_EMPTY ((HRESULT)0x08890001)
#define MA_AUDCLNT_S_THREAD_ALREADY_REGISTERED ((HRESULT)0x08890002)
#define MA_AUDCLNT_S_POSITION_STALLED ((HRESULT)0x08890003)
#define MA_DS_OK ((HRESULT)0)
#define MA_DS_NO_VIRTUALIZATION ((HRESULT)0x0878000A)
#define MA_DSERR_ALLOCATED ((HRESULT)0x8878000A)
#define MA_DSERR_CONTROLUNAVAIL ((HRESULT)0x8878001E)
#define MA_DSERR_INVALIDPARAM ((HRESULT)0x80070057) /*E_INVALIDARG*/
#define MA_DSERR_INVALIDCALL ((HRESULT)0x88780032)
#define MA_DSERR_GENERIC ((HRESULT)0x80004005) /*E_FAIL*/
#define MA_DSERR_PRIOLEVELNEEDED ((HRESULT)0x88780046)
#define MA_DSERR_OUTOFMEMORY ((HRESULT)0x8007000E) /*E_OUTOFMEMORY*/
#define MA_DSERR_BADFORMAT ((HRESULT)0x88780064)
#define MA_DSERR_UNSUPPORTED ((HRESULT)0x80004001) /*E_NOTIMPL*/
#define MA_DSERR_NODRIVER ((HRESULT)0x88780078)
#define MA_DSERR_ALREADYINITIALIZED ((HRESULT)0x88780082)
#define MA_DSERR_NOAGGREGATION ((HRESULT)0x80040110) /*CLASS_E_NOAGGREGATION*/
#define MA_DSERR_BUFFERLOST ((HRESULT)0x88780096)
#define MA_DSERR_OTHERAPPHASPRIO ((HRESULT)0x887800A0)
#define MA_DSERR_UNINITIALIZED ((HRESULT)0x887800AA)
#define MA_DSERR_NOINTERFACE ((HRESULT)0x80004002) /*E_NOINTERFACE*/
#define MA_DSERR_ACCESSDENIED ((HRESULT)0x80070005) /*E_ACCESSDENIED*/
#define MA_DSERR_BUFFERTOOSMALL ((HRESULT)0x887800B4)
#define MA_DSERR_DS8_REQUIRED ((HRESULT)0x887800BE)
#define MA_DSERR_SENDLOOP ((HRESULT)0x887800C8)
#define MA_DSERR_BADSENDBUFFERGUID ((HRESULT)0x887800D2)
#define MA_DSERR_OBJECTNOTFOUND ((HRESULT)0x88781161)
#define MA_DSERR_FXUNAVAILABLE ((HRESULT)0x887800DC)
static ma_result ma_result_from_HRESULT(HRESULT hr)
{
switch (hr)
{
case NOERROR: return MA_SUCCESS;
/*case S_OK: return MA_SUCCESS;*/
case E_POINTER: return MA_INVALID_ARGS;
case E_UNEXPECTED: return MA_ERROR;
case E_NOTIMPL: return MA_NOT_IMPLEMENTED;
case E_OUTOFMEMORY: return MA_OUT_OF_MEMORY;
case E_INVALIDARG: return MA_INVALID_ARGS;
case E_NOINTERFACE: return MA_API_NOT_FOUND;
case E_HANDLE: return MA_INVALID_ARGS;
case E_ABORT: return MA_ERROR;
case E_FAIL: return MA_ERROR;
case E_ACCESSDENIED: return MA_ACCESS_DENIED;
/* WASAPI */
case MA_AUDCLNT_E_NOT_INITIALIZED: return MA_DEVICE_NOT_INITIALIZED;
case MA_AUDCLNT_E_ALREADY_INITIALIZED: return MA_DEVICE_ALREADY_INITIALIZED;
case MA_AUDCLNT_E_WRONG_ENDPOINT_TYPE: return MA_INVALID_ARGS;
case MA_AUDCLNT_E_DEVICE_INVALIDATED: return MA_UNAVAILABLE;
case MA_AUDCLNT_E_NOT_STOPPED: return MA_DEVICE_NOT_STOPPED;
case MA_AUDCLNT_E_BUFFER_TOO_LARGE: return MA_TOO_BIG;
case MA_AUDCLNT_E_OUT_OF_ORDER: return MA_INVALID_OPERATION;
case MA_AUDCLNT_E_UNSUPPORTED_FORMAT: return MA_FORMAT_NOT_SUPPORTED;
case MA_AUDCLNT_E_INVALID_SIZE: return MA_INVALID_ARGS;
case MA_AUDCLNT_E_DEVICE_IN_USE: return MA_BUSY;
case MA_AUDCLNT_E_BUFFER_OPERATION_PENDING: return MA_INVALID_OPERATION;
case MA_AUDCLNT_E_THREAD_NOT_REGISTERED: return MA_DOES_NOT_EXIST;
case MA_AUDCLNT_E_NO_SINGLE_PROCESS: return MA_INVALID_OPERATION;
case MA_AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: return MA_SHARE_MODE_NOT_SUPPORTED;
case MA_AUDCLNT_E_ENDPOINT_CREATE_FAILED: return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
case MA_AUDCLNT_E_SERVICE_NOT_RUNNING: return MA_NOT_CONNECTED;
case MA_AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: return MA_INVALID_ARGS;
case MA_AUDCLNT_E_EXCLUSIVE_MODE_ONLY: return MA_SHARE_MODE_NOT_SUPPORTED;
case MA_AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: return MA_INVALID_ARGS;
case MA_AUDCLNT_E_EVENTHANDLE_NOT_SET: return MA_INVALID_ARGS;
case MA_AUDCLNT_E_INCORRECT_BUFFER_SIZE: return MA_INVALID_ARGS;
case MA_AUDCLNT_E_BUFFER_SIZE_ERROR: return MA_INVALID_ARGS;
case MA_AUDCLNT_E_CPUUSAGE_EXCEEDED: return MA_ERROR;
case MA_AUDCLNT_E_BUFFER_ERROR: return MA_ERROR;
case MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED: return MA_INVALID_ARGS;
case MA_AUDCLNT_E_INVALID_DEVICE_PERIOD: return MA_INVALID_ARGS;
case MA_AUDCLNT_E_INVALID_STREAM_FLAG: return MA_INVALID_ARGS;
case MA_AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE: return MA_INVALID_OPERATION;
case MA_AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES: return MA_OUT_OF_MEMORY;
case MA_AUDCLNT_E_OFFLOAD_MODE_ONLY: return MA_INVALID_OPERATION;
case MA_AUDCLNT_E_NONOFFLOAD_MODE_ONLY: return MA_INVALID_OPERATION;
case MA_AUDCLNT_E_RESOURCES_INVALIDATED: return MA_INVALID_DATA;
case MA_AUDCLNT_E_RAW_MODE_UNSUPPORTED: return MA_INVALID_OPERATION;
case MA_AUDCLNT_E_ENGINE_PERIODICITY_LOCKED: return MA_INVALID_OPERATION;
case MA_AUDCLNT_E_ENGINE_FORMAT_LOCKED: return MA_INVALID_OPERATION;
case MA_AUDCLNT_E_HEADTRACKING_ENABLED: return MA_INVALID_OPERATION;
case MA_AUDCLNT_E_HEADTRACKING_UNSUPPORTED: return MA_INVALID_OPERATION;
case MA_AUDCLNT_S_BUFFER_EMPTY: return MA_NO_SPACE;
case MA_AUDCLNT_S_THREAD_ALREADY_REGISTERED: return MA_ALREADY_EXISTS;
case MA_AUDCLNT_S_POSITION_STALLED: return MA_ERROR;
/* DirectSound */
/*case MA_DS_OK: return MA_SUCCESS;*/ /* S_OK */
case MA_DS_NO_VIRTUALIZATION: return MA_SUCCESS;
case MA_DSERR_ALLOCATED: return MA_ALREADY_IN_USE;
case MA_DSERR_CONTROLUNAVAIL: return MA_INVALID_OPERATION;
/*case MA_DSERR_INVALIDPARAM: return MA_INVALID_ARGS;*/ /* E_INVALIDARG */
case MA_DSERR_INVALIDCALL: return MA_INVALID_OPERATION;
/*case MA_DSERR_GENERIC: return MA_ERROR;*/ /* E_FAIL */
case MA_DSERR_PRIOLEVELNEEDED: return MA_INVALID_OPERATION;
/*case MA_DSERR_OUTOFMEMORY: return MA_OUT_OF_MEMORY;*/ /* E_OUTOFMEMORY */
case MA_DSERR_BADFORMAT: return MA_FORMAT_NOT_SUPPORTED;
/*case MA_DSERR_UNSUPPORTED: return MA_NOT_IMPLEMENTED;*/ /* E_NOTIMPL */
case MA_DSERR_NODRIVER: return MA_FAILED_TO_INIT_BACKEND;
case MA_DSERR_ALREADYINITIALIZED: return MA_DEVICE_ALREADY_INITIALIZED;
case MA_DSERR_NOAGGREGATION: return MA_ERROR;
case MA_DSERR_BUFFERLOST: return MA_UNAVAILABLE;
case MA_DSERR_OTHERAPPHASPRIO: return MA_ACCESS_DENIED;
case MA_DSERR_UNINITIALIZED: return MA_DEVICE_NOT_INITIALIZED;
/*case MA_DSERR_NOINTERFACE: return MA_API_NOT_FOUND;*/ /* E_NOINTERFACE */
/*case MA_DSERR_ACCESSDENIED: return MA_ACCESS_DENIED;*/ /* E_ACCESSDENIED */
case MA_DSERR_BUFFERTOOSMALL: return MA_NO_SPACE;
case MA_DSERR_DS8_REQUIRED: return MA_INVALID_OPERATION;
case MA_DSERR_SENDLOOP: return MA_DEADLOCK;
case MA_DSERR_BADSENDBUFFERGUID: return MA_INVALID_ARGS;
case MA_DSERR_OBJECTNOTFOUND: return MA_NO_DEVICE;
case MA_DSERR_FXUNAVAILABLE: return MA_UNAVAILABLE;
default: return MA_ERROR;
}
}
typedef HRESULT (WINAPI * MA_PFN_CoInitializeEx)(LPVOID pvReserved, DWORD dwCoInit);
typedef void (WINAPI * MA_PFN_CoUninitialize)(void);
typedef HRESULT (WINAPI * MA_PFN_CoCreateInstance)(REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv);
typedef void (WINAPI * MA_PFN_CoTaskMemFree)(LPVOID pv);
typedef HRESULT (WINAPI * MA_PFN_PropVariantClear)(PROPVARIANT *pvar);
typedef int (WINAPI * MA_PFN_StringFromGUID2)(const GUID* const rguid, LPOLESTR lpsz, int cchMax);
typedef HWND (WINAPI * MA_PFN_GetForegroundWindow)(void);
typedef HWND (WINAPI * MA_PFN_GetDesktopWindow)(void);
/* Microsoft documents these APIs as returning LSTATUS, but the Win32 API shipping with some compilers do not define it. It's just a LONG. */
typedef LONG (WINAPI * MA_PFN_RegOpenKeyExA)(HKEY hKey, LPCSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult);
typedef LONG (WINAPI * MA_PFN_RegCloseKey)(HKEY hKey);
typedef LONG (WINAPI * MA_PFN_RegQueryValueExA)(HKEY hKey, LPCSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData);
#endif
#define MA_DEFAULT_PLAYBACK_DEVICE_NAME "Default Playback Device"
#define MA_DEFAULT_CAPTURE_DEVICE_NAME "Default Capture Device"
MA_API const char* ma_log_level_to_string(ma_uint32 logLevel)
{
switch (logLevel)
{
case MA_LOG_LEVEL_VERBOSE: return "";
case MA_LOG_LEVEL_INFO: return "INFO";
case MA_LOG_LEVEL_WARNING: return "WARNING";
case MA_LOG_LEVEL_ERROR: return "ERROR";
default: return "ERROR";
}
}
/* Posts a log message. */
static void ma_post_log_message(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message)
{
if (pContext == NULL) {
if (pDevice != NULL) {
pContext = pDevice->pContext;
}
}
/* All logs must be output when debug output is enabled. */
#if defined(MA_DEBUG_OUTPUT)
printf("%s: %s\n", ma_log_level_to_string(logLevel), message);
#endif
if (pContext == NULL) {
return;
}
#if defined(MA_LOG_LEVEL)
if (logLevel <= MA_LOG_LEVEL) {
ma_log_proc onLog;
onLog = pContext->logCallback;
if (onLog) {
onLog(pContext, pDevice, logLevel, message);
}
}
#endif
}
/*
We need to emulate _vscprintf() for the VC6 build. This can be more efficient, but since it's only VC6, and it's just a
logging function, I'm happy to keep this simple. In the VC6 build we can implement this in terms of _vsnprintf().
*/
#if defined(_MSC_VER) && _MSC_VER < 1900
int ma_vscprintf(const char* format, va_list args)
{
#if _MSC_VER > 1200
return _vscprintf(format, args);
#else
int result;
char* pTempBuffer = NULL;
size_t tempBufferCap = 1024;
if (format == NULL) {
errno = EINVAL;
return -1;
}
for (;;) {
char* pNewTempBuffer = (char*)ma_realloc(pTempBuffer, tempBufferCap, NULL); /* TODO: Add support for custom memory allocators? */
if (pNewTempBuffer == NULL) {
ma_free(pTempBuffer, NULL);
errno = ENOMEM;
return -1; /* Out of memory. */
}
pTempBuffer = pNewTempBuffer;
result = _vsnprintf(pTempBuffer, tempBufferCap, format, args);
ma_free(pTempBuffer, NULL);
if (result != -1) {
break; /* Got it. */
}
/* Buffer wasn't big enough. Ideally it'd be nice to use an error code to know the reason for sure, but this is reliable enough. */
tempBufferCap *= 2;
}
return result;
#endif
}
#endif
/* Posts a formatted log message. */
static void ma_post_log_messagev(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* pFormat, va_list args)
{
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || ((!defined(_MSC_VER) || _MSC_VER >= 1900) && !defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
{
char pFormattedMessage[1024];
vsnprintf(pFormattedMessage, sizeof(pFormattedMessage), pFormat, args);
ma_post_log_message(pContext, pDevice, logLevel, pFormattedMessage);
}
#else
{
/*
Without snprintf() we need to first measure the string and then heap allocate it. I'm only aware of Visual Studio having support for this without snprintf(), so we'll
need to restrict this branch to Visual Studio. For other compilers we need to just not support formatted logging because I don't want the security risk of overflowing
a fixed sized stack allocated buffer.
*/
#if defined(_MSC_VER) && _MSC_VER >= 1200 /* 1200 = VC6 */
int formattedLen;
va_list args2;
#if _MSC_VER >= 1800
va_copy(args2, args);
#else
args2 = args;
#endif
formattedLen = ma_vscprintf(pFormat, args2);
va_end(args2);
if (formattedLen > 0) {
char* pFormattedMessage = NULL;
ma_allocation_callbacks* pAllocationCallbacks = NULL;
/* Make sure we have a context so we can allocate memory. */
if (pContext == NULL) {
if (pDevice != NULL) {
pContext = pDevice->pContext;
}
}
if (pContext != NULL) {
pAllocationCallbacks = &pContext->allocationCallbacks;
}
pFormattedMessage = (char*)ma_malloc(formattedLen + 1, pAllocationCallbacks);
if (pFormattedMessage != NULL) {
/* We'll get errors on newer versions of Visual Studio if we try to use vsprintf(). */
#if _MSC_VER >= 1400 /* 1400 = Visual Studio 2005 */
vsprintf_s(pFormattedMessage, formattedLen + 1, pFormat, args);
#else
vsprintf(pFormattedMessage, pFormat, args);
#endif
ma_post_log_message(pContext, pDevice, logLevel, pFormattedMessage);
ma_free(pFormattedMessage, pAllocationCallbacks);
}
}
#else
/* Can't do anything because we don't have a safe way of to emulate vsnprintf() without a manual solution. */
(void)pContext;
(void)pDevice;
(void)logLevel;
(void)pFormat;
(void)args;
#endif
}
#endif
}
MA_API void ma_post_log_messagef(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* pFormat, ...)
{
va_list args;
va_start(args, pFormat);
{
ma_post_log_messagev(pContext, pDevice, logLevel, pFormat, args);
}
va_end(args);
}
/* Posts an log message. Throw a breakpoint in here if you're needing to debug. The return value is always "resultCode". */
static ma_result ma_context_post_error(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message, ma_result resultCode)
{
ma_post_log_message(pContext, pDevice, logLevel, message);
return resultCode;
}
static ma_result ma_post_error(ma_device* pDevice, ma_uint32 logLevel, const char* message, ma_result resultCode)
{
return ma_context_post_error(NULL, pDevice, logLevel, message, resultCode);
}
/*******************************************************************************
Timing
*******************************************************************************/
#ifdef MA_WIN32
static LARGE_INTEGER g_ma_TimerFrequency; /* <-- Initialized to zero since it's static. */
static void ma_timer_init(ma_timer* pTimer)
{
LARGE_INTEGER counter;
if (g_ma_TimerFrequency.QuadPart == 0) {
QueryPerformanceFrequency(&g_ma_TimerFrequency);
}
QueryPerformanceCounter(&counter);
pTimer->counter = counter.QuadPart;
}
static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
{
LARGE_INTEGER counter;
if (!QueryPerformanceCounter(&counter)) {
return 0;
}
return (double)(counter.QuadPart - pTimer->counter) / g_ma_TimerFrequency.QuadPart;
}
#elif defined(MA_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200)
static ma_uint64 g_ma_TimerFrequency = 0;
static void ma_timer_init(ma_timer* pTimer)
{
mach_timebase_info_data_t baseTime;
mach_timebase_info(&baseTime);
g_ma_TimerFrequency = (baseTime.denom * 1e9) / baseTime.numer;
pTimer->counter = mach_absolute_time();
}
static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
{
ma_uint64 newTimeCounter = mach_absolute_time();
ma_uint64 oldTimeCounter = pTimer->counter;
return (newTimeCounter - oldTimeCounter) / g_ma_TimerFrequency;
}
#elif defined(MA_EMSCRIPTEN)
static MA_INLINE void ma_timer_init(ma_timer* pTimer)
{
pTimer->counterD = emscripten_get_now();
}
static MA_INLINE double ma_timer_get_time_in_seconds(ma_timer* pTimer)
{
return (emscripten_get_now() - pTimer->counterD) / 1000; /* Emscripten is in milliseconds. */
}
#else
#if _POSIX_C_SOURCE >= 199309L
#if defined(CLOCK_MONOTONIC)
#define MA_CLOCK_ID CLOCK_MONOTONIC
#else
#define MA_CLOCK_ID CLOCK_REALTIME
#endif
static void ma_timer_init(ma_timer* pTimer)
{
struct timespec newTime;
clock_gettime(MA_CLOCK_ID, &newTime);
pTimer->counter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec;
}
static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
{
ma_uint64 newTimeCounter;
ma_uint64 oldTimeCounter;
struct timespec newTime;
clock_gettime(MA_CLOCK_ID, &newTime);
newTimeCounter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec;
oldTimeCounter = pTimer->counter;
return (newTimeCounter - oldTimeCounter) / 1000000000.0;
}
#else
static void ma_timer_init(ma_timer* pTimer)
{
struct timeval newTime;
gettimeofday(&newTime, NULL);
pTimer->counter = (newTime.tv_sec * 1000000) + newTime.tv_usec;
}
static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
{
ma_uint64 newTimeCounter;
ma_uint64 oldTimeCounter;
struct timeval newTime;
gettimeofday(&newTime, NULL);
newTimeCounter = (newTime.tv_sec * 1000000) + newTime.tv_usec;
oldTimeCounter = pTimer->counter;
return (newTimeCounter - oldTimeCounter) / 1000000.0;
}
#endif
#endif
/*******************************************************************************
Dynamic Linking
*******************************************************************************/
MA_API ma_handle ma_dlopen(ma_context* pContext, const char* filename)
{
ma_handle handle;
#if MA_LOG_LEVEL >= MA_LOG_LEVEL_VERBOSE
if (pContext != NULL) {
char message[256];
ma_strappend(message, sizeof(message), "Loading library: ", filename);
ma_post_log_message(pContext, NULL, MA_LOG_LEVEL_VERBOSE, message);
}
#endif
#ifdef _WIN32
#ifdef MA_WIN32_DESKTOP
handle = (ma_handle)LoadLibraryA(filename);
#else
/* *sigh* It appears there is no ANSI version of LoadPackagedLibrary()... */
WCHAR filenameW[4096];
if (MultiByteToWideChar(CP_UTF8, 0, filename, -1, filenameW, sizeof(filenameW)) == 0) {
handle = NULL;
} else {
handle = (ma_handle)LoadPackagedLibrary(filenameW, 0);
}
#endif
#else
handle = (ma_handle)dlopen(filename, RTLD_NOW);
#endif
/*
I'm not considering failure to load a library an error nor a warning because seamlessly falling through to a lower-priority
backend is a deliberate design choice. Instead I'm logging it as an informational message.
*/
#if MA_LOG_LEVEL >= MA_LOG_LEVEL_INFO
if (handle == NULL) {
char message[256];
ma_strappend(message, sizeof(message), "Failed to load library: ", filename);
ma_post_log_message(pContext, NULL, MA_LOG_LEVEL_INFO, message);
}
#endif
(void)pContext; /* It's possible for pContext to be unused. */
return handle;
}
MA_API void ma_dlclose(ma_context* pContext, ma_handle handle)
{
#ifdef _WIN32
FreeLibrary((HMODULE)handle);
#else
dlclose((void*)handle);
#endif
(void)pContext;
}
MA_API ma_proc ma_dlsym(ma_context* pContext, ma_handle handle, const char* symbol)
{
ma_proc proc;
#if MA_LOG_LEVEL >= MA_LOG_LEVEL_VERBOSE
if (pContext != NULL) {
char message[256];
ma_strappend(message, sizeof(message), "Loading symbol: ", symbol);
ma_post_log_message(pContext, NULL, MA_LOG_LEVEL_VERBOSE, message);
}
#endif
#ifdef _WIN32
proc = (ma_proc)GetProcAddress((HMODULE)handle, symbol);
#else
#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#endif
proc = (ma_proc)dlsym((void*)handle, symbol);
#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
#pragma GCC diagnostic pop
#endif
#endif
#if MA_LOG_LEVEL >= MA_LOG_LEVEL_WARNING
if (handle == NULL) {
char message[256];
ma_strappend(message, sizeof(message), "Failed to load symbol: ", symbol);
ma_post_log_message(pContext, NULL, MA_LOG_LEVEL_WARNING, message);
}
#endif
(void)pContext; /* It's possible for pContext to be unused. */
return proc;
}
#if 0
static ma_uint32 ma_get_closest_standard_sample_rate(ma_uint32 sampleRateIn)
{
ma_uint32 closestRate = 0;
ma_uint32 closestDiff = 0xFFFFFFFF;
size_t iStandardRate;
for (iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) {
ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate];
ma_uint32 diff;
if (sampleRateIn > standardRate) {
diff = sampleRateIn - standardRate;
} else {
diff = standardRate - sampleRateIn;
}
if (diff == 0) {
return standardRate; /* The input sample rate is a standard rate. */
}
if (closestDiff > diff) {
closestDiff = diff;
closestRate = standardRate;
}
}
return closestRate;
}
#endif
static void ma_device__on_data(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
{
float masterVolumeFactor;
ma_device_get_master_volume(pDevice, &masterVolumeFactor); /* Use ma_device_get_master_volume() to ensure the volume is loaded atomically. */
if (pDevice->onData) {
if (!pDevice->noPreZeroedOutputBuffer && pFramesOut != NULL) {
ma_silence_pcm_frames(pFramesOut, frameCount, pDevice->playback.format, pDevice->playback.channels);
}
/* Volume control of input makes things a bit awkward because the input buffer is read-only. We'll need to use a temp buffer and loop in this case. */
if (pFramesIn != NULL && masterVolumeFactor < 1) {
ma_uint8 tempFramesIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 bpfCapture = ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
ma_uint32 bpfPlayback = ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
ma_uint32 totalFramesProcessed = 0;
while (totalFramesProcessed < frameCount) {
ma_uint32 framesToProcessThisIteration = frameCount - totalFramesProcessed;
if (framesToProcessThisIteration > sizeof(tempFramesIn)/bpfCapture) {
framesToProcessThisIteration = sizeof(tempFramesIn)/bpfCapture;
}
ma_copy_and_apply_volume_factor_pcm_frames(tempFramesIn, ma_offset_ptr(pFramesIn, totalFramesProcessed*bpfCapture), framesToProcessThisIteration, pDevice->capture.format, pDevice->capture.channels, masterVolumeFactor);
pDevice->onData(pDevice, ma_offset_ptr(pFramesOut, totalFramesProcessed*bpfPlayback), tempFramesIn, framesToProcessThisIteration);
totalFramesProcessed += framesToProcessThisIteration;
}
} else {
pDevice->onData(pDevice, pFramesOut, pFramesIn, frameCount);
}
/* Volume control and clipping for playback devices. */
if (pFramesOut != NULL) {
if (masterVolumeFactor < 1) {
if (pFramesIn == NULL) { /* <-- In full-duplex situations, the volume will have been applied to the input samples before the data callback. Applying it again post-callback will incorrectly compound it. */
ma_apply_volume_factor_pcm_frames(pFramesOut, frameCount, pDevice->playback.format, pDevice->playback.channels, masterVolumeFactor);
}
}
if (!pDevice->noClip && pDevice->playback.format == ma_format_f32) {
ma_clip_pcm_frames_f32((float*)pFramesOut, frameCount, pDevice->playback.channels);
}
}
}
}
/* A helper function for reading sample data from the client. */
static void ma_device__read_frames_from_client(ma_device* pDevice, ma_uint32 frameCount, void* pFramesOut)
{
MA_ASSERT(pDevice != NULL);
MA_ASSERT(frameCount > 0);
MA_ASSERT(pFramesOut != NULL);
if (pDevice->playback.converter.isPassthrough) {
ma_device__on_data(pDevice, pFramesOut, NULL, frameCount);
} else {
ma_result result;
ma_uint64 totalFramesReadOut;
ma_uint64 totalFramesReadIn;
void* pRunningFramesOut;
totalFramesReadOut = 0;
totalFramesReadIn = 0;
pRunningFramesOut = pFramesOut;
while (totalFramesReadOut < frameCount) {
ma_uint8 pIntermediaryBuffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In client format. */
ma_uint64 intermediaryBufferCap = sizeof(pIntermediaryBuffer) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
ma_uint64 framesToReadThisIterationIn;
ma_uint64 framesReadThisIterationIn;
ma_uint64 framesToReadThisIterationOut;
ma_uint64 framesReadThisIterationOut;
ma_uint64 requiredInputFrameCount;
framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
framesToReadThisIterationIn = framesToReadThisIterationOut;
if (framesToReadThisIterationIn > intermediaryBufferCap) {
framesToReadThisIterationIn = intermediaryBufferCap;
}
requiredInputFrameCount = ma_data_converter_get_required_input_frame_count(&pDevice->playback.converter, framesToReadThisIterationOut);
if (framesToReadThisIterationIn > requiredInputFrameCount) {
framesToReadThisIterationIn = requiredInputFrameCount;
}
if (framesToReadThisIterationIn > 0) {
ma_device__on_data(pDevice, pIntermediaryBuffer, NULL, (ma_uint32)framesToReadThisIterationIn);
totalFramesReadIn += framesToReadThisIterationIn;
}
/*
At this point we have our decoded data in input format and now we need to convert to output format. Note that even if we didn't read any
input frames, we still want to try processing frames because there may some output frames generated from cached input data.
*/
framesReadThisIterationIn = framesToReadThisIterationIn;
framesReadThisIterationOut = framesToReadThisIterationOut;
result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, pIntermediaryBuffer, &framesReadThisIterationIn, pRunningFramesOut, &framesReadThisIterationOut);
if (result != MA_SUCCESS) {
break;
}
totalFramesReadOut += framesReadThisIterationOut;
pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesReadThisIterationOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
if (framesReadThisIterationIn == 0 && framesReadThisIterationOut == 0) {
break; /* We're done. */
}
}
}
}
/* A helper for sending sample data to the client. */
static void ma_device__send_frames_to_client(ma_device* pDevice, ma_uint32 frameCountInDeviceFormat, const void* pFramesInDeviceFormat)
{
MA_ASSERT(pDevice != NULL);
MA_ASSERT(frameCountInDeviceFormat > 0);
MA_ASSERT(pFramesInDeviceFormat != NULL);
if (pDevice->capture.converter.isPassthrough) {
ma_device__on_data(pDevice, NULL, pFramesInDeviceFormat, frameCountInDeviceFormat);
} else {
ma_result result;
ma_uint8 pFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint64 framesInClientFormatCap = sizeof(pFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
ma_uint64 totalDeviceFramesProcessed = 0;
ma_uint64 totalClientFramesProcessed = 0;
const void* pRunningFramesInDeviceFormat = pFramesInDeviceFormat;
/* We just keep going until we've exhaused all of our input frames and cannot generate any more output frames. */
for (;;) {
ma_uint64 deviceFramesProcessedThisIteration;
ma_uint64 clientFramesProcessedThisIteration;
deviceFramesProcessedThisIteration = (frameCountInDeviceFormat - totalDeviceFramesProcessed);
clientFramesProcessedThisIteration = framesInClientFormatCap;
result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningFramesInDeviceFormat, &deviceFramesProcessedThisIteration, pFramesInClientFormat, &clientFramesProcessedThisIteration);
if (result != MA_SUCCESS) {
break;
}
if (clientFramesProcessedThisIteration > 0) {
ma_device__on_data(pDevice, NULL, pFramesInClientFormat, (ma_uint32)clientFramesProcessedThisIteration); /* Safe cast. */
}
pRunningFramesInDeviceFormat = ma_offset_ptr(pRunningFramesInDeviceFormat, deviceFramesProcessedThisIteration * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
totalDeviceFramesProcessed += deviceFramesProcessedThisIteration;
totalClientFramesProcessed += clientFramesProcessedThisIteration;
if (deviceFramesProcessedThisIteration == 0 && clientFramesProcessedThisIteration == 0) {
break; /* We're done. */
}
}
}
}
static ma_result ma_device__handle_duplex_callback_capture(ma_device* pDevice, ma_uint32 frameCountInDeviceFormat, const void* pFramesInDeviceFormat, ma_pcm_rb* pRB)
{
ma_result result;
ma_uint32 totalDeviceFramesProcessed = 0;
const void* pRunningFramesInDeviceFormat = pFramesInDeviceFormat;
MA_ASSERT(pDevice != NULL);
MA_ASSERT(frameCountInDeviceFormat > 0);
MA_ASSERT(pFramesInDeviceFormat != NULL);
MA_ASSERT(pRB != NULL);
/* Write to the ring buffer. The ring buffer is in the client format which means we need to convert. */
for (;;) {
ma_uint32 framesToProcessInDeviceFormat = (frameCountInDeviceFormat - totalDeviceFramesProcessed);
ma_uint32 framesToProcessInClientFormat = MA_DATA_CONVERTER_STACK_BUFFER_SIZE / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
ma_uint64 framesProcessedInDeviceFormat;
ma_uint64 framesProcessedInClientFormat;
void* pFramesInClientFormat;
result = ma_pcm_rb_acquire_write(pRB, &framesToProcessInClientFormat, &pFramesInClientFormat);
if (result != MA_SUCCESS) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to acquire capture PCM frames from ring buffer.", result);
break;
}
if (framesToProcessInClientFormat == 0) {
if (ma_pcm_rb_pointer_distance(pRB) == (ma_int32)ma_pcm_rb_get_subbuffer_size(pRB)) {
break; /* Overrun. Not enough room in the ring buffer for input frame. Excess frames are dropped. */
}
}
/* Convert. */
framesProcessedInDeviceFormat = framesToProcessInDeviceFormat;
framesProcessedInClientFormat = framesToProcessInClientFormat;
result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningFramesInDeviceFormat, &framesProcessedInDeviceFormat, pFramesInClientFormat, &framesProcessedInClientFormat);
if (result != MA_SUCCESS) {
break;
}
result = ma_pcm_rb_commit_write(pRB, (ma_uint32)framesProcessedInClientFormat, pFramesInClientFormat); /* Safe cast. */
if (result != MA_SUCCESS) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to commit capture PCM frames to ring buffer.", result);
break;
}
pRunningFramesInDeviceFormat = ma_offset_ptr(pRunningFramesInDeviceFormat, framesProcessedInDeviceFormat * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
totalDeviceFramesProcessed += (ma_uint32)framesProcessedInDeviceFormat; /* Safe cast. */
/* We're done when we're unable to process any client nor device frames. */
if (framesProcessedInClientFormat == 0 && framesProcessedInDeviceFormat == 0) {
break; /* Done. */
}
}
return MA_SUCCESS;
}
static ma_result ma_device__handle_duplex_callback_playback(ma_device* pDevice, ma_uint32 frameCount, void* pFramesInInternalFormat, ma_pcm_rb* pRB)
{
ma_result result;
ma_uint8 playbackFramesInExternalFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint8 silentInputFrames[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 totalFramesToReadFromClient;
ma_uint32 totalFramesReadFromClient;
ma_uint32 totalFramesReadOut = 0;
MA_ASSERT(pDevice != NULL);
MA_ASSERT(frameCount > 0);
MA_ASSERT(pFramesInInternalFormat != NULL);
MA_ASSERT(pRB != NULL);
/*
Sitting in the ring buffer should be captured data from the capture callback in external format. If there's not enough data in there for
the whole frameCount frames we just use silence instead for the input data.
*/
MA_ZERO_MEMORY(silentInputFrames, sizeof(silentInputFrames));
/* We need to calculate how many output frames are required to be read from the client to completely fill frameCount internal frames. */
totalFramesToReadFromClient = (ma_uint32)ma_data_converter_get_required_input_frame_count(&pDevice->playback.converter, frameCount);
totalFramesReadFromClient = 0;
while (totalFramesReadFromClient < totalFramesToReadFromClient && ma_device_is_started(pDevice)) {
ma_uint32 framesRemainingFromClient;
ma_uint32 framesToProcessFromClient;
ma_uint32 inputFrameCount;
void* pInputFrames;
framesRemainingFromClient = (totalFramesToReadFromClient - totalFramesReadFromClient);
framesToProcessFromClient = sizeof(playbackFramesInExternalFormat) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
if (framesToProcessFromClient > framesRemainingFromClient) {
framesToProcessFromClient = framesRemainingFromClient;
}
/* We need to grab captured samples before firing the callback. If there's not enough input samples we just pass silence. */
inputFrameCount = framesToProcessFromClient;
result = ma_pcm_rb_acquire_read(pRB, &inputFrameCount, &pInputFrames);
if (result == MA_SUCCESS) {
if (inputFrameCount > 0) {
/* Use actual input frames. */
ma_device__on_data(pDevice, playbackFramesInExternalFormat, pInputFrames, inputFrameCount);
} else {
if (ma_pcm_rb_pointer_distance(pRB) == 0) {
break; /* Underrun. */
}
}
/* We're done with the captured samples. */
result = ma_pcm_rb_commit_read(pRB, inputFrameCount, pInputFrames);
if (result != MA_SUCCESS) {
break; /* Don't know what to do here... Just abandon ship. */
}
} else {
/* Use silent input frames. */
inputFrameCount = ma_min(
sizeof(playbackFramesInExternalFormat) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels),
sizeof(silentInputFrames) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels)
);
ma_device__on_data(pDevice, playbackFramesInExternalFormat, silentInputFrames, inputFrameCount);
}
/* We have samples in external format so now we need to convert to internal format and output to the device. */
{
ma_uint64 framesConvertedIn = inputFrameCount;
ma_uint64 framesConvertedOut = (frameCount - totalFramesReadOut);
ma_data_converter_process_pcm_frames(&pDevice->playback.converter, playbackFramesInExternalFormat, &framesConvertedIn, pFramesInInternalFormat, &framesConvertedOut);
totalFramesReadFromClient += (ma_uint32)framesConvertedIn; /* Safe cast. */
totalFramesReadOut += (ma_uint32)framesConvertedOut; /* Safe cast. */
pFramesInInternalFormat = ma_offset_ptr(pFramesInInternalFormat, framesConvertedOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
}
}
return MA_SUCCESS;
}
/* A helper for changing the state of the device. */
static MA_INLINE void ma_device__set_state(ma_device* pDevice, ma_uint32 newState)
{
c89atomic_exchange_32(&pDevice->state, newState);
}
#ifdef MA_WIN32
GUID MA_GUID_KSDATAFORMAT_SUBTYPE_PCM = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
GUID MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = {0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
/*GUID MA_GUID_KSDATAFORMAT_SUBTYPE_ALAW = {0x00000006, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};*/
/*GUID MA_GUID_KSDATAFORMAT_SUBTYPE_MULAW = {0x00000007, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};*/
#endif
MA_API ma_uint32 ma_get_format_priority_index(ma_format format) /* Lower = better. */
{
ma_uint32 i;
for (i = 0; i < ma_countof(g_maFormatPriorities); ++i) {
if (g_maFormatPriorities[i] == format) {
return i;
}
}
/* Getting here means the format could not be found or is equal to ma_format_unknown. */
return (ma_uint32)-1;
}
static ma_result ma_device__post_init_setup(ma_device* pDevice, ma_device_type deviceType);
static ma_bool32 ma_device_descriptor_is_valid(const ma_device_descriptor* pDeviceDescriptor)
{
if (pDeviceDescriptor == NULL) {
return MA_FALSE;
}
if (pDeviceDescriptor->format == ma_format_unknown) {
return MA_FALSE;
}
if (pDeviceDescriptor->channels < MA_MIN_CHANNELS || pDeviceDescriptor->channels > MA_MAX_CHANNELS) {
return MA_FALSE;
}
if (pDeviceDescriptor->sampleRate == 0) {
return MA_FALSE;
}
return MA_TRUE;
}
/* TODO: Remove the pCallbacks parameter when we move all backends to the new callbacks system, at which time we can just reference the context directly. */
static ma_result ma_device_audio_thread__default_read_write(ma_device* pDevice, ma_backend_callbacks* pCallbacks)
{
ma_result result = MA_SUCCESS;
ma_bool32 exitLoop = MA_FALSE;
ma_uint8 capturedDeviceData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint8 playbackDeviceData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 capturedDeviceDataCapInFrames = sizeof(capturedDeviceData) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
ma_uint32 playbackDeviceDataCapInFrames = sizeof(playbackDeviceData) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
MA_ASSERT(pDevice != NULL);
/* Just some quick validation on the device type and the available callbacks. */
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
if (pCallbacks->onDeviceRead == NULL) {
return MA_NOT_IMPLEMENTED;
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
if (pCallbacks->onDeviceWrite == NULL) {
return MA_NOT_IMPLEMENTED;
}
}
/* NOTE: The device was started outside of this function, in the worker thread. */
while (ma_device_get_state(pDevice) == MA_STATE_STARTED && !exitLoop) {
switch (pDevice->type) {
case ma_device_type_duplex:
{
/* The process is: onDeviceRead() -> convert -> callback -> convert -> onDeviceWrite() */
ma_uint32 totalCapturedDeviceFramesProcessed = 0;
ma_uint32 capturedDevicePeriodSizeInFrames = ma_min(pDevice->capture.internalPeriodSizeInFrames, pDevice->playback.internalPeriodSizeInFrames);
while (totalCapturedDeviceFramesProcessed < capturedDevicePeriodSizeInFrames) {
ma_uint32 capturedDeviceFramesRemaining;
ma_uint32 capturedDeviceFramesProcessed;
ma_uint32 capturedDeviceFramesToProcess;
ma_uint32 capturedDeviceFramesToTryProcessing = capturedDevicePeriodSizeInFrames - totalCapturedDeviceFramesProcessed;
if (capturedDeviceFramesToTryProcessing > capturedDeviceDataCapInFrames) {
capturedDeviceFramesToTryProcessing = capturedDeviceDataCapInFrames;
}
result = pCallbacks->onDeviceRead(pDevice, capturedDeviceData, capturedDeviceFramesToTryProcessing, &capturedDeviceFramesToProcess);
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
capturedDeviceFramesRemaining = capturedDeviceFramesToProcess;
capturedDeviceFramesProcessed = 0;
/* At this point we have our captured data in device format and we now need to convert it to client format. */
for (;;) {
ma_uint8 capturedClientData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint8 playbackClientData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 capturedClientDataCapInFrames = sizeof(capturedClientData) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
ma_uint32 playbackClientDataCapInFrames = sizeof(playbackClientData) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
ma_uint64 capturedClientFramesToProcessThisIteration = ma_min(capturedClientDataCapInFrames, playbackClientDataCapInFrames);
ma_uint64 capturedDeviceFramesToProcessThisIteration = capturedDeviceFramesRemaining;
ma_uint8* pRunningCapturedDeviceFrames = ma_offset_ptr(capturedDeviceData, capturedDeviceFramesProcessed * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
/* Convert capture data from device format to client format. */
result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningCapturedDeviceFrames, &capturedDeviceFramesToProcessThisIteration, capturedClientData, &capturedClientFramesToProcessThisIteration);
if (result != MA_SUCCESS) {
break;
}
/*
If we weren't able to generate any output frames it must mean we've exhaused all of our input. The only time this would not be the case is if capturedClientData was too small
which should never be the case when it's of the size MA_DATA_CONVERTER_STACK_BUFFER_SIZE.
*/
if (capturedClientFramesToProcessThisIteration == 0) {
break;
}
ma_device__on_data(pDevice, playbackClientData, capturedClientData, (ma_uint32)capturedClientFramesToProcessThisIteration); /* Safe cast .*/
capturedDeviceFramesProcessed += (ma_uint32)capturedDeviceFramesToProcessThisIteration; /* Safe cast. */
capturedDeviceFramesRemaining -= (ma_uint32)capturedDeviceFramesToProcessThisIteration; /* Safe cast. */
/* At this point the playbackClientData buffer should be holding data that needs to be written to the device. */
for (;;) {
ma_uint64 convertedClientFrameCount = capturedClientFramesToProcessThisIteration;
ma_uint64 convertedDeviceFrameCount = playbackDeviceDataCapInFrames;
result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, playbackClientData, &convertedClientFrameCount, playbackDeviceData, &convertedDeviceFrameCount);
if (result != MA_SUCCESS) {
break;
}
result = pCallbacks->onDeviceWrite(pDevice, playbackDeviceData, (ma_uint32)convertedDeviceFrameCount, NULL); /* Safe cast. */
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
capturedClientFramesToProcessThisIteration -= (ma_uint32)convertedClientFrameCount; /* Safe cast. */
if (capturedClientFramesToProcessThisIteration == 0) {
break;
}
}
/* In case an error happened from ma_device_write__null()... */
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
}
totalCapturedDeviceFramesProcessed += capturedDeviceFramesProcessed;
}
} break;
case ma_device_type_capture:
case ma_device_type_loopback:
{
ma_uint32 periodSizeInFrames = pDevice->capture.internalPeriodSizeInFrames;
ma_uint32 framesReadThisPeriod = 0;
while (framesReadThisPeriod < periodSizeInFrames) {
ma_uint32 framesRemainingInPeriod = periodSizeInFrames - framesReadThisPeriod;
ma_uint32 framesProcessed;
ma_uint32 framesToReadThisIteration = framesRemainingInPeriod;
if (framesToReadThisIteration > capturedDeviceDataCapInFrames) {
framesToReadThisIteration = capturedDeviceDataCapInFrames;
}
result = pCallbacks->onDeviceRead(pDevice, capturedDeviceData, framesToReadThisIteration, &framesProcessed);
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
ma_device__send_frames_to_client(pDevice, framesProcessed, capturedDeviceData);
framesReadThisPeriod += framesProcessed;
}
} break;
case ma_device_type_playback:
{
/* We write in chunks of the period size, but use a stack allocated buffer for the intermediary. */
ma_uint32 periodSizeInFrames = pDevice->playback.internalPeriodSizeInFrames;
ma_uint32 framesWrittenThisPeriod = 0;
while (framesWrittenThisPeriod < periodSizeInFrames) {
ma_uint32 framesRemainingInPeriod = periodSizeInFrames - framesWrittenThisPeriod;
ma_uint32 framesProcessed;
ma_uint32 framesToWriteThisIteration = framesRemainingInPeriod;
if (framesToWriteThisIteration > playbackDeviceDataCapInFrames) {
framesToWriteThisIteration = playbackDeviceDataCapInFrames;
}
ma_device__read_frames_from_client(pDevice, framesToWriteThisIteration, playbackDeviceData);
result = pCallbacks->onDeviceWrite(pDevice, playbackDeviceData, framesToWriteThisIteration, &framesProcessed);
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
framesWrittenThisPeriod += framesProcessed;
}
} break;
/* Should never get here. */
default: break;
}
}
return result;
}
/*******************************************************************************
Null Backend
*******************************************************************************/
#ifdef MA_HAS_NULL
#define MA_DEVICE_OP_NONE__NULL 0
#define MA_DEVICE_OP_START__NULL 1
#define MA_DEVICE_OP_SUSPEND__NULL 2
#define MA_DEVICE_OP_KILL__NULL 3
static ma_thread_result MA_THREADCALL ma_device_thread__null(void* pData)
{
ma_device* pDevice = (ma_device*)pData;
MA_ASSERT(pDevice != NULL);
for (;;) { /* Keep the thread alive until the device is uninitialized. */
ma_uint32 operation;
/* Wait for an operation to be requested. */
ma_event_wait(&pDevice->null_device.operationEvent);
/* At this point an event should have been triggered. */
operation = pDevice->null_device.operation;
/* Starting the device needs to put the thread into a loop. */
if (operation == MA_DEVICE_OP_START__NULL) {
/* Reset the timer just in case. */
ma_timer_init(&pDevice->null_device.timer);
/* Getting here means a suspend or kill operation has been requested. */
pDevice->null_device.operationResult = MA_SUCCESS;
ma_event_signal(&pDevice->null_device.operationCompletionEvent);
ma_semaphore_release(&pDevice->null_device.operationSemaphore);
continue;
}
/* Suspending the device means we need to stop the timer and just continue the loop. */
if (operation == MA_DEVICE_OP_SUSPEND__NULL) {
/* We need to add the current run time to the prior run time, then reset the timer. */
pDevice->null_device.priorRunTime += ma_timer_get_time_in_seconds(&pDevice->null_device.timer);
ma_timer_init(&pDevice->null_device.timer);
/* We're done. */
pDevice->null_device.operationResult = MA_SUCCESS;
ma_event_signal(&pDevice->null_device.operationCompletionEvent);
ma_semaphore_release(&pDevice->null_device.operationSemaphore);
continue;
}
/* Killing the device means we need to get out of this loop so that this thread can terminate. */
if (operation == MA_DEVICE_OP_KILL__NULL) {
pDevice->null_device.operationResult = MA_SUCCESS;
ma_event_signal(&pDevice->null_device.operationCompletionEvent);
ma_semaphore_release(&pDevice->null_device.operationSemaphore);
break;
}
/* Getting a signal on a "none" operation probably means an error. Return invalid operation. */
if (operation == MA_DEVICE_OP_NONE__NULL) {
MA_ASSERT(MA_FALSE); /* <-- Trigger this in debug mode to ensure developers are aware they're doing something wrong (or there's a bug in a miniaudio). */
pDevice->null_device.operationResult = MA_INVALID_OPERATION;
ma_event_signal(&pDevice->null_device.operationCompletionEvent);
ma_semaphore_release(&pDevice->null_device.operationSemaphore);
continue; /* Continue the loop. Don't terminate. */
}
}
return (ma_thread_result)0;
}
static ma_result ma_device_do_operation__null(ma_device* pDevice, ma_uint32 operation)
{
ma_result result;
/*
TODO: Need to review this and consider just using mutual exclusion. I think the original motivation
for this was to just post the event to a queue and return immediately, but that has since changed
and now this function is synchronous. I think this can be simplified to just use a mutex.
*/
/*
The first thing to do is wait for an operation slot to become available. We only have a single slot for this, but we could extend this later
to support queing of operations.
*/
result = ma_semaphore_wait(&pDevice->null_device.operationSemaphore);
if (result != MA_SUCCESS) {
return result; /* Failed to wait for the event. */
}
/*
When we get here it means the background thread is not referencing the operation code and it can be changed. After changing this we need to
signal an event to the worker thread to let it know that it can start work.
*/
pDevice->null_device.operation = operation;
/* Once the operation code has been set, the worker thread can start work. */
if (ma_event_signal(&pDevice->null_device.operationEvent) != MA_SUCCESS) {
return MA_ERROR;
}
/* We want everything to be synchronous so we're going to wait for the worker thread to complete it's operation. */
if (ma_event_wait(&pDevice->null_device.operationCompletionEvent) != MA_SUCCESS) {
return MA_ERROR;
}
return pDevice->null_device.operationResult;
}
static ma_uint64 ma_device_get_total_run_time_in_frames__null(ma_device* pDevice)
{
ma_uint32 internalSampleRate;
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
internalSampleRate = pDevice->capture.internalSampleRate;
} else {
internalSampleRate = pDevice->playback.internalSampleRate;
}
return (ma_uint64)((pDevice->null_device.priorRunTime + ma_timer_get_time_in_seconds(&pDevice->null_device.timer)) * internalSampleRate);
}
static ma_result ma_context_enumerate_devices__null(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
{
ma_bool32 cbResult = MA_TRUE;
MA_ASSERT(pContext != NULL);
MA_ASSERT(callback != NULL);
/* Playback. */
if (cbResult) {
ma_device_info deviceInfo;
MA_ZERO_OBJECT(&deviceInfo);
ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), "NULL Playback Device", (size_t)-1);
cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
}
/* Capture. */
if (cbResult) {
ma_device_info deviceInfo;
MA_ZERO_OBJECT(&deviceInfo);
ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), "NULL Capture Device", (size_t)-1);
cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
}
(void)cbResult; /* Silence a static analysis warning. */
return MA_SUCCESS;
}
static ma_result ma_context_get_device_info__null(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
{
MA_ASSERT(pContext != NULL);
if (pDeviceID != NULL && pDeviceID->nullbackend != 0) {
return MA_NO_DEVICE; /* Don't know the device. */
}
/* Name / Description */
if (deviceType == ma_device_type_playback) {
ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Playback Device", (size_t)-1);
} else {
ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Capture Device", (size_t)-1);
}
/* Support everything on the null backend. */
pDeviceInfo->nativeDataFormats[0].format = ma_format_unknown;
pDeviceInfo->nativeDataFormats[0].channels = 0;
pDeviceInfo->nativeDataFormats[0].sampleRate = 0;
pDeviceInfo->nativeDataFormats[0].flags = 0;
pDeviceInfo->nativeDataFormatCount = 1;
(void)pContext;
return MA_SUCCESS;
}
static ma_result ma_device_uninit__null(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
/* Keep it clean and wait for the device thread to finish before returning. */
ma_device_do_operation__null(pDevice, MA_DEVICE_OP_KILL__NULL);
/* Wait for the thread to finish before continuing. */
ma_thread_wait(&pDevice->null_device.deviceThread);
/* At this point the loop in the device thread is as good as terminated so we can uninitialize our events. */
ma_semaphore_uninit(&pDevice->null_device.operationSemaphore);
ma_event_uninit(&pDevice->null_device.operationCompletionEvent);
ma_event_uninit(&pDevice->null_device.operationEvent);
return MA_SUCCESS;
}
static ma_uint32 ma_calculate_buffer_size_in_frames__null(const ma_device_config* pConfig, const ma_device_descriptor* pDescriptor)
{
if (pDescriptor->periodSizeInFrames == 0) {
if (pDescriptor->periodSizeInMilliseconds == 0) {
if (pConfig->performanceProfile == ma_performance_profile_low_latency) {
return ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, pDescriptor->sampleRate);
} else {
return ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, pDescriptor->sampleRate);
}
} else {
return ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, pDescriptor->sampleRate);
}
} else {
return pDescriptor->periodSizeInFrames;
}
}
static ma_result ma_device_init__null(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
{
ma_result result;
MA_ASSERT(pDevice != NULL);
MA_ZERO_OBJECT(&pDevice->null_device);
if (pConfig->deviceType == ma_device_type_loopback) {
return MA_DEVICE_TYPE_NOT_SUPPORTED;
}
/* The null backend supports everything exactly as we specify it. */
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
pDescriptorCapture->format = (pDescriptorCapture->format != ma_format_unknown) ? pDescriptorCapture->format : MA_DEFAULT_FORMAT;
pDescriptorCapture->channels = (pDescriptorCapture->channels != 0) ? pDescriptorCapture->channels : MA_DEFAULT_CHANNELS;
pDescriptorCapture->sampleRate = (pDescriptorCapture->sampleRate != 0) ? pDescriptorCapture->sampleRate : MA_DEFAULT_SAMPLE_RATE;
if (pDescriptorCapture->channelMap[0] == MA_CHANNEL_NONE) {
ma_get_standard_channel_map(ma_standard_channel_map_default, pDescriptorCapture->channels, pDescriptorCapture->channelMap);
}
pDescriptorCapture->periodSizeInFrames = ma_calculate_buffer_size_in_frames__null(pConfig, pDescriptorCapture);
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
pDescriptorPlayback->format = (pDescriptorPlayback->format != ma_format_unknown) ? pDescriptorPlayback->format : MA_DEFAULT_FORMAT;
pDescriptorPlayback->channels = (pDescriptorPlayback->channels != 0) ? pDescriptorPlayback->channels : MA_DEFAULT_CHANNELS;
pDescriptorPlayback->sampleRate = (pDescriptorPlayback->sampleRate != 0) ? pDescriptorPlayback->sampleRate : MA_DEFAULT_SAMPLE_RATE;
if (pDescriptorPlayback->channelMap[0] == MA_CHANNEL_NONE) {
ma_get_standard_channel_map(ma_standard_channel_map_default, pDescriptorPlayback->channels, pDescriptorPlayback->channelMap);
}
pDescriptorPlayback->periodSizeInFrames = ma_calculate_buffer_size_in_frames__null(pConfig, pDescriptorPlayback);
}
/*
In order to get timing right, we need to create a thread that does nothing but keeps track of the timer. This timer is started when the
first period is "written" to it, and then stopped in ma_device_stop__null().
*/
result = ma_event_init(&pDevice->null_device.operationEvent);
if (result != MA_SUCCESS) {
return result;
}
result = ma_event_init(&pDevice->null_device.operationCompletionEvent);
if (result != MA_SUCCESS) {
return result;
}
result = ma_semaphore_init(1, &pDevice->null_device.operationSemaphore); /* <-- It's important that the initial value is set to 1. */
if (result != MA_SUCCESS) {
return result;
}
result = ma_thread_create(&pDevice->null_device.deviceThread, pDevice->pContext->threadPriority, 0, ma_device_thread__null, pDevice);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
static ma_result ma_device_start__null(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
ma_device_do_operation__null(pDevice, MA_DEVICE_OP_START__NULL);
c89atomic_exchange_8(&pDevice->null_device.isStarted, MA_TRUE);
return MA_SUCCESS;
}
static ma_result ma_device_stop__null(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
ma_device_do_operation__null(pDevice, MA_DEVICE_OP_SUSPEND__NULL);
c89atomic_exchange_8(&pDevice->null_device.isStarted, MA_FALSE);
return MA_SUCCESS;
}
static ma_result ma_device_write__null(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
{
ma_result result = MA_SUCCESS;
ma_uint32 totalPCMFramesProcessed;
ma_bool32 wasStartedOnEntry;
if (pFramesWritten != NULL) {
*pFramesWritten = 0;
}
wasStartedOnEntry = c89atomic_load_8(&pDevice->null_device.isStarted);
/* Keep going until everything has been read. */
totalPCMFramesProcessed = 0;
while (totalPCMFramesProcessed < frameCount) {
ma_uint64 targetFrame;
/* If there are any frames remaining in the current period, consume those first. */
if (pDevice->null_device.currentPeriodFramesRemainingPlayback > 0) {
ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed);
ma_uint32 framesToProcess = pDevice->null_device.currentPeriodFramesRemainingPlayback;
if (framesToProcess > framesRemaining) {
framesToProcess = framesRemaining;
}
/* We don't actually do anything with pPCMFrames, so just mark it as unused to prevent a warning. */
(void)pPCMFrames;
pDevice->null_device.currentPeriodFramesRemainingPlayback -= framesToProcess;
totalPCMFramesProcessed += framesToProcess;
}
/* If we've consumed the current period we'll need to mark it as such an ensure the device is started if it's not already. */
if (pDevice->null_device.currentPeriodFramesRemainingPlayback == 0) {
pDevice->null_device.currentPeriodFramesRemainingPlayback = 0;
if (!c89atomic_load_8(&pDevice->null_device.isStarted) && !wasStartedOnEntry) {
result = ma_device_start__null(pDevice);
if (result != MA_SUCCESS) {
break;
}
}
}
/* If we've consumed the whole buffer we can return now. */
MA_ASSERT(totalPCMFramesProcessed <= frameCount);
if (totalPCMFramesProcessed == frameCount) {
break;
}
/* Getting here means we've still got more frames to consume, we but need to wait for it to become available. */
targetFrame = pDevice->null_device.lastProcessedFramePlayback;
for (;;) {
ma_uint64 currentFrame;
/* Stop waiting if the device has been stopped. */
if (!c89atomic_load_8(&pDevice->null_device.isStarted)) {
break;
}
currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice);
if (currentFrame >= targetFrame) {
break;
}
/* Getting here means we haven't yet reached the target sample, so continue waiting. */
ma_sleep(10);
}
pDevice->null_device.lastProcessedFramePlayback += pDevice->playback.internalPeriodSizeInFrames;
pDevice->null_device.currentPeriodFramesRemainingPlayback = pDevice->playback.internalPeriodSizeInFrames;
}
if (pFramesWritten != NULL) {
*pFramesWritten = totalPCMFramesProcessed;
}
return result;
}
static ma_result ma_device_read__null(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
{
ma_result result = MA_SUCCESS;
ma_uint32 totalPCMFramesProcessed;
if (pFramesRead != NULL) {
*pFramesRead = 0;
}
/* Keep going until everything has been read. */
totalPCMFramesProcessed = 0;
while (totalPCMFramesProcessed < frameCount) {
ma_uint64 targetFrame;
/* If there are any frames remaining in the current period, consume those first. */
if (pDevice->null_device.currentPeriodFramesRemainingCapture > 0) {
ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed);
ma_uint32 framesToProcess = pDevice->null_device.currentPeriodFramesRemainingCapture;
if (framesToProcess > framesRemaining) {
framesToProcess = framesRemaining;
}
/* We need to ensure the output buffer is zeroed. */
MA_ZERO_MEMORY(ma_offset_ptr(pPCMFrames, totalPCMFramesProcessed*bpf), framesToProcess*bpf);
pDevice->null_device.currentPeriodFramesRemainingCapture -= framesToProcess;
totalPCMFramesProcessed += framesToProcess;
}
/* If we've consumed the current period we'll need to mark it as such an ensure the device is started if it's not already. */
if (pDevice->null_device.currentPeriodFramesRemainingCapture == 0) {
pDevice->null_device.currentPeriodFramesRemainingCapture = 0;
}
/* If we've consumed the whole buffer we can return now. */
MA_ASSERT(totalPCMFramesProcessed <= frameCount);
if (totalPCMFramesProcessed == frameCount) {
break;
}
/* Getting here means we've still got more frames to consume, we but need to wait for it to become available. */
targetFrame = pDevice->null_device.lastProcessedFrameCapture + pDevice->capture.internalPeriodSizeInFrames;
for (;;) {
ma_uint64 currentFrame;
/* Stop waiting if the device has been stopped. */
if (!c89atomic_load_8(&pDevice->null_device.isStarted)) {
break;
}
currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice);
if (currentFrame >= targetFrame) {
break;
}
/* Getting here means we haven't yet reached the target sample, so continue waiting. */
ma_sleep(10);
}
pDevice->null_device.lastProcessedFrameCapture += pDevice->capture.internalPeriodSizeInFrames;
pDevice->null_device.currentPeriodFramesRemainingCapture = pDevice->capture.internalPeriodSizeInFrames;
}
if (pFramesRead != NULL) {
*pFramesRead = totalPCMFramesProcessed;
}
return result;
}
static ma_result ma_context_uninit__null(ma_context* pContext)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pContext->backend == ma_backend_null);
(void)pContext;
return MA_SUCCESS;
}
static ma_result ma_context_init__null(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
{
MA_ASSERT(pContext != NULL);
(void)pConfig;
(void)pContext;
pCallbacks->onContextInit = ma_context_init__null;
pCallbacks->onContextUninit = ma_context_uninit__null;
pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__null;
pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__null;
pCallbacks->onDeviceInit = ma_device_init__null;
pCallbacks->onDeviceUninit = ma_device_uninit__null;
pCallbacks->onDeviceStart = ma_device_start__null;
pCallbacks->onDeviceStop = ma_device_stop__null;
pCallbacks->onDeviceRead = ma_device_read__null;
pCallbacks->onDeviceWrite = ma_device_write__null;
pCallbacks->onDeviceAudioThread = NULL; /* Our backend is asynchronous with a blocking read-write API which means we can get miniaudio to deal with the audio thread. */
/* The null backend always works. */
return MA_SUCCESS;
}
#endif
/*******************************************************************************
WIN32 COMMON
*******************************************************************************/
#if defined(MA_WIN32)
#if defined(MA_WIN32_DESKTOP)
#define ma_CoInitializeEx(pContext, pvReserved, dwCoInit) ((MA_PFN_CoInitializeEx)pContext->win32.CoInitializeEx)(pvReserved, dwCoInit)
#define ma_CoUninitialize(pContext) ((MA_PFN_CoUninitialize)pContext->win32.CoUninitialize)()
#define ma_CoCreateInstance(pContext, rclsid, pUnkOuter, dwClsContext, riid, ppv) ((MA_PFN_CoCreateInstance)pContext->win32.CoCreateInstance)(rclsid, pUnkOuter, dwClsContext, riid, ppv)
#define ma_CoTaskMemFree(pContext, pv) ((MA_PFN_CoTaskMemFree)pContext->win32.CoTaskMemFree)(pv)
#define ma_PropVariantClear(pContext, pvar) ((MA_PFN_PropVariantClear)pContext->win32.PropVariantClear)(pvar)
#else
#define ma_CoInitializeEx(pContext, pvReserved, dwCoInit) CoInitializeEx(pvReserved, dwCoInit)
#define ma_CoUninitialize(pContext) CoUninitialize()
#define ma_CoCreateInstance(pContext, rclsid, pUnkOuter, dwClsContext, riid, ppv) CoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, ppv)
#define ma_CoTaskMemFree(pContext, pv) CoTaskMemFree(pv)
#define ma_PropVariantClear(pContext, pvar) PropVariantClear(pvar)
#endif
#if !defined(MAXULONG_PTR) && !defined(__WATCOMC__)
typedef size_t DWORD_PTR;
#endif
#if !defined(WAVE_FORMAT_44M08)
#define WAVE_FORMAT_44M08 0x00000100
#define WAVE_FORMAT_44S08 0x00000200
#define WAVE_FORMAT_44M16 0x00000400
#define WAVE_FORMAT_44S16 0x00000800
#define WAVE_FORMAT_48M08 0x00001000
#define WAVE_FORMAT_48S08 0x00002000
#define WAVE_FORMAT_48M16 0x00004000
#define WAVE_FORMAT_48S16 0x00008000
#define WAVE_FORMAT_96M08 0x00010000
#define WAVE_FORMAT_96S08 0x00020000
#define WAVE_FORMAT_96M16 0x00040000
#define WAVE_FORMAT_96S16 0x00080000
#endif
#ifndef SPEAKER_FRONT_LEFT
#define SPEAKER_FRONT_LEFT 0x1
#define SPEAKER_FRONT_RIGHT 0x2
#define SPEAKER_FRONT_CENTER 0x4
#define SPEAKER_LOW_FREQUENCY 0x8
#define SPEAKER_BACK_LEFT 0x10
#define SPEAKER_BACK_RIGHT 0x20
#define SPEAKER_FRONT_LEFT_OF_CENTER 0x40
#define SPEAKER_FRONT_RIGHT_OF_CENTER 0x80
#define SPEAKER_BACK_CENTER 0x100
#define SPEAKER_SIDE_LEFT 0x200
#define SPEAKER_SIDE_RIGHT 0x400
#define SPEAKER_TOP_CENTER 0x800
#define SPEAKER_TOP_FRONT_LEFT 0x1000
#define SPEAKER_TOP_FRONT_CENTER 0x2000
#define SPEAKER_TOP_FRONT_RIGHT 0x4000
#define SPEAKER_TOP_BACK_LEFT 0x8000
#define SPEAKER_TOP_BACK_CENTER 0x10000
#define SPEAKER_TOP_BACK_RIGHT 0x20000
#endif
/*
The SDK that comes with old versions of MSVC (VC6, for example) does not appear to define WAVEFORMATEXTENSIBLE. We
define our own implementation in this case.
*/
#if (defined(_MSC_VER) && !defined(_WAVEFORMATEXTENSIBLE_)) || defined(__DMC__)
typedef struct
{
WAVEFORMATEX Format;
union
{
WORD wValidBitsPerSample;
WORD wSamplesPerBlock;
WORD wReserved;
} Samples;
DWORD dwChannelMask;
GUID SubFormat;
} WAVEFORMATEXTENSIBLE;
#endif
#ifndef WAVE_FORMAT_EXTENSIBLE
#define WAVE_FORMAT_EXTENSIBLE 0xFFFE
#endif
#ifndef WAVE_FORMAT_IEEE_FLOAT
#define WAVE_FORMAT_IEEE_FLOAT 0x0003
#endif
/* Converts an individual Win32-style channel identifier (SPEAKER_FRONT_LEFT, etc.) to miniaudio. */
static ma_uint8 ma_channel_id_to_ma__win32(DWORD id)
{
switch (id)
{
case SPEAKER_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT;
case SPEAKER_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT;
case SPEAKER_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER;
case SPEAKER_LOW_FREQUENCY: return MA_CHANNEL_LFE;
case SPEAKER_BACK_LEFT: return MA_CHANNEL_BACK_LEFT;
case SPEAKER_BACK_RIGHT: return MA_CHANNEL_BACK_RIGHT;
case SPEAKER_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER;
case SPEAKER_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER;
case SPEAKER_BACK_CENTER: return MA_CHANNEL_BACK_CENTER;
case SPEAKER_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT;
case SPEAKER_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT;
case SPEAKER_TOP_CENTER: return MA_CHANNEL_TOP_CENTER;
case SPEAKER_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT;
case SPEAKER_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER;
case SPEAKER_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT;
case SPEAKER_TOP_BACK_LEFT: return MA_CHANNEL_TOP_BACK_LEFT;
case SPEAKER_TOP_BACK_CENTER: return MA_CHANNEL_TOP_BACK_CENTER;
case SPEAKER_TOP_BACK_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT;
default: return 0;
}
}
/* Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to Win32-style. */
static DWORD ma_channel_id_to_win32(DWORD id)
{
switch (id)
{
case MA_CHANNEL_MONO: return SPEAKER_FRONT_CENTER;
case MA_CHANNEL_FRONT_LEFT: return SPEAKER_FRONT_LEFT;
case MA_CHANNEL_FRONT_RIGHT: return SPEAKER_FRONT_RIGHT;
case MA_CHANNEL_FRONT_CENTER: return SPEAKER_FRONT_CENTER;
case MA_CHANNEL_LFE: return SPEAKER_LOW_FREQUENCY;
case MA_CHANNEL_BACK_LEFT: return SPEAKER_BACK_LEFT;
case MA_CHANNEL_BACK_RIGHT: return SPEAKER_BACK_RIGHT;
case MA_CHANNEL_FRONT_LEFT_CENTER: return SPEAKER_FRONT_LEFT_OF_CENTER;
case MA_CHANNEL_FRONT_RIGHT_CENTER: return SPEAKER_FRONT_RIGHT_OF_CENTER;
case MA_CHANNEL_BACK_CENTER: return SPEAKER_BACK_CENTER;
case MA_CHANNEL_SIDE_LEFT: return SPEAKER_SIDE_LEFT;
case MA_CHANNEL_SIDE_RIGHT: return SPEAKER_SIDE_RIGHT;
case MA_CHANNEL_TOP_CENTER: return SPEAKER_TOP_CENTER;
case MA_CHANNEL_TOP_FRONT_LEFT: return SPEAKER_TOP_FRONT_LEFT;
case MA_CHANNEL_TOP_FRONT_CENTER: return SPEAKER_TOP_FRONT_CENTER;
case MA_CHANNEL_TOP_FRONT_RIGHT: return SPEAKER_TOP_FRONT_RIGHT;
case MA_CHANNEL_TOP_BACK_LEFT: return SPEAKER_TOP_BACK_LEFT;
case MA_CHANNEL_TOP_BACK_CENTER: return SPEAKER_TOP_BACK_CENTER;
case MA_CHANNEL_TOP_BACK_RIGHT: return SPEAKER_TOP_BACK_RIGHT;
default: return 0;
}
}
/* Converts a channel mapping to a Win32-style channel mask. */
static DWORD ma_channel_map_to_channel_mask__win32(const ma_channel* pChannelMap, ma_uint32 channels)
{
DWORD dwChannelMask = 0;
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; ++iChannel) {
dwChannelMask |= ma_channel_id_to_win32(pChannelMap[iChannel]);
}
return dwChannelMask;
}
/* Converts a Win32-style channel mask to a miniaudio channel map. */
static void ma_channel_mask_to_channel_map__win32(DWORD dwChannelMask, ma_uint32 channels, ma_channel* pChannelMap)
{
if (channels == 1 && dwChannelMask == 0) {
pChannelMap[0] = MA_CHANNEL_MONO;
} else if (channels == 2 && dwChannelMask == 0) {
pChannelMap[0] = MA_CHANNEL_FRONT_LEFT;
pChannelMap[1] = MA_CHANNEL_FRONT_RIGHT;
} else {
if (channels == 1 && (dwChannelMask & SPEAKER_FRONT_CENTER) != 0) {
pChannelMap[0] = MA_CHANNEL_MONO;
} else {
/* Just iterate over each bit. */
ma_uint32 iChannel = 0;
ma_uint32 iBit;
for (iBit = 0; iBit < 32 && iChannel < channels; ++iBit) {
DWORD bitValue = (dwChannelMask & (1UL << iBit));
if (bitValue != 0) {
/* The bit is set. */
pChannelMap[iChannel] = ma_channel_id_to_ma__win32(bitValue);
iChannel += 1;
}
}
}
}
}
#ifdef __cplusplus
static ma_bool32 ma_is_guid_equal(const void* a, const void* b)
{
return IsEqualGUID(*(const GUID*)a, *(const GUID*)b);
}
#else
#define ma_is_guid_equal(a, b) IsEqualGUID((const GUID*)a, (const GUID*)b)
#endif
static MA_INLINE ma_bool32 ma_is_guid_null(const void* guid)
{
static GUID nullguid = {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
return ma_is_guid_equal(guid, &nullguid);
}
static ma_format ma_format_from_WAVEFORMATEX(const WAVEFORMATEX* pWF)
{
MA_ASSERT(pWF != NULL);
if (pWF->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
const WAVEFORMATEXTENSIBLE* pWFEX = (const WAVEFORMATEXTENSIBLE*)pWF;
if (ma_is_guid_equal(&pWFEX->SubFormat, &MA_GUID_KSDATAFORMAT_SUBTYPE_PCM)) {
if (pWFEX->Samples.wValidBitsPerSample == 32) {
return ma_format_s32;
}
if (pWFEX->Samples.wValidBitsPerSample == 24) {
if (pWFEX->Format.wBitsPerSample == 32) {
/*return ma_format_s24_32;*/
}
if (pWFEX->Format.wBitsPerSample == 24) {
return ma_format_s24;
}
}
if (pWFEX->Samples.wValidBitsPerSample == 16) {
return ma_format_s16;
}
if (pWFEX->Samples.wValidBitsPerSample == 8) {
return ma_format_u8;
}
}
if (ma_is_guid_equal(&pWFEX->SubFormat, &MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
if (pWFEX->Samples.wValidBitsPerSample == 32) {
return ma_format_f32;
}
/*
if (pWFEX->Samples.wValidBitsPerSample == 64) {
return ma_format_f64;
}
*/
}
} else {
if (pWF->wFormatTag == WAVE_FORMAT_PCM) {
if (pWF->wBitsPerSample == 32) {
return ma_format_s32;
}
if (pWF->wBitsPerSample == 24) {
return ma_format_s24;
}
if (pWF->wBitsPerSample == 16) {
return ma_format_s16;
}
if (pWF->wBitsPerSample == 8) {
return ma_format_u8;
}
}
if (pWF->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
if (pWF->wBitsPerSample == 32) {
return ma_format_f32;
}
if (pWF->wBitsPerSample == 64) {
/*return ma_format_f64;*/
}
}
}
return ma_format_unknown;
}
#endif
/*******************************************************************************
WASAPI Backend
*******************************************************************************/
#ifdef MA_HAS_WASAPI
#if 0
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4091) /* 'typedef ': ignored on left of '' when no variable is declared */
#endif
#include
#include
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#endif /* 0 */
/* Some compilers don't define VerifyVersionInfoW. Need to write this ourselves. */
#define MA_WIN32_WINNT_VISTA 0x0600
#define MA_VER_MINORVERSION 0x01
#define MA_VER_MAJORVERSION 0x02
#define MA_VER_SERVICEPACKMAJOR 0x20
#define MA_VER_GREATER_EQUAL 0x03
typedef struct {
DWORD dwOSVersionInfoSize;
DWORD dwMajorVersion;
DWORD dwMinorVersion;
DWORD dwBuildNumber;
DWORD dwPlatformId;
WCHAR szCSDVersion[128];
WORD wServicePackMajor;
WORD wServicePackMinor;
WORD wSuiteMask;
BYTE wProductType;
BYTE wReserved;
} ma_OSVERSIONINFOEXW;
typedef BOOL (WINAPI * ma_PFNVerifyVersionInfoW) (ma_OSVERSIONINFOEXW* lpVersionInfo, DWORD dwTypeMask, DWORDLONG dwlConditionMask);
typedef ULONGLONG (WINAPI * ma_PFNVerSetConditionMask)(ULONGLONG dwlConditionMask, DWORD dwTypeBitMask, BYTE dwConditionMask);
#ifndef PROPERTYKEY_DEFINED
#define PROPERTYKEY_DEFINED
#ifndef __WATCOMC__
typedef struct
{
GUID fmtid;
DWORD pid;
} PROPERTYKEY;
#endif
#endif
/* Some compilers don't define PropVariantInit(). We just do this ourselves since it's just a memset(). */
static MA_INLINE void ma_PropVariantInit(PROPVARIANT* pProp)
{
MA_ZERO_OBJECT(pProp);
}
static const PROPERTYKEY MA_PKEY_Device_FriendlyName = {{0xA45C254E, 0xDF1C, 0x4EFD, {0x80, 0x20, 0x67, 0xD1, 0x46, 0xA8, 0x50, 0xE0}}, 14};
static const PROPERTYKEY MA_PKEY_AudioEngine_DeviceFormat = {{0xF19F064D, 0x82C, 0x4E27, {0xBC, 0x73, 0x68, 0x82, 0xA1, 0xBB, 0x8E, 0x4C}}, 0};
static const IID MA_IID_IUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; /* 00000000-0000-0000-C000-000000000046 */
#ifndef MA_WIN32_DESKTOP
static const IID MA_IID_IAgileObject = {0x94EA2B94, 0xE9CC, 0x49E0, {0xC0, 0xFF, 0xEE, 0x64, 0xCA, 0x8F, 0x5B, 0x90}}; /* 94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90 */
#endif
static const IID MA_IID_IAudioClient = {0x1CB9AD4C, 0xDBFA, 0x4C32, {0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2}}; /* 1CB9AD4C-DBFA-4C32-B178-C2F568A703B2 = __uuidof(IAudioClient) */
static const IID MA_IID_IAudioClient2 = {0x726778CD, 0xF60A, 0x4EDA, {0x82, 0xDE, 0xE4, 0x76, 0x10, 0xCD, 0x78, 0xAA}}; /* 726778CD-F60A-4EDA-82DE-E47610CD78AA = __uuidof(IAudioClient2) */
static const IID MA_IID_IAudioClient3 = {0x7ED4EE07, 0x8E67, 0x4CD4, {0x8C, 0x1A, 0x2B, 0x7A, 0x59, 0x87, 0xAD, 0x42}}; /* 7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42 = __uuidof(IAudioClient3) */
static const IID MA_IID_IAudioRenderClient = {0xF294ACFC, 0x3146, 0x4483, {0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2}}; /* F294ACFC-3146-4483-A7BF-ADDCA7C260E2 = __uuidof(IAudioRenderClient) */
static const IID MA_IID_IAudioCaptureClient = {0xC8ADBD64, 0xE71E, 0x48A0, {0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17}}; /* C8ADBD64-E71E-48A0-A4DE-185C395CD317 = __uuidof(IAudioCaptureClient) */
static const IID MA_IID_IMMNotificationClient = {0x7991EEC9, 0x7E89, 0x4D85, {0x83, 0x90, 0x6C, 0x70, 0x3C, 0xEC, 0x60, 0xC0}}; /* 7991EEC9-7E89-4D85-8390-6C703CEC60C0 = __uuidof(IMMNotificationClient) */
#ifndef MA_WIN32_DESKTOP
static const IID MA_IID_DEVINTERFACE_AUDIO_RENDER = {0xE6327CAD, 0xDCEC, 0x4949, {0xAE, 0x8A, 0x99, 0x1E, 0x97, 0x6A, 0x79, 0xD2}}; /* E6327CAD-DCEC-4949-AE8A-991E976A79D2 */
static const IID MA_IID_DEVINTERFACE_AUDIO_CAPTURE = {0x2EEF81BE, 0x33FA, 0x4800, {0x96, 0x70, 0x1C, 0xD4, 0x74, 0x97, 0x2C, 0x3F}}; /* 2EEF81BE-33FA-4800-9670-1CD474972C3F */
static const IID MA_IID_IActivateAudioInterfaceCompletionHandler = {0x41D949AB, 0x9862, 0x444A, {0x80, 0xF6, 0xC2, 0x61, 0x33, 0x4D, 0xA5, 0xEB}}; /* 41D949AB-9862-444A-80F6-C261334DA5EB */
#endif
static const IID MA_CLSID_MMDeviceEnumerator_Instance = {0xBCDE0395, 0xE52F, 0x467C, {0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}}; /* BCDE0395-E52F-467C-8E3D-C4579291692E = __uuidof(MMDeviceEnumerator) */
static const IID MA_IID_IMMDeviceEnumerator_Instance = {0xA95664D2, 0x9614, 0x4F35, {0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6}}; /* A95664D2-9614-4F35-A746-DE8DB63617E6 = __uuidof(IMMDeviceEnumerator) */
#ifdef __cplusplus
#define MA_CLSID_MMDeviceEnumerator MA_CLSID_MMDeviceEnumerator_Instance
#define MA_IID_IMMDeviceEnumerator MA_IID_IMMDeviceEnumerator_Instance
#else
#define MA_CLSID_MMDeviceEnumerator &MA_CLSID_MMDeviceEnumerator_Instance
#define MA_IID_IMMDeviceEnumerator &MA_IID_IMMDeviceEnumerator_Instance
#endif
typedef struct ma_IUnknown ma_IUnknown;
#ifdef MA_WIN32_DESKTOP
#define MA_MM_DEVICE_STATE_ACTIVE 1
#define MA_MM_DEVICE_STATE_DISABLED 2
#define MA_MM_DEVICE_STATE_NOTPRESENT 4
#define MA_MM_DEVICE_STATE_UNPLUGGED 8
typedef struct ma_IMMDeviceEnumerator ma_IMMDeviceEnumerator;
typedef struct ma_IMMDeviceCollection ma_IMMDeviceCollection;
typedef struct ma_IMMDevice ma_IMMDevice;
#else
typedef struct ma_IActivateAudioInterfaceCompletionHandler ma_IActivateAudioInterfaceCompletionHandler;
typedef struct ma_IActivateAudioInterfaceAsyncOperation ma_IActivateAudioInterfaceAsyncOperation;
#endif
typedef struct ma_IPropertyStore ma_IPropertyStore;
typedef struct ma_IAudioClient ma_IAudioClient;
typedef struct ma_IAudioClient2 ma_IAudioClient2;
typedef struct ma_IAudioClient3 ma_IAudioClient3;
typedef struct ma_IAudioRenderClient ma_IAudioRenderClient;
typedef struct ma_IAudioCaptureClient ma_IAudioCaptureClient;
typedef ma_int64 MA_REFERENCE_TIME;
#define MA_AUDCLNT_STREAMFLAGS_CROSSPROCESS 0x00010000
#define MA_AUDCLNT_STREAMFLAGS_LOOPBACK 0x00020000
#define MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK 0x00040000
#define MA_AUDCLNT_STREAMFLAGS_NOPERSIST 0x00080000
#define MA_AUDCLNT_STREAMFLAGS_RATEADJUST 0x00100000
#define MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000
#define MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000
#define MA_AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED 0x10000000
#define MA_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE 0x20000000
#define MA_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED 0x40000000
/* Buffer flags. */
#define MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY 1
#define MA_AUDCLNT_BUFFERFLAGS_SILENT 2
#define MA_AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR 4
typedef enum
{
ma_eRender = 0,
ma_eCapture = 1,
ma_eAll = 2
} ma_EDataFlow;
typedef enum
{
ma_eConsole = 0,
ma_eMultimedia = 1,
ma_eCommunications = 2
} ma_ERole;
typedef enum
{
MA_AUDCLNT_SHAREMODE_SHARED,
MA_AUDCLNT_SHAREMODE_EXCLUSIVE
} MA_AUDCLNT_SHAREMODE;
typedef enum
{
MA_AudioCategory_Other = 0 /* <-- miniaudio is only caring about Other. */
} MA_AUDIO_STREAM_CATEGORY;
typedef struct
{
ma_uint32 cbSize;
BOOL bIsOffload;
MA_AUDIO_STREAM_CATEGORY eCategory;
} ma_AudioClientProperties;
/* IUnknown */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IUnknown* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IUnknown* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IUnknown* pThis);
} ma_IUnknownVtbl;
struct ma_IUnknown
{
ma_IUnknownVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IUnknown_QueryInterface(ma_IUnknown* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IUnknown_AddRef(ma_IUnknown* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IUnknown_Release(ma_IUnknown* pThis) { return pThis->lpVtbl->Release(pThis); }
#ifdef MA_WIN32_DESKTOP
/* IMMNotificationClient */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMNotificationClient* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMNotificationClient* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IMMNotificationClient* pThis);
/* IMMNotificationClient */
HRESULT (STDMETHODCALLTYPE * OnDeviceStateChanged) (ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, DWORD dwNewState);
HRESULT (STDMETHODCALLTYPE * OnDeviceAdded) (ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID);
HRESULT (STDMETHODCALLTYPE * OnDeviceRemoved) (ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID);
HRESULT (STDMETHODCALLTYPE * OnDefaultDeviceChanged)(ma_IMMNotificationClient* pThis, ma_EDataFlow dataFlow, ma_ERole role, LPCWSTR pDefaultDeviceID);
HRESULT (STDMETHODCALLTYPE * OnPropertyValueChanged)(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, const PROPERTYKEY key);
} ma_IMMNotificationClientVtbl;
/* IMMDeviceEnumerator */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDeviceEnumerator* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDeviceEnumerator* pThis);
/* IMMDeviceEnumerator */
HRESULT (STDMETHODCALLTYPE * EnumAudioEndpoints) (ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, DWORD dwStateMask, ma_IMMDeviceCollection** ppDevices);
HRESULT (STDMETHODCALLTYPE * GetDefaultAudioEndpoint) (ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, ma_ERole role, ma_IMMDevice** ppEndpoint);
HRESULT (STDMETHODCALLTYPE * GetDevice) (ma_IMMDeviceEnumerator* pThis, LPCWSTR pID, ma_IMMDevice** ppDevice);
HRESULT (STDMETHODCALLTYPE * RegisterEndpointNotificationCallback) (ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient);
HRESULT (STDMETHODCALLTYPE * UnregisterEndpointNotificationCallback)(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient);
} ma_IMMDeviceEnumeratorVtbl;
struct ma_IMMDeviceEnumerator
{
ma_IMMDeviceEnumeratorVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IMMDeviceEnumerator_QueryInterface(ma_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IMMDeviceEnumerator_AddRef(ma_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IMMDeviceEnumerator_Release(ma_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IMMDeviceEnumerator_EnumAudioEndpoints(ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, DWORD dwStateMask, ma_IMMDeviceCollection** ppDevices) { return pThis->lpVtbl->EnumAudioEndpoints(pThis, dataFlow, dwStateMask, ppDevices); }
static MA_INLINE HRESULT ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, ma_ERole role, ma_IMMDevice** ppEndpoint) { return pThis->lpVtbl->GetDefaultAudioEndpoint(pThis, dataFlow, role, ppEndpoint); }
static MA_INLINE HRESULT ma_IMMDeviceEnumerator_GetDevice(ma_IMMDeviceEnumerator* pThis, LPCWSTR pID, ma_IMMDevice** ppDevice) { return pThis->lpVtbl->GetDevice(pThis, pID, ppDevice); }
static MA_INLINE HRESULT ma_IMMDeviceEnumerator_RegisterEndpointNotificationCallback(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient) { return pThis->lpVtbl->RegisterEndpointNotificationCallback(pThis, pClient); }
static MA_INLINE HRESULT ma_IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient) { return pThis->lpVtbl->UnregisterEndpointNotificationCallback(pThis, pClient); }
/* IMMDeviceCollection */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDeviceCollection* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDeviceCollection* pThis);
/* IMMDeviceCollection */
HRESULT (STDMETHODCALLTYPE * GetCount)(ma_IMMDeviceCollection* pThis, UINT* pDevices);
HRESULT (STDMETHODCALLTYPE * Item) (ma_IMMDeviceCollection* pThis, UINT nDevice, ma_IMMDevice** ppDevice);
} ma_IMMDeviceCollectionVtbl;
struct ma_IMMDeviceCollection
{
ma_IMMDeviceCollectionVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IMMDeviceCollection_QueryInterface(ma_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IMMDeviceCollection_AddRef(ma_IMMDeviceCollection* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IMMDeviceCollection_Release(ma_IMMDeviceCollection* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IMMDeviceCollection_GetCount(ma_IMMDeviceCollection* pThis, UINT* pDevices) { return pThis->lpVtbl->GetCount(pThis, pDevices); }
static MA_INLINE HRESULT ma_IMMDeviceCollection_Item(ma_IMMDeviceCollection* pThis, UINT nDevice, ma_IMMDevice** ppDevice) { return pThis->lpVtbl->Item(pThis, nDevice, ppDevice); }
/* IMMDevice */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDevice* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDevice* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDevice* pThis);
/* IMMDevice */
HRESULT (STDMETHODCALLTYPE * Activate) (ma_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, PROPVARIANT* pActivationParams, void** ppInterface);
HRESULT (STDMETHODCALLTYPE * OpenPropertyStore)(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties);
HRESULT (STDMETHODCALLTYPE * GetId) (ma_IMMDevice* pThis, LPWSTR *pID);
HRESULT (STDMETHODCALLTYPE * GetState) (ma_IMMDevice* pThis, DWORD *pState);
} ma_IMMDeviceVtbl;
struct ma_IMMDevice
{
ma_IMMDeviceVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IMMDevice_QueryInterface(ma_IMMDevice* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IMMDevice_AddRef(ma_IMMDevice* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IMMDevice_Release(ma_IMMDevice* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IMMDevice_Activate(ma_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, PROPVARIANT* pActivationParams, void** ppInterface) { return pThis->lpVtbl->Activate(pThis, iid, dwClsCtx, pActivationParams, ppInterface); }
static MA_INLINE HRESULT ma_IMMDevice_OpenPropertyStore(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties) { return pThis->lpVtbl->OpenPropertyStore(pThis, stgmAccess, ppProperties); }
static MA_INLINE HRESULT ma_IMMDevice_GetId(ma_IMMDevice* pThis, LPWSTR *pID) { return pThis->lpVtbl->GetId(pThis, pID); }
static MA_INLINE HRESULT ma_IMMDevice_GetState(ma_IMMDevice* pThis, DWORD *pState) { return pThis->lpVtbl->GetState(pThis, pState); }
#else
/* IActivateAudioInterfaceAsyncOperation */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IActivateAudioInterfaceAsyncOperation* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IActivateAudioInterfaceAsyncOperation* pThis);
/* IActivateAudioInterfaceAsyncOperation */
HRESULT (STDMETHODCALLTYPE * GetActivateResult)(ma_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, ma_IUnknown** ppActivatedInterface);
} ma_IActivateAudioInterfaceAsyncOperationVtbl;
struct ma_IActivateAudioInterfaceAsyncOperation
{
ma_IActivateAudioInterfaceAsyncOperationVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IActivateAudioInterfaceAsyncOperation_QueryInterface(ma_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IActivateAudioInterfaceAsyncOperation_AddRef(ma_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IActivateAudioInterfaceAsyncOperation_Release(ma_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(ma_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, ma_IUnknown** ppActivatedInterface) { return pThis->lpVtbl->GetActivateResult(pThis, pActivateResult, ppActivatedInterface); }
#endif
/* IPropertyStore */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IPropertyStore* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IPropertyStore* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IPropertyStore* pThis);
/* IPropertyStore */
HRESULT (STDMETHODCALLTYPE * GetCount)(ma_IPropertyStore* pThis, DWORD* pPropCount);
HRESULT (STDMETHODCALLTYPE * GetAt) (ma_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey);
HRESULT (STDMETHODCALLTYPE * GetValue)(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, PROPVARIANT* pPropVar);
HRESULT (STDMETHODCALLTYPE * SetValue)(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const PROPVARIANT* const pPropVar);
HRESULT (STDMETHODCALLTYPE * Commit) (ma_IPropertyStore* pThis);
} ma_IPropertyStoreVtbl;
struct ma_IPropertyStore
{
ma_IPropertyStoreVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IPropertyStore_QueryInterface(ma_IPropertyStore* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IPropertyStore_AddRef(ma_IPropertyStore* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IPropertyStore_Release(ma_IPropertyStore* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IPropertyStore_GetCount(ma_IPropertyStore* pThis, DWORD* pPropCount) { return pThis->lpVtbl->GetCount(pThis, pPropCount); }
static MA_INLINE HRESULT ma_IPropertyStore_GetAt(ma_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey) { return pThis->lpVtbl->GetAt(pThis, propIndex, pPropKey); }
static MA_INLINE HRESULT ma_IPropertyStore_GetValue(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, PROPVARIANT* pPropVar) { return pThis->lpVtbl->GetValue(pThis, pKey, pPropVar); }
static MA_INLINE HRESULT ma_IPropertyStore_SetValue(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const PROPVARIANT* const pPropVar) { return pThis->lpVtbl->SetValue(pThis, pKey, pPropVar); }
static MA_INLINE HRESULT ma_IPropertyStore_Commit(ma_IPropertyStore* pThis) { return pThis->lpVtbl->Commit(pThis); }
/* IAudioClient */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient* pThis);
/* IAudioClient */
HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient* pThis, ma_uint32* pNumBufferFrames);
HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient* pThis, MA_REFERENCE_TIME* pLatency);
HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient* pThis, ma_uint32* pNumPaddingFrames);
HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch);
HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient* pThis, WAVEFORMATEX** ppDeviceFormat);
HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod);
HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient* pThis);
HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient* pThis);
HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient* pThis);
HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient* pThis, HANDLE eventHandle);
HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient* pThis, const IID* const riid, void** pp);
} ma_IAudioClientVtbl;
struct ma_IAudioClient
{
ma_IAudioClientVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IAudioClient_QueryInterface(ma_IAudioClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IAudioClient_AddRef(ma_IAudioClient* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IAudioClient_Release(ma_IAudioClient* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IAudioClient_Initialize(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); }
static MA_INLINE HRESULT ma_IAudioClient_GetBufferSize(ma_IAudioClient* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); }
static MA_INLINE HRESULT ma_IAudioClient_GetStreamLatency(ma_IAudioClient* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); }
static MA_INLINE HRESULT ma_IAudioClient_GetCurrentPadding(ma_IAudioClient* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); }
static MA_INLINE HRESULT ma_IAudioClient_IsFormatSupported(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); }
static MA_INLINE HRESULT ma_IAudioClient_GetMixFormat(ma_IAudioClient* pThis, WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); }
static MA_INLINE HRESULT ma_IAudioClient_GetDevicePeriod(ma_IAudioClient* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); }
static MA_INLINE HRESULT ma_IAudioClient_Start(ma_IAudioClient* pThis) { return pThis->lpVtbl->Start(pThis); }
static MA_INLINE HRESULT ma_IAudioClient_Stop(ma_IAudioClient* pThis) { return pThis->lpVtbl->Stop(pThis); }
static MA_INLINE HRESULT ma_IAudioClient_Reset(ma_IAudioClient* pThis) { return pThis->lpVtbl->Reset(pThis); }
static MA_INLINE HRESULT ma_IAudioClient_SetEventHandle(ma_IAudioClient* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); }
static MA_INLINE HRESULT ma_IAudioClient_GetService(ma_IAudioClient* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); }
/* IAudioClient2 */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient2* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient2* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient2* pThis);
/* IAudioClient */
HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient2* pThis, ma_uint32* pNumBufferFrames);
HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pLatency);
HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient2* pThis, ma_uint32* pNumPaddingFrames);
HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch);
HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient2* pThis, WAVEFORMATEX** ppDeviceFormat);
HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod);
HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient2* pThis);
HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient2* pThis);
HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient2* pThis);
HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient2* pThis, HANDLE eventHandle);
HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient2* pThis, const IID* const riid, void** pp);
/* IAudioClient2 */
HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (ma_IAudioClient2* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable);
HRESULT (STDMETHODCALLTYPE * SetClientProperties)(ma_IAudioClient2* pThis, const ma_AudioClientProperties* pProperties);
HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(ma_IAudioClient2* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration);
} ma_IAudioClient2Vtbl;
struct ma_IAudioClient2
{
ma_IAudioClient2Vtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IAudioClient2_QueryInterface(ma_IAudioClient2* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IAudioClient2_AddRef(ma_IAudioClient2* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IAudioClient2_Release(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IAudioClient2_Initialize(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); }
static MA_INLINE HRESULT ma_IAudioClient2_GetBufferSize(ma_IAudioClient2* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); }
static MA_INLINE HRESULT ma_IAudioClient2_GetStreamLatency(ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); }
static MA_INLINE HRESULT ma_IAudioClient2_GetCurrentPadding(ma_IAudioClient2* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); }
static MA_INLINE HRESULT ma_IAudioClient2_IsFormatSupported(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); }
static MA_INLINE HRESULT ma_IAudioClient2_GetMixFormat(ma_IAudioClient2* pThis, WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); }
static MA_INLINE HRESULT ma_IAudioClient2_GetDevicePeriod(ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); }
static MA_INLINE HRESULT ma_IAudioClient2_Start(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Start(pThis); }
static MA_INLINE HRESULT ma_IAudioClient2_Stop(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Stop(pThis); }
static MA_INLINE HRESULT ma_IAudioClient2_Reset(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Reset(pThis); }
static MA_INLINE HRESULT ma_IAudioClient2_SetEventHandle(ma_IAudioClient2* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); }
static MA_INLINE HRESULT ma_IAudioClient2_GetService(ma_IAudioClient2* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); }
static MA_INLINE HRESULT ma_IAudioClient2_IsOffloadCapable(ma_IAudioClient2* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); }
static MA_INLINE HRESULT ma_IAudioClient2_SetClientProperties(ma_IAudioClient2* pThis, const ma_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); }
static MA_INLINE HRESULT ma_IAudioClient2_GetBufferSizeLimits(ma_IAudioClient2* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration) { return pThis->lpVtbl->GetBufferSizeLimits(pThis, pFormat, eventDriven, pMinBufferDuration, pMaxBufferDuration); }
/* IAudioClient3 */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient3* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient3* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient3* pThis);
/* IAudioClient */
HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient3* pThis, ma_uint32* pNumBufferFrames);
HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pLatency);
HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient3* pThis, ma_uint32* pNumPaddingFrames);
HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch);
HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient3* pThis, WAVEFORMATEX** ppDeviceFormat);
HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod);
HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient3* pThis);
HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient3* pThis);
HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient3* pThis);
HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient3* pThis, HANDLE eventHandle);
HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient3* pThis, const IID* const riid, void** pp);
/* IAudioClient2 */
HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (ma_IAudioClient3* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable);
HRESULT (STDMETHODCALLTYPE * SetClientProperties)(ma_IAudioClient3* pThis, const ma_AudioClientProperties* pProperties);
HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration);
/* IAudioClient3 */
HRESULT (STDMETHODCALLTYPE * GetSharedModeEnginePeriod) (ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, ma_uint32* pDefaultPeriodInFrames, ma_uint32* pFundamentalPeriodInFrames, ma_uint32* pMinPeriodInFrames, ma_uint32* pMaxPeriodInFrames);
HRESULT (STDMETHODCALLTYPE * GetCurrentSharedModeEnginePeriod)(ma_IAudioClient3* pThis, WAVEFORMATEX** ppFormat, ma_uint32* pCurrentPeriodInFrames);
HRESULT (STDMETHODCALLTYPE * InitializeSharedAudioStream) (ma_IAudioClient3* pThis, DWORD streamFlags, ma_uint32 periodInFrames, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
} ma_IAudioClient3Vtbl;
struct ma_IAudioClient3
{
ma_IAudioClient3Vtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IAudioClient3_QueryInterface(ma_IAudioClient3* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IAudioClient3_AddRef(ma_IAudioClient3* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IAudioClient3_Release(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IAudioClient3_Initialize(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); }
static MA_INLINE HRESULT ma_IAudioClient3_GetBufferSize(ma_IAudioClient3* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); }
static MA_INLINE HRESULT ma_IAudioClient3_GetStreamLatency(ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); }
static MA_INLINE HRESULT ma_IAudioClient3_GetCurrentPadding(ma_IAudioClient3* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); }
static MA_INLINE HRESULT ma_IAudioClient3_IsFormatSupported(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); }
static MA_INLINE HRESULT ma_IAudioClient3_GetMixFormat(ma_IAudioClient3* pThis, WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); }
static MA_INLINE HRESULT ma_IAudioClient3_GetDevicePeriod(ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); }
static MA_INLINE HRESULT ma_IAudioClient3_Start(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Start(pThis); }
static MA_INLINE HRESULT ma_IAudioClient3_Stop(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Stop(pThis); }
static MA_INLINE HRESULT ma_IAudioClient3_Reset(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Reset(pThis); }
static MA_INLINE HRESULT ma_IAudioClient3_SetEventHandle(ma_IAudioClient3* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); }
static MA_INLINE HRESULT ma_IAudioClient3_GetService(ma_IAudioClient3* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); }
static MA_INLINE HRESULT ma_IAudioClient3_IsOffloadCapable(ma_IAudioClient3* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); }
static MA_INLINE HRESULT ma_IAudioClient3_SetClientProperties(ma_IAudioClient3* pThis, const ma_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); }
static MA_INLINE HRESULT ma_IAudioClient3_GetBufferSizeLimits(ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration) { return pThis->lpVtbl->GetBufferSizeLimits(pThis, pFormat, eventDriven, pMinBufferDuration, pMaxBufferDuration); }
static MA_INLINE HRESULT ma_IAudioClient3_GetSharedModeEnginePeriod(ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, ma_uint32* pDefaultPeriodInFrames, ma_uint32* pFundamentalPeriodInFrames, ma_uint32* pMinPeriodInFrames, ma_uint32* pMaxPeriodInFrames) { return pThis->lpVtbl->GetSharedModeEnginePeriod(pThis, pFormat, pDefaultPeriodInFrames, pFundamentalPeriodInFrames, pMinPeriodInFrames, pMaxPeriodInFrames); }
static MA_INLINE HRESULT ma_IAudioClient3_GetCurrentSharedModeEnginePeriod(ma_IAudioClient3* pThis, WAVEFORMATEX** ppFormat, ma_uint32* pCurrentPeriodInFrames) { return pThis->lpVtbl->GetCurrentSharedModeEnginePeriod(pThis, ppFormat, pCurrentPeriodInFrames); }
static MA_INLINE HRESULT ma_IAudioClient3_InitializeSharedAudioStream(ma_IAudioClient3* pThis, DWORD streamFlags, ma_uint32 periodInFrames, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGUID) { return pThis->lpVtbl->InitializeSharedAudioStream(pThis, streamFlags, periodInFrames, pFormat, pAudioSessionGUID); }
/* IAudioRenderClient */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioRenderClient* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioRenderClient* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioRenderClient* pThis);
/* IAudioRenderClient */
HRESULT (STDMETHODCALLTYPE * GetBuffer) (ma_IAudioRenderClient* pThis, ma_uint32 numFramesRequested, BYTE** ppData);
HRESULT (STDMETHODCALLTYPE * ReleaseBuffer)(ma_IAudioRenderClient* pThis, ma_uint32 numFramesWritten, DWORD dwFlags);
} ma_IAudioRenderClientVtbl;
struct ma_IAudioRenderClient
{
ma_IAudioRenderClientVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IAudioRenderClient_QueryInterface(ma_IAudioRenderClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IAudioRenderClient_AddRef(ma_IAudioRenderClient* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IAudioRenderClient_Release(ma_IAudioRenderClient* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IAudioRenderClient_GetBuffer(ma_IAudioRenderClient* pThis, ma_uint32 numFramesRequested, BYTE** ppData) { return pThis->lpVtbl->GetBuffer(pThis, numFramesRequested, ppData); }
static MA_INLINE HRESULT ma_IAudioRenderClient_ReleaseBuffer(ma_IAudioRenderClient* pThis, ma_uint32 numFramesWritten, DWORD dwFlags) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesWritten, dwFlags); }
/* IAudioCaptureClient */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioCaptureClient* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioCaptureClient* pThis);
/* IAudioRenderClient */
HRESULT (STDMETHODCALLTYPE * GetBuffer) (ma_IAudioCaptureClient* pThis, BYTE** ppData, ma_uint32* pNumFramesToRead, DWORD* pFlags, ma_uint64* pDevicePosition, ma_uint64* pQPCPosition);
HRESULT (STDMETHODCALLTYPE * ReleaseBuffer) (ma_IAudioCaptureClient* pThis, ma_uint32 numFramesRead);
HRESULT (STDMETHODCALLTYPE * GetNextPacketSize)(ma_IAudioCaptureClient* pThis, ma_uint32* pNumFramesInNextPacket);
} ma_IAudioCaptureClientVtbl;
struct ma_IAudioCaptureClient
{
ma_IAudioCaptureClientVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IAudioCaptureClient_QueryInterface(ma_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IAudioCaptureClient_AddRef(ma_IAudioCaptureClient* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IAudioCaptureClient_Release(ma_IAudioCaptureClient* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IAudioCaptureClient_GetBuffer(ma_IAudioCaptureClient* pThis, BYTE** ppData, ma_uint32* pNumFramesToRead, DWORD* pFlags, ma_uint64* pDevicePosition, ma_uint64* pQPCPosition) { return pThis->lpVtbl->GetBuffer(pThis, ppData, pNumFramesToRead, pFlags, pDevicePosition, pQPCPosition); }
static MA_INLINE HRESULT ma_IAudioCaptureClient_ReleaseBuffer(ma_IAudioCaptureClient* pThis, ma_uint32 numFramesRead) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesRead); }
static MA_INLINE HRESULT ma_IAudioCaptureClient_GetNextPacketSize(ma_IAudioCaptureClient* pThis, ma_uint32* pNumFramesInNextPacket) { return pThis->lpVtbl->GetNextPacketSize(pThis, pNumFramesInNextPacket); }
#ifndef MA_WIN32_DESKTOP
#include
typedef struct ma_completion_handler_uwp ma_completion_handler_uwp;
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_completion_handler_uwp* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_completion_handler_uwp* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_completion_handler_uwp* pThis);
/* IActivateAudioInterfaceCompletionHandler */
HRESULT (STDMETHODCALLTYPE * ActivateCompleted)(ma_completion_handler_uwp* pThis, ma_IActivateAudioInterfaceAsyncOperation* pActivateOperation);
} ma_completion_handler_uwp_vtbl;
struct ma_completion_handler_uwp
{
ma_completion_handler_uwp_vtbl* lpVtbl;
MA_ATOMIC ma_uint32 counter;
HANDLE hEvent;
};
static HRESULT STDMETHODCALLTYPE ma_completion_handler_uwp_QueryInterface(ma_completion_handler_uwp* pThis, const IID* const riid, void** ppObject)
{
/*
We need to "implement" IAgileObject which is just an indicator that's used internally by WASAPI for some multithreading management. To
"implement" this, we just make sure we return pThis when the IAgileObject is requested.
*/
if (!ma_is_guid_equal(riid, &MA_IID_IUnknown) && !ma_is_guid_equal(riid, &MA_IID_IActivateAudioInterfaceCompletionHandler) && !ma_is_guid_equal(riid, &MA_IID_IAgileObject)) {
*ppObject = NULL;
return E_NOINTERFACE;
}
/* Getting here means the IID is IUnknown or IMMNotificationClient. */
*ppObject = (void*)pThis;
((ma_completion_handler_uwp_vtbl*)pThis->lpVtbl)->AddRef(pThis);
return S_OK;
}
static ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_AddRef(ma_completion_handler_uwp* pThis)
{
return (ULONG)c89atomic_fetch_add_32(&pThis->counter, 1) + 1;
}
static ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_Release(ma_completion_handler_uwp* pThis)
{
ma_uint32 newRefCount = c89atomic_fetch_sub_32(&pThis->counter, 1) - 1;
if (newRefCount == 0) {
return 0; /* We don't free anything here because we never allocate the object on the heap. */
}
return (ULONG)newRefCount;
}
static HRESULT STDMETHODCALLTYPE ma_completion_handler_uwp_ActivateCompleted(ma_completion_handler_uwp* pThis, ma_IActivateAudioInterfaceAsyncOperation* pActivateOperation)
{
(void)pActivateOperation;
SetEvent(pThis->hEvent);
return S_OK;
}
static ma_completion_handler_uwp_vtbl g_maCompletionHandlerVtblInstance = {
ma_completion_handler_uwp_QueryInterface,
ma_completion_handler_uwp_AddRef,
ma_completion_handler_uwp_Release,
ma_completion_handler_uwp_ActivateCompleted
};
static ma_result ma_completion_handler_uwp_init(ma_completion_handler_uwp* pHandler)
{
MA_ASSERT(pHandler != NULL);
MA_ZERO_OBJECT(pHandler);
pHandler->lpVtbl = &g_maCompletionHandlerVtblInstance;
pHandler->counter = 1;
pHandler->hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
if (pHandler->hEvent == NULL) {
return ma_result_from_GetLastError(GetLastError());
}
return MA_SUCCESS;
}
static void ma_completion_handler_uwp_uninit(ma_completion_handler_uwp* pHandler)
{
if (pHandler->hEvent != NULL) {
CloseHandle(pHandler->hEvent);
}
}
static void ma_completion_handler_uwp_wait(ma_completion_handler_uwp* pHandler)
{
WaitForSingleObject(pHandler->hEvent, INFINITE);
}
#endif /* !MA_WIN32_DESKTOP */
/* We need a virtual table for our notification client object that's used for detecting changes to the default device. */
#ifdef MA_WIN32_DESKTOP
static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_QueryInterface(ma_IMMNotificationClient* pThis, const IID* const riid, void** ppObject)
{
/*
We care about two interfaces - IUnknown and IMMNotificationClient. If the requested IID is something else
we just return E_NOINTERFACE. Otherwise we need to increment the reference counter and return S_OK.
*/
if (!ma_is_guid_equal(riid, &MA_IID_IUnknown) && !ma_is_guid_equal(riid, &MA_IID_IMMNotificationClient)) {
*ppObject = NULL;
return E_NOINTERFACE;
}
/* Getting here means the IID is IUnknown or IMMNotificationClient. */
*ppObject = (void*)pThis;
((ma_IMMNotificationClientVtbl*)pThis->lpVtbl)->AddRef(pThis);
return S_OK;
}
static ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_AddRef(ma_IMMNotificationClient* pThis)
{
return (ULONG)c89atomic_fetch_add_32(&pThis->counter, 1) + 1;
}
static ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_Release(ma_IMMNotificationClient* pThis)
{
ma_uint32 newRefCount = c89atomic_fetch_sub_32(&pThis->counter, 1) - 1;
if (newRefCount == 0) {
return 0; /* We don't free anything here because we never allocate the object on the heap. */
}
return (ULONG)newRefCount;
}
static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceStateChanged(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, DWORD dwNewState)
{
ma_bool32 isThisDevice = MA_FALSE;
#ifdef MA_DEBUG_OUTPUT
/*printf("IMMNotificationClient_OnDeviceStateChanged(pDeviceID=%S, dwNewState=%u)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)", (unsigned int)dwNewState);*/
#endif
if ((dwNewState & MA_MM_DEVICE_STATE_ACTIVE) != 0) {
return S_OK;
}
/*
There have been reports of a hang when a playback device is disconnected. The idea with this code is to explicitly stop the device if we detect
that the device is disabled or has been unplugged.
*/
if (pThis->pDevice->wasapi.allowCaptureAutoStreamRouting && (pThis->pDevice->type == ma_device_type_capture || pThis->pDevice->type == ma_device_type_duplex || pThis->pDevice->type == ma_device_type_loopback)) {
if (wcscmp(pThis->pDevice->capture.id.wasapi, pDeviceID) == 0) {
isThisDevice = MA_TRUE;
}
}
if (pThis->pDevice->wasapi.allowPlaybackAutoStreamRouting && (pThis->pDevice->type == ma_device_type_playback || pThis->pDevice->type == ma_device_type_duplex)) {
if (wcscmp(pThis->pDevice->playback.id.wasapi, pDeviceID) == 0) {
isThisDevice = MA_TRUE;
}
}
if (isThisDevice) {
ma_device_stop(pThis->pDevice);
}
return S_OK;
}
static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceAdded(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID)
{
#ifdef MA_DEBUG_OUTPUT
/*printf("IMMNotificationClient_OnDeviceAdded(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)");*/
#endif
/* We don't need to worry about this event for our purposes. */
(void)pThis;
(void)pDeviceID;
return S_OK;
}
static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceRemoved(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID)
{
#ifdef MA_DEBUG_OUTPUT
/*printf("IMMNotificationClient_OnDeviceRemoved(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)");*/
#endif
/* We don't need to worry about this event for our purposes. */
(void)pThis;
(void)pDeviceID;
return S_OK;
}
static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDefaultDeviceChanged(ma_IMMNotificationClient* pThis, ma_EDataFlow dataFlow, ma_ERole role, LPCWSTR pDefaultDeviceID)
{
#ifdef MA_DEBUG_OUTPUT
/*printf("IMMNotificationClient_OnDefaultDeviceChanged(dataFlow=%d, role=%d, pDefaultDeviceID=%S)\n", dataFlow, role, (pDefaultDeviceID != NULL) ? pDefaultDeviceID : L"(NULL)");*/
#endif
/* We only ever use the eConsole role in miniaudio. */
if (role != ma_eConsole) {
return S_OK;
}
/* We only care about devices with the same data flow and role as the current device. */
if ((pThis->pDevice->type == ma_device_type_playback && dataFlow != ma_eRender) ||
(pThis->pDevice->type == ma_device_type_capture && dataFlow != ma_eCapture)) {
return S_OK;
}
/* Don't do automatic stream routing if we're not allowed. */
if ((dataFlow == ma_eRender && pThis->pDevice->wasapi.allowPlaybackAutoStreamRouting == MA_FALSE) ||
(dataFlow == ma_eCapture && pThis->pDevice->wasapi.allowCaptureAutoStreamRouting == MA_FALSE)) {
return S_OK;
}
/*
Not currently supporting automatic stream routing in exclusive mode. This is not working correctly on my machine due to
AUDCLNT_E_DEVICE_IN_USE errors when reinitializing the device. If this is a bug in miniaudio, we can try re-enabling this once
it's fixed.
*/
if ((dataFlow == ma_eRender && pThis->pDevice->playback.shareMode == ma_share_mode_exclusive) ||
(dataFlow == ma_eCapture && pThis->pDevice->capture.shareMode == ma_share_mode_exclusive)) {
return S_OK;
}
/*
We don't change the device here - we change it in the worker thread to keep synchronization simple. To do this I'm just setting a flag to
indicate that the default device has changed. Loopback devices are treated as capture devices so we need to do a bit of a dance to handle
that properly.
*/
if (dataFlow == ma_eRender && pThis->pDevice->type != ma_device_type_loopback) {
c89atomic_exchange_8(&pThis->pDevice->wasapi.hasDefaultPlaybackDeviceChanged, MA_TRUE);
}
if (dataFlow == ma_eCapture || pThis->pDevice->type == ma_device_type_loopback) {
c89atomic_exchange_8(&pThis->pDevice->wasapi.hasDefaultCaptureDeviceChanged, MA_TRUE);
}
(void)pDefaultDeviceID;
return S_OK;
}
static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnPropertyValueChanged(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, const PROPERTYKEY key)
{
#ifdef MA_DEBUG_OUTPUT
/*printf("IMMNotificationClient_OnPropertyValueChanged(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)");*/
#endif
(void)pThis;
(void)pDeviceID;
(void)key;
return S_OK;
}
static ma_IMMNotificationClientVtbl g_maNotificationCientVtbl = {
ma_IMMNotificationClient_QueryInterface,
ma_IMMNotificationClient_AddRef,
ma_IMMNotificationClient_Release,
ma_IMMNotificationClient_OnDeviceStateChanged,
ma_IMMNotificationClient_OnDeviceAdded,
ma_IMMNotificationClient_OnDeviceRemoved,
ma_IMMNotificationClient_OnDefaultDeviceChanged,
ma_IMMNotificationClient_OnPropertyValueChanged
};
#endif /* MA_WIN32_DESKTOP */
#ifdef MA_WIN32_DESKTOP
typedef ma_IMMDevice ma_WASAPIDeviceInterface;
#else
typedef ma_IUnknown ma_WASAPIDeviceInterface;
#endif
static void ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(const WAVEFORMATEX* pWF, ma_share_mode shareMode, ma_device_info* pInfo)
{
MA_ASSERT(pWF != NULL);
MA_ASSERT(pInfo != NULL);
if (pInfo->nativeDataFormatCount >= ma_countof(pInfo->nativeDataFormats)) {
return; /* Too many data formats. Need to ignore this one. Don't think this should ever happen with WASAPI. */
}
pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].format = ma_format_from_WAVEFORMATEX(pWF);
pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].channels = pWF->nChannels;
pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].sampleRate = pWF->nSamplesPerSec;
pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].flags = (shareMode == ma_share_mode_exclusive) ? MA_DATA_FORMAT_FLAG_EXCLUSIVE_MODE : 0;
pInfo->nativeDataFormatCount += 1;
}
static ma_result ma_context_get_device_info_from_IAudioClient__wasapi(ma_context* pContext, /*ma_IMMDevice**/void* pMMDevice, ma_IAudioClient* pAudioClient, ma_device_info* pInfo)
{
HRESULT hr;
WAVEFORMATEX* pWF = NULL;
#ifdef MA_WIN32_DESKTOP
ma_IPropertyStore *pProperties;
#endif
MA_ASSERT(pAudioClient != NULL);
MA_ASSERT(pInfo != NULL);
/* Shared Mode. We use GetMixFormat() here. */
hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pAudioClient, (WAVEFORMATEX**)&pWF);
if (SUCCEEDED(hr)) {
ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(pWF, ma_share_mode_shared, pInfo);
} else {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve mix format for device info retrieval.", ma_result_from_HRESULT(hr));
}
/* Exlcusive Mode. We repeatedly call IsFormatSupported() here. This is not currently support on UWP. */
#ifdef MA_WIN32_DESKTOP
/*
The first thing to do is get the format from PKEY_AudioEngine_DeviceFormat. This should give us a channel count we assume is
correct which will simplify our searching.
*/
hr = ma_IMMDevice_OpenPropertyStore((ma_IMMDevice*)pMMDevice, STGM_READ, &pProperties);
if (SUCCEEDED(hr)) {
PROPVARIANT var;
ma_PropVariantInit(&var);
hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_AudioEngine_DeviceFormat, &var);
if (SUCCEEDED(hr)) {
pWF = (WAVEFORMATEX*)var.blob.pBlobData;
/*
In my testing, the format returned by PKEY_AudioEngine_DeviceFormat is suitable for exclusive mode so we check this format
first. If this fails, fall back to a search.
*/
hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, pWF, NULL);
if (SUCCEEDED(hr)) {
/* The format returned by PKEY_AudioEngine_DeviceFormat is supported. */
ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(pWF, ma_share_mode_exclusive, pInfo);
} else {
/*
The format returned by PKEY_AudioEngine_DeviceFormat is not supported, so fall back to a search. We assume the channel
count returned by MA_PKEY_AudioEngine_DeviceFormat is valid and correct. For simplicity we're only returning one format.
*/
ma_uint32 channels = pInfo->minChannels;
ma_format formatsToSearch[] = {
ma_format_s16,
ma_format_s24,
/*ma_format_s24_32,*/
ma_format_f32,
ma_format_s32,
ma_format_u8
};
ma_channel defaultChannelMap[MA_MAX_CHANNELS];
WAVEFORMATEXTENSIBLE wf;
ma_bool32 found;
ma_uint32 iFormat;
/* Make sure we don't overflow the channel map. */
if (channels > MA_MAX_CHANNELS) {
channels = MA_MAX_CHANNELS;
}
ma_get_standard_channel_map(ma_standard_channel_map_microsoft, channels, defaultChannelMap);
MA_ZERO_OBJECT(&wf);
wf.Format.cbSize = sizeof(wf);
wf.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
wf.Format.nChannels = (WORD)channels;
wf.dwChannelMask = ma_channel_map_to_channel_mask__win32(defaultChannelMap, channels);
found = MA_FALSE;
for (iFormat = 0; iFormat < ma_countof(formatsToSearch); ++iFormat) {
ma_format format = formatsToSearch[iFormat];
ma_uint32 iSampleRate;
wf.Format.wBitsPerSample = (WORD)(ma_get_bytes_per_sample(format)*8);
wf.Format.nBlockAlign = (WORD)(wf.Format.nChannels * wf.Format.wBitsPerSample / 8);
wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec;
wf.Samples.wValidBitsPerSample = /*(format == ma_format_s24_32) ? 24 :*/ wf.Format.wBitsPerSample;
if (format == ma_format_f32) {
wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
} else {
wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM;
}
for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iSampleRate) {
wf.Format.nSamplesPerSec = g_maStandardSampleRatePriorities[iSampleRate];
hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, (WAVEFORMATEX*)&wf, NULL);
if (SUCCEEDED(hr)) {
ma_add_native_data_format_to_device_info_from_WAVEFORMATEX((WAVEFORMATEX*)&wf, ma_share_mode_exclusive, pInfo);
found = MA_TRUE;
break;
}
}
if (found) {
break;
}
}
ma_PropVariantClear(pContext, &var);
if (!found) {
ma_IPropertyStore_Release(pProperties);
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to find suitable device format for device info retrieval.", MA_FORMAT_NOT_SUPPORTED);
}
}
} else {
ma_IPropertyStore_Release(pProperties);
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve device format for device info retrieval.", ma_result_from_HRESULT(hr));
}
ma_IPropertyStore_Release(pProperties);
} else {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to open property store for device info retrieval.", ma_result_from_HRESULT(hr));
}
#endif
return MA_SUCCESS;
}
#ifdef MA_WIN32_DESKTOP
static ma_EDataFlow ma_device_type_to_EDataFlow(ma_device_type deviceType)
{
if (deviceType == ma_device_type_playback) {
return ma_eRender;
} else if (deviceType == ma_device_type_capture) {
return ma_eCapture;
} else {
MA_ASSERT(MA_FALSE);
return ma_eRender; /* Should never hit this. */
}
}
static ma_result ma_context_create_IMMDeviceEnumerator__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator** ppDeviceEnumerator)
{
HRESULT hr;
ma_IMMDeviceEnumerator* pDeviceEnumerator;
MA_ASSERT(pContext != NULL);
MA_ASSERT(ppDeviceEnumerator != NULL);
*ppDeviceEnumerator = NULL; /* Safety. */
hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
if (FAILED(hr)) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.", ma_result_from_HRESULT(hr));
}
*ppDeviceEnumerator = pDeviceEnumerator;
return MA_SUCCESS;
}
static LPWSTR ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator* pDeviceEnumerator, ma_device_type deviceType)
{
HRESULT hr;
ma_IMMDevice* pMMDefaultDevice = NULL;
LPWSTR pDefaultDeviceID = NULL;
ma_EDataFlow dataFlow;
ma_ERole role;
MA_ASSERT(pContext != NULL);
MA_ASSERT(pDeviceEnumerator != NULL);
(void)pContext;
/* Grab the EDataFlow type from the device type. */
dataFlow = ma_device_type_to_EDataFlow(deviceType);
/* The role is always eConsole, but we may make this configurable later. */
role = ma_eConsole;
hr = ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(pDeviceEnumerator, dataFlow, role, &pMMDefaultDevice);
if (FAILED(hr)) {
return NULL;
}
hr = ma_IMMDevice_GetId(pMMDefaultDevice, &pDefaultDeviceID);
ma_IMMDevice_Release(pMMDefaultDevice);
pMMDefaultDevice = NULL;
if (FAILED(hr)) {
return NULL;
}
return pDefaultDeviceID;
}
static LPWSTR ma_context_get_default_device_id__wasapi(ma_context* pContext, ma_device_type deviceType) /* Free the returned pointer with ma_CoTaskMemFree() */
{
ma_result result;
ma_IMMDeviceEnumerator* pDeviceEnumerator;
LPWSTR pDefaultDeviceID = NULL;
MA_ASSERT(pContext != NULL);
result = ma_context_create_IMMDeviceEnumerator__wasapi(pContext, &pDeviceEnumerator);
if (result != MA_SUCCESS) {
return NULL;
}
pDefaultDeviceID = ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(pContext, pDeviceEnumerator, deviceType);
ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
return pDefaultDeviceID;
}
static ma_result ma_context_get_MMDevice__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IMMDevice** ppMMDevice)
{
ma_IMMDeviceEnumerator* pDeviceEnumerator;
HRESULT hr;
MA_ASSERT(pContext != NULL);
MA_ASSERT(ppMMDevice != NULL);
hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
if (FAILED(hr)) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create IMMDeviceEnumerator.", ma_result_from_HRESULT(hr));
}
if (pDeviceID == NULL) {
hr = ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(pDeviceEnumerator, (deviceType == ma_device_type_capture) ? ma_eCapture : ma_eRender, ma_eConsole, ppMMDevice);
} else {
hr = ma_IMMDeviceEnumerator_GetDevice(pDeviceEnumerator, pDeviceID->wasapi, ppMMDevice);
}
ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
if (FAILED(hr)) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve IMMDevice.", ma_result_from_HRESULT(hr));
}
return MA_SUCCESS;
}
static ma_result ma_context_get_device_info_from_MMDevice__wasapi(ma_context* pContext, ma_IMMDevice* pMMDevice, LPWSTR pDefaultDeviceID, ma_bool32 onlySimpleInfo, ma_device_info* pInfo)
{
LPWSTR pDeviceID;
HRESULT hr;
MA_ASSERT(pContext != NULL);
MA_ASSERT(pMMDevice != NULL);
MA_ASSERT(pInfo != NULL);
/* ID. */
hr = ma_IMMDevice_GetId(pMMDevice, &pDeviceID);
if (SUCCEEDED(hr)) {
size_t idlen = wcslen(pDeviceID);
if (idlen+1 > ma_countof(pInfo->id.wasapi)) {
ma_CoTaskMemFree(pContext, pDeviceID);
MA_ASSERT(MA_FALSE); /* NOTE: If this is triggered, please report it. It means the format of the ID must haved change and is too long to fit in our fixed sized buffer. */
return MA_ERROR;
}
MA_COPY_MEMORY(pInfo->id.wasapi, pDeviceID, idlen * sizeof(wchar_t));
pInfo->id.wasapi[idlen] = '\0';
if (pDefaultDeviceID != NULL) {
if (wcscmp(pDeviceID, pDefaultDeviceID) == 0) {
/* It's a default device. */
pInfo->isDefault = MA_TRUE;
}
}
ma_CoTaskMemFree(pContext, pDeviceID);
}
{
ma_IPropertyStore *pProperties;
hr = ma_IMMDevice_OpenPropertyStore(pMMDevice, STGM_READ, &pProperties);
if (SUCCEEDED(hr)) {
PROPVARIANT var;
/* Description / Friendly Name */
ma_PropVariantInit(&var);
hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &var);
if (SUCCEEDED(hr)) {
WideCharToMultiByte(CP_UTF8, 0, var.pwszVal, -1, pInfo->name, sizeof(pInfo->name), 0, FALSE);
ma_PropVariantClear(pContext, &var);
}
ma_IPropertyStore_Release(pProperties);
}
}
/* Format */
if (!onlySimpleInfo) {
ma_IAudioClient* pAudioClient;
hr = ma_IMMDevice_Activate(pMMDevice, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioClient);
if (SUCCEEDED(hr)) {
ma_result result = ma_context_get_device_info_from_IAudioClient__wasapi(pContext, pMMDevice, pAudioClient, pInfo);
ma_IAudioClient_Release(pAudioClient);
return result;
} else {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate audio client for device info retrieval.", ma_result_from_HRESULT(hr));
}
}
return MA_SUCCESS;
}
static ma_result ma_context_enumerate_devices_by_type__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator* pDeviceEnumerator, ma_device_type deviceType, ma_enum_devices_callback_proc callback, void* pUserData)
{
ma_result result = MA_SUCCESS;
UINT deviceCount;
HRESULT hr;
ma_uint32 iDevice;
LPWSTR pDefaultDeviceID = NULL;
ma_IMMDeviceCollection* pDeviceCollection = NULL;
MA_ASSERT(pContext != NULL);
MA_ASSERT(callback != NULL);
/* Grab the default device. We use this to know whether or not flag the returned device info as being the default. */
pDefaultDeviceID = ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(pContext, pDeviceEnumerator, deviceType);
/* We need to enumerate the devices which returns a device collection. */
hr = ma_IMMDeviceEnumerator_EnumAudioEndpoints(pDeviceEnumerator, ma_device_type_to_EDataFlow(deviceType), MA_MM_DEVICE_STATE_ACTIVE, &pDeviceCollection);
if (SUCCEEDED(hr)) {
hr = ma_IMMDeviceCollection_GetCount(pDeviceCollection, &deviceCount);
if (FAILED(hr)) {
result = ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to get device count.", ma_result_from_HRESULT(hr));
goto done;
}
for (iDevice = 0; iDevice < deviceCount; ++iDevice) {
ma_device_info deviceInfo;
ma_IMMDevice* pMMDevice;
MA_ZERO_OBJECT(&deviceInfo);
hr = ma_IMMDeviceCollection_Item(pDeviceCollection, iDevice, &pMMDevice);
if (SUCCEEDED(hr)) {
result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, pDefaultDeviceID, MA_TRUE, &deviceInfo); /* MA_TRUE = onlySimpleInfo. */
ma_IMMDevice_Release(pMMDevice);
if (result == MA_SUCCESS) {
ma_bool32 cbResult = callback(pContext, deviceType, &deviceInfo, pUserData);
if (cbResult == MA_FALSE) {
break;
}
}
}
}
}
done:
if (pDefaultDeviceID != NULL) {
ma_CoTaskMemFree(pContext, pDefaultDeviceID);
pDefaultDeviceID = NULL;
}
if (pDeviceCollection != NULL) {
ma_IMMDeviceCollection_Release(pDeviceCollection);
pDeviceCollection = NULL;
}
return result;
}
static ma_result ma_context_get_IAudioClient_Desktop__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IAudioClient** ppAudioClient, ma_IMMDevice** ppMMDevice)
{
ma_result result;
HRESULT hr;
MA_ASSERT(pContext != NULL);
MA_ASSERT(ppAudioClient != NULL);
MA_ASSERT(ppMMDevice != NULL);
result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, ppMMDevice);
if (result != MA_SUCCESS) {
return result;
}
hr = ma_IMMDevice_Activate(*ppMMDevice, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)ppAudioClient);
if (FAILED(hr)) {
return ma_result_from_HRESULT(hr);
}
return MA_SUCCESS;
}
#else
static ma_result ma_context_get_IAudioClient_UWP__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IAudioClient** ppAudioClient, ma_IUnknown** ppActivatedInterface)
{
ma_IActivateAudioInterfaceAsyncOperation *pAsyncOp = NULL;
ma_completion_handler_uwp completionHandler;
IID iid;
LPOLESTR iidStr;
HRESULT hr;
ma_result result;
HRESULT activateResult;
ma_IUnknown* pActivatedInterface;
MA_ASSERT(pContext != NULL);
MA_ASSERT(ppAudioClient != NULL);
if (pDeviceID != NULL) {
MA_COPY_MEMORY(&iid, pDeviceID->wasapi, sizeof(iid));
} else {
if (deviceType == ma_device_type_playback) {
iid = MA_IID_DEVINTERFACE_AUDIO_RENDER;
} else {
iid = MA_IID_DEVINTERFACE_AUDIO_CAPTURE;
}
}
#if defined(__cplusplus)
hr = StringFromIID(iid, &iidStr);
#else
hr = StringFromIID(&iid, &iidStr);
#endif
if (FAILED(hr)) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to convert device IID to string for ActivateAudioInterfaceAsync(). Out of memory.", ma_result_from_HRESULT(hr));
}
result = ma_completion_handler_uwp_init(&completionHandler);
if (result != MA_SUCCESS) {
ma_CoTaskMemFree(pContext, iidStr);
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for waiting for ActivateAudioInterfaceAsync().", result);
}
#if defined(__cplusplus)
hr = ActivateAudioInterfaceAsync(iidStr, MA_IID_IAudioClient, NULL, (IActivateAudioInterfaceCompletionHandler*)&completionHandler, (IActivateAudioInterfaceAsyncOperation**)&pAsyncOp);
#else
hr = ActivateAudioInterfaceAsync(iidStr, &MA_IID_IAudioClient, NULL, (IActivateAudioInterfaceCompletionHandler*)&completionHandler, (IActivateAudioInterfaceAsyncOperation**)&pAsyncOp);
#endif
if (FAILED(hr)) {
ma_completion_handler_uwp_uninit(&completionHandler);
ma_CoTaskMemFree(pContext, iidStr);
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] ActivateAudioInterfaceAsync() failed.", ma_result_from_HRESULT(hr));
}
ma_CoTaskMemFree(pContext, iidStr);
/* Wait for the async operation for finish. */
ma_completion_handler_uwp_wait(&completionHandler);
ma_completion_handler_uwp_uninit(&completionHandler);
hr = ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(pAsyncOp, &activateResult, &pActivatedInterface);
ma_IActivateAudioInterfaceAsyncOperation_Release(pAsyncOp);
if (FAILED(hr) || FAILED(activateResult)) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate device.", FAILED(hr) ? ma_result_from_HRESULT(hr) : ma_result_from_HRESULT(activateResult));
}
/* Here is where we grab the IAudioClient interface. */
hr = ma_IUnknown_QueryInterface(pActivatedInterface, &MA_IID_IAudioClient, (void**)ppAudioClient);
if (FAILED(hr)) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to query IAudioClient interface.", ma_result_from_HRESULT(hr));
}
if (ppActivatedInterface) {
*ppActivatedInterface = pActivatedInterface;
} else {
ma_IUnknown_Release(pActivatedInterface);
}
return MA_SUCCESS;
}
#endif
static ma_result ma_context_get_IAudioClient__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IAudioClient** ppAudioClient, ma_WASAPIDeviceInterface** ppDeviceInterface)
{
#ifdef MA_WIN32_DESKTOP
return ma_context_get_IAudioClient_Desktop__wasapi(pContext, deviceType, pDeviceID, ppAudioClient, ppDeviceInterface);
#else
return ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, ppAudioClient, ppDeviceInterface);
#endif
}
static ma_result ma_context_enumerate_devices__wasapi(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
{
/* Different enumeration for desktop and UWP. */
#ifdef MA_WIN32_DESKTOP
/* Desktop */
HRESULT hr;
ma_IMMDeviceEnumerator* pDeviceEnumerator;
hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
if (FAILED(hr)) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.", ma_result_from_HRESULT(hr));
}
ma_context_enumerate_devices_by_type__wasapi(pContext, pDeviceEnumerator, ma_device_type_playback, callback, pUserData);
ma_context_enumerate_devices_by_type__wasapi(pContext, pDeviceEnumerator, ma_device_type_capture, callback, pUserData);
ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
#else
/*
UWP
The MMDevice API is only supported on desktop applications. For now, while I'm still figuring out how to properly enumerate
over devices without using MMDevice, I'm restricting devices to defaults.
Hint: DeviceInformation::FindAllAsync() with DeviceClass.AudioCapture/AudioRender. https://blogs.windows.com/buildingapps/2014/05/15/real-time-audio-in-windows-store-and-windows-phone-apps/
*/
if (callback) {
ma_bool32 cbResult = MA_TRUE;
/* Playback. */
if (cbResult) {
ma_device_info deviceInfo;
MA_ZERO_OBJECT(&deviceInfo);
ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
deviceInfo.isDefault = MA_TRUE;
cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
}
/* Capture. */
if (cbResult) {
ma_device_info deviceInfo;
MA_ZERO_OBJECT(&deviceInfo);
ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
deviceInfo.isDefault = MA_TRUE;
cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
}
}
#endif
return MA_SUCCESS;
}
static ma_result ma_context_get_device_info__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
{
#ifdef MA_WIN32_DESKTOP
ma_result result;
ma_IMMDevice* pMMDevice = NULL;
LPWSTR pDefaultDeviceID = NULL;
result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, &pMMDevice);
if (result != MA_SUCCESS) {
return result;
}
/* We need the default device ID so we can set the isDefault flag in the device info. */
pDefaultDeviceID = ma_context_get_default_device_id__wasapi(pContext, deviceType);
result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, pDefaultDeviceID, MA_FALSE, pDeviceInfo); /* MA_FALSE = !onlySimpleInfo. */
if (pDefaultDeviceID != NULL) {
ma_CoTaskMemFree(pContext, pDefaultDeviceID);
pDefaultDeviceID = NULL;
}
ma_IMMDevice_Release(pMMDevice);
return result;
#else
ma_IAudioClient* pAudioClient;
ma_result result;
/* UWP currently only uses default devices. */
if (deviceType == ma_device_type_playback) {
ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
} else {
ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
}
result = ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, &pAudioClient, NULL);
if (result != MA_SUCCESS) {
return result;
}
result = ma_context_get_device_info_from_IAudioClient__wasapi(pContext, NULL, pAudioClient, pDeviceInfo);
pDeviceInfo->isDefault = MA_TRUE; /* UWP only supports default devices. */
ma_IAudioClient_Release(pAudioClient);
return result;
#endif
}
static ma_result ma_device_uninit__wasapi(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
#ifdef MA_WIN32_DESKTOP
if (pDevice->wasapi.pDeviceEnumerator) {
((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator)->lpVtbl->UnregisterEndpointNotificationCallback((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator, &pDevice->wasapi.notificationClient);
ma_IMMDeviceEnumerator_Release((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator);
}
#endif
if (pDevice->wasapi.pRenderClient) {
ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient);
}
if (pDevice->wasapi.pCaptureClient) {
ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
}
if (pDevice->wasapi.pAudioClientPlayback) {
ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
}
if (pDevice->wasapi.pAudioClientCapture) {
ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
}
if (pDevice->wasapi.hEventPlayback) {
CloseHandle(pDevice->wasapi.hEventPlayback);
}
if (pDevice->wasapi.hEventCapture) {
CloseHandle(pDevice->wasapi.hEventCapture);
}
return MA_SUCCESS;
}
typedef struct
{
/* Input. */
ma_format formatIn;
ma_uint32 channelsIn;
ma_uint32 sampleRateIn;
ma_channel channelMapIn[MA_MAX_CHANNELS];
ma_uint32 periodSizeInFramesIn;
ma_uint32 periodSizeInMillisecondsIn;
ma_uint32 periodsIn;
/*ma_bool32 usingDefaultFormat;
ma_bool32 usingDefaultChannels;
ma_bool32 usingDefaultSampleRate;
ma_bool32 usingDefaultChannelMap;*/
ma_share_mode shareMode;
ma_performance_profile performanceProfile;
ma_bool32 noAutoConvertSRC;
ma_bool32 noDefaultQualitySRC;
ma_bool32 noHardwareOffloading;
/* Output. */
ma_IAudioClient* pAudioClient;
ma_IAudioRenderClient* pRenderClient;
ma_IAudioCaptureClient* pCaptureClient;
ma_format formatOut;
ma_uint32 channelsOut;
ma_uint32 sampleRateOut;
ma_channel channelMapOut[MA_MAX_CHANNELS];
ma_uint32 periodSizeInFramesOut;
ma_uint32 periodsOut;
ma_bool32 usingAudioClient3;
char deviceName[256];
} ma_device_init_internal_data__wasapi;
static ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_init_internal_data__wasapi* pData)
{
HRESULT hr;
ma_result result = MA_SUCCESS;
const char* errorMsg = "";
MA_AUDCLNT_SHAREMODE shareMode = MA_AUDCLNT_SHAREMODE_SHARED;
DWORD streamFlags = 0;
MA_REFERENCE_TIME periodDurationInMicroseconds;
ma_bool32 wasInitializedUsingIAudioClient3 = MA_FALSE;
WAVEFORMATEXTENSIBLE wf;
ma_WASAPIDeviceInterface* pDeviceInterface = NULL;
ma_IAudioClient2* pAudioClient2;
ma_uint32 nativeSampleRate;
MA_ASSERT(pContext != NULL);
MA_ASSERT(pData != NULL);
/* This function is only used to initialize one device type: either playback, capture or loopback. Never full-duplex. */
if (deviceType == ma_device_type_duplex) {
return MA_INVALID_ARGS;
}
pData->pAudioClient = NULL;
pData->pRenderClient = NULL;
pData->pCaptureClient = NULL;
streamFlags = MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
if (!pData->noAutoConvertSRC && pData->sampleRateIn != 0 && pData->shareMode != ma_share_mode_exclusive) { /* <-- Exclusive streams must use the native sample rate. */
streamFlags |= MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM;
}
if (!pData->noDefaultQualitySRC && pData->sampleRateIn != 0 && (streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) != 0) {
streamFlags |= MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
}
if (deviceType == ma_device_type_loopback) {
streamFlags |= MA_AUDCLNT_STREAMFLAGS_LOOPBACK;
}
result = ma_context_get_IAudioClient__wasapi(pContext, deviceType, pDeviceID, &pData->pAudioClient, &pDeviceInterface);
if (result != MA_SUCCESS) {
goto done;
}
MA_ZERO_OBJECT(&wf);
/* Try enabling hardware offloading. */
if (!pData->noHardwareOffloading) {
hr = ma_IAudioClient_QueryInterface(pData->pAudioClient, &MA_IID_IAudioClient2, (void**)&pAudioClient2);
if (SUCCEEDED(hr)) {
BOOL isHardwareOffloadingSupported = 0;
hr = ma_IAudioClient2_IsOffloadCapable(pAudioClient2, MA_AudioCategory_Other, &isHardwareOffloadingSupported);
if (SUCCEEDED(hr) && isHardwareOffloadingSupported) {
ma_AudioClientProperties clientProperties;
MA_ZERO_OBJECT(&clientProperties);
clientProperties.cbSize = sizeof(clientProperties);
clientProperties.bIsOffload = 1;
clientProperties.eCategory = MA_AudioCategory_Other;
ma_IAudioClient2_SetClientProperties(pAudioClient2, &clientProperties);
}
pAudioClient2->lpVtbl->Release(pAudioClient2);
}
}
/* Here is where we try to determine the best format to use with the device. If the client if wanting exclusive mode, first try finding the best format for that. If this fails, fall back to shared mode. */
result = MA_FORMAT_NOT_SUPPORTED;
if (pData->shareMode == ma_share_mode_exclusive) {
#ifdef MA_WIN32_DESKTOP
/* In exclusive mode on desktop we always use the backend's native format. */
ma_IPropertyStore* pStore = NULL;
hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pStore);
if (SUCCEEDED(hr)) {
PROPVARIANT prop;
ma_PropVariantInit(&prop);
hr = ma_IPropertyStore_GetValue(pStore, &MA_PKEY_AudioEngine_DeviceFormat, &prop);
if (SUCCEEDED(hr)) {
WAVEFORMATEX* pActualFormat = (WAVEFORMATEX*)prop.blob.pBlobData;
hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pData->pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, pActualFormat, NULL);
if (SUCCEEDED(hr)) {
MA_COPY_MEMORY(&wf, pActualFormat, sizeof(WAVEFORMATEXTENSIBLE));
}
ma_PropVariantClear(pContext, &prop);
}
ma_IPropertyStore_Release(pStore);
}
#else
/*
I do not know how to query the device's native format on UWP so for now I'm just disabling support for
exclusive mode. The alternative is to enumerate over different formats and check IsFormatSupported()
until you find one that works.
TODO: Add support for exclusive mode to UWP.
*/
hr = S_FALSE;
#endif
if (hr == S_OK) {
shareMode = MA_AUDCLNT_SHAREMODE_EXCLUSIVE;
result = MA_SUCCESS;
} else {
result = MA_SHARE_MODE_NOT_SUPPORTED;
}
} else {
/* In shared mode we are always using the format reported by the operating system. */
WAVEFORMATEXTENSIBLE* pNativeFormat = NULL;
hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pData->pAudioClient, (WAVEFORMATEX**)&pNativeFormat);
if (hr != S_OK) {
result = MA_FORMAT_NOT_SUPPORTED;
} else {
MA_COPY_MEMORY(&wf, pNativeFormat, sizeof(wf));
result = MA_SUCCESS;
}
ma_CoTaskMemFree(pContext, pNativeFormat);
shareMode = MA_AUDCLNT_SHAREMODE_SHARED;
}
/* Return an error if we still haven't found a format. */
if (result != MA_SUCCESS) {
errorMsg = "[WASAPI] Failed to find best device mix format.";
goto done;
}
/*
Override the native sample rate with the one requested by the caller, but only if we're not using the default sample rate. We'll use
WASAPI to perform the sample rate conversion.
*/
nativeSampleRate = wf.Format.nSamplesPerSec;
if (streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) {
wf.Format.nSamplesPerSec = (pData->sampleRateIn != 0) ? pData->sampleRateIn : MA_DEFAULT_SAMPLE_RATE;
wf.Format.nAvgBytesPerSec = wf.Format.nSamplesPerSec * wf.Format.nBlockAlign;
}
pData->formatOut = ma_format_from_WAVEFORMATEX((WAVEFORMATEX*)&wf);
if (pData->formatOut == ma_format_unknown) {
/*
The format isn't supported. This is almost certainly because the exclusive mode format isn't supported by miniaudio. We need to return MA_SHARE_MODE_NOT_SUPPORTED
in this case so that the caller can detect it and fall back to shared mode if desired. We should never get here if shared mode was requested, but just for
completeness we'll check for it and return MA_FORMAT_NOT_SUPPORTED.
*/
if (shareMode == MA_AUDCLNT_SHAREMODE_EXCLUSIVE) {
result = MA_SHARE_MODE_NOT_SUPPORTED;
} else {
result = MA_FORMAT_NOT_SUPPORTED;
}
errorMsg = "[WASAPI] Native format not supported.";
goto done;
}
pData->channelsOut = wf.Format.nChannels;
pData->sampleRateOut = wf.Format.nSamplesPerSec;
/* Get the internal channel map based on the channel mask. */
ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pData->channelsOut, pData->channelMapOut);
/* Period size. */
pData->periodsOut = (pData->periodsIn != 0) ? pData->periodsIn : MA_DEFAULT_PERIODS;
pData->periodSizeInFramesOut = pData->periodSizeInFramesIn;
if (pData->periodSizeInFramesOut == 0) {
if (pData->periodSizeInMillisecondsIn == 0) {
if (pData->performanceProfile == ma_performance_profile_low_latency) {
pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, wf.Format.nSamplesPerSec);
} else {
pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, wf.Format.nSamplesPerSec);
}
} else {
pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(pData->periodSizeInMillisecondsIn, wf.Format.nSamplesPerSec);
}
}
periodDurationInMicroseconds = ((ma_uint64)pData->periodSizeInFramesOut * 1000 * 1000) / wf.Format.nSamplesPerSec;
/* Slightly different initialization for shared and exclusive modes. We try exclusive mode first, and if it fails, fall back to shared mode. */
if (shareMode == MA_AUDCLNT_SHAREMODE_EXCLUSIVE) {
MA_REFERENCE_TIME bufferDuration = periodDurationInMicroseconds * 10;
/*
If the periodicy is too small, Initialize() will fail with AUDCLNT_E_INVALID_DEVICE_PERIOD. In this case we should just keep increasing
it and trying it again.
*/
hr = E_FAIL;
for (;;) {
hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, bufferDuration, (WAVEFORMATEX*)&wf, NULL);
if (hr == MA_AUDCLNT_E_INVALID_DEVICE_PERIOD) {
if (bufferDuration > 500*10000) {
break;
} else {
if (bufferDuration == 0) { /* <-- Just a sanity check to prevent an infinit loop. Should never happen, but it makes me feel better. */
break;
}
bufferDuration = bufferDuration * 2;
continue;
}
} else {
break;
}
}
if (hr == MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) {
ma_uint32 bufferSizeInFrames;
hr = ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pData->pAudioClient, &bufferSizeInFrames);
if (SUCCEEDED(hr)) {
bufferDuration = (MA_REFERENCE_TIME)((10000.0 * 1000 / wf.Format.nSamplesPerSec * bufferSizeInFrames) + 0.5);
/* Unfortunately we need to release and re-acquire the audio client according to MSDN. Seems silly - why not just call IAudioClient_Initialize() again?! */
ma_IAudioClient_Release((ma_IAudioClient*)pData->pAudioClient);
#ifdef MA_WIN32_DESKTOP
hr = ma_IMMDevice_Activate(pDeviceInterface, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pData->pAudioClient);
#else
hr = ma_IUnknown_QueryInterface(pDeviceInterface, &MA_IID_IAudioClient, (void**)&pData->pAudioClient);
#endif
if (SUCCEEDED(hr)) {
hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, bufferDuration, (WAVEFORMATEX*)&wf, NULL);
}
}
}
if (FAILED(hr)) {
/* Failed to initialize in exclusive mode. Don't fall back to shared mode - instead tell the client about it. They can reinitialize in shared mode if they want. */
if (hr == E_ACCESSDENIED) {
errorMsg = "[WASAPI] Failed to initialize device in exclusive mode. Access denied.", result = MA_ACCESS_DENIED;
} else if (hr == MA_AUDCLNT_E_DEVICE_IN_USE) {
errorMsg = "[WASAPI] Failed to initialize device in exclusive mode. Device in use.", result = MA_BUSY;
} else {
errorMsg = "[WASAPI] Failed to initialize device in exclusive mode."; result = ma_result_from_HRESULT(hr);
}
goto done;
}
}
if (shareMode == MA_AUDCLNT_SHAREMODE_SHARED) {
/*
Low latency shared mode via IAudioClient3.
NOTE
====
Contrary to the documentation on MSDN (https://docs.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-initializesharedaudiostream), the
use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM and AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY with IAudioClient3_InitializeSharedAudioStream() absolutely does not work. Using
any of these flags will result in HRESULT code 0x88890021. The other problem is that calling IAudioClient3_GetSharedModeEnginePeriod() with a sample rate different to
that returned by IAudioClient_GetMixFormat() also results in an error. I'm therefore disabling low-latency shared mode with AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM.
*/
#ifndef MA_WASAPI_NO_LOW_LATENCY_SHARED_MODE
if ((streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) == 0 || nativeSampleRate == wf.Format.nSamplesPerSec) {
ma_IAudioClient3* pAudioClient3 = NULL;
hr = ma_IAudioClient_QueryInterface(pData->pAudioClient, &MA_IID_IAudioClient3, (void**)&pAudioClient3);
if (SUCCEEDED(hr)) {
ma_uint32 defaultPeriodInFrames;
ma_uint32 fundamentalPeriodInFrames;
ma_uint32 minPeriodInFrames;
ma_uint32 maxPeriodInFrames;
hr = ma_IAudioClient3_GetSharedModeEnginePeriod(pAudioClient3, (WAVEFORMATEX*)&wf, &defaultPeriodInFrames, &fundamentalPeriodInFrames, &minPeriodInFrames, &maxPeriodInFrames);
if (SUCCEEDED(hr)) {
ma_uint32 desiredPeriodInFrames = pData->periodSizeInFramesOut;
ma_uint32 actualPeriodInFrames = desiredPeriodInFrames;
/* Make sure the period size is a multiple of fundamentalPeriodInFrames. */
actualPeriodInFrames = actualPeriodInFrames / fundamentalPeriodInFrames;
actualPeriodInFrames = actualPeriodInFrames * fundamentalPeriodInFrames;
/* The period needs to be clamped between minPeriodInFrames and maxPeriodInFrames. */
actualPeriodInFrames = ma_clamp(actualPeriodInFrames, minPeriodInFrames, maxPeriodInFrames);
#if defined(MA_DEBUG_OUTPUT)
printf("[WASAPI] Trying IAudioClient3_InitializeSharedAudioStream(actualPeriodInFrames=%d)\n", actualPeriodInFrames);
printf(" defaultPeriodInFrames=%d\n", defaultPeriodInFrames);
printf(" fundamentalPeriodInFrames=%d\n", fundamentalPeriodInFrames);
printf(" minPeriodInFrames=%d\n", minPeriodInFrames);
printf(" maxPeriodInFrames=%d\n", maxPeriodInFrames);
#endif
/* If the client requested a largish buffer than we don't actually want to use low latency shared mode because it forces small buffers. */
if (actualPeriodInFrames >= desiredPeriodInFrames) {
/*
MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY must not be in the stream flags. If either of these are specified,
IAudioClient3_InitializeSharedAudioStream() will fail.
*/
hr = ma_IAudioClient3_InitializeSharedAudioStream(pAudioClient3, streamFlags & ~(MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY), actualPeriodInFrames, (WAVEFORMATEX*)&wf, NULL);
if (SUCCEEDED(hr)) {
wasInitializedUsingIAudioClient3 = MA_TRUE;
pData->periodSizeInFramesOut = actualPeriodInFrames;
#if defined(MA_DEBUG_OUTPUT)
printf("[WASAPI] Using IAudioClient3\n");
printf(" periodSizeInFramesOut=%d\n", pData->periodSizeInFramesOut);
#endif
} else {
#if defined(MA_DEBUG_OUTPUT)
printf("[WASAPI] IAudioClient3_InitializeSharedAudioStream failed. Falling back to IAudioClient.\n");
#endif
}
} else {
#if defined(MA_DEBUG_OUTPUT)
printf("[WASAPI] Not using IAudioClient3 because the desired period size is larger than the maximum supported by IAudioClient3.\n");
#endif
}
} else {
#if defined(MA_DEBUG_OUTPUT)
printf("[WASAPI] IAudioClient3_GetSharedModeEnginePeriod failed. Falling back to IAudioClient.\n");
#endif
}
ma_IAudioClient3_Release(pAudioClient3);
pAudioClient3 = NULL;
}
}
#else
#if defined(MA_DEBUG_OUTPUT)
printf("[WASAPI] Not using IAudioClient3 because MA_WASAPI_NO_LOW_LATENCY_SHARED_MODE is enabled.\n");
#endif
#endif
/* If we don't have an IAudioClient3 then we need to use the normal initialization routine. */
if (!wasInitializedUsingIAudioClient3) {
MA_REFERENCE_TIME bufferDuration = periodDurationInMicroseconds * pData->periodsOut * 10; /* <-- Multiply by 10 for microseconds to 100-nanoseconds. */
hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, 0, (WAVEFORMATEX*)&wf, NULL);
if (FAILED(hr)) {
if (hr == E_ACCESSDENIED) {
errorMsg = "[WASAPI] Failed to initialize device. Access denied.", result = MA_ACCESS_DENIED;
} else if (hr == MA_AUDCLNT_E_DEVICE_IN_USE) {
errorMsg = "[WASAPI] Failed to initialize device. Device in use.", result = MA_BUSY;
} else {
errorMsg = "[WASAPI] Failed to initialize device.", result = ma_result_from_HRESULT(hr);
}
goto done;
}
}
}
if (!wasInitializedUsingIAudioClient3) {
ma_uint32 bufferSizeInFrames;
hr = ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pData->pAudioClient, &bufferSizeInFrames);
if (FAILED(hr)) {
errorMsg = "[WASAPI] Failed to get audio client's actual buffer size.", result = ma_result_from_HRESULT(hr);
goto done;
}
pData->periodSizeInFramesOut = bufferSizeInFrames / pData->periodsOut;
}
pData->usingAudioClient3 = wasInitializedUsingIAudioClient3;
if (deviceType == ma_device_type_playback) {
hr = ma_IAudioClient_GetService((ma_IAudioClient*)pData->pAudioClient, &MA_IID_IAudioRenderClient, (void**)&pData->pRenderClient);
} else {
hr = ma_IAudioClient_GetService((ma_IAudioClient*)pData->pAudioClient, &MA_IID_IAudioCaptureClient, (void**)&pData->pCaptureClient);
}
if (FAILED(hr)) {
errorMsg = "[WASAPI] Failed to get audio client service.", result = ma_result_from_HRESULT(hr);
goto done;
}
/* Grab the name of the device. */
#ifdef MA_WIN32_DESKTOP
{
ma_IPropertyStore *pProperties;
hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pProperties);
if (SUCCEEDED(hr)) {
PROPVARIANT varName;
ma_PropVariantInit(&varName);
hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &varName);
if (SUCCEEDED(hr)) {
WideCharToMultiByte(CP_UTF8, 0, varName.pwszVal, -1, pData->deviceName, sizeof(pData->deviceName), 0, FALSE);
ma_PropVariantClear(pContext, &varName);
}
ma_IPropertyStore_Release(pProperties);
}
}
#endif
done:
/* Clean up. */
#ifdef MA_WIN32_DESKTOP
if (pDeviceInterface != NULL) {
ma_IMMDevice_Release(pDeviceInterface);
}
#else
if (pDeviceInterface != NULL) {
ma_IUnknown_Release(pDeviceInterface);
}
#endif
if (result != MA_SUCCESS) {
if (pData->pRenderClient) {
ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pData->pRenderClient);
pData->pRenderClient = NULL;
}
if (pData->pCaptureClient) {
ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pData->pCaptureClient);
pData->pCaptureClient = NULL;
}
if (pData->pAudioClient) {
ma_IAudioClient_Release((ma_IAudioClient*)pData->pAudioClient);
pData->pAudioClient = NULL;
}
if (errorMsg != NULL && errorMsg[0] != '\0') {
ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, errorMsg, result);
}
return result;
} else {
return MA_SUCCESS;
}
}
static ma_result ma_device_reinit__wasapi(ma_device* pDevice, ma_device_type deviceType)
{
ma_device_init_internal_data__wasapi data;
ma_result result;
MA_ASSERT(pDevice != NULL);
/* We only re-initialize the playback or capture device. Never a full-duplex device. */
if (deviceType == ma_device_type_duplex) {
return MA_INVALID_ARGS;
}
if (deviceType == ma_device_type_playback) {
data.formatIn = pDevice->playback.format;
data.channelsIn = pDevice->playback.channels;
MA_COPY_MEMORY(data.channelMapIn, pDevice->playback.channelMap, sizeof(pDevice->playback.channelMap));
data.shareMode = pDevice->playback.shareMode;
} else {
data.formatIn = pDevice->capture.format;
data.channelsIn = pDevice->capture.channels;
MA_COPY_MEMORY(data.channelMapIn, pDevice->capture.channelMap, sizeof(pDevice->capture.channelMap));
data.shareMode = pDevice->capture.shareMode;
}
data.sampleRateIn = pDevice->sampleRate;
data.periodSizeInFramesIn = pDevice->wasapi.originalPeriodSizeInFrames;
data.periodSizeInMillisecondsIn = pDevice->wasapi.originalPeriodSizeInMilliseconds;
data.periodsIn = pDevice->wasapi.originalPeriods;
data.performanceProfile = pDevice->wasapi.originalPerformanceProfile;
data.noAutoConvertSRC = pDevice->wasapi.noAutoConvertSRC;
data.noDefaultQualitySRC = pDevice->wasapi.noDefaultQualitySRC;
data.noHardwareOffloading = pDevice->wasapi.noHardwareOffloading;
result = ma_device_init_internal__wasapi(pDevice->pContext, deviceType, NULL, &data);
if (result != MA_SUCCESS) {
return result;
}
/* At this point we have some new objects ready to go. We need to uninitialize the previous ones and then set the new ones. */
if (deviceType == ma_device_type_capture || deviceType == ma_device_type_loopback) {
if (pDevice->wasapi.pCaptureClient) {
ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
pDevice->wasapi.pCaptureClient = NULL;
}
if (pDevice->wasapi.pAudioClientCapture) {
ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
pDevice->wasapi.pAudioClientCapture = NULL;
}
pDevice->wasapi.pAudioClientCapture = data.pAudioClient;
pDevice->wasapi.pCaptureClient = data.pCaptureClient;
pDevice->capture.internalFormat = data.formatOut;
pDevice->capture.internalChannels = data.channelsOut;
pDevice->capture.internalSampleRate = data.sampleRateOut;
MA_COPY_MEMORY(pDevice->capture.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
pDevice->capture.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
pDevice->capture.internalPeriods = data.periodsOut;
ma_strcpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), data.deviceName);
ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, pDevice->wasapi.hEventCapture);
pDevice->wasapi.periodSizeInFramesCapture = data.periodSizeInFramesOut;
ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &pDevice->wasapi.actualPeriodSizeInFramesCapture);
/* The device may be in a started state. If so we need to immediately restart it. */
if (c89atomic_load_8(&pDevice->wasapi.isStartedCapture)) {
HRESULT hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal capture device after reinitialization.", ma_result_from_HRESULT(hr));
}
}
}
if (deviceType == ma_device_type_playback) {
if (pDevice->wasapi.pRenderClient) {
ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient);
pDevice->wasapi.pRenderClient = NULL;
}
if (pDevice->wasapi.pAudioClientPlayback) {
ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
pDevice->wasapi.pAudioClientPlayback = NULL;
}
pDevice->wasapi.pAudioClientPlayback = data.pAudioClient;
pDevice->wasapi.pRenderClient = data.pRenderClient;
pDevice->playback.internalFormat = data.formatOut;
pDevice->playback.internalChannels = data.channelsOut;
pDevice->playback.internalSampleRate = data.sampleRateOut;
MA_COPY_MEMORY(pDevice->playback.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
pDevice->playback.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
pDevice->playback.internalPeriods = data.periodsOut;
ma_strcpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), data.deviceName);
ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, pDevice->wasapi.hEventPlayback);
pDevice->wasapi.periodSizeInFramesPlayback = data.periodSizeInFramesOut;
ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualPeriodSizeInFramesPlayback);
/* The device may be in a started state. If so we need to immediately restart it. */
if (c89atomic_load_8(&pDevice->wasapi.isStartedPlayback)) {
HRESULT hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal playback device after reinitialization.", ma_result_from_HRESULT(hr));
}
}
}
return MA_SUCCESS;
}
static ma_result ma_device_init__wasapi(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
{
ma_result result = MA_SUCCESS;
#ifdef MA_WIN32_DESKTOP
HRESULT hr;
ma_IMMDeviceEnumerator* pDeviceEnumerator;
#endif
MA_ASSERT(pDevice != NULL);
MA_ZERO_OBJECT(&pDevice->wasapi);
pDevice->wasapi.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC;
pDevice->wasapi.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC;
pDevice->wasapi.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading;
/* Exclusive mode is not allowed with loopback. */
if (pConfig->deviceType == ma_device_type_loopback && pConfig->playback.shareMode == ma_share_mode_exclusive) {
return MA_INVALID_DEVICE_CONFIG;
}
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
ma_device_init_internal_data__wasapi data;
data.formatIn = pDescriptorCapture->format;
data.channelsIn = pDescriptorCapture->channels;
data.sampleRateIn = pDescriptorCapture->sampleRate;
MA_COPY_MEMORY(data.channelMapIn, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap));
data.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames;
data.periodSizeInMillisecondsIn = pDescriptorCapture->periodSizeInMilliseconds;
data.periodsIn = pDescriptorCapture->periodCount;
data.shareMode = pDescriptorCapture->shareMode;
data.performanceProfile = pConfig->performanceProfile;
data.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC;
data.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC;
data.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading;
result = ma_device_init_internal__wasapi(pDevice->pContext, (pConfig->deviceType == ma_device_type_loopback) ? ma_device_type_loopback : ma_device_type_capture, pDescriptorCapture->pDeviceID, &data);
if (result != MA_SUCCESS) {
return result;
}
pDevice->wasapi.pAudioClientCapture = data.pAudioClient;
pDevice->wasapi.pCaptureClient = data.pCaptureClient;
pDevice->wasapi.originalPeriodSizeInMilliseconds = pDescriptorCapture->periodSizeInMilliseconds;
pDevice->wasapi.originalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames;
pDevice->wasapi.originalPeriods = pDescriptorCapture->periodCount;
pDevice->wasapi.originalPerformanceProfile = pConfig->performanceProfile;
/*
The event for capture needs to be manual reset for the same reason as playback. We keep the initial state set to unsignaled,
however, because we want to block until we actually have something for the first call to ma_device_read().
*/
pDevice->wasapi.hEventCapture = CreateEventW(NULL, FALSE, FALSE, NULL); /* Auto reset, unsignaled by default. */
if (pDevice->wasapi.hEventCapture == NULL) {
result = ma_result_from_GetLastError(GetLastError());
if (pDevice->wasapi.pCaptureClient != NULL) {
ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
pDevice->wasapi.pCaptureClient = NULL;
}
if (pDevice->wasapi.pAudioClientCapture != NULL) {
ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
pDevice->wasapi.pAudioClientCapture = NULL;
}
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for capture.", result);
}
ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, pDevice->wasapi.hEventCapture);
pDevice->wasapi.periodSizeInFramesCapture = data.periodSizeInFramesOut;
ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &pDevice->wasapi.actualPeriodSizeInFramesCapture);
/* The descriptor needs to be updated with actual values. */
pDescriptorCapture->format = data.formatOut;
pDescriptorCapture->channels = data.channelsOut;
pDescriptorCapture->sampleRate = data.sampleRateOut;
MA_COPY_MEMORY(pDescriptorCapture->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
pDescriptorCapture->periodSizeInFrames = data.periodSizeInFramesOut;
pDescriptorCapture->periodCount = data.periodsOut;
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
ma_device_init_internal_data__wasapi data;
data.formatIn = pDescriptorPlayback->format;
data.channelsIn = pDescriptorPlayback->channels;
data.sampleRateIn = pDescriptorPlayback->sampleRate;
MA_COPY_MEMORY(data.channelMapIn, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap));
data.periodSizeInFramesIn = pDescriptorPlayback->periodSizeInFrames;
data.periodSizeInMillisecondsIn = pDescriptorPlayback->periodSizeInMilliseconds;
data.periodsIn = pDescriptorPlayback->periodCount;
data.shareMode = pDescriptorPlayback->shareMode;
data.performanceProfile = pConfig->performanceProfile;
data.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC;
data.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC;
data.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading;
result = ma_device_init_internal__wasapi(pDevice->pContext, ma_device_type_playback, pDescriptorPlayback->pDeviceID, &data);
if (result != MA_SUCCESS) {
if (pConfig->deviceType == ma_device_type_duplex) {
if (pDevice->wasapi.pCaptureClient != NULL) {
ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
pDevice->wasapi.pCaptureClient = NULL;
}
if (pDevice->wasapi.pAudioClientCapture != NULL) {
ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
pDevice->wasapi.pAudioClientCapture = NULL;
}
CloseHandle(pDevice->wasapi.hEventCapture);
pDevice->wasapi.hEventCapture = NULL;
}
return result;
}
pDevice->wasapi.pAudioClientPlayback = data.pAudioClient;
pDevice->wasapi.pRenderClient = data.pRenderClient;
pDevice->wasapi.originalPeriodSizeInMilliseconds = pDescriptorPlayback->periodSizeInMilliseconds;
pDevice->wasapi.originalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames;
pDevice->wasapi.originalPeriods = pDescriptorPlayback->periodCount;
pDevice->wasapi.originalPerformanceProfile = pConfig->performanceProfile;
/*
The event for playback is needs to be manual reset because we want to explicitly control the fact that it becomes signalled
only after the whole available space has been filled, never before.
The playback event also needs to be initially set to a signaled state so that the first call to ma_device_write() is able
to get passed WaitForMultipleObjects().
*/
pDevice->wasapi.hEventPlayback = CreateEventW(NULL, FALSE, TRUE, NULL); /* Auto reset, signaled by default. */
if (pDevice->wasapi.hEventPlayback == NULL) {
result = ma_result_from_GetLastError(GetLastError());
if (pConfig->deviceType == ma_device_type_duplex) {
if (pDevice->wasapi.pCaptureClient != NULL) {
ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
pDevice->wasapi.pCaptureClient = NULL;
}
if (pDevice->wasapi.pAudioClientCapture != NULL) {
ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
pDevice->wasapi.pAudioClientCapture = NULL;
}
CloseHandle(pDevice->wasapi.hEventCapture);
pDevice->wasapi.hEventCapture = NULL;
}
if (pDevice->wasapi.pRenderClient != NULL) {
ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient);
pDevice->wasapi.pRenderClient = NULL;
}
if (pDevice->wasapi.pAudioClientPlayback != NULL) {
ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
pDevice->wasapi.pAudioClientPlayback = NULL;
}
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for playback.", result);
}
ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, pDevice->wasapi.hEventPlayback);
pDevice->wasapi.periodSizeInFramesPlayback = data.periodSizeInFramesOut;
ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualPeriodSizeInFramesPlayback);
/* The descriptor needs to be updated with actual values. */
pDescriptorPlayback->format = data.formatOut;
pDescriptorPlayback->channels = data.channelsOut;
pDescriptorPlayback->sampleRate = data.sampleRateOut;
MA_COPY_MEMORY(pDescriptorPlayback->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
pDescriptorPlayback->periodSizeInFrames = data.periodSizeInFramesOut;
pDescriptorPlayback->periodCount = data.periodsOut;
}
/*
We need to register a notification client to detect when the device has been disabled, unplugged or re-routed (when the default device changes). When
we are connecting to the default device we want to do automatic stream routing when the device is disabled or unplugged. Otherwise we want to just
stop the device outright and let the application handle it.
*/
#ifdef MA_WIN32_DESKTOP
if (pConfig->wasapi.noAutoStreamRouting == MA_FALSE) {
if ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.pDeviceID == NULL) {
pDevice->wasapi.allowCaptureAutoStreamRouting = MA_TRUE;
}
if ((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.pDeviceID == NULL) {
pDevice->wasapi.allowPlaybackAutoStreamRouting = MA_TRUE;
}
}
hr = ma_CoCreateInstance(pDevice->pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
if (FAILED(hr)) {
ma_device_uninit__wasapi(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.", ma_result_from_HRESULT(hr));
}
pDevice->wasapi.notificationClient.lpVtbl = (void*)&g_maNotificationCientVtbl;
pDevice->wasapi.notificationClient.counter = 1;
pDevice->wasapi.notificationClient.pDevice = pDevice;
hr = pDeviceEnumerator->lpVtbl->RegisterEndpointNotificationCallback(pDeviceEnumerator, &pDevice->wasapi.notificationClient);
if (SUCCEEDED(hr)) {
pDevice->wasapi.pDeviceEnumerator = (ma_ptr)pDeviceEnumerator;
} else {
/* Not the end of the world if we fail to register the notification callback. We just won't support automatic stream routing. */
ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
}
#endif
c89atomic_exchange_8(&pDevice->wasapi.isStartedCapture, MA_FALSE);
c89atomic_exchange_8(&pDevice->wasapi.isStartedPlayback, MA_FALSE);
return MA_SUCCESS;
}
static ma_result ma_device__get_available_frames__wasapi(ma_device* pDevice, ma_IAudioClient* pAudioClient, ma_uint32* pFrameCount)
{
ma_uint32 paddingFramesCount;
HRESULT hr;
ma_share_mode shareMode;
MA_ASSERT(pDevice != NULL);
MA_ASSERT(pFrameCount != NULL);
*pFrameCount = 0;
if ((ma_ptr)pAudioClient != pDevice->wasapi.pAudioClientPlayback && (ma_ptr)pAudioClient != pDevice->wasapi.pAudioClientCapture) {
return MA_INVALID_OPERATION;
}
hr = ma_IAudioClient_GetCurrentPadding(pAudioClient, &paddingFramesCount);
if (FAILED(hr)) {
return ma_result_from_HRESULT(hr);
}
/* Slightly different rules for exclusive and shared modes. */
shareMode = ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) ? pDevice->playback.shareMode : pDevice->capture.shareMode;
if (shareMode == ma_share_mode_exclusive) {
*pFrameCount = paddingFramesCount;
} else {
if ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) {
*pFrameCount = pDevice->wasapi.actualPeriodSizeInFramesPlayback - paddingFramesCount;
} else {
*pFrameCount = paddingFramesCount;
}
}
return MA_SUCCESS;
}
static ma_bool32 ma_device_is_reroute_required__wasapi(ma_device* pDevice, ma_device_type deviceType)
{
MA_ASSERT(pDevice != NULL);
if (deviceType == ma_device_type_playback) {
return c89atomic_load_8(&pDevice->wasapi.hasDefaultPlaybackDeviceChanged);
}
if (deviceType == ma_device_type_capture || deviceType == ma_device_type_loopback) {
return c89atomic_load_8(&pDevice->wasapi.hasDefaultCaptureDeviceChanged);
}
return MA_FALSE;
}
static ma_result ma_device_reroute__wasapi(ma_device* pDevice, ma_device_type deviceType)
{
ma_result result;
if (deviceType == ma_device_type_duplex) {
return MA_INVALID_ARGS;
}
if (deviceType == ma_device_type_playback) {
c89atomic_exchange_8(&pDevice->wasapi.hasDefaultPlaybackDeviceChanged, MA_FALSE);
}
if (deviceType == ma_device_type_capture || deviceType == ma_device_type_loopback) {
c89atomic_exchange_8(&pDevice->wasapi.hasDefaultCaptureDeviceChanged, MA_FALSE);
}
#ifdef MA_DEBUG_OUTPUT
printf("=== CHANGING DEVICE ===\n");
#endif
result = ma_device_reinit__wasapi(pDevice, deviceType);
if (result != MA_SUCCESS) {
return result;
}
ma_device__post_init_setup(pDevice, deviceType);
return MA_SUCCESS;
}
static ma_result ma_device_stop__wasapi(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
/*
It's possible for the main loop to get stuck if the device is disconnected.
In loopback mode it's possible for WaitForSingleObject() to get stuck in a deadlock when nothing is being played. When nothing
is being played, the event is never signalled internally by WASAPI which means we will deadlock when stopping the device.
*/
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
SetEvent((HANDLE)pDevice->wasapi.hEventCapture);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
SetEvent((HANDLE)pDevice->wasapi.hEventPlayback);
}
return MA_SUCCESS;
}
static ma_result ma_device_audio_thread__wasapi(ma_device* pDevice)
{
ma_result result;
HRESULT hr;
ma_bool32 exitLoop = MA_FALSE;
ma_uint32 framesWrittenToPlaybackDevice = 0;
ma_uint32 mappedDeviceBufferSizeInFramesCapture = 0;
ma_uint32 mappedDeviceBufferSizeInFramesPlayback = 0;
ma_uint32 mappedDeviceBufferFramesRemainingCapture = 0;
ma_uint32 mappedDeviceBufferFramesRemainingPlayback = 0;
BYTE* pMappedDeviceBufferCapture = NULL;
BYTE* pMappedDeviceBufferPlayback = NULL;
ma_uint32 bpfCaptureDevice = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
ma_uint32 bpfPlaybackDevice = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
ma_uint32 bpfCaptureClient = ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
ma_uint32 bpfPlaybackClient = ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
ma_uint8 inputDataInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 inputDataInClientFormatCap = sizeof(inputDataInClientFormat) / bpfCaptureClient;
ma_uint8 outputDataInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 outputDataInClientFormatCap = sizeof(outputDataInClientFormat) / bpfPlaybackClient;
ma_uint32 outputDataInClientFormatCount = 0;
ma_uint32 outputDataInClientFormatConsumed = 0;
ma_uint32 periodSizeInFramesCapture = 0;
MA_ASSERT(pDevice != NULL);
/* The capture device needs to be started immediately. */
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
periodSizeInFramesCapture = pDevice->capture.internalPeriodSizeInFrames;
hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal capture device.", ma_result_from_HRESULT(hr));
}
c89atomic_exchange_8(&pDevice->wasapi.isStartedCapture, MA_TRUE);
}
while (ma_device_get_state(pDevice) == MA_STATE_STARTED && !exitLoop) {
/* We may need to reroute the device. */
if (ma_device_is_reroute_required__wasapi(pDevice, ma_device_type_playback)) {
result = ma_device_reroute__wasapi(pDevice, ma_device_type_playback);
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
}
if (ma_device_is_reroute_required__wasapi(pDevice, ma_device_type_capture)) {
result = ma_device_reroute__wasapi(pDevice, (pDevice->type == ma_device_type_loopback) ? ma_device_type_loopback : ma_device_type_capture);
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
}
switch (pDevice->type)
{
case ma_device_type_duplex:
{
ma_uint32 framesAvailableCapture;
ma_uint32 framesAvailablePlayback;
DWORD flagsCapture; /* Passed to IAudioCaptureClient_GetBuffer(). */
/* The process is to map the playback buffer and fill it as quickly as possible from input data. */
if (pMappedDeviceBufferPlayback == NULL) {
/* WASAPI is weird with exclusive mode. You need to wait on the event _before_ querying the available frames. */
if (pDevice->playback.shareMode == ma_share_mode_exclusive) {
if (WaitForSingleObject(pDevice->wasapi.hEventPlayback, INFINITE) != WAIT_OBJECT_0) {
return MA_ERROR; /* Wait failed. */
}
}
result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &framesAvailablePlayback);
if (result != MA_SUCCESS) {
return result;
}
/*printf("TRACE 1: framesAvailablePlayback=%d\n", framesAvailablePlayback);*/
/* In exclusive mode, the frame count needs to exactly match the value returned by GetCurrentPadding(). */
if (pDevice->playback.shareMode != ma_share_mode_exclusive) {
if (framesAvailablePlayback > pDevice->wasapi.periodSizeInFramesPlayback) {
framesAvailablePlayback = pDevice->wasapi.periodSizeInFramesPlayback;
}
}
/* If there's no frames available in the playback device we need to wait for more. */
if (framesAvailablePlayback == 0) {
/* In exclusive mode we waited at the top. */
if (pDevice->playback.shareMode != ma_share_mode_exclusive) {
if (WaitForSingleObject(pDevice->wasapi.hEventPlayback, INFINITE) != WAIT_OBJECT_0) {
return MA_ERROR; /* Wait failed. */
}
}
continue;
}
/* We're ready to map the playback device's buffer. We don't release this until it's been entirely filled. */
hr = ma_IAudioRenderClient_GetBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, framesAvailablePlayback, &pMappedDeviceBufferPlayback);
if (FAILED(hr)) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from playback device in preparation for writing to the device.", ma_result_from_HRESULT(hr));
exitLoop = MA_TRUE;
break;
}
mappedDeviceBufferSizeInFramesPlayback = framesAvailablePlayback;
mappedDeviceBufferFramesRemainingPlayback = framesAvailablePlayback;
}
/* At this point we should have a buffer available for output. We need to keep writing input samples to it. */
for (;;) {
/* Try grabbing some captured data if we haven't already got a mapped buffer. */
if (pMappedDeviceBufferCapture == NULL) {
if (pDevice->capture.shareMode == ma_share_mode_shared) {
if (WaitForSingleObject(pDevice->wasapi.hEventCapture, INFINITE) != WAIT_OBJECT_0) {
return MA_ERROR; /* Wait failed. */
}
}
result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &framesAvailableCapture);
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
/*printf("TRACE 2: framesAvailableCapture=%d\n", framesAvailableCapture);*/
/* Wait for more if nothing is available. */
if (framesAvailableCapture == 0) {
/* In exclusive mode we waited at the top. */
if (pDevice->capture.shareMode != ma_share_mode_shared) {
if (WaitForSingleObject(pDevice->wasapi.hEventCapture, INFINITE) != WAIT_OBJECT_0) {
return MA_ERROR; /* Wait failed. */
}
}
continue;
}
/* Getting here means there's data available for writing to the output device. */
mappedDeviceBufferSizeInFramesCapture = ma_min(framesAvailableCapture, periodSizeInFramesCapture);
hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pMappedDeviceBufferCapture, &mappedDeviceBufferSizeInFramesCapture, &flagsCapture, NULL, NULL);
if (FAILED(hr)) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from capture device in preparation for writing to the device.", ma_result_from_HRESULT(hr));
exitLoop = MA_TRUE;
break;
}
/* Overrun detection. */
if ((flagsCapture & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) {
/* Glitched. Probably due to an overrun. */
#ifdef MA_DEBUG_OUTPUT
printf("[WASAPI] Data discontinuity (possible overrun). framesAvailableCapture=%d, mappedBufferSizeInFramesCapture=%d\n", framesAvailableCapture, mappedDeviceBufferSizeInFramesCapture);
#endif
/*
Exeriment: If we get an overrun it probably means we're straddling the end of the buffer. In order to prevent a never-ending sequence of glitches let's experiment
by dropping every frame until we're left with only a single period. To do this we just keep retrieving and immediately releasing buffers until we're down to the
last period.
*/
if (framesAvailableCapture >= pDevice->wasapi.actualPeriodSizeInFramesCapture) {
#ifdef MA_DEBUG_OUTPUT
printf("[WASAPI] Synchronizing capture stream. ");
#endif
do
{
hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, mappedDeviceBufferSizeInFramesCapture);
if (FAILED(hr)) {
break;
}
framesAvailableCapture -= mappedDeviceBufferSizeInFramesCapture;
if (framesAvailableCapture > 0) {
mappedDeviceBufferSizeInFramesCapture = ma_min(framesAvailableCapture, periodSizeInFramesCapture);
hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pMappedDeviceBufferCapture, &mappedDeviceBufferSizeInFramesCapture, &flagsCapture, NULL, NULL);
if (FAILED(hr)) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from capture device in preparation for writing to the device.", ma_result_from_HRESULT(hr));
exitLoop = MA_TRUE;
break;
}
} else {
pMappedDeviceBufferCapture = NULL;
mappedDeviceBufferSizeInFramesCapture = 0;
}
} while (framesAvailableCapture > periodSizeInFramesCapture);
#ifdef MA_DEBUG_OUTPUT
printf("framesAvailableCapture=%d, mappedBufferSizeInFramesCapture=%d\n", framesAvailableCapture, mappedDeviceBufferSizeInFramesCapture);
#endif
}
} else {
#ifdef MA_DEBUG_OUTPUT
if (flagsCapture != 0) {
printf("[WASAPI] Capture Flags: %ld\n", flagsCapture);
}
#endif
}
mappedDeviceBufferFramesRemainingCapture = mappedDeviceBufferSizeInFramesCapture;
}
/* At this point we should have both input and output data available. We now need to convert the data and post it to the client. */
for (;;) {
BYTE* pRunningDeviceBufferCapture;
BYTE* pRunningDeviceBufferPlayback;
ma_uint32 framesToProcess;
ma_uint32 framesProcessed;
pRunningDeviceBufferCapture = pMappedDeviceBufferCapture + ((mappedDeviceBufferSizeInFramesCapture - mappedDeviceBufferFramesRemainingCapture ) * bpfCaptureDevice);
pRunningDeviceBufferPlayback = pMappedDeviceBufferPlayback + ((mappedDeviceBufferSizeInFramesPlayback - mappedDeviceBufferFramesRemainingPlayback) * bpfPlaybackDevice);
/* There may be some data sitting in the converter that needs to be processed first. Once this is exhaused, run the data callback again. */
if (!pDevice->playback.converter.isPassthrough && outputDataInClientFormatConsumed < outputDataInClientFormatCount) {
ma_uint64 convertedFrameCountClient = (outputDataInClientFormatCount - outputDataInClientFormatConsumed);
ma_uint64 convertedFrameCountDevice = mappedDeviceBufferFramesRemainingPlayback;
void* pConvertedFramesClient = outputDataInClientFormat + (outputDataInClientFormatConsumed * bpfPlaybackClient);
void* pConvertedFramesDevice = pRunningDeviceBufferPlayback;
result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, pConvertedFramesClient, &convertedFrameCountClient, pConvertedFramesDevice, &convertedFrameCountDevice);
if (result != MA_SUCCESS) {
break;
}
outputDataInClientFormatConsumed += (ma_uint32)convertedFrameCountClient; /* Safe cast. */
mappedDeviceBufferFramesRemainingPlayback -= (ma_uint32)convertedFrameCountDevice; /* Safe cast. */
if (mappedDeviceBufferFramesRemainingPlayback == 0) {
break;
}
}
/*
Getting here means we need to fire the callback. If format conversion is unnecessary, we can optimize this by passing the pointers to the internal
buffers directly to the callback.
*/
if (pDevice->capture.converter.isPassthrough && pDevice->playback.converter.isPassthrough) {
/* Optimal path. We can pass mapped pointers directly to the callback. */
framesToProcess = ma_min(mappedDeviceBufferFramesRemainingCapture, mappedDeviceBufferFramesRemainingPlayback);
framesProcessed = framesToProcess;
ma_device__on_data(pDevice, pRunningDeviceBufferPlayback, pRunningDeviceBufferCapture, framesToProcess);
mappedDeviceBufferFramesRemainingCapture -= framesProcessed;
mappedDeviceBufferFramesRemainingPlayback -= framesProcessed;
if (mappedDeviceBufferFramesRemainingCapture == 0) {
break; /* Exhausted input data. */
}
if (mappedDeviceBufferFramesRemainingPlayback == 0) {
break; /* Exhausted output data. */
}
} else if (pDevice->capture.converter.isPassthrough) {
/* The input buffer is a passthrough, but the playback buffer requires a conversion. */
framesToProcess = ma_min(mappedDeviceBufferFramesRemainingCapture, outputDataInClientFormatCap);
framesProcessed = framesToProcess;
ma_device__on_data(pDevice, outputDataInClientFormat, pRunningDeviceBufferCapture, framesToProcess);
outputDataInClientFormatCount = framesProcessed;
outputDataInClientFormatConsumed = 0;
mappedDeviceBufferFramesRemainingCapture -= framesProcessed;
if (mappedDeviceBufferFramesRemainingCapture == 0) {
break; /* Exhausted input data. */
}
} else if (pDevice->playback.converter.isPassthrough) {
/* The input buffer requires conversion, the playback buffer is passthrough. */
ma_uint64 capturedDeviceFramesToProcess = mappedDeviceBufferFramesRemainingCapture;
ma_uint64 capturedClientFramesToProcess = ma_min(inputDataInClientFormatCap, mappedDeviceBufferFramesRemainingPlayback);
result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningDeviceBufferCapture, &capturedDeviceFramesToProcess, inputDataInClientFormat, &capturedClientFramesToProcess);
if (result != MA_SUCCESS) {
break;
}
if (capturedClientFramesToProcess == 0) {
break;
}
ma_device__on_data(pDevice, pRunningDeviceBufferPlayback, inputDataInClientFormat, (ma_uint32)capturedClientFramesToProcess); /* Safe cast. */
mappedDeviceBufferFramesRemainingCapture -= (ma_uint32)capturedDeviceFramesToProcess;
mappedDeviceBufferFramesRemainingPlayback -= (ma_uint32)capturedClientFramesToProcess;
} else {
ma_uint64 capturedDeviceFramesToProcess = mappedDeviceBufferFramesRemainingCapture;
ma_uint64 capturedClientFramesToProcess = ma_min(inputDataInClientFormatCap, outputDataInClientFormatCap);
result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningDeviceBufferCapture, &capturedDeviceFramesToProcess, inputDataInClientFormat, &capturedClientFramesToProcess);
if (result != MA_SUCCESS) {
break;
}
if (capturedClientFramesToProcess == 0) {
break;
}
ma_device__on_data(pDevice, outputDataInClientFormat, inputDataInClientFormat, (ma_uint32)capturedClientFramesToProcess);
mappedDeviceBufferFramesRemainingCapture -= (ma_uint32)capturedDeviceFramesToProcess;
outputDataInClientFormatCount = (ma_uint32)capturedClientFramesToProcess;
outputDataInClientFormatConsumed = 0;
}
}
/* If at this point we've run out of capture data we need to release the buffer. */
if (mappedDeviceBufferFramesRemainingCapture == 0 && pMappedDeviceBufferCapture != NULL) {
hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, mappedDeviceBufferSizeInFramesCapture);
if (FAILED(hr)) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to release internal buffer from capture device after reading from the device.", ma_result_from_HRESULT(hr));
exitLoop = MA_TRUE;
break;
}
/*printf("TRACE: Released capture buffer\n");*/
pMappedDeviceBufferCapture = NULL;
mappedDeviceBufferFramesRemainingCapture = 0;
mappedDeviceBufferSizeInFramesCapture = 0;
}
/* Get out of this loop if we're run out of room in the playback buffer. */
if (mappedDeviceBufferFramesRemainingPlayback == 0) {
break;
}
}
/* If at this point we've run out of data we need to release the buffer. */
if (mappedDeviceBufferFramesRemainingPlayback == 0 && pMappedDeviceBufferPlayback != NULL) {
hr = ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, mappedDeviceBufferSizeInFramesPlayback, 0);
if (FAILED(hr)) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to release internal buffer from playback device after writing to the device.", ma_result_from_HRESULT(hr));
exitLoop = MA_TRUE;
break;
}
/*printf("TRACE: Released playback buffer\n");*/
framesWrittenToPlaybackDevice += mappedDeviceBufferSizeInFramesPlayback;
pMappedDeviceBufferPlayback = NULL;
mappedDeviceBufferFramesRemainingPlayback = 0;
mappedDeviceBufferSizeInFramesPlayback = 0;
}
if (!c89atomic_load_8(&pDevice->wasapi.isStartedPlayback)) {
ma_uint32 startThreshold = pDevice->playback.internalPeriodSizeInFrames * 1;
/* Prevent a deadlock. If we don't clamp against the actual buffer size we'll never end up starting the playback device which will result in a deadlock. */
if (startThreshold > pDevice->wasapi.actualPeriodSizeInFramesPlayback) {
startThreshold = pDevice->wasapi.actualPeriodSizeInFramesPlayback;
}
if (pDevice->playback.shareMode == ma_share_mode_exclusive || framesWrittenToPlaybackDevice >= startThreshold) {
hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
if (FAILED(hr)) {
ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal playback device.", ma_result_from_HRESULT(hr));
}
c89atomic_exchange_8(&pDevice->wasapi.isStartedPlayback, MA_TRUE);
}
}
} break;
case ma_device_type_capture:
case ma_device_type_loopback:
{
ma_uint32 framesAvailableCapture;
DWORD flagsCapture; /* Passed to IAudioCaptureClient_GetBuffer(). */
/* Wait for data to become available first. */
if (WaitForSingleObject(pDevice->wasapi.hEventCapture, INFINITE) != WAIT_OBJECT_0) {
exitLoop = MA_TRUE;
break; /* Wait failed. */
}
/* See how many frames are available. Since we waited at the top, I don't think this should ever return 0. I'm checking for this anyway. */
result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &framesAvailableCapture);
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
if (framesAvailableCapture < pDevice->wasapi.periodSizeInFramesCapture) {
continue; /* Nothing available. Keep waiting. */
}
/* Map the data buffer in preparation for sending to the client. */
mappedDeviceBufferSizeInFramesCapture = framesAvailableCapture;
hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pMappedDeviceBufferCapture, &mappedDeviceBufferSizeInFramesCapture, &flagsCapture, NULL, NULL);
if (FAILED(hr)) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from capture device in preparation for writing to the device.", ma_result_from_HRESULT(hr));
exitLoop = MA_TRUE;
break;
}
/* Overrun detection. */
if ((flagsCapture & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) {
/* Glitched. Probably due to an overrun. */
#ifdef MA_DEBUG_OUTPUT
printf("[WASAPI] Data discontinuity (possible overrun). framesAvailableCapture=%d, mappedBufferSizeInFramesCapture=%d\n", framesAvailableCapture, mappedDeviceBufferSizeInFramesCapture);
#endif
/*
Exeriment: If we get an overrun it probably means we're straddling the end of the buffer. In order to prevent a never-ending sequence of glitches let's experiment
by dropping every frame until we're left with only a single period. To do this we just keep retrieving and immediately releasing buffers until we're down to the
last period.
*/
if (framesAvailableCapture >= pDevice->wasapi.actualPeriodSizeInFramesCapture) {
#ifdef MA_DEBUG_OUTPUT
printf("[WASAPI] Synchronizing capture stream. ");
#endif
do
{
hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, mappedDeviceBufferSizeInFramesCapture);
if (FAILED(hr)) {
break;
}
framesAvailableCapture -= mappedDeviceBufferSizeInFramesCapture;
if (framesAvailableCapture > 0) {
mappedDeviceBufferSizeInFramesCapture = ma_min(framesAvailableCapture, periodSizeInFramesCapture);
hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pMappedDeviceBufferCapture, &mappedDeviceBufferSizeInFramesCapture, &flagsCapture, NULL, NULL);
if (FAILED(hr)) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from capture device in preparation for writing to the device.", ma_result_from_HRESULT(hr));
exitLoop = MA_TRUE;
break;
}
} else {
pMappedDeviceBufferCapture = NULL;
mappedDeviceBufferSizeInFramesCapture = 0;
}
} while (framesAvailableCapture > periodSizeInFramesCapture);
#ifdef MA_DEBUG_OUTPUT
printf("framesAvailableCapture=%d, mappedBufferSizeInFramesCapture=%d\n", framesAvailableCapture, mappedDeviceBufferSizeInFramesCapture);
#endif
}
} else {
#ifdef MA_DEBUG_OUTPUT
if (flagsCapture != 0) {
printf("[WASAPI] Capture Flags: %ld\n", flagsCapture);
}
#endif
}
/* We should have a buffer at this point, but let's just do a sanity check anyway. */
if (mappedDeviceBufferSizeInFramesCapture > 0 && pMappedDeviceBufferCapture != NULL) {
ma_device__send_frames_to_client(pDevice, mappedDeviceBufferSizeInFramesCapture, pMappedDeviceBufferCapture);
/* At this point we're done with the buffer. */
hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, mappedDeviceBufferSizeInFramesCapture);
pMappedDeviceBufferCapture = NULL; /* <-- Important. Not doing this can result in an error once we leave this loop because it will use this to know whether or not a final ReleaseBuffer() needs to be called. */
mappedDeviceBufferSizeInFramesCapture = 0;
if (FAILED(hr)) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to release internal buffer from capture device after reading from the device.", ma_result_from_HRESULT(hr));
exitLoop = MA_TRUE;
break;
}
}
} break;
case ma_device_type_playback:
{
ma_uint32 framesAvailablePlayback;
/* Wait for space to become available first. */
if (WaitForSingleObject(pDevice->wasapi.hEventPlayback, INFINITE) != WAIT_OBJECT_0) {
exitLoop = MA_TRUE;
break; /* Wait failed. */
}
/* Check how much space is available. If this returns 0 we just keep waiting. */
result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &framesAvailablePlayback);
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
if (framesAvailablePlayback < pDevice->wasapi.periodSizeInFramesPlayback) {
continue; /* No space available. */
}
/* Map a the data buffer in preparation for the callback. */
hr = ma_IAudioRenderClient_GetBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, framesAvailablePlayback, &pMappedDeviceBufferPlayback);
if (FAILED(hr)) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from playback device in preparation for writing to the device.", ma_result_from_HRESULT(hr));
exitLoop = MA_TRUE;
break;
}
/* We should have a buffer at this point. */
ma_device__read_frames_from_client(pDevice, framesAvailablePlayback, pMappedDeviceBufferPlayback);
/* At this point we're done writing to the device and we just need to release the buffer. */
hr = ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, framesAvailablePlayback, 0);
pMappedDeviceBufferPlayback = NULL; /* <-- Important. Not doing this can result in an error once we leave this loop because it will use this to know whether or not a final ReleaseBuffer() needs to be called. */
mappedDeviceBufferSizeInFramesPlayback = 0;
if (FAILED(hr)) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to release internal buffer from playback device after writing to the device.", ma_result_from_HRESULT(hr));
exitLoop = MA_TRUE;
break;
}
framesWrittenToPlaybackDevice += framesAvailablePlayback;
if (!c89atomic_load_8(&pDevice->wasapi.isStartedPlayback)) {
if (pDevice->playback.shareMode == ma_share_mode_exclusive || framesWrittenToPlaybackDevice >= pDevice->playback.internalPeriodSizeInFrames*1) {
hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
if (FAILED(hr)) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal playback device.", ma_result_from_HRESULT(hr));
exitLoop = MA_TRUE;
break;
}
c89atomic_exchange_8(&pDevice->wasapi.isStartedPlayback, MA_TRUE);
}
}
} break;
default: return MA_INVALID_ARGS;
}
}
/* Here is where the device needs to be stopped. */
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
/* Any mapped buffers need to be released. */
if (pMappedDeviceBufferCapture != NULL) {
hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, mappedDeviceBufferSizeInFramesCapture);
}
hr = ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal capture device.", ma_result_from_HRESULT(hr));
}
/* The audio client needs to be reset otherwise restarting will fail. */
hr = ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal capture device.", ma_result_from_HRESULT(hr));
}
c89atomic_exchange_8(&pDevice->wasapi.isStartedCapture, MA_FALSE);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
/* Any mapped buffers need to be released. */
if (pMappedDeviceBufferPlayback != NULL) {
hr = ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, mappedDeviceBufferSizeInFramesPlayback, 0);
}
/*
The buffer needs to be drained before stopping the device. Not doing this will result in the last few frames not getting output to
the speakers. This is a problem for very short sounds because it'll result in a significant portion of it not getting played.
*/
if (c89atomic_load_8(&pDevice->wasapi.isStartedPlayback)) {
/* We need to make sure we put a timeout here or else we'll risk getting stuck in a deadlock in some cases. */
DWORD waitTime = pDevice->wasapi.actualPeriodSizeInFramesPlayback / pDevice->playback.internalSampleRate;
if (pDevice->playback.shareMode == ma_share_mode_exclusive) {
WaitForSingleObject(pDevice->wasapi.hEventPlayback, waitTime);
} else {
ma_uint32 prevFramesAvaialablePlayback = (ma_uint32)-1;
ma_uint32 framesAvailablePlayback;
for (;;) {
result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &framesAvailablePlayback);
if (result != MA_SUCCESS) {
break;
}
if (framesAvailablePlayback >= pDevice->wasapi.actualPeriodSizeInFramesPlayback) {
break;
}
/*
Just a safety check to avoid an infinite loop. If this iteration results in a situation where the number of available frames
has not changed, get out of the loop. I don't think this should ever happen, but I think it's nice to have just in case.
*/
if (framesAvailablePlayback == prevFramesAvaialablePlayback) {
break;
}
prevFramesAvaialablePlayback = framesAvailablePlayback;
WaitForSingleObject(pDevice->wasapi.hEventPlayback, waitTime);
ResetEvent(pDevice->wasapi.hEventPlayback); /* Manual reset. */
}
}
}
hr = ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal playback device.", ma_result_from_HRESULT(hr));
}
/* The audio client needs to be reset otherwise restarting will fail. */
hr = ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal playback device.", ma_result_from_HRESULT(hr));
}
c89atomic_exchange_8(&pDevice->wasapi.isStartedPlayback, MA_FALSE);
}
return MA_SUCCESS;
}
static ma_result ma_context_uninit__wasapi(ma_context* pContext)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pContext->backend == ma_backend_wasapi);
(void)pContext;
return MA_SUCCESS;
}
static ma_result ma_context_init__wasapi(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
{
ma_result result = MA_SUCCESS;
MA_ASSERT(pContext != NULL);
(void)pConfig;
#ifdef MA_WIN32_DESKTOP
/*
WASAPI is only supported in Vista SP1 and newer. The reason for SP1 and not the base version of Vista is that event-driven
exclusive mode does not work until SP1.
Unfortunately older compilers don't define these functions so we need to dynamically load them in order to avoid a link error.
*/
{
ma_OSVERSIONINFOEXW osvi;
ma_handle kernel32DLL;
ma_PFNVerifyVersionInfoW _VerifyVersionInfoW;
ma_PFNVerSetConditionMask _VerSetConditionMask;
kernel32DLL = ma_dlopen(pContext, "kernel32.dll");
if (kernel32DLL == NULL) {
return MA_NO_BACKEND;
}
_VerifyVersionInfoW = (ma_PFNVerifyVersionInfoW )ma_dlsym(pContext, kernel32DLL, "VerifyVersionInfoW");
_VerSetConditionMask = (ma_PFNVerSetConditionMask)ma_dlsym(pContext, kernel32DLL, "VerSetConditionMask");
if (_VerifyVersionInfoW == NULL || _VerSetConditionMask == NULL) {
ma_dlclose(pContext, kernel32DLL);
return MA_NO_BACKEND;
}
MA_ZERO_OBJECT(&osvi);
osvi.dwOSVersionInfoSize = sizeof(osvi);
osvi.dwMajorVersion = ((MA_WIN32_WINNT_VISTA >> 8) & 0xFF);
osvi.dwMinorVersion = ((MA_WIN32_WINNT_VISTA >> 0) & 0xFF);
osvi.wServicePackMajor = 1;
if (_VerifyVersionInfoW(&osvi, MA_VER_MAJORVERSION | MA_VER_MINORVERSION | MA_VER_SERVICEPACKMAJOR, _VerSetConditionMask(_VerSetConditionMask(_VerSetConditionMask(0, MA_VER_MAJORVERSION, MA_VER_GREATER_EQUAL), MA_VER_MINORVERSION, MA_VER_GREATER_EQUAL), MA_VER_SERVICEPACKMAJOR, MA_VER_GREATER_EQUAL))) {
result = MA_SUCCESS;
} else {
result = MA_NO_BACKEND;
}
ma_dlclose(pContext, kernel32DLL);
}
#endif
if (result != MA_SUCCESS) {
return result;
}
pCallbacks->onContextInit = ma_context_init__wasapi;
pCallbacks->onContextUninit = ma_context_uninit__wasapi;
pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__wasapi;
pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__wasapi;
pCallbacks->onDeviceInit = ma_device_init__wasapi;
pCallbacks->onDeviceUninit = ma_device_uninit__wasapi;
pCallbacks->onDeviceStart = NULL; /* Not used. Started in onDeviceAudioThread. */
pCallbacks->onDeviceStop = ma_device_stop__wasapi; /* Required to ensure the capture event is signalled when stopping a loopback device while nothing is playing. */
pCallbacks->onDeviceRead = NULL; /* Not used. Reading is done manually in the audio thread. */
pCallbacks->onDeviceWrite = NULL; /* Not used. Writing is done manually in the audio thread. */
pCallbacks->onDeviceAudioThread = ma_device_audio_thread__wasapi;
return result;
}
#endif
/******************************************************************************
DirectSound Backend
******************************************************************************/
#ifdef MA_HAS_DSOUND
/*#include */
/*static const GUID MA_GUID_IID_DirectSoundNotify = {0xb0210783, 0x89cd, 0x11d0, {0xaf, 0x08, 0x00, 0xa0, 0xc9, 0x25, 0xcd, 0x16}};*/
/* miniaudio only uses priority or exclusive modes. */
#define MA_DSSCL_NORMAL 1
#define MA_DSSCL_PRIORITY 2
#define MA_DSSCL_EXCLUSIVE 3
#define MA_DSSCL_WRITEPRIMARY 4
#define MA_DSCAPS_PRIMARYMONO 0x00000001
#define MA_DSCAPS_PRIMARYSTEREO 0x00000002
#define MA_DSCAPS_PRIMARY8BIT 0x00000004
#define MA_DSCAPS_PRIMARY16BIT 0x00000008
#define MA_DSCAPS_CONTINUOUSRATE 0x00000010
#define MA_DSCAPS_EMULDRIVER 0x00000020
#define MA_DSCAPS_CERTIFIED 0x00000040
#define MA_DSCAPS_SECONDARYMONO 0x00000100
#define MA_DSCAPS_SECONDARYSTEREO 0x00000200
#define MA_DSCAPS_SECONDARY8BIT 0x00000400
#define MA_DSCAPS_SECONDARY16BIT 0x00000800
#define MA_DSBCAPS_PRIMARYBUFFER 0x00000001
#define MA_DSBCAPS_STATIC 0x00000002
#define MA_DSBCAPS_LOCHARDWARE 0x00000004
#define MA_DSBCAPS_LOCSOFTWARE 0x00000008
#define MA_DSBCAPS_CTRL3D 0x00000010
#define MA_DSBCAPS_CTRLFREQUENCY 0x00000020
#define MA_DSBCAPS_CTRLPAN 0x00000040
#define MA_DSBCAPS_CTRLVOLUME 0x00000080
#define MA_DSBCAPS_CTRLPOSITIONNOTIFY 0x00000100
#define MA_DSBCAPS_CTRLFX 0x00000200
#define MA_DSBCAPS_STICKYFOCUS 0x00004000
#define MA_DSBCAPS_GLOBALFOCUS 0x00008000
#define MA_DSBCAPS_GETCURRENTPOSITION2 0x00010000
#define MA_DSBCAPS_MUTE3DATMAXDISTANCE 0x00020000
#define MA_DSBCAPS_LOCDEFER 0x00040000
#define MA_DSBCAPS_TRUEPLAYPOSITION 0x00080000
#define MA_DSBPLAY_LOOPING 0x00000001
#define MA_DSBPLAY_LOCHARDWARE 0x00000002
#define MA_DSBPLAY_LOCSOFTWARE 0x00000004
#define MA_DSBPLAY_TERMINATEBY_TIME 0x00000008
#define MA_DSBPLAY_TERMINATEBY_DISTANCE 0x00000010
#define MA_DSBPLAY_TERMINATEBY_PRIORITY 0x00000020
#define MA_DSCBSTART_LOOPING 0x00000001
typedef struct
{
DWORD dwSize;
DWORD dwFlags;
DWORD dwBufferBytes;
DWORD dwReserved;
WAVEFORMATEX* lpwfxFormat;
GUID guid3DAlgorithm;
} MA_DSBUFFERDESC;
typedef struct
{
DWORD dwSize;
DWORD dwFlags;
DWORD dwBufferBytes;
DWORD dwReserved;
WAVEFORMATEX* lpwfxFormat;
DWORD dwFXCount;
void* lpDSCFXDesc; /* <-- miniaudio doesn't use this, so set to void*. */
} MA_DSCBUFFERDESC;
typedef struct
{
DWORD dwSize;
DWORD dwFlags;
DWORD dwMinSecondarySampleRate;
DWORD dwMaxSecondarySampleRate;
DWORD dwPrimaryBuffers;
DWORD dwMaxHwMixingAllBuffers;
DWORD dwMaxHwMixingStaticBuffers;
DWORD dwMaxHwMixingStreamingBuffers;
DWORD dwFreeHwMixingAllBuffers;
DWORD dwFreeHwMixingStaticBuffers;
DWORD dwFreeHwMixingStreamingBuffers;
DWORD dwMaxHw3DAllBuffers;
DWORD dwMaxHw3DStaticBuffers;
DWORD dwMaxHw3DStreamingBuffers;
DWORD dwFreeHw3DAllBuffers;
DWORD dwFreeHw3DStaticBuffers;
DWORD dwFreeHw3DStreamingBuffers;
DWORD dwTotalHwMemBytes;
DWORD dwFreeHwMemBytes;
DWORD dwMaxContigFreeHwMemBytes;
DWORD dwUnlockTransferRateHwBuffers;
DWORD dwPlayCpuOverheadSwBuffers;
DWORD dwReserved1;
DWORD dwReserved2;
} MA_DSCAPS;
typedef struct
{
DWORD dwSize;
DWORD dwFlags;
DWORD dwBufferBytes;
DWORD dwUnlockTransferRate;
DWORD dwPlayCpuOverhead;
} MA_DSBCAPS;
typedef struct
{
DWORD dwSize;
DWORD dwFlags;
DWORD dwFormats;
DWORD dwChannels;
} MA_DSCCAPS;
typedef struct
{
DWORD dwSize;
DWORD dwFlags;
DWORD dwBufferBytes;
DWORD dwReserved;
} MA_DSCBCAPS;
typedef struct
{
DWORD dwOffset;
HANDLE hEventNotify;
} MA_DSBPOSITIONNOTIFY;
typedef struct ma_IDirectSound ma_IDirectSound;
typedef struct ma_IDirectSoundBuffer ma_IDirectSoundBuffer;
typedef struct ma_IDirectSoundCapture ma_IDirectSoundCapture;
typedef struct ma_IDirectSoundCaptureBuffer ma_IDirectSoundCaptureBuffer;
typedef struct ma_IDirectSoundNotify ma_IDirectSoundNotify;
/*
COM objects. The way these work is that you have a vtable (a list of function pointers, kind of
like how C++ works internally), and then you have a structure with a single member, which is a
pointer to the vtable. The vtable is where the methods of the object are defined. Methods need
to be in a specific order, and parent classes need to have their methods declared first.
*/
/* IDirectSound */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSound* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSound* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSound* pThis);
/* IDirectSound */
HRESULT (STDMETHODCALLTYPE * CreateSoundBuffer) (ma_IDirectSound* pThis, const MA_DSBUFFERDESC* pDSBufferDesc, ma_IDirectSoundBuffer** ppDSBuffer, void* pUnkOuter);
HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSound* pThis, MA_DSCAPS* pDSCaps);
HRESULT (STDMETHODCALLTYPE * DuplicateSoundBuffer)(ma_IDirectSound* pThis, ma_IDirectSoundBuffer* pDSBufferOriginal, ma_IDirectSoundBuffer** ppDSBufferDuplicate);
HRESULT (STDMETHODCALLTYPE * SetCooperativeLevel) (ma_IDirectSound* pThis, HWND hwnd, DWORD dwLevel);
HRESULT (STDMETHODCALLTYPE * Compact) (ma_IDirectSound* pThis);
HRESULT (STDMETHODCALLTYPE * GetSpeakerConfig) (ma_IDirectSound* pThis, DWORD* pSpeakerConfig);
HRESULT (STDMETHODCALLTYPE * SetSpeakerConfig) (ma_IDirectSound* pThis, DWORD dwSpeakerConfig);
HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSound* pThis, const GUID* pGuidDevice);
} ma_IDirectSoundVtbl;
struct ma_IDirectSound
{
ma_IDirectSoundVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IDirectSound_QueryInterface(ma_IDirectSound* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IDirectSound_AddRef(ma_IDirectSound* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IDirectSound_Release(ma_IDirectSound* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IDirectSound_CreateSoundBuffer(ma_IDirectSound* pThis, const MA_DSBUFFERDESC* pDSBufferDesc, ma_IDirectSoundBuffer** ppDSBuffer, void* pUnkOuter) { return pThis->lpVtbl->CreateSoundBuffer(pThis, pDSBufferDesc, ppDSBuffer, pUnkOuter); }
static MA_INLINE HRESULT ma_IDirectSound_GetCaps(ma_IDirectSound* pThis, MA_DSCAPS* pDSCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCaps); }
static MA_INLINE HRESULT ma_IDirectSound_DuplicateSoundBuffer(ma_IDirectSound* pThis, ma_IDirectSoundBuffer* pDSBufferOriginal, ma_IDirectSoundBuffer** ppDSBufferDuplicate) { return pThis->lpVtbl->DuplicateSoundBuffer(pThis, pDSBufferOriginal, ppDSBufferDuplicate); }
static MA_INLINE HRESULT ma_IDirectSound_SetCooperativeLevel(ma_IDirectSound* pThis, HWND hwnd, DWORD dwLevel) { return pThis->lpVtbl->SetCooperativeLevel(pThis, hwnd, dwLevel); }
static MA_INLINE HRESULT ma_IDirectSound_Compact(ma_IDirectSound* pThis) { return pThis->lpVtbl->Compact(pThis); }
static MA_INLINE HRESULT ma_IDirectSound_GetSpeakerConfig(ma_IDirectSound* pThis, DWORD* pSpeakerConfig) { return pThis->lpVtbl->GetSpeakerConfig(pThis, pSpeakerConfig); }
static MA_INLINE HRESULT ma_IDirectSound_SetSpeakerConfig(ma_IDirectSound* pThis, DWORD dwSpeakerConfig) { return pThis->lpVtbl->SetSpeakerConfig(pThis, dwSpeakerConfig); }
static MA_INLINE HRESULT ma_IDirectSound_Initialize(ma_IDirectSound* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); }
/* IDirectSoundBuffer */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundBuffer* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundBuffer* pThis);
/* IDirectSoundBuffer */
HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundBuffer* pThis, MA_DSBCAPS* pDSBufferCaps);
HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(ma_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor);
HRESULT (STDMETHODCALLTYPE * GetFormat) (ma_IDirectSoundBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten);
HRESULT (STDMETHODCALLTYPE * GetVolume) (ma_IDirectSoundBuffer* pThis, LONG* pVolume);
HRESULT (STDMETHODCALLTYPE * GetPan) (ma_IDirectSoundBuffer* pThis, LONG* pPan);
HRESULT (STDMETHODCALLTYPE * GetFrequency) (ma_IDirectSoundBuffer* pThis, DWORD* pFrequency);
HRESULT (STDMETHODCALLTYPE * GetStatus) (ma_IDirectSoundBuffer* pThis, DWORD* pStatus);
HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundBuffer* pThis, ma_IDirectSound* pDirectSound, const MA_DSBUFFERDESC* pDSBufferDesc);
HRESULT (STDMETHODCALLTYPE * Lock) (ma_IDirectSoundBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags);
HRESULT (STDMETHODCALLTYPE * Play) (ma_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags);
HRESULT (STDMETHODCALLTYPE * SetCurrentPosition)(ma_IDirectSoundBuffer* pThis, DWORD dwNewPosition);
HRESULT (STDMETHODCALLTYPE * SetFormat) (ma_IDirectSoundBuffer* pThis, const WAVEFORMATEX* pFormat);
HRESULT (STDMETHODCALLTYPE * SetVolume) (ma_IDirectSoundBuffer* pThis, LONG volume);
HRESULT (STDMETHODCALLTYPE * SetPan) (ma_IDirectSoundBuffer* pThis, LONG pan);
HRESULT (STDMETHODCALLTYPE * SetFrequency) (ma_IDirectSoundBuffer* pThis, DWORD dwFrequency);
HRESULT (STDMETHODCALLTYPE * Stop) (ma_IDirectSoundBuffer* pThis);
HRESULT (STDMETHODCALLTYPE * Unlock) (ma_IDirectSoundBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2);
HRESULT (STDMETHODCALLTYPE * Restore) (ma_IDirectSoundBuffer* pThis);
} ma_IDirectSoundBufferVtbl;
struct ma_IDirectSoundBuffer
{
ma_IDirectSoundBufferVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IDirectSoundBuffer_QueryInterface(ma_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IDirectSoundBuffer_AddRef(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IDirectSoundBuffer_Release(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetCaps(ma_IDirectSoundBuffer* pThis, MA_DSBCAPS* pDSBufferCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSBufferCaps); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetCurrentPosition(ma_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCurrentPlayCursor, pCurrentWriteCursor); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetFormat(ma_IDirectSoundBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten) { return pThis->lpVtbl->GetFormat(pThis, pFormat, dwSizeAllocated, pSizeWritten); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetVolume(ma_IDirectSoundBuffer* pThis, LONG* pVolume) { return pThis->lpVtbl->GetVolume(pThis, pVolume); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetPan(ma_IDirectSoundBuffer* pThis, LONG* pPan) { return pThis->lpVtbl->GetPan(pThis, pPan); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetFrequency(ma_IDirectSoundBuffer* pThis, DWORD* pFrequency) { return pThis->lpVtbl->GetFrequency(pThis, pFrequency); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetStatus(ma_IDirectSoundBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_Initialize(ma_IDirectSoundBuffer* pThis, ma_IDirectSound* pDirectSound, const MA_DSBUFFERDESC* pDSBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSound, pDSBufferDesc); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_Lock(ma_IDirectSoundBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags) { return pThis->lpVtbl->Lock(pThis, dwOffset, dwBytes, ppAudioPtr1, pAudioBytes1, ppAudioPtr2, pAudioBytes2, dwFlags); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_Play(ma_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags) { return pThis->lpVtbl->Play(pThis, dwReserved1, dwPriority, dwFlags); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetCurrentPosition(ma_IDirectSoundBuffer* pThis, DWORD dwNewPosition) { return pThis->lpVtbl->SetCurrentPosition(pThis, dwNewPosition); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetFormat(ma_IDirectSoundBuffer* pThis, const WAVEFORMATEX* pFormat) { return pThis->lpVtbl->SetFormat(pThis, pFormat); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetVolume(ma_IDirectSoundBuffer* pThis, LONG volume) { return pThis->lpVtbl->SetVolume(pThis, volume); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetPan(ma_IDirectSoundBuffer* pThis, LONG pan) { return pThis->lpVtbl->SetPan(pThis, pan); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetFrequency(ma_IDirectSoundBuffer* pThis, DWORD dwFrequency) { return pThis->lpVtbl->SetFrequency(pThis, dwFrequency); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_Stop(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_Unlock(ma_IDirectSoundBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2) { return pThis->lpVtbl->Unlock(pThis, pAudioPtr1, dwAudioBytes1, pAudioPtr2, dwAudioBytes2); }
static MA_INLINE HRESULT ma_IDirectSoundBuffer_Restore(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Restore(pThis); }
/* IDirectSoundCapture */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundCapture* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundCapture* pThis);
/* IDirectSoundCapture */
HRESULT (STDMETHODCALLTYPE * CreateCaptureBuffer)(ma_IDirectSoundCapture* pThis, const MA_DSCBUFFERDESC* pDSCBufferDesc, ma_IDirectSoundCaptureBuffer** ppDSCBuffer, void* pUnkOuter);
HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundCapture* pThis, MA_DSCCAPS* pDSCCaps);
HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundCapture* pThis, const GUID* pGuidDevice);
} ma_IDirectSoundCaptureVtbl;
struct ma_IDirectSoundCapture
{
ma_IDirectSoundCaptureVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IDirectSoundCapture_QueryInterface(ma_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IDirectSoundCapture_AddRef(ma_IDirectSoundCapture* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IDirectSoundCapture_Release(ma_IDirectSoundCapture* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IDirectSoundCapture_CreateCaptureBuffer(ma_IDirectSoundCapture* pThis, const MA_DSCBUFFERDESC* pDSCBufferDesc, ma_IDirectSoundCaptureBuffer** ppDSCBuffer, void* pUnkOuter) { return pThis->lpVtbl->CreateCaptureBuffer(pThis, pDSCBufferDesc, ppDSCBuffer, pUnkOuter); }
static MA_INLINE HRESULT ma_IDirectSoundCapture_GetCaps (ma_IDirectSoundCapture* pThis, MA_DSCCAPS* pDSCCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCCaps); }
static MA_INLINE HRESULT ma_IDirectSoundCapture_Initialize (ma_IDirectSoundCapture* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); }
/* IDirectSoundCaptureBuffer */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundCaptureBuffer* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundCaptureBuffer* pThis);
/* IDirectSoundCaptureBuffer */
HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundCaptureBuffer* pThis, MA_DSCBCAPS* pDSCBCaps);
HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition);
HRESULT (STDMETHODCALLTYPE * GetFormat) (ma_IDirectSoundCaptureBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten);
HRESULT (STDMETHODCALLTYPE * GetStatus) (ma_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus);
HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundCaptureBuffer* pThis, ma_IDirectSoundCapture* pDirectSoundCapture, const MA_DSCBUFFERDESC* pDSCBufferDesc);
HRESULT (STDMETHODCALLTYPE * Lock) (ma_IDirectSoundCaptureBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags);
HRESULT (STDMETHODCALLTYPE * Start) (ma_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags);
HRESULT (STDMETHODCALLTYPE * Stop) (ma_IDirectSoundCaptureBuffer* pThis);
HRESULT (STDMETHODCALLTYPE * Unlock) (ma_IDirectSoundCaptureBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2);
} ma_IDirectSoundCaptureBufferVtbl;
struct ma_IDirectSoundCaptureBuffer
{
ma_IDirectSoundCaptureBufferVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_QueryInterface(ma_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IDirectSoundCaptureBuffer_AddRef(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IDirectSoundCaptureBuffer_Release(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetCaps(ma_IDirectSoundCaptureBuffer* pThis, MA_DSCBCAPS* pDSCBCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCBCaps); }
static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetCurrentPosition(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCapturePosition, pReadPosition); }
static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetFormat(ma_IDirectSoundCaptureBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten) { return pThis->lpVtbl->GetFormat(pThis, pFormat, dwSizeAllocated, pSizeWritten); }
static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetStatus(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); }
static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Initialize(ma_IDirectSoundCaptureBuffer* pThis, ma_IDirectSoundCapture* pDirectSoundCapture, const MA_DSCBUFFERDESC* pDSCBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSoundCapture, pDSCBufferDesc); }
static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Lock(ma_IDirectSoundCaptureBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags) { return pThis->lpVtbl->Lock(pThis, dwOffset, dwBytes, ppAudioPtr1, pAudioBytes1, ppAudioPtr2, pAudioBytes2, dwFlags); }
static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Start(ma_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags) { return pThis->lpVtbl->Start(pThis, dwFlags); }
static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Stop(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); }
static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Unlock(ma_IDirectSoundCaptureBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2) { return pThis->lpVtbl->Unlock(pThis, pAudioPtr1, dwAudioBytes1, pAudioPtr2, dwAudioBytes2); }
/* IDirectSoundNotify */
typedef struct
{
/* IUnknown */
HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject);
ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundNotify* pThis);
ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundNotify* pThis);
/* IDirectSoundNotify */
HRESULT (STDMETHODCALLTYPE * SetNotificationPositions)(ma_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MA_DSBPOSITIONNOTIFY* pPositionNotifies);
} ma_IDirectSoundNotifyVtbl;
struct ma_IDirectSoundNotify
{
ma_IDirectSoundNotifyVtbl* lpVtbl;
};
static MA_INLINE HRESULT ma_IDirectSoundNotify_QueryInterface(ma_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
static MA_INLINE ULONG ma_IDirectSoundNotify_AddRef(ma_IDirectSoundNotify* pThis) { return pThis->lpVtbl->AddRef(pThis); }
static MA_INLINE ULONG ma_IDirectSoundNotify_Release(ma_IDirectSoundNotify* pThis) { return pThis->lpVtbl->Release(pThis); }
static MA_INLINE HRESULT ma_IDirectSoundNotify_SetNotificationPositions(ma_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MA_DSBPOSITIONNOTIFY* pPositionNotifies) { return pThis->lpVtbl->SetNotificationPositions(pThis, dwPositionNotifies, pPositionNotifies); }
typedef BOOL (CALLBACK * ma_DSEnumCallbackAProc) (LPGUID pDeviceGUID, LPCSTR pDeviceDescription, LPCSTR pModule, LPVOID pContext);
typedef HRESULT (WINAPI * ma_DirectSoundCreateProc) (const GUID* pcGuidDevice, ma_IDirectSound** ppDS8, LPUNKNOWN pUnkOuter);
typedef HRESULT (WINAPI * ma_DirectSoundEnumerateAProc) (ma_DSEnumCallbackAProc pDSEnumCallback, LPVOID pContext);
typedef HRESULT (WINAPI * ma_DirectSoundCaptureCreateProc) (const GUID* pcGuidDevice, ma_IDirectSoundCapture** ppDSC8, LPUNKNOWN pUnkOuter);
typedef HRESULT (WINAPI * ma_DirectSoundCaptureEnumerateAProc)(ma_DSEnumCallbackAProc pDSEnumCallback, LPVOID pContext);
static ma_uint32 ma_get_best_sample_rate_within_range(ma_uint32 sampleRateMin, ma_uint32 sampleRateMax)
{
/* Normalize the range in case we were given something stupid. */
if (sampleRateMin < MA_MIN_SAMPLE_RATE) {
sampleRateMin = MA_MIN_SAMPLE_RATE;
}
if (sampleRateMax > MA_MAX_SAMPLE_RATE) {
sampleRateMax = MA_MAX_SAMPLE_RATE;
}
if (sampleRateMin > sampleRateMax) {
sampleRateMin = sampleRateMax;
}
if (sampleRateMin == sampleRateMax) {
return sampleRateMax;
} else {
size_t iStandardRate;
for (iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) {
ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate];
if (standardRate >= sampleRateMin && standardRate <= sampleRateMax) {
return standardRate;
}
}
}
/* Should never get here. */
MA_ASSERT(MA_FALSE);
return 0;
}
/*
Retrieves the channel count and channel map for the given speaker configuration. If the speaker configuration is unknown,
the channel count and channel map will be left unmodified.
*/
static void ma_get_channels_from_speaker_config__dsound(DWORD speakerConfig, WORD* pChannelsOut, DWORD* pChannelMapOut)
{
WORD channels;
DWORD channelMap;
channels = 0;
if (pChannelsOut != NULL) {
channels = *pChannelsOut;
}
channelMap = 0;
if (pChannelMapOut != NULL) {
channelMap = *pChannelMapOut;
}
/*
The speaker configuration is a combination of speaker config and speaker geometry. The lower 8 bits is what we care about. The upper
16 bits is for the geometry.
*/
switch ((BYTE)(speakerConfig)) {
case 1 /*DSSPEAKER_HEADPHONE*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
case 2 /*DSSPEAKER_MONO*/: channels = 1; channelMap = SPEAKER_FRONT_CENTER; break;
case 3 /*DSSPEAKER_QUAD*/: channels = 4; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
case 4 /*DSSPEAKER_STEREO*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
case 5 /*DSSPEAKER_SURROUND*/: channels = 4; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_CENTER; break;
case 6 /*DSSPEAKER_5POINT1_BACK*/ /*DSSPEAKER_5POINT1*/: channels = 6; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
case 7 /*DSSPEAKER_7POINT1_WIDE*/ /*DSSPEAKER_7POINT1*/: channels = 8; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER; break;
case 8 /*DSSPEAKER_7POINT1_SURROUND*/: channels = 8; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT; break;
case 9 /*DSSPEAKER_5POINT1_SURROUND*/: channels = 6; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT; break;
default: break;
}
if (pChannelsOut != NULL) {
*pChannelsOut = channels;
}
if (pChannelMapOut != NULL) {
*pChannelMapOut = channelMap;
}
}
static ma_result ma_context_create_IDirectSound__dsound(ma_context* pContext, ma_share_mode shareMode, const ma_device_id* pDeviceID, ma_IDirectSound** ppDirectSound)
{
ma_IDirectSound* pDirectSound;
HWND hWnd;
HRESULT hr;
MA_ASSERT(pContext != NULL);
MA_ASSERT(ppDirectSound != NULL);
*ppDirectSound = NULL;
pDirectSound = NULL;
if (FAILED(((ma_DirectSoundCreateProc)pContext->dsound.DirectSoundCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSound, NULL))) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCreate() failed for playback device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
}
/* The cooperative level must be set before doing anything else. */
hWnd = ((MA_PFN_GetForegroundWindow)pContext->win32.GetForegroundWindow)();
if (hWnd == NULL) {
hWnd = ((MA_PFN_GetDesktopWindow)pContext->win32.GetDesktopWindow)();
}
hr = ma_IDirectSound_SetCooperativeLevel(pDirectSound, hWnd, (shareMode == ma_share_mode_exclusive) ? MA_DSSCL_EXCLUSIVE : MA_DSSCL_PRIORITY);
if (FAILED(hr)) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_SetCooperateiveLevel() failed for playback device.", ma_result_from_HRESULT(hr));
}
*ppDirectSound = pDirectSound;
return MA_SUCCESS;
}
static ma_result ma_context_create_IDirectSoundCapture__dsound(ma_context* pContext, ma_share_mode shareMode, const ma_device_id* pDeviceID, ma_IDirectSoundCapture** ppDirectSoundCapture)
{
ma_IDirectSoundCapture* pDirectSoundCapture;
HRESULT hr;
MA_ASSERT(pContext != NULL);
MA_ASSERT(ppDirectSoundCapture != NULL);
/* DirectSound does not support exclusive mode for capture. */
if (shareMode == ma_share_mode_exclusive) {
return MA_SHARE_MODE_NOT_SUPPORTED;
}
*ppDirectSoundCapture = NULL;
pDirectSoundCapture = NULL;
hr = ((ma_DirectSoundCaptureCreateProc)pContext->dsound.DirectSoundCaptureCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSoundCapture, NULL);
if (FAILED(hr)) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCaptureCreate() failed for capture device.", ma_result_from_HRESULT(hr));
}
*ppDirectSoundCapture = pDirectSoundCapture;
return MA_SUCCESS;
}
static ma_result ma_context_get_format_info_for_IDirectSoundCapture__dsound(ma_context* pContext, ma_IDirectSoundCapture* pDirectSoundCapture, WORD* pChannels, WORD* pBitsPerSample, DWORD* pSampleRate)
{
HRESULT hr;
MA_DSCCAPS caps;
WORD bitsPerSample;
DWORD sampleRate;
MA_ASSERT(pContext != NULL);
MA_ASSERT(pDirectSoundCapture != NULL);
if (pChannels) {
*pChannels = 0;
}
if (pBitsPerSample) {
*pBitsPerSample = 0;
}
if (pSampleRate) {
*pSampleRate = 0;
}
MA_ZERO_OBJECT(&caps);
caps.dwSize = sizeof(caps);
hr = ma_IDirectSoundCapture_GetCaps(pDirectSoundCapture, &caps);
if (FAILED(hr)) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_GetCaps() failed for capture device.", ma_result_from_HRESULT(hr));
}
if (pChannels) {
*pChannels = (WORD)caps.dwChannels;
}
/* The device can support multiple formats. We just go through the different formats in order of priority and pick the first one. This the same type of system as the WinMM backend. */
bitsPerSample = 16;
sampleRate = 48000;
if (caps.dwChannels == 1) {
if ((caps.dwFormats & WAVE_FORMAT_48M16) != 0) {
sampleRate = 48000;
} else if ((caps.dwFormats & WAVE_FORMAT_44M16) != 0) {
sampleRate = 44100;
} else if ((caps.dwFormats & WAVE_FORMAT_2M16) != 0) {
sampleRate = 22050;
} else if ((caps.dwFormats & WAVE_FORMAT_1M16) != 0) {
sampleRate = 11025;
} else if ((caps.dwFormats & WAVE_FORMAT_96M16) != 0) {
sampleRate = 96000;
} else {
bitsPerSample = 8;
if ((caps.dwFormats & WAVE_FORMAT_48M08) != 0) {
sampleRate = 48000;
} else if ((caps.dwFormats & WAVE_FORMAT_44M08) != 0) {
sampleRate = 44100;
} else if ((caps.dwFormats & WAVE_FORMAT_2M08) != 0) {
sampleRate = 22050;
} else if ((caps.dwFormats & WAVE_FORMAT_1M08) != 0) {
sampleRate = 11025;
} else if ((caps.dwFormats & WAVE_FORMAT_96M08) != 0) {
sampleRate = 96000;
} else {
bitsPerSample = 16; /* Didn't find it. Just fall back to 16-bit. */
}
}
} else if (caps.dwChannels == 2) {
if ((caps.dwFormats & WAVE_FORMAT_48S16) != 0) {
sampleRate = 48000;
} else if ((caps.dwFormats & WAVE_FORMAT_44S16) != 0) {
sampleRate = 44100;
} else if ((caps.dwFormats & WAVE_FORMAT_2S16) != 0) {
sampleRate = 22050;
} else if ((caps.dwFormats & WAVE_FORMAT_1S16) != 0) {
sampleRate = 11025;
} else if ((caps.dwFormats & WAVE_FORMAT_96S16) != 0) {
sampleRate = 96000;
} else {
bitsPerSample = 8;
if ((caps.dwFormats & WAVE_FORMAT_48S08) != 0) {
sampleRate = 48000;
} else if ((caps.dwFormats & WAVE_FORMAT_44S08) != 0) {
sampleRate = 44100;
} else if ((caps.dwFormats & WAVE_FORMAT_2S08) != 0) {
sampleRate = 22050;
} else if ((caps.dwFormats & WAVE_FORMAT_1S08) != 0) {
sampleRate = 11025;
} else if ((caps.dwFormats & WAVE_FORMAT_96S08) != 0) {
sampleRate = 96000;
} else {
bitsPerSample = 16; /* Didn't find it. Just fall back to 16-bit. */
}
}
}
if (pBitsPerSample) {
*pBitsPerSample = bitsPerSample;
}
if (pSampleRate) {
*pSampleRate = sampleRate;
}
return MA_SUCCESS;
}
typedef struct
{
ma_context* pContext;
ma_device_type deviceType;
ma_enum_devices_callback_proc callback;
void* pUserData;
ma_bool32 terminated;
} ma_context_enumerate_devices_callback_data__dsound;
static BOOL CALLBACK ma_context_enumerate_devices_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext)
{
ma_context_enumerate_devices_callback_data__dsound* pData = (ma_context_enumerate_devices_callback_data__dsound*)lpContext;
ma_device_info deviceInfo;
(void)lpcstrModule;
MA_ZERO_OBJECT(&deviceInfo);
/* ID. */
if (lpGuid != NULL) {
MA_COPY_MEMORY(deviceInfo.id.dsound, lpGuid, 16);
} else {
MA_ZERO_MEMORY(deviceInfo.id.dsound, 16);
deviceInfo.isDefault = MA_TRUE;
}
/* Name / Description */
ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), lpcstrDescription, (size_t)-1);
/* Call the callback function, but make sure we stop enumerating if the callee requested so. */
MA_ASSERT(pData != NULL);
pData->terminated = !pData->callback(pData->pContext, pData->deviceType, &deviceInfo, pData->pUserData);
if (pData->terminated) {
return FALSE; /* Stop enumeration. */
} else {
return TRUE; /* Continue enumeration. */
}
}
static ma_result ma_context_enumerate_devices__dsound(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
{
ma_context_enumerate_devices_callback_data__dsound data;
MA_ASSERT(pContext != NULL);
MA_ASSERT(callback != NULL);
data.pContext = pContext;
data.callback = callback;
data.pUserData = pUserData;
data.terminated = MA_FALSE;
/* Playback. */
if (!data.terminated) {
data.deviceType = ma_device_type_playback;
((ma_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(ma_context_enumerate_devices_callback__dsound, &data);
}
/* Capture. */
if (!data.terminated) {
data.deviceType = ma_device_type_capture;
((ma_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(ma_context_enumerate_devices_callback__dsound, &data);
}
return MA_SUCCESS;
}
typedef struct
{
const ma_device_id* pDeviceID;
ma_device_info* pDeviceInfo;
ma_bool32 found;
} ma_context_get_device_info_callback_data__dsound;
static BOOL CALLBACK ma_context_get_device_info_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext)
{
ma_context_get_device_info_callback_data__dsound* pData = (ma_context_get_device_info_callback_data__dsound*)lpContext;
MA_ASSERT(pData != NULL);
if ((pData->pDeviceID == NULL || ma_is_guid_null(pData->pDeviceID->dsound)) && (lpGuid == NULL || ma_is_guid_null(lpGuid))) {
/* Default device. */
ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1);
pData->pDeviceInfo->isDefault = MA_TRUE;
pData->found = MA_TRUE;
return FALSE; /* Stop enumeration. */
} else {
/* Not the default device. */
if (lpGuid != NULL && pData->pDeviceID != NULL) {
if (memcmp(pData->pDeviceID->dsound, lpGuid, sizeof(pData->pDeviceID->dsound)) == 0) {
ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1);
pData->found = MA_TRUE;
return FALSE; /* Stop enumeration. */
}
}
}
(void)lpcstrModule;
return TRUE;
}
static ma_result ma_context_get_device_info__dsound(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
{
ma_result result;
HRESULT hr;
if (pDeviceID != NULL) {
ma_context_get_device_info_callback_data__dsound data;
/* ID. */
MA_COPY_MEMORY(pDeviceInfo->id.dsound, pDeviceID->dsound, 16);
/* Name / Description. This is retrieved by enumerating over each device until we find that one that matches the input ID. */
data.pDeviceID = pDeviceID;
data.pDeviceInfo = pDeviceInfo;
data.found = MA_FALSE;
if (deviceType == ma_device_type_playback) {
((ma_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(ma_context_get_device_info_callback__dsound, &data);
} else {
((ma_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(ma_context_get_device_info_callback__dsound, &data);
}
if (!data.found) {
return MA_NO_DEVICE;
}
} else {
/* I don't think there's a way to get the name of the default device with DirectSound. In this case we just need to use defaults. */
/* ID */
MA_ZERO_MEMORY(pDeviceInfo->id.dsound, 16);
/* Name / Description */
if (deviceType == ma_device_type_playback) {
ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
} else {
ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
}
pDeviceInfo->isDefault = MA_TRUE;
}
/* Retrieving detailed information is slightly different depending on the device type. */
if (deviceType == ma_device_type_playback) {
/* Playback. */
ma_IDirectSound* pDirectSound;
MA_DSCAPS caps;
WORD channels;
result = ma_context_create_IDirectSound__dsound(pContext, ma_share_mode_shared, pDeviceID, &pDirectSound);
if (result != MA_SUCCESS) {
return result;
}
MA_ZERO_OBJECT(&caps);
caps.dwSize = sizeof(caps);
hr = ma_IDirectSound_GetCaps(pDirectSound, &caps);
if (FAILED(hr)) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device.", ma_result_from_HRESULT(hr));
}
/* Channels. Only a single channel count is reported for DirectSound. */
if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) {
/* It supports at least stereo, but could support more. */
DWORD speakerConfig;
channels = 2;
/* Look at the speaker configuration to get a better idea on the channel count. */
hr = ma_IDirectSound_GetSpeakerConfig(pDirectSound, &speakerConfig);
if (SUCCEEDED(hr)) {
ma_get_channels_from_speaker_config__dsound(speakerConfig, &channels, NULL);
}
} else {
/* It does not support stereo, which means we are stuck with mono. */
channels = 1;
}
/*
In DirectSound, our native formats are centered around sample rates. All formats are supported, and we're only reporting a single channel
count. However, DirectSound can report a range of supported sample rates. We're only going to include standard rates known by miniaudio
in order to keep the size of this within reason.
*/
if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) {
/* Multiple sample rates are supported. We'll report in order of our preferred sample rates. */
size_t iStandardSampleRate;
for (iStandardSampleRate = 0; iStandardSampleRate < ma_countof(g_maStandardSampleRatePriorities); iStandardSampleRate += 1) {
ma_uint32 sampleRate = g_maStandardSampleRatePriorities[iStandardSampleRate];
if (sampleRate >= caps.dwMinSecondarySampleRate && sampleRate <= caps.dwMaxSecondarySampleRate) {
pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = ma_format_unknown;
pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
pDeviceInfo->nativeDataFormatCount += 1;
}
}
} else {
/* Only a single sample rate is supported. */
pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = ma_format_unknown;
pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = caps.dwMaxSecondarySampleRate;
pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
pDeviceInfo->nativeDataFormatCount += 1;
}
ma_IDirectSound_Release(pDirectSound);
} else {
/*
Capture. This is a little different to playback due to the say the supported formats are reported. Technically capture
devices can support a number of different formats, but for simplicity and consistency with ma_device_init() I'm just
reporting the best format.
*/
ma_IDirectSoundCapture* pDirectSoundCapture;
WORD channels;
WORD bitsPerSample;
DWORD sampleRate;
result = ma_context_create_IDirectSoundCapture__dsound(pContext, ma_share_mode_shared, pDeviceID, &pDirectSoundCapture);
if (result != MA_SUCCESS) {
return result;
}
result = ma_context_get_format_info_for_IDirectSoundCapture__dsound(pContext, pDirectSoundCapture, &channels, &bitsPerSample, &sampleRate);
if (result != MA_SUCCESS) {
ma_IDirectSoundCapture_Release(pDirectSoundCapture);
return result;
}
ma_IDirectSoundCapture_Release(pDirectSoundCapture);
/* The format is always an integer format and is based on the bits per sample. */
if (bitsPerSample == 8) {
pDeviceInfo->formats[0] = ma_format_u8;
} else if (bitsPerSample == 16) {
pDeviceInfo->formats[0] = ma_format_s16;
} else if (bitsPerSample == 24) {
pDeviceInfo->formats[0] = ma_format_s24;
} else if (bitsPerSample == 32) {
pDeviceInfo->formats[0] = ma_format_s32;
} else {
return MA_FORMAT_NOT_SUPPORTED;
}
pDeviceInfo->nativeDataFormats[0].channels = channels;
pDeviceInfo->nativeDataFormats[0].sampleRate = sampleRate;
pDeviceInfo->nativeDataFormats[0].flags = 0;
pDeviceInfo->nativeDataFormatCount = 1;
}
return MA_SUCCESS;
}
static ma_result ma_device_uninit__dsound(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
if (pDevice->dsound.pCaptureBuffer != NULL) {
ma_IDirectSoundCaptureBuffer_Release((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
}
if (pDevice->dsound.pCapture != NULL) {
ma_IDirectSoundCapture_Release((ma_IDirectSoundCapture*)pDevice->dsound.pCapture);
}
if (pDevice->dsound.pPlaybackBuffer != NULL) {
ma_IDirectSoundBuffer_Release((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer);
}
if (pDevice->dsound.pPlaybackPrimaryBuffer != NULL) {
ma_IDirectSoundBuffer_Release((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer);
}
if (pDevice->dsound.pPlayback != NULL) {
ma_IDirectSound_Release((ma_IDirectSound*)pDevice->dsound.pPlayback);
}
return MA_SUCCESS;
}
static ma_result ma_config_to_WAVEFORMATEXTENSIBLE(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const ma_channel* pChannelMap, WAVEFORMATEXTENSIBLE* pWF)
{
GUID subformat;
if (format == ma_format_unknown) {
format = MA_DEFAULT_FORMAT;
}
if (channels == 0) {
channels = MA_DEFAULT_CHANNELS;
}
if (sampleRate == 0) {
sampleRate = MA_DEFAULT_SAMPLE_RATE;
}
switch (format)
{
case ma_format_u8:
case ma_format_s16:
case ma_format_s24:
/*case ma_format_s24_32:*/
case ma_format_s32:
{
subformat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM;
} break;
case ma_format_f32:
{
subformat = MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
} break;
default:
return MA_FORMAT_NOT_SUPPORTED;
}
MA_ZERO_OBJECT(pWF);
pWF->Format.cbSize = sizeof(*pWF);
pWF->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
pWF->Format.nChannels = (WORD)channels;
pWF->Format.nSamplesPerSec = (DWORD)sampleRate;
pWF->Format.wBitsPerSample = (WORD)(ma_get_bytes_per_sample(format)*8);
pWF->Format.nBlockAlign = (WORD)(pWF->Format.nChannels * pWF->Format.wBitsPerSample / 8);
pWF->Format.nAvgBytesPerSec = pWF->Format.nBlockAlign * pWF->Format.nSamplesPerSec;
pWF->Samples.wValidBitsPerSample = pWF->Format.wBitsPerSample;
pWF->dwChannelMask = ma_channel_map_to_channel_mask__win32(pChannelMap, channels);
pWF->SubFormat = subformat;
return MA_SUCCESS;
}
static ma_uint32 ma_calculate_period_size_in_frames__dsound(ma_uint32 periodSizeInFrames, ma_uint32 periodSizeInMilliseconds, ma_uint32 sampleRate, ma_performance_profile performanceProfile)
{
/* DirectSound has a minimum period size of 20ms. */
ma_uint32 minPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(20, sampleRate);
if (periodSizeInFrames == 0) {
if (periodSizeInMilliseconds == 0) {
if (performanceProfile == ma_performance_profile_low_latency) {
periodSizeInFrames = minPeriodSizeInFrames;
} else {
periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, sampleRate);
}
} else {
periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(periodSizeInMilliseconds, sampleRate);
}
}
if (periodSizeInFrames < minPeriodSizeInFrames) {
periodSizeInFrames = minPeriodSizeInFrames;
}
return periodSizeInFrames;
}
static ma_result ma_device_init__dsound(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
{
ma_result result;
HRESULT hr;
MA_ASSERT(pDevice != NULL);
MA_ZERO_OBJECT(&pDevice->dsound);
if (pConfig->deviceType == ma_device_type_loopback) {
return MA_DEVICE_TYPE_NOT_SUPPORTED;
}
/*
Unfortunately DirectSound uses different APIs and data structures for playback and catpure devices. We need to initialize
the capture device first because we'll want to match it's buffer size and period count on the playback side if we're using
full-duplex mode.
*/
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
WAVEFORMATEXTENSIBLE wf;
MA_DSCBUFFERDESC descDS;
ma_uint32 periodSizeInFrames;
ma_uint32 periodCount;
char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */
WAVEFORMATEXTENSIBLE* pActualFormat;
result = ma_config_to_WAVEFORMATEXTENSIBLE(pDescriptorCapture->format, pDescriptorCapture->channels, pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, &wf);
if (result != MA_SUCCESS) {
return result;
}
result = ma_context_create_IDirectSoundCapture__dsound(pDevice->pContext, pDescriptorCapture->shareMode, pDescriptorCapture->pDeviceID, (ma_IDirectSoundCapture**)&pDevice->dsound.pCapture);
if (result != MA_SUCCESS) {
ma_device_uninit__dsound(pDevice);
return result;
}
result = ma_context_get_format_info_for_IDirectSoundCapture__dsound(pDevice->pContext, (ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &wf.Format.nChannels, &wf.Format.wBitsPerSample, &wf.Format.nSamplesPerSec);
if (result != MA_SUCCESS) {
ma_device_uninit__dsound(pDevice);
return result;
}
wf.Format.nBlockAlign = (WORD)(wf.Format.nChannels * wf.Format.wBitsPerSample / 8);
wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec;
wf.Samples.wValidBitsPerSample = wf.Format.wBitsPerSample;
wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM;
/* The size of the buffer must be a clean multiple of the period count. */
periodSizeInFrames = ma_calculate_period_size_in_frames__dsound(pDescriptorCapture->periodSizeInFrames, pDescriptorCapture->periodSizeInMilliseconds, wf.Format.nSamplesPerSec, pConfig->performanceProfile);
periodCount = (pDescriptorCapture->periodCount > 0) ? pDescriptorCapture->periodCount : MA_DEFAULT_PERIODS;
MA_ZERO_OBJECT(&descDS);
descDS.dwSize = sizeof(descDS);
descDS.dwFlags = 0;
descDS.dwBufferBytes = periodSizeInFrames * periodCount * wf.Format.nBlockAlign;
descDS.lpwfxFormat = (WAVEFORMATEX*)&wf;
hr = ma_IDirectSoundCapture_CreateCaptureBuffer((ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (ma_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL);
if (FAILED(hr)) {
ma_device_uninit__dsound(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_CreateCaptureBuffer() failed for capture device.", ma_result_from_HRESULT(hr));
}
/* Get the _actual_ properties of the buffer. */
pActualFormat = (WAVEFORMATEXTENSIBLE*)rawdata;
hr = ma_IDirectSoundCaptureBuffer_GetFormat((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, (WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL);
if (FAILED(hr)) {
ma_device_uninit__dsound(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to retrieve the actual format of the capture device's buffer.", ma_result_from_HRESULT(hr));
}
/* We can now start setting the output data formats. */
pDescriptorCapture->format = ma_format_from_WAVEFORMATEX((WAVEFORMATEX*)pActualFormat);
pDescriptorCapture->channels = pActualFormat->Format.nChannels;
pDescriptorCapture->sampleRate = pActualFormat->Format.nSamplesPerSec;
/* Get the native channel map based on the channel mask. */
if (pActualFormat->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDescriptorCapture->channels, pDescriptorCapture->channelMap);
} else {
ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDescriptorCapture->channels, pDescriptorCapture->channelMap);
}
/*
After getting the actual format the size of the buffer in frames may have actually changed. However, we want this to be as close to what the
user has asked for as possible, so let's go ahead and release the old capture buffer and create a new one in this case.
*/
if (periodSizeInFrames != (descDS.dwBufferBytes / ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) / periodCount)) {
descDS.dwBufferBytes = periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) * periodCount;
ma_IDirectSoundCaptureBuffer_Release((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
hr = ma_IDirectSoundCapture_CreateCaptureBuffer((ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (ma_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL);
if (FAILED(hr)) {
ma_device_uninit__dsound(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Second attempt at IDirectSoundCapture_CreateCaptureBuffer() failed for capture device.", ma_result_from_HRESULT(hr));
}
}
/* DirectSound should give us a buffer exactly the size we asked for. */
pDescriptorCapture->periodSizeInFrames = periodSizeInFrames;
pDescriptorCapture->periodCount = periodCount;
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
WAVEFORMATEXTENSIBLE wf;
MA_DSBUFFERDESC descDSPrimary;
MA_DSCAPS caps;
char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */
WAVEFORMATEXTENSIBLE* pActualFormat;
ma_uint32 periodSizeInFrames;
ma_uint32 periodCount;
MA_DSBUFFERDESC descDS;
result = ma_config_to_WAVEFORMATEXTENSIBLE(pDescriptorPlayback->format, pDescriptorPlayback->channels, pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, &wf);
if (result != MA_SUCCESS) {
return result;
}
result = ma_context_create_IDirectSound__dsound(pDevice->pContext, pDescriptorPlayback->shareMode, pDescriptorPlayback->pDeviceID, (ma_IDirectSound**)&pDevice->dsound.pPlayback);
if (result != MA_SUCCESS) {
ma_device_uninit__dsound(pDevice);
return result;
}
MA_ZERO_OBJECT(&descDSPrimary);
descDSPrimary.dwSize = sizeof(MA_DSBUFFERDESC);
descDSPrimary.dwFlags = MA_DSBCAPS_PRIMARYBUFFER | MA_DSBCAPS_CTRLVOLUME;
hr = ma_IDirectSound_CreateSoundBuffer((ma_IDirectSound*)pDevice->dsound.pPlayback, &descDSPrimary, (ma_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackPrimaryBuffer, NULL);
if (FAILED(hr)) {
ma_device_uninit__dsound(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's primary buffer.", ma_result_from_HRESULT(hr));
}
/* We may want to make some adjustments to the format if we are using defaults. */
MA_ZERO_OBJECT(&caps);
caps.dwSize = sizeof(caps);
hr = ma_IDirectSound_GetCaps((ma_IDirectSound*)pDevice->dsound.pPlayback, &caps);
if (FAILED(hr)) {
ma_device_uninit__dsound(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device.", ma_result_from_HRESULT(hr));
}
if (pDescriptorPlayback->channels == 0) {
if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) {
DWORD speakerConfig;
/* It supports at least stereo, but could support more. */
wf.Format.nChannels = 2;
/* Look at the speaker configuration to get a better idea on the channel count. */
if (SUCCEEDED(ma_IDirectSound_GetSpeakerConfig((ma_IDirectSound*)pDevice->dsound.pPlayback, &speakerConfig))) {
ma_get_channels_from_speaker_config__dsound(speakerConfig, &wf.Format.nChannels, &wf.dwChannelMask);
}
} else {
/* It does not support stereo, which means we are stuck with mono. */
wf.Format.nChannels = 1;
}
}
if (pDescriptorPlayback->sampleRate == 0) {
/* We base the sample rate on the values returned by GetCaps(). */
if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) {
wf.Format.nSamplesPerSec = ma_get_best_sample_rate_within_range(caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate);
} else {
wf.Format.nSamplesPerSec = caps.dwMaxSecondarySampleRate;
}
}
wf.Format.nBlockAlign = (WORD)(wf.Format.nChannels * wf.Format.wBitsPerSample / 8);
wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec;
/*
From MSDN:
The method succeeds even if the hardware does not support the requested format; DirectSound sets the buffer to the closest
supported format. To determine whether this has happened, an application can call the GetFormat method for the primary buffer
and compare the result with the format that was requested with the SetFormat method.
*/
hr = ma_IDirectSoundBuffer_SetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (WAVEFORMATEX*)&wf);
if (FAILED(hr)) {
ma_device_uninit__dsound(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to set format of playback device's primary buffer.", ma_result_from_HRESULT(hr));
}
/* Get the _actual_ properties of the buffer. */
pActualFormat = (WAVEFORMATEXTENSIBLE*)rawdata;
hr = ma_IDirectSoundBuffer_GetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL);
if (FAILED(hr)) {
ma_device_uninit__dsound(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to retrieve the actual format of the playback device's primary buffer.", ma_result_from_HRESULT(hr));
}
/* We now have enough information to start setting some output properties. */
pDescriptorPlayback->format = ma_format_from_WAVEFORMATEX((WAVEFORMATEX*)pActualFormat);
pDescriptorPlayback->channels = pActualFormat->Format.nChannels;
pDescriptorPlayback->sampleRate = pActualFormat->Format.nSamplesPerSec;
/* Get the internal channel map based on the channel mask. */
if (pActualFormat->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDescriptorPlayback->channels, pDescriptorPlayback->channelMap);
} else {
ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDescriptorPlayback->channels, pDescriptorPlayback->channelMap);
}
/* The size of the buffer must be a clean multiple of the period count. */
periodSizeInFrames = ma_calculate_period_size_in_frames__dsound(pDescriptorPlayback->periodSizeInFrames, pDescriptorPlayback->periodSizeInMilliseconds, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
periodCount = (pDescriptorPlayback->periodCount > 0) ? pDescriptorPlayback->periodCount : MA_DEFAULT_PERIODS;
/*
Meaning of dwFlags (from MSDN):
DSBCAPS_CTRLPOSITIONNOTIFY
The buffer has position notification capability.
DSBCAPS_GLOBALFOCUS
With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to
another application, even if the new application uses DirectSound.
DSBCAPS_GETCURRENTPOSITION2
In the first version of DirectSound, the play cursor was significantly ahead of the actual playing sound on emulated
sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the
application can get a more accurate play cursor.
*/
MA_ZERO_OBJECT(&descDS);
descDS.dwSize = sizeof(descDS);
descDS.dwFlags = MA_DSBCAPS_CTRLPOSITIONNOTIFY | MA_DSBCAPS_GLOBALFOCUS | MA_DSBCAPS_GETCURRENTPOSITION2;
descDS.dwBufferBytes = periodSizeInFrames * periodCount * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels);
descDS.lpwfxFormat = (WAVEFORMATEX*)&wf;
hr = ma_IDirectSound_CreateSoundBuffer((ma_IDirectSound*)pDevice->dsound.pPlayback, &descDS, (ma_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackBuffer, NULL);
if (FAILED(hr)) {
ma_device_uninit__dsound(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's secondary buffer.", ma_result_from_HRESULT(hr));
}
/* DirectSound should give us a buffer exactly the size we asked for. */
pDescriptorPlayback->periodSizeInFrames = periodSizeInFrames;
pDescriptorPlayback->periodCount = periodCount;
}
return MA_SUCCESS;
}
static ma_result ma_device_audio_thread__dsound(ma_device* pDevice)
{
ma_result result = MA_SUCCESS;
ma_uint32 bpfDeviceCapture = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
ma_uint32 bpfDevicePlayback = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
HRESULT hr;
DWORD lockOffsetInBytesCapture;
DWORD lockSizeInBytesCapture;
DWORD mappedSizeInBytesCapture;
DWORD mappedDeviceFramesProcessedCapture;
void* pMappedDeviceBufferCapture;
DWORD lockOffsetInBytesPlayback;
DWORD lockSizeInBytesPlayback;
DWORD mappedSizeInBytesPlayback;
void* pMappedDeviceBufferPlayback;
DWORD prevReadCursorInBytesCapture = 0;
DWORD prevPlayCursorInBytesPlayback = 0;
ma_bool32 physicalPlayCursorLoopFlagPlayback = 0;
DWORD virtualWriteCursorInBytesPlayback = 0;
ma_bool32 virtualWriteCursorLoopFlagPlayback = 0;
ma_bool32 isPlaybackDeviceStarted = MA_FALSE;
ma_uint32 framesWrittenToPlaybackDevice = 0; /* For knowing whether or not the playback device needs to be started. */
ma_uint32 waitTimeInMilliseconds = 1;
MA_ASSERT(pDevice != NULL);
/* The first thing to do is start the capture device. The playback device is only started after the first period is written. */
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
if (FAILED(ma_IDirectSoundCaptureBuffer_Start((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, MA_DSCBSTART_LOOPING))) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Start() failed.", MA_FAILED_TO_START_BACKEND_DEVICE);
}
}
while (ma_device_get_state(pDevice) == MA_STATE_STARTED) {
switch (pDevice->type)
{
case ma_device_type_duplex:
{
DWORD physicalCaptureCursorInBytes;
DWORD physicalReadCursorInBytes;
hr = ma_IDirectSoundCaptureBuffer_GetCurrentPosition((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &physicalCaptureCursorInBytes, &physicalReadCursorInBytes);
if (FAILED(hr)) {
return ma_result_from_HRESULT(hr);
}
/* If nothing is available we just sleep for a bit and return from this iteration. */
if (physicalReadCursorInBytes == prevReadCursorInBytesCapture) {
ma_sleep(waitTimeInMilliseconds);
continue; /* Nothing is available in the capture buffer. */
}
/*
The current position has moved. We need to map all of the captured samples and write them to the playback device, making sure
we don't return until every frame has been copied over.
*/
if (prevReadCursorInBytesCapture < physicalReadCursorInBytes) {
/* The capture position has not looped. This is the simple case. */
lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
lockSizeInBytesCapture = (physicalReadCursorInBytes - prevReadCursorInBytesCapture);
} else {
/*
The capture position has looped. This is the more complex case. Map to the end of the buffer. If this does not return anything,
do it again from the start.
*/
if (prevReadCursorInBytesCapture < pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) {
/* Lock up to the end of the buffer. */
lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
lockSizeInBytesCapture = (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) - prevReadCursorInBytesCapture;
} else {
/* Lock starting from the start of the buffer. */
lockOffsetInBytesCapture = 0;
lockSizeInBytesCapture = physicalReadCursorInBytes;
}
}
if (lockSizeInBytesCapture == 0) {
ma_sleep(waitTimeInMilliseconds);
continue; /* Nothing is available in the capture buffer. */
}
hr = ma_IDirectSoundCaptureBuffer_Lock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, lockOffsetInBytesCapture, lockSizeInBytesCapture, &pMappedDeviceBufferCapture, &mappedSizeInBytesCapture, NULL, NULL, 0);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from capture device in preparation for writing to the device.", ma_result_from_HRESULT(hr));
}
/* At this point we have some input data that we need to output. We do not return until every mapped frame of the input data is written to the playback device. */
mappedDeviceFramesProcessedCapture = 0;
for (;;) { /* Keep writing to the playback device. */
ma_uint8 inputFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 inputFramesInClientFormatCap = sizeof(inputFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
ma_uint8 outputFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 outputFramesInClientFormatCap = sizeof(outputFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
ma_uint32 outputFramesInClientFormatCount;
ma_uint32 outputFramesInClientFormatConsumed = 0;
ma_uint64 clientCapturedFramesToProcess = ma_min(inputFramesInClientFormatCap, outputFramesInClientFormatCap);
ma_uint64 deviceCapturedFramesToProcess = (mappedSizeInBytesCapture / bpfDeviceCapture) - mappedDeviceFramesProcessedCapture;
void* pRunningMappedDeviceBufferCapture = ma_offset_ptr(pMappedDeviceBufferCapture, mappedDeviceFramesProcessedCapture * bpfDeviceCapture);
result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningMappedDeviceBufferCapture, &deviceCapturedFramesToProcess, inputFramesInClientFormat, &clientCapturedFramesToProcess);
if (result != MA_SUCCESS) {
break;
}
outputFramesInClientFormatCount = (ma_uint32)clientCapturedFramesToProcess;
mappedDeviceFramesProcessedCapture += (ma_uint32)deviceCapturedFramesToProcess;
ma_device__on_data(pDevice, outputFramesInClientFormat, inputFramesInClientFormat, (ma_uint32)clientCapturedFramesToProcess);
/* At this point we have input and output data in client format. All we need to do now is convert it to the output device format. This may take a few passes. */
for (;;) {
ma_uint32 framesWrittenThisIteration;
DWORD physicalPlayCursorInBytes;
DWORD physicalWriteCursorInBytes;
DWORD availableBytesPlayback;
DWORD silentPaddingInBytes = 0; /* <-- Must be initialized to 0. */
/* We need the physical play and write cursors. */
if (FAILED(ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes))) {
break;
}
if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) {
physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback;
}
prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes;
/* If there's any bytes available for writing we can do that now. The space between the virtual cursor position and play cursor. */
if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
/* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */
if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) {
availableBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */
} else {
/* This is an error. */
#ifdef MA_DEBUG_OUTPUT
printf("[DirectSound] (Duplex/Playback) WARNING: Play cursor has moved in front of the write cursor (same loop iterations). physicalPlayCursorInBytes=%ld, virtualWriteCursorInBytes=%ld.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback);
#endif
availableBytesPlayback = 0;
}
} else {
/* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */
if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) {
availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
} else {
/* This is an error. */
#ifdef MA_DEBUG_OUTPUT
printf("[DirectSound] (Duplex/Playback) WARNING: Write cursor has moved behind the play cursor (different loop iterations). physicalPlayCursorInBytes=%ld, virtualWriteCursorInBytes=%ld.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback);
#endif
availableBytesPlayback = 0;
}
}
#ifdef MA_DEBUG_OUTPUT
/*printf("[DirectSound] (Duplex/Playback) physicalPlayCursorInBytes=%d, availableBytesPlayback=%d\n", physicalPlayCursorInBytes, availableBytesPlayback);*/
#endif
/* If there's no room available for writing we need to wait for more. */
if (availableBytesPlayback == 0) {
/* If we haven't started the device yet, this will never get beyond 0. In this case we need to get the device started. */
if (!isPlaybackDeviceStarted) {
hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
if (FAILED(hr)) {
ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.", ma_result_from_HRESULT(hr));
}
isPlaybackDeviceStarted = MA_TRUE;
} else {
ma_sleep(waitTimeInMilliseconds);
continue;
}
}
/* Getting here means there room available somewhere. We limit this to either the end of the buffer or the physical play cursor, whichever is closest. */
lockOffsetInBytesPlayback = virtualWriteCursorInBytesPlayback;
if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
/* Same loop iteration. Go up to the end of the buffer. */
lockSizeInBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
} else {
/* Different loop iterations. Go up to the physical play cursor. */
lockSizeInBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
}
hr = ma_IDirectSoundBuffer_Lock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, lockOffsetInBytesPlayback, lockSizeInBytesPlayback, &pMappedDeviceBufferPlayback, &mappedSizeInBytesPlayback, NULL, NULL, 0);
if (FAILED(hr)) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from playback device in preparation for writing to the device.", ma_result_from_HRESULT(hr));
break;
}
/*
Experiment: If the playback buffer is being starved, pad it with some silence to get it back in sync. This will cause a glitch, but it may prevent
endless glitching due to it constantly running out of data.
*/
if (isPlaybackDeviceStarted) {
DWORD bytesQueuedForPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - availableBytesPlayback;
if (bytesQueuedForPlayback < (pDevice->playback.internalPeriodSizeInFrames*bpfDevicePlayback)) {
silentPaddingInBytes = (pDevice->playback.internalPeriodSizeInFrames*2*bpfDevicePlayback) - bytesQueuedForPlayback;
if (silentPaddingInBytes > lockSizeInBytesPlayback) {
silentPaddingInBytes = lockSizeInBytesPlayback;
}
#ifdef MA_DEBUG_OUTPUT
printf("[DirectSound] (Duplex/Playback) Playback buffer starved. availableBytesPlayback=%ld, silentPaddingInBytes=%ld\n", availableBytesPlayback, silentPaddingInBytes);
#endif
}
}
/* At this point we have a buffer for output. */
if (silentPaddingInBytes > 0) {
MA_ZERO_MEMORY(pMappedDeviceBufferPlayback, silentPaddingInBytes);
framesWrittenThisIteration = silentPaddingInBytes/bpfDevicePlayback;
} else {
ma_uint64 convertedFrameCountIn = (outputFramesInClientFormatCount - outputFramesInClientFormatConsumed);
ma_uint64 convertedFrameCountOut = mappedSizeInBytesPlayback/bpfDevicePlayback;
void* pConvertedFramesIn = ma_offset_ptr(outputFramesInClientFormat, outputFramesInClientFormatConsumed * bpfDevicePlayback);
void* pConvertedFramesOut = pMappedDeviceBufferPlayback;
result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, pConvertedFramesIn, &convertedFrameCountIn, pConvertedFramesOut, &convertedFrameCountOut);
if (result != MA_SUCCESS) {
break;
}
outputFramesInClientFormatConsumed += (ma_uint32)convertedFrameCountOut;
framesWrittenThisIteration = (ma_uint32)convertedFrameCountOut;
}
hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedDeviceBufferPlayback, framesWrittenThisIteration*bpfDevicePlayback, NULL, 0);
if (FAILED(hr)) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from playback device after writing to the device.", ma_result_from_HRESULT(hr));
break;
}
virtualWriteCursorInBytesPlayback += framesWrittenThisIteration*bpfDevicePlayback;
if ((virtualWriteCursorInBytesPlayback/bpfDevicePlayback) == pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods) {
virtualWriteCursorInBytesPlayback = 0;
virtualWriteCursorLoopFlagPlayback = !virtualWriteCursorLoopFlagPlayback;
}
/*
We may need to start the device. We want two full periods to be written before starting the playback device. Having an extra period adds
a bit of a buffer to prevent the playback buffer from getting starved.
*/
framesWrittenToPlaybackDevice += framesWrittenThisIteration;
if (!isPlaybackDeviceStarted && framesWrittenToPlaybackDevice >= (pDevice->playback.internalPeriodSizeInFrames*2)) {
hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
if (FAILED(hr)) {
ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.", ma_result_from_HRESULT(hr));
}
isPlaybackDeviceStarted = MA_TRUE;
}
if (framesWrittenThisIteration < mappedSizeInBytesPlayback/bpfDevicePlayback) {
break; /* We're finished with the output data.*/
}
}
if (clientCapturedFramesToProcess == 0) {
break; /* We just consumed every input sample. */
}
}
/* At this point we're done with the mapped portion of the capture buffer. */
hr = ma_IDirectSoundCaptureBuffer_Unlock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pMappedDeviceBufferCapture, mappedSizeInBytesCapture, NULL, 0);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from capture device after reading from the device.", ma_result_from_HRESULT(hr));
}
prevReadCursorInBytesCapture = (lockOffsetInBytesCapture + mappedSizeInBytesCapture);
} break;
case ma_device_type_capture:
{
DWORD physicalCaptureCursorInBytes;
DWORD physicalReadCursorInBytes;
hr = ma_IDirectSoundCaptureBuffer_GetCurrentPosition((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &physicalCaptureCursorInBytes, &physicalReadCursorInBytes);
if (FAILED(hr)) {
return MA_ERROR;
}
/* If the previous capture position is the same as the current position we need to wait a bit longer. */
if (prevReadCursorInBytesCapture == physicalReadCursorInBytes) {
ma_sleep(waitTimeInMilliseconds);
continue;
}
/* Getting here means we have capture data available. */
if (prevReadCursorInBytesCapture < physicalReadCursorInBytes) {
/* The capture position has not looped. This is the simple case. */
lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
lockSizeInBytesCapture = (physicalReadCursorInBytes - prevReadCursorInBytesCapture);
} else {
/*
The capture position has looped. This is the more complex case. Map to the end of the buffer. If this does not return anything,
do it again from the start.
*/
if (prevReadCursorInBytesCapture < pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) {
/* Lock up to the end of the buffer. */
lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
lockSizeInBytesCapture = (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) - prevReadCursorInBytesCapture;
} else {
/* Lock starting from the start of the buffer. */
lockOffsetInBytesCapture = 0;
lockSizeInBytesCapture = physicalReadCursorInBytes;
}
}
#ifdef MA_DEBUG_OUTPUT
/*printf("[DirectSound] (Capture) physicalCaptureCursorInBytes=%d, physicalReadCursorInBytes=%d\n", physicalCaptureCursorInBytes, physicalReadCursorInBytes);*/
/*printf("[DirectSound] (Capture) lockOffsetInBytesCapture=%d, lockSizeInBytesCapture=%d\n", lockOffsetInBytesCapture, lockSizeInBytesCapture);*/
#endif
if (lockSizeInBytesCapture < pDevice->capture.internalPeriodSizeInFrames) {
ma_sleep(waitTimeInMilliseconds);
continue; /* Nothing is available in the capture buffer. */
}
hr = ma_IDirectSoundCaptureBuffer_Lock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, lockOffsetInBytesCapture, lockSizeInBytesCapture, &pMappedDeviceBufferCapture, &mappedSizeInBytesCapture, NULL, NULL, 0);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from capture device in preparation for writing to the device.", ma_result_from_HRESULT(hr));
}
#ifdef MA_DEBUG_OUTPUT
if (lockSizeInBytesCapture != mappedSizeInBytesCapture) {
printf("[DirectSound] (Capture) lockSizeInBytesCapture=%ld != mappedSizeInBytesCapture=%ld\n", lockSizeInBytesCapture, mappedSizeInBytesCapture);
}
#endif
ma_device__send_frames_to_client(pDevice, mappedSizeInBytesCapture/bpfDeviceCapture, pMappedDeviceBufferCapture);
hr = ma_IDirectSoundCaptureBuffer_Unlock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pMappedDeviceBufferCapture, mappedSizeInBytesCapture, NULL, 0);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from capture device after reading from the device.", ma_result_from_HRESULT(hr));
}
prevReadCursorInBytesCapture = lockOffsetInBytesCapture + mappedSizeInBytesCapture;
if (prevReadCursorInBytesCapture == (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture)) {
prevReadCursorInBytesCapture = 0;
}
} break;
case ma_device_type_playback:
{
DWORD availableBytesPlayback;
DWORD physicalPlayCursorInBytes;
DWORD physicalWriteCursorInBytes;
hr = ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes);
if (FAILED(hr)) {
break;
}
if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) {
physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback;
}
prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes;
/* If there's any bytes available for writing we can do that now. The space between the virtual cursor position and play cursor. */
if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
/* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */
if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) {
availableBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */
} else {
/* This is an error. */
#ifdef MA_DEBUG_OUTPUT
printf("[DirectSound] (Playback) WARNING: Play cursor has moved in front of the write cursor (same loop iterations). physicalPlayCursorInBytes=%ld, virtualWriteCursorInBytes=%ld.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback);
#endif
availableBytesPlayback = 0;
}
} else {
/* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */
if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) {
availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
} else {
/* This is an error. */
#ifdef MA_DEBUG_OUTPUT
printf("[DirectSound] (Playback) WARNING: Write cursor has moved behind the play cursor (different loop iterations). physicalPlayCursorInBytes=%ld, virtualWriteCursorInBytes=%ld.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback);
#endif
availableBytesPlayback = 0;
}
}
#ifdef MA_DEBUG_OUTPUT
/*printf("[DirectSound] (Playback) physicalPlayCursorInBytes=%d, availableBytesPlayback=%d\n", physicalPlayCursorInBytes, availableBytesPlayback);*/
#endif
/* If there's no room available for writing we need to wait for more. */
if (availableBytesPlayback < pDevice->playback.internalPeriodSizeInFrames) {
/* If we haven't started the device yet, this will never get beyond 0. In this case we need to get the device started. */
if (availableBytesPlayback == 0 && !isPlaybackDeviceStarted) {
hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.", ma_result_from_HRESULT(hr));
}
isPlaybackDeviceStarted = MA_TRUE;
} else {
ma_sleep(waitTimeInMilliseconds);
continue;
}
}
/* Getting here means there room available somewhere. We limit this to either the end of the buffer or the physical play cursor, whichever is closest. */
lockOffsetInBytesPlayback = virtualWriteCursorInBytesPlayback;
if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
/* Same loop iteration. Go up to the end of the buffer. */
lockSizeInBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
} else {
/* Different loop iterations. Go up to the physical play cursor. */
lockSizeInBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
}
hr = ma_IDirectSoundBuffer_Lock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, lockOffsetInBytesPlayback, lockSizeInBytesPlayback, &pMappedDeviceBufferPlayback, &mappedSizeInBytesPlayback, NULL, NULL, 0);
if (FAILED(hr)) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from playback device in preparation for writing to the device.", ma_result_from_HRESULT(hr));
break;
}
/* At this point we have a buffer for output. */
ma_device__read_frames_from_client(pDevice, (mappedSizeInBytesPlayback/bpfDevicePlayback), pMappedDeviceBufferPlayback);
hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedDeviceBufferPlayback, mappedSizeInBytesPlayback, NULL, 0);
if (FAILED(hr)) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from playback device after writing to the device.", ma_result_from_HRESULT(hr));
break;
}
virtualWriteCursorInBytesPlayback += mappedSizeInBytesPlayback;
if (virtualWriteCursorInBytesPlayback == pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) {
virtualWriteCursorInBytesPlayback = 0;
virtualWriteCursorLoopFlagPlayback = !virtualWriteCursorLoopFlagPlayback;
}
/*
We may need to start the device. We want two full periods to be written before starting the playback device. Having an extra period adds
a bit of a buffer to prevent the playback buffer from getting starved.
*/
framesWrittenToPlaybackDevice += mappedSizeInBytesPlayback/bpfDevicePlayback;
if (!isPlaybackDeviceStarted && framesWrittenToPlaybackDevice >= pDevice->playback.internalPeriodSizeInFrames) {
hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.", ma_result_from_HRESULT(hr));
}
isPlaybackDeviceStarted = MA_TRUE;
}
} break;
default: return MA_INVALID_ARGS; /* Invalid device type. */
}
if (result != MA_SUCCESS) {
return result;
}
}
/* Getting here means the device is being stopped. */
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
hr = ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Stop() failed.", ma_result_from_HRESULT(hr));
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
/* The playback device should be drained before stopping. All we do is wait until the available bytes is equal to the size of the buffer. */
if (isPlaybackDeviceStarted) {
for (;;) {
DWORD availableBytesPlayback = 0;
DWORD physicalPlayCursorInBytes;
DWORD physicalWriteCursorInBytes;
hr = ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes);
if (FAILED(hr)) {
break;
}
if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) {
physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback;
}
prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes;
if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
/* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */
if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) {
availableBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */
} else {
break;
}
} else {
/* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */
if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) {
availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
} else {
break;
}
}
if (availableBytesPlayback >= (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback)) {
break;
}
ma_sleep(waitTimeInMilliseconds);
}
}
hr = ma_IDirectSoundBuffer_Stop((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer);
if (FAILED(hr)) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Stop() failed.", ma_result_from_HRESULT(hr));
}
ma_IDirectSoundBuffer_SetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0);
}
return MA_SUCCESS;
}
static ma_result ma_context_uninit__dsound(ma_context* pContext)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pContext->backend == ma_backend_dsound);
ma_dlclose(pContext, pContext->dsound.hDSoundDLL);
return MA_SUCCESS;
}
static ma_result ma_context_init__dsound(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
{
MA_ASSERT(pContext != NULL);
(void)pConfig;
pContext->dsound.hDSoundDLL = ma_dlopen(pContext, "dsound.dll");
if (pContext->dsound.hDSoundDLL == NULL) {
return MA_API_NOT_FOUND;
}
pContext->dsound.DirectSoundCreate = ma_dlsym(pContext, pContext->dsound.hDSoundDLL, "DirectSoundCreate");
pContext->dsound.DirectSoundEnumerateA = ma_dlsym(pContext, pContext->dsound.hDSoundDLL, "DirectSoundEnumerateA");
pContext->dsound.DirectSoundCaptureCreate = ma_dlsym(pContext, pContext->dsound.hDSoundDLL, "DirectSoundCaptureCreate");
pContext->dsound.DirectSoundCaptureEnumerateA = ma_dlsym(pContext, pContext->dsound.hDSoundDLL, "DirectSoundCaptureEnumerateA");
pCallbacks->onContextInit = ma_context_init__dsound;
pCallbacks->onContextUninit = ma_context_uninit__dsound;
pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__dsound;
pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__dsound;
pCallbacks->onDeviceInit = ma_device_init__dsound;
pCallbacks->onDeviceUninit = ma_device_uninit__dsound;
pCallbacks->onDeviceStart = NULL; /* Not used. Started in onDeviceAudioThread. */
pCallbacks->onDeviceStop = NULL; /* Not used. Stopped in onDeviceAudioThread. */
pCallbacks->onDeviceRead = NULL; /* Not used. Data is read directly in onDeviceAudioThread. */
pCallbacks->onDeviceWrite = NULL; /* Not used. Data is written directly in onDeviceAudioThread. */
pCallbacks->onDeviceAudioThread = ma_device_audio_thread__dsound;
return MA_SUCCESS;
}
#endif
/******************************************************************************
WinMM Backend
******************************************************************************/
#ifdef MA_HAS_WINMM
/*
Some older compilers don't have WAVEOUTCAPS2A and WAVEINCAPS2A, so we'll need to write this ourselves. These structures
are exactly the same as the older ones but they have a few GUIDs for manufacturer/product/name identification. I'm keeping
the names the same as the Win32 library for consistency, but namespaced to avoid naming conflicts with the Win32 version.
*/
typedef struct
{
WORD wMid;
WORD wPid;
MMVERSION vDriverVersion;
CHAR szPname[MAXPNAMELEN];
DWORD dwFormats;
WORD wChannels;
WORD wReserved1;
DWORD dwSupport;
GUID ManufacturerGuid;
GUID ProductGuid;
GUID NameGuid;
} MA_WAVEOUTCAPS2A;
typedef struct
{
WORD wMid;
WORD wPid;
MMVERSION vDriverVersion;
CHAR szPname[MAXPNAMELEN];
DWORD dwFormats;
WORD wChannels;
WORD wReserved1;
GUID ManufacturerGuid;
GUID ProductGuid;
GUID NameGuid;
} MA_WAVEINCAPS2A;
typedef UINT (WINAPI * MA_PFN_waveOutGetNumDevs)(void);
typedef MMRESULT (WINAPI * MA_PFN_waveOutGetDevCapsA)(ma_uintptr uDeviceID, LPWAVEOUTCAPSA pwoc, UINT cbwoc);
typedef MMRESULT (WINAPI * MA_PFN_waveOutOpen)(LPHWAVEOUT phwo, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen);
typedef MMRESULT (WINAPI * MA_PFN_waveOutClose)(HWAVEOUT hwo);
typedef MMRESULT (WINAPI * MA_PFN_waveOutPrepareHeader)(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh);
typedef MMRESULT (WINAPI * MA_PFN_waveOutUnprepareHeader)(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh);
typedef MMRESULT (WINAPI * MA_PFN_waveOutWrite)(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh);
typedef MMRESULT (WINAPI * MA_PFN_waveOutReset)(HWAVEOUT hwo);
typedef UINT (WINAPI * MA_PFN_waveInGetNumDevs)(void);
typedef MMRESULT (WINAPI * MA_PFN_waveInGetDevCapsA)(ma_uintptr uDeviceID, LPWAVEINCAPSA pwic, UINT cbwic);
typedef MMRESULT (WINAPI * MA_PFN_waveInOpen)(LPHWAVEIN phwi, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen);
typedef MMRESULT (WINAPI * MA_PFN_waveInClose)(HWAVEIN hwi);
typedef MMRESULT (WINAPI * MA_PFN_waveInPrepareHeader)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh);
typedef MMRESULT (WINAPI * MA_PFN_waveInUnprepareHeader)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh);
typedef MMRESULT (WINAPI * MA_PFN_waveInAddBuffer)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh);
typedef MMRESULT (WINAPI * MA_PFN_waveInStart)(HWAVEIN hwi);
typedef MMRESULT (WINAPI * MA_PFN_waveInReset)(HWAVEIN hwi);
static ma_result ma_result_from_MMRESULT(MMRESULT resultMM)
{
switch (resultMM) {
case MMSYSERR_NOERROR: return MA_SUCCESS;
case MMSYSERR_BADDEVICEID: return MA_INVALID_ARGS;
case MMSYSERR_INVALHANDLE: return MA_INVALID_ARGS;
case MMSYSERR_NOMEM: return MA_OUT_OF_MEMORY;
case MMSYSERR_INVALFLAG: return MA_INVALID_ARGS;
case MMSYSERR_INVALPARAM: return MA_INVALID_ARGS;
case MMSYSERR_HANDLEBUSY: return MA_BUSY;
case MMSYSERR_ERROR: return MA_ERROR;
default: return MA_ERROR;
}
}
static char* ma_find_last_character(char* str, char ch)
{
char* last;
if (str == NULL) {
return NULL;
}
last = NULL;
while (*str != '\0') {
if (*str == ch) {
last = str;
}
str += 1;
}
return last;
}
static ma_uint32 ma_get_period_size_in_bytes(ma_uint32 periodSizeInFrames, ma_format format, ma_uint32 channels)
{
return periodSizeInFrames * ma_get_bytes_per_frame(format, channels);
}
/*
Our own "WAVECAPS" structure that contains generic information shared between WAVEOUTCAPS2 and WAVEINCAPS2 so
we can do things generically and typesafely. Names are being kept the same for consistency.
*/
typedef struct
{
CHAR szPname[MAXPNAMELEN];
DWORD dwFormats;
WORD wChannels;
GUID NameGuid;
} MA_WAVECAPSA;
static ma_result ma_get_best_info_from_formats_flags__winmm(DWORD dwFormats, WORD channels, WORD* pBitsPerSample, DWORD* pSampleRate)
{
WORD bitsPerSample = 0;
DWORD sampleRate = 0;
if (pBitsPerSample) {
*pBitsPerSample = 0;
}
if (pSampleRate) {
*pSampleRate = 0;
}
if (channels == 1) {
bitsPerSample = 16;
if ((dwFormats & WAVE_FORMAT_48M16) != 0) {
sampleRate = 48000;
} else if ((dwFormats & WAVE_FORMAT_44M16) != 0) {
sampleRate = 44100;
} else if ((dwFormats & WAVE_FORMAT_2M16) != 0) {
sampleRate = 22050;
} else if ((dwFormats & WAVE_FORMAT_1M16) != 0) {
sampleRate = 11025;
} else if ((dwFormats & WAVE_FORMAT_96M16) != 0) {
sampleRate = 96000;
} else {
bitsPerSample = 8;
if ((dwFormats & WAVE_FORMAT_48M08) != 0) {
sampleRate = 48000;
} else if ((dwFormats & WAVE_FORMAT_44M08) != 0) {
sampleRate = 44100;
} else if ((dwFormats & WAVE_FORMAT_2M08) != 0) {
sampleRate = 22050;
} else if ((dwFormats & WAVE_FORMAT_1M08) != 0) {
sampleRate = 11025;
} else if ((dwFormats & WAVE_FORMAT_96M08) != 0) {
sampleRate = 96000;
} else {
return MA_FORMAT_NOT_SUPPORTED;
}
}
} else {
bitsPerSample = 16;
if ((dwFormats & WAVE_FORMAT_48S16) != 0) {
sampleRate = 48000;
} else if ((dwFormats & WAVE_FORMAT_44S16) != 0) {
sampleRate = 44100;
} else if ((dwFormats & WAVE_FORMAT_2S16) != 0) {
sampleRate = 22050;
} else if ((dwFormats & WAVE_FORMAT_1S16) != 0) {
sampleRate = 11025;
} else if ((dwFormats & WAVE_FORMAT_96S16) != 0) {
sampleRate = 96000;
} else {
bitsPerSample = 8;
if ((dwFormats & WAVE_FORMAT_48S08) != 0) {
sampleRate = 48000;
} else if ((dwFormats & WAVE_FORMAT_44S08) != 0) {
sampleRate = 44100;
} else if ((dwFormats & WAVE_FORMAT_2S08) != 0) {
sampleRate = 22050;
} else if ((dwFormats & WAVE_FORMAT_1S08) != 0) {
sampleRate = 11025;
} else if ((dwFormats & WAVE_FORMAT_96S08) != 0) {
sampleRate = 96000;
} else {
return MA_FORMAT_NOT_SUPPORTED;
}
}
}
if (pBitsPerSample) {
*pBitsPerSample = bitsPerSample;
}
if (pSampleRate) {
*pSampleRate = sampleRate;
}
return MA_SUCCESS;
}
static ma_result ma_formats_flags_to_WAVEFORMATEX__winmm(DWORD dwFormats, WORD channels, WAVEFORMATEX* pWF)
{
ma_result result;
MA_ASSERT(pWF != NULL);
MA_ZERO_OBJECT(pWF);
pWF->cbSize = sizeof(*pWF);
pWF->wFormatTag = WAVE_FORMAT_PCM;
pWF->nChannels = (WORD)channels;
if (pWF->nChannels > 2) {
pWF->nChannels = 2;
}
result = ma_get_best_info_from_formats_flags__winmm(dwFormats, channels, &pWF->wBitsPerSample, &pWF->nSamplesPerSec);
if (result != MA_SUCCESS) {
return result;
}
pWF->nBlockAlign = (WORD)(pWF->nChannels * pWF->wBitsPerSample / 8);
pWF->nAvgBytesPerSec = pWF->nBlockAlign * pWF->nSamplesPerSec;
return MA_SUCCESS;
}
static ma_result ma_context_get_device_info_from_WAVECAPS(ma_context* pContext, MA_WAVECAPSA* pCaps, ma_device_info* pDeviceInfo)
{
WORD bitsPerSample;
DWORD sampleRate;
ma_result result;
MA_ASSERT(pContext != NULL);
MA_ASSERT(pCaps != NULL);
MA_ASSERT(pDeviceInfo != NULL);
/*
Name / Description
Unfortunately the name specified in WAVE(OUT/IN)CAPS2 is limited to 31 characters. This results in an unprofessional looking
situation where the names of the devices are truncated. To help work around this, we need to look at the name GUID and try
looking in the registry for the full name. If we can't find it there, we need to just fall back to the default name.
*/
/* Set the default to begin with. */
ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), pCaps->szPname, (size_t)-1);
/*
Now try the registry. There's a few things to consider here:
- The name GUID can be null, in which we case we just need to stick to the original 31 characters.
- If the name GUID is not present in the registry we'll also need to stick to the original 31 characters.
- I like consistency, so I want the returned device names to be consistent with those returned by WASAPI and DirectSound. The
problem, however is that WASAPI and DirectSound use " ()" format (such as "Speakers (High Definition Audio)"),
but WinMM does not specificy the component name. From my admittedly limited testing, I've notice the component name seems to
usually fit within the 31 characters of the fixed sized buffer, so what I'm going to do is parse that string for the component
name, and then concatenate the name from the registry.
*/
if (!ma_is_guid_null(&pCaps->NameGuid)) {
wchar_t guidStrW[256];
if (((MA_PFN_StringFromGUID2)pContext->win32.StringFromGUID2)(&pCaps->NameGuid, guidStrW, ma_countof(guidStrW)) > 0) {
char guidStr[256];
char keyStr[1024];
HKEY hKey;
WideCharToMultiByte(CP_UTF8, 0, guidStrW, -1, guidStr, sizeof(guidStr), 0, FALSE);
ma_strcpy_s(keyStr, sizeof(keyStr), "SYSTEM\\CurrentControlSet\\Control\\MediaCategories\\");
ma_strcat_s(keyStr, sizeof(keyStr), guidStr);
if (((MA_PFN_RegOpenKeyExA)pContext->win32.RegOpenKeyExA)(HKEY_LOCAL_MACHINE, keyStr, 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
BYTE nameFromReg[512];
DWORD nameFromRegSize = sizeof(nameFromReg);
result = ((MA_PFN_RegQueryValueExA)pContext->win32.RegQueryValueExA)(hKey, "Name", 0, NULL, (LPBYTE)nameFromReg, (LPDWORD)&nameFromRegSize);
((MA_PFN_RegCloseKey)pContext->win32.RegCloseKey)(hKey);
if (result == ERROR_SUCCESS) {
/* We have the value from the registry, so now we need to construct the name string. */
char name[1024];
if (ma_strcpy_s(name, sizeof(name), pDeviceInfo->name) == 0) {
char* nameBeg = ma_find_last_character(name, '(');
if (nameBeg != NULL) {
size_t leadingLen = (nameBeg - name);
ma_strncpy_s(nameBeg + 1, sizeof(name) - leadingLen, (const char*)nameFromReg, (size_t)-1);
/* The closing ")", if it can fit. */
if (leadingLen + nameFromRegSize < sizeof(name)-1) {
ma_strcat_s(name, sizeof(name), ")");
}
ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), name, (size_t)-1);
}
}
}
}
}
}
result = ma_get_best_info_from_formats_flags__winmm(pCaps->dwFormats, pCaps->wChannels, &bitsPerSample, &sampleRate);
if (result != MA_SUCCESS) {
return result;
}
if (bitsPerSample == 8) {
pDeviceInfo->nativeDataFormats[0].format = ma_format_u8;
} else if (bitsPerSample == 16) {
pDeviceInfo->nativeDataFormats[0].format = ma_format_s16;
} else if (bitsPerSample == 24) {
pDeviceInfo->nativeDataFormats[0].format = ma_format_s24;
} else if (bitsPerSample == 32) {
pDeviceInfo->nativeDataFormats[0].format = ma_format_s32;
} else {
return MA_FORMAT_NOT_SUPPORTED;
}
pDeviceInfo->nativeDataFormats[0].channels = pCaps->wChannels;
pDeviceInfo->nativeDataFormats[0].sampleRate = sampleRate;
pDeviceInfo->nativeDataFormats[0].flags = 0;
pDeviceInfo->nativeDataFormatCount = 1;
return MA_SUCCESS;
}
static ma_result ma_context_get_device_info_from_WAVEOUTCAPS2(ma_context* pContext, MA_WAVEOUTCAPS2A* pCaps, ma_device_info* pDeviceInfo)
{
MA_WAVECAPSA caps;
MA_ASSERT(pContext != NULL);
MA_ASSERT(pCaps != NULL);
MA_ASSERT(pDeviceInfo != NULL);
MA_COPY_MEMORY(caps.szPname, pCaps->szPname, sizeof(caps.szPname));
caps.dwFormats = pCaps->dwFormats;
caps.wChannels = pCaps->wChannels;
caps.NameGuid = pCaps->NameGuid;
return ma_context_get_device_info_from_WAVECAPS(pContext, &caps, pDeviceInfo);
}
static ma_result ma_context_get_device_info_from_WAVEINCAPS2(ma_context* pContext, MA_WAVEINCAPS2A* pCaps, ma_device_info* pDeviceInfo)
{
MA_WAVECAPSA caps;
MA_ASSERT(pContext != NULL);
MA_ASSERT(pCaps != NULL);
MA_ASSERT(pDeviceInfo != NULL);
MA_COPY_MEMORY(caps.szPname, pCaps->szPname, sizeof(caps.szPname));
caps.dwFormats = pCaps->dwFormats;
caps.wChannels = pCaps->wChannels;
caps.NameGuid = pCaps->NameGuid;
return ma_context_get_device_info_from_WAVECAPS(pContext, &caps, pDeviceInfo);
}
static ma_result ma_context_enumerate_devices__winmm(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
{
UINT playbackDeviceCount;
UINT captureDeviceCount;
UINT iPlaybackDevice;
UINT iCaptureDevice;
MA_ASSERT(pContext != NULL);
MA_ASSERT(callback != NULL);
/* Playback. */
playbackDeviceCount = ((MA_PFN_waveOutGetNumDevs)pContext->winmm.waveOutGetNumDevs)();
for (iPlaybackDevice = 0; iPlaybackDevice < playbackDeviceCount; ++iPlaybackDevice) {
MMRESULT result;
MA_WAVEOUTCAPS2A caps;
MA_ZERO_OBJECT(&caps);
result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(iPlaybackDevice, (WAVEOUTCAPSA*)&caps, sizeof(caps));
if (result == MMSYSERR_NOERROR) {
ma_device_info deviceInfo;
MA_ZERO_OBJECT(&deviceInfo);
deviceInfo.id.winmm = iPlaybackDevice;
/* The first enumerated device is the default device. */
if (iPlaybackDevice == 0) {
deviceInfo.isDefault = MA_TRUE;
}
if (ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, &deviceInfo) == MA_SUCCESS) {
ma_bool32 cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
if (cbResult == MA_FALSE) {
return MA_SUCCESS; /* Enumeration was stopped. */
}
}
}
}
/* Capture. */
captureDeviceCount = ((MA_PFN_waveInGetNumDevs)pContext->winmm.waveInGetNumDevs)();
for (iCaptureDevice = 0; iCaptureDevice < captureDeviceCount; ++iCaptureDevice) {
MMRESULT result;
MA_WAVEINCAPS2A caps;
MA_ZERO_OBJECT(&caps);
result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(iCaptureDevice, (WAVEINCAPSA*)&caps, sizeof(caps));
if (result == MMSYSERR_NOERROR) {
ma_device_info deviceInfo;
MA_ZERO_OBJECT(&deviceInfo);
deviceInfo.id.winmm = iCaptureDevice;
/* The first enumerated device is the default device. */
if (iCaptureDevice == 0) {
deviceInfo.isDefault = MA_TRUE;
}
if (ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, &deviceInfo) == MA_SUCCESS) {
ma_bool32 cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
if (cbResult == MA_FALSE) {
return MA_SUCCESS; /* Enumeration was stopped. */
}
}
}
}
return MA_SUCCESS;
}
static ma_result ma_context_get_device_info__winmm(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo)
{
UINT winMMDeviceID;
MA_ASSERT(pContext != NULL);
winMMDeviceID = 0;
if (pDeviceID != NULL) {
winMMDeviceID = (UINT)pDeviceID->winmm;
}
pDeviceInfo->id.winmm = winMMDeviceID;
/* The first ID is the default device. */
if (winMMDeviceID == 0) {
pDeviceInfo->isDefault = MA_TRUE;
}
if (deviceType == ma_device_type_playback) {
MMRESULT result;
MA_WAVEOUTCAPS2A caps;
MA_ZERO_OBJECT(&caps);
result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceID, (WAVEOUTCAPSA*)&caps, sizeof(caps));
if (result == MMSYSERR_NOERROR) {
return ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, pDeviceInfo);
}
} else {
MMRESULT result;
MA_WAVEINCAPS2A caps;
MA_ZERO_OBJECT(&caps);
result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceID, (WAVEINCAPSA*)&caps, sizeof(caps));
if (result == MMSYSERR_NOERROR) {
return ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, pDeviceInfo);
}
}
return MA_NO_DEVICE;
}
static ma_result ma_device_uninit__winmm(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
((MA_PFN_waveInClose)pDevice->pContext->winmm.waveInClose)((HWAVEIN)pDevice->winmm.hDeviceCapture);
CloseHandle((HANDLE)pDevice->winmm.hEventCapture);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((HWAVEOUT)pDevice->winmm.hDevicePlayback);
((MA_PFN_waveOutClose)pDevice->pContext->winmm.waveOutClose)((HWAVEOUT)pDevice->winmm.hDevicePlayback);
CloseHandle((HANDLE)pDevice->winmm.hEventPlayback);
}
ma__free_from_callbacks(pDevice->winmm._pHeapData, &pDevice->pContext->allocationCallbacks);
MA_ZERO_OBJECT(&pDevice->winmm); /* Safety. */
return MA_SUCCESS;
}
static ma_uint32 ma_calculate_period_size_in_frames__winmm(ma_uint32 periodSizeInFrames, ma_uint32 periodSizeInMilliseconds, ma_uint32 sampleRate, ma_performance_profile performanceProfile)
{
/* WinMM has a minimum period size of 40ms. */
ma_uint32 minPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(40, sampleRate);
if (periodSizeInFrames == 0) {
if (periodSizeInMilliseconds == 0) {
if (performanceProfile == ma_performance_profile_low_latency) {
periodSizeInFrames = minPeriodSizeInFrames;
} else {
periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, sampleRate);
}
} else {
periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(periodSizeInMilliseconds, sampleRate);
}
}
if (periodSizeInFrames < minPeriodSizeInFrames) {
periodSizeInFrames = minPeriodSizeInFrames;
}
return periodSizeInFrames;
}
static ma_result ma_device_init__winmm(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
{
const char* errorMsg = "";
ma_result errorCode = MA_ERROR;
ma_result result = MA_SUCCESS;
ma_uint32 heapSize;
UINT winMMDeviceIDPlayback = 0;
UINT winMMDeviceIDCapture = 0;
MA_ASSERT(pDevice != NULL);
MA_ZERO_OBJECT(&pDevice->winmm);
if (pConfig->deviceType == ma_device_type_loopback) {
return MA_DEVICE_TYPE_NOT_SUPPORTED;
}
/* No exlusive mode with WinMM. */
if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
return MA_SHARE_MODE_NOT_SUPPORTED;
}
if (pDescriptorPlayback->pDeviceID != NULL) {
winMMDeviceIDPlayback = (UINT)pDescriptorPlayback->pDeviceID->winmm;
}
if (pDescriptorCapture->pDeviceID != NULL) {
winMMDeviceIDCapture = (UINT)pDescriptorCapture->pDeviceID->winmm;
}
/* The capture device needs to be initialized first. */
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
WAVEINCAPSA caps;
WAVEFORMATEX wf;
MMRESULT resultMM;
/* We use an event to know when a new fragment needs to be enqueued. */
pDevice->winmm.hEventCapture = (ma_handle)CreateEventW(NULL, TRUE, TRUE, NULL);
if (pDevice->winmm.hEventCapture == NULL) {
errorMsg = "[WinMM] Failed to create event for fragment enqueing for the capture device.", errorCode = ma_result_from_GetLastError(GetLastError());
goto on_error;
}
/* The format should be based on the device's actual format. */
if (((MA_PFN_waveInGetDevCapsA)pDevice->pContext->winmm.waveInGetDevCapsA)(winMMDeviceIDCapture, &caps, sizeof(caps)) != MMSYSERR_NOERROR) {
errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED;
goto on_error;
}
result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf);
if (result != MA_SUCCESS) {
errorMsg = "[WinMM] Could not find appropriate format for internal device.", errorCode = result;
goto on_error;
}
resultMM = ((MA_PFN_waveInOpen)pDevice->pContext->winmm.waveInOpen)((LPHWAVEIN)&pDevice->winmm.hDeviceCapture, winMMDeviceIDCapture, &wf, (DWORD_PTR)pDevice->winmm.hEventCapture, (DWORD_PTR)pDevice, CALLBACK_EVENT | WAVE_ALLOWSYNC);
if (resultMM != MMSYSERR_NOERROR) {
errorMsg = "[WinMM] Failed to open capture device.", errorCode = MA_FAILED_TO_OPEN_BACKEND_DEVICE;
goto on_error;
}
pDescriptorCapture->format = ma_format_from_WAVEFORMATEX(&wf);
pDescriptorCapture->channels = wf.nChannels;
pDescriptorCapture->sampleRate = wf.nSamplesPerSec;
ma_get_standard_channel_map(ma_standard_channel_map_microsoft, pDescriptorCapture->channels, pDescriptorCapture->channelMap);
pDescriptorCapture->periodCount = pDescriptorCapture->periodCount;
pDescriptorCapture->periodSizeInFrames = ma_calculate_period_size_in_frames__winmm(pDescriptorCapture->periodSizeInFrames, pDescriptorCapture->periodSizeInMilliseconds, pDescriptorCapture->sampleRate, pConfig->performanceProfile);
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
WAVEOUTCAPSA caps;
WAVEFORMATEX wf;
MMRESULT resultMM;
/* We use an event to know when a new fragment needs to be enqueued. */
pDevice->winmm.hEventPlayback = (ma_handle)CreateEvent(NULL, TRUE, TRUE, NULL);
if (pDevice->winmm.hEventPlayback == NULL) {
errorMsg = "[WinMM] Failed to create event for fragment enqueing for the playback device.", errorCode = ma_result_from_GetLastError(GetLastError());
goto on_error;
}
/* The format should be based on the device's actual format. */
if (((MA_PFN_waveOutGetDevCapsA)pDevice->pContext->winmm.waveOutGetDevCapsA)(winMMDeviceIDPlayback, &caps, sizeof(caps)) != MMSYSERR_NOERROR) {
errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED;
goto on_error;
}
result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf);
if (result != MA_SUCCESS) {
errorMsg = "[WinMM] Could not find appropriate format for internal device.", errorCode = result;
goto on_error;
}
resultMM = ((MA_PFN_waveOutOpen)pDevice->pContext->winmm.waveOutOpen)((LPHWAVEOUT)&pDevice->winmm.hDevicePlayback, winMMDeviceIDPlayback, &wf, (DWORD_PTR)pDevice->winmm.hEventPlayback, (DWORD_PTR)pDevice, CALLBACK_EVENT | WAVE_ALLOWSYNC);
if (resultMM != MMSYSERR_NOERROR) {
errorMsg = "[WinMM] Failed to open playback device.", errorCode = MA_FAILED_TO_OPEN_BACKEND_DEVICE;
goto on_error;
}
pDescriptorPlayback->format = ma_format_from_WAVEFORMATEX(&wf);
pDescriptorPlayback->channels = wf.nChannels;
pDescriptorPlayback->sampleRate = wf.nSamplesPerSec;
ma_get_standard_channel_map(ma_standard_channel_map_microsoft, pDescriptorPlayback->channels, pDescriptorPlayback->channelMap);
pDescriptorPlayback->periodCount = pDescriptorPlayback->periodCount;
pDescriptorPlayback->periodSizeInFrames = ma_calculate_period_size_in_frames__winmm(pDescriptorPlayback->periodSizeInFrames, pDescriptorPlayback->periodSizeInMilliseconds, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
}
/*
The heap allocated data is allocated like so:
[Capture WAVEHDRs][Playback WAVEHDRs][Capture Intermediary Buffer][Playback Intermediary Buffer]
*/
heapSize = 0;
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
heapSize += sizeof(WAVEHDR)*pDescriptorCapture->periodCount + (pDescriptorCapture->periodSizeInFrames * pDescriptorCapture->periodCount * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels));
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
heapSize += sizeof(WAVEHDR)*pDescriptorPlayback->periodCount + (pDescriptorPlayback->periodSizeInFrames * pDescriptorPlayback->periodCount * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels));
}
pDevice->winmm._pHeapData = (ma_uint8*)ma__calloc_from_callbacks(heapSize, &pDevice->pContext->allocationCallbacks);
if (pDevice->winmm._pHeapData == NULL) {
errorMsg = "[WinMM] Failed to allocate memory for the intermediary buffer.", errorCode = MA_OUT_OF_MEMORY;
goto on_error;
}
MA_ZERO_MEMORY(pDevice->winmm._pHeapData, heapSize);
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
ma_uint32 iPeriod;
if (pConfig->deviceType == ma_device_type_capture) {
pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData;
pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDescriptorCapture->periodCount));
} else {
pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData;
pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDescriptorCapture->periodCount + pDescriptorPlayback->periodCount));
}
/* Prepare headers. */
for (iPeriod = 0; iPeriod < pDescriptorCapture->periodCount; ++iPeriod) {
ma_uint32 periodSizeInBytes = ma_get_period_size_in_bytes(pDescriptorCapture->periodSizeInFrames, pDescriptorCapture->format, pDescriptorCapture->channels);
((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].lpData = (LPSTR)(pDevice->winmm.pIntermediaryBufferCapture + (periodSizeInBytes*iPeriod));
((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwBufferLength = periodSizeInBytes;
((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwFlags = 0L;
((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwLoops = 0L;
((MA_PFN_waveInPrepareHeader)pDevice->pContext->winmm.waveInPrepareHeader)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(WAVEHDR));
/*
The user data of the WAVEHDR structure is a single flag the controls whether or not it is ready for writing. Consider it to be named "isLocked". A value of 0 means
it's unlocked and available for writing. A value of 1 means it's locked.
*/
((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwUser = 0;
}
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
ma_uint32 iPeriod;
if (pConfig->deviceType == ma_device_type_playback) {
pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData;
pDevice->winmm.pIntermediaryBufferPlayback = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*pDescriptorPlayback->periodCount);
} else {
pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDescriptorCapture->periodCount));
pDevice->winmm.pIntermediaryBufferPlayback = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDescriptorCapture->periodCount + pDescriptorPlayback->periodCount)) + (pDescriptorCapture->periodSizeInFrames*pDescriptorCapture->periodCount*ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels));
}
/* Prepare headers. */
for (iPeriod = 0; iPeriod < pDescriptorPlayback->periodCount; ++iPeriod) {
ma_uint32 periodSizeInBytes = ma_get_period_size_in_bytes(pDescriptorPlayback->periodSizeInFrames, pDescriptorPlayback->format, pDescriptorPlayback->channels);
((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].lpData = (LPSTR)(pDevice->winmm.pIntermediaryBufferPlayback + (periodSizeInBytes*iPeriod));
((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwBufferLength = periodSizeInBytes;
((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwFlags = 0L;
((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwLoops = 0L;
((MA_PFN_waveOutPrepareHeader)pDevice->pContext->winmm.waveOutPrepareHeader)((HWAVEOUT)pDevice->winmm.hDevicePlayback, &((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(WAVEHDR));
/*
The user data of the WAVEHDR structure is a single flag the controls whether or not it is ready for writing. Consider it to be named "isLocked". A value of 0 means
it's unlocked and available for writing. A value of 1 means it's locked.
*/
((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwUser = 0;
}
}
return MA_SUCCESS;
on_error:
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
if (pDevice->winmm.pWAVEHDRCapture != NULL) {
ma_uint32 iPeriod;
for (iPeriod = 0; iPeriod < pDescriptorCapture->periodCount; ++iPeriod) {
((MA_PFN_waveInUnprepareHeader)pDevice->pContext->winmm.waveInUnprepareHeader)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(WAVEHDR));
}
}
((MA_PFN_waveInClose)pDevice->pContext->winmm.waveInClose)((HWAVEIN)pDevice->winmm.hDeviceCapture);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
if (pDevice->winmm.pWAVEHDRCapture != NULL) {
ma_uint32 iPeriod;
for (iPeriod = 0; iPeriod < pDescriptorPlayback->periodCount; ++iPeriod) {
((MA_PFN_waveOutUnprepareHeader)pDevice->pContext->winmm.waveOutUnprepareHeader)((HWAVEOUT)pDevice->winmm.hDevicePlayback, &((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(WAVEHDR));
}
}
((MA_PFN_waveOutClose)pDevice->pContext->winmm.waveOutClose)((HWAVEOUT)pDevice->winmm.hDevicePlayback);
}
ma__free_from_callbacks(pDevice->winmm._pHeapData, &pDevice->pContext->allocationCallbacks);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, errorMsg, errorCode);
}
static ma_result ma_device_start__winmm(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
MMRESULT resultMM;
WAVEHDR* pWAVEHDR;
ma_uint32 iPeriod;
pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRCapture;
/* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */
ResetEvent((HANDLE)pDevice->winmm.hEventCapture);
/* To start the device we attach all of the buffers and then start it. As the buffers are filled with data we will get notifications. */
for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) {
resultMM = ((MA_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((LPWAVEHDR)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(WAVEHDR));
if (resultMM != MMSYSERR_NOERROR) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] Failed to attach input buffers to capture device in preparation for capture.", ma_result_from_MMRESULT(resultMM));
}
/* Make sure all of the buffers start out locked. We don't want to access them until the backend tells us we can. */
pWAVEHDR[iPeriod].dwUser = 1; /* 1 = locked. */
}
/* Capture devices need to be explicitly started, unlike playback devices. */
resultMM = ((MA_PFN_waveInStart)pDevice->pContext->winmm.waveInStart)((HWAVEIN)pDevice->winmm.hDeviceCapture);
if (resultMM != MMSYSERR_NOERROR) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] Failed to start backend device.", ma_result_from_MMRESULT(resultMM));
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
/* Don't need to do anything for playback. It'll be started automatically in ma_device_start__winmm(). */
}
return MA_SUCCESS;
}
static ma_result ma_device_stop__winmm(ma_device* pDevice)
{
MMRESULT resultMM;
MA_ASSERT(pDevice != NULL);
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
if (pDevice->winmm.hDeviceCapture == NULL) {
return MA_INVALID_ARGS;
}
resultMM = ((MA_PFN_waveInReset)pDevice->pContext->winmm.waveInReset)((HWAVEIN)pDevice->winmm.hDeviceCapture);
if (resultMM != MMSYSERR_NOERROR) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] WARNING: Failed to reset capture device.", ma_result_from_MMRESULT(resultMM));
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
ma_uint32 iPeriod;
WAVEHDR* pWAVEHDR;
if (pDevice->winmm.hDevicePlayback == NULL) {
return MA_INVALID_ARGS;
}
/* We need to drain the device. To do this we just loop over each header and if it's locked just wait for the event. */
pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback;
for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; iPeriod += 1) {
if (pWAVEHDR[iPeriod].dwUser == 1) { /* 1 = locked. */
if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventPlayback, INFINITE) != WAIT_OBJECT_0) {
break; /* An error occurred so just abandon ship and stop the device without draining. */
}
pWAVEHDR[iPeriod].dwUser = 0;
}
}
resultMM = ((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((HWAVEOUT)pDevice->winmm.hDevicePlayback);
if (resultMM != MMSYSERR_NOERROR) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] WARNING: Failed to reset playback device.", ma_result_from_MMRESULT(resultMM));
}
}
return MA_SUCCESS;
}
static ma_result ma_device_write__winmm(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
{
ma_result result = MA_SUCCESS;
MMRESULT resultMM;
ma_uint32 totalFramesWritten;
WAVEHDR* pWAVEHDR;
MA_ASSERT(pDevice != NULL);
MA_ASSERT(pPCMFrames != NULL);
if (pFramesWritten != NULL) {
*pFramesWritten = 0;
}
pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback;
/* Keep processing as much data as possible. */
totalFramesWritten = 0;
while (totalFramesWritten < frameCount) {
/* If the current header has some space available we need to write part of it. */
if (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser == 0) { /* 0 = unlocked. */
/*
This header has room in it. We copy as much of it as we can. If we end up fully consuming the buffer we need to
write it out and move on to the next iteration.
*/
ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
ma_uint32 framesRemainingInHeader = (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwBufferLength/bpf) - pDevice->winmm.headerFramesConsumedPlayback;
ma_uint32 framesToCopy = ma_min(framesRemainingInHeader, (frameCount - totalFramesWritten));
const void* pSrc = ma_offset_ptr(pPCMFrames, totalFramesWritten*bpf);
void* pDst = ma_offset_ptr(pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].lpData, pDevice->winmm.headerFramesConsumedPlayback*bpf);
MA_COPY_MEMORY(pDst, pSrc, framesToCopy*bpf);
pDevice->winmm.headerFramesConsumedPlayback += framesToCopy;
totalFramesWritten += framesToCopy;
/* If we've consumed the buffer entirely we need to write it out to the device. */
if (pDevice->winmm.headerFramesConsumedPlayback == (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwBufferLength/bpf)) {
pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser = 1; /* 1 = locked. */
pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwFlags &= ~WHDR_DONE; /* <-- Need to make sure the WHDR_DONE flag is unset. */
/* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */
ResetEvent((HANDLE)pDevice->winmm.hEventPlayback);
/* The device will be started here. */
resultMM = ((MA_PFN_waveOutWrite)pDevice->pContext->winmm.waveOutWrite)((HWAVEOUT)pDevice->winmm.hDevicePlayback, &pWAVEHDR[pDevice->winmm.iNextHeaderPlayback], sizeof(WAVEHDR));
if (resultMM != MMSYSERR_NOERROR) {
result = ma_result_from_MMRESULT(resultMM);
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] waveOutWrite() failed.", result);
break;
}
/* Make sure we move to the next header. */
pDevice->winmm.iNextHeaderPlayback = (pDevice->winmm.iNextHeaderPlayback + 1) % pDevice->playback.internalPeriods;
pDevice->winmm.headerFramesConsumedPlayback = 0;
}
/* If at this point we have consumed the entire input buffer we can return. */
MA_ASSERT(totalFramesWritten <= frameCount);
if (totalFramesWritten == frameCount) {
break;
}
/* Getting here means there's more to process. */
continue;
}
/* Getting here means there isn't enough room in the buffer and we need to wait for one to become available. */
if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventPlayback, INFINITE) != WAIT_OBJECT_0) {
result = MA_ERROR;
break;
}
/* Something happened. If the next buffer has been marked as done we need to reset a bit of state. */
if ((pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwFlags & WHDR_DONE) != 0) {
pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser = 0; /* 0 = unlocked (make it available for writing). */
pDevice->winmm.headerFramesConsumedPlayback = 0;
}
/* If the device has been stopped we need to break. */
if (ma_device_get_state(pDevice) != MA_STATE_STARTED) {
break;
}
}
if (pFramesWritten != NULL) {
*pFramesWritten = totalFramesWritten;
}
return result;
}
static ma_result ma_device_read__winmm(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
{
ma_result result = MA_SUCCESS;
MMRESULT resultMM;
ma_uint32 totalFramesRead;
WAVEHDR* pWAVEHDR;
MA_ASSERT(pDevice != NULL);
MA_ASSERT(pPCMFrames != NULL);
if (pFramesRead != NULL) {
*pFramesRead = 0;
}
pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRCapture;
/* Keep processing as much data as possible. */
totalFramesRead = 0;
while (totalFramesRead < frameCount) {
/* If the current header has some space available we need to write part of it. */
if (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser == 0) { /* 0 = unlocked. */
/* The buffer is available for reading. If we fully consume it we need to add it back to the buffer. */
ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
ma_uint32 framesRemainingInHeader = (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwBufferLength/bpf) - pDevice->winmm.headerFramesConsumedCapture;
ma_uint32 framesToCopy = ma_min(framesRemainingInHeader, (frameCount - totalFramesRead));
const void* pSrc = ma_offset_ptr(pWAVEHDR[pDevice->winmm.iNextHeaderCapture].lpData, pDevice->winmm.headerFramesConsumedCapture*bpf);
void* pDst = ma_offset_ptr(pPCMFrames, totalFramesRead*bpf);
MA_COPY_MEMORY(pDst, pSrc, framesToCopy*bpf);
pDevice->winmm.headerFramesConsumedCapture += framesToCopy;
totalFramesRead += framesToCopy;
/* If we've consumed the buffer entirely we need to add it back to the device. */
if (pDevice->winmm.headerFramesConsumedCapture == (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwBufferLength/bpf)) {
pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser = 1; /* 1 = locked. */
pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwFlags &= ~WHDR_DONE; /* <-- Need to make sure the WHDR_DONE flag is unset. */
/* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */
ResetEvent((HANDLE)pDevice->winmm.hEventCapture);
/* The device will be started here. */
resultMM = ((MA_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((LPWAVEHDR)pDevice->winmm.pWAVEHDRCapture)[pDevice->winmm.iNextHeaderCapture], sizeof(WAVEHDR));
if (resultMM != MMSYSERR_NOERROR) {
result = ma_result_from_MMRESULT(resultMM);
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] waveInAddBuffer() failed.", result);
break;
}
/* Make sure we move to the next header. */
pDevice->winmm.iNextHeaderCapture = (pDevice->winmm.iNextHeaderCapture + 1) % pDevice->capture.internalPeriods;
pDevice->winmm.headerFramesConsumedCapture = 0;
}
/* If at this point we have filled the entire input buffer we can return. */
MA_ASSERT(totalFramesRead <= frameCount);
if (totalFramesRead == frameCount) {
break;
}
/* Getting here means there's more to process. */
continue;
}
/* Getting here means there isn't enough any data left to send to the client which means we need to wait for more. */
if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventCapture, INFINITE) != WAIT_OBJECT_0) {
result = MA_ERROR;
break;
}
/* Something happened. If the next buffer has been marked as done we need to reset a bit of state. */
if ((pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwFlags & WHDR_DONE) != 0) {
pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser = 0; /* 0 = unlocked (make it available for reading). */
pDevice->winmm.headerFramesConsumedCapture = 0;
}
/* If the device has been stopped we need to break. */
if (ma_device_get_state(pDevice) != MA_STATE_STARTED) {
break;
}
}
if (pFramesRead != NULL) {
*pFramesRead = totalFramesRead;
}
return result;
}
static ma_result ma_context_uninit__winmm(ma_context* pContext)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pContext->backend == ma_backend_winmm);
ma_dlclose(pContext, pContext->winmm.hWinMM);
return MA_SUCCESS;
}
static ma_result ma_context_init__winmm(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
{
MA_ASSERT(pContext != NULL);
(void)pConfig;
pContext->winmm.hWinMM = ma_dlopen(pContext, "winmm.dll");
if (pContext->winmm.hWinMM == NULL) {
return MA_NO_BACKEND;
}
pContext->winmm.waveOutGetNumDevs = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutGetNumDevs");
pContext->winmm.waveOutGetDevCapsA = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutGetDevCapsA");
pContext->winmm.waveOutOpen = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutOpen");
pContext->winmm.waveOutClose = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutClose");
pContext->winmm.waveOutPrepareHeader = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutPrepareHeader");
pContext->winmm.waveOutUnprepareHeader = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutUnprepareHeader");
pContext->winmm.waveOutWrite = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutWrite");
pContext->winmm.waveOutReset = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutReset");
pContext->winmm.waveInGetNumDevs = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInGetNumDevs");
pContext->winmm.waveInGetDevCapsA = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInGetDevCapsA");
pContext->winmm.waveInOpen = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInOpen");
pContext->winmm.waveInClose = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInClose");
pContext->winmm.waveInPrepareHeader = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInPrepareHeader");
pContext->winmm.waveInUnprepareHeader = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInUnprepareHeader");
pContext->winmm.waveInAddBuffer = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInAddBuffer");
pContext->winmm.waveInStart = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInStart");
pContext->winmm.waveInReset = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInReset");
pCallbacks->onContextInit = ma_context_init__winmm;
pCallbacks->onContextUninit = ma_context_uninit__winmm;
pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__winmm;
pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__winmm;
pCallbacks->onDeviceInit = ma_device_init__winmm;
pCallbacks->onDeviceUninit = ma_device_uninit__winmm;
pCallbacks->onDeviceStart = ma_device_start__winmm;
pCallbacks->onDeviceStop = ma_device_stop__winmm;
pCallbacks->onDeviceRead = ma_device_read__winmm;
pCallbacks->onDeviceWrite = ma_device_write__winmm;
pCallbacks->onDeviceAudioThread = NULL; /* This is a blocking read-write API, so this can be NULL since miniaudio will manage the audio thread for us. */
return MA_SUCCESS;
}
#endif
/******************************************************************************
ALSA Backend
******************************************************************************/
#ifdef MA_HAS_ALSA
#ifdef MA_NO_RUNTIME_LINKING
/* asoundlib.h marks some functions with "inline" which isn't always supported. Need to emulate it. */
#if !defined(__cplusplus)
#if defined(__STRICT_ANSI__)
#if !defined(inline)
#define inline __inline__ __attribute__((always_inline))
#define MA_INLINE_DEFINED
#endif
#endif
#endif
#include
#if defined(MA_INLINE_DEFINED)
#undef inline
#undef MA_INLINE_DEFINED
#endif
typedef snd_pcm_uframes_t ma_snd_pcm_uframes_t;
typedef snd_pcm_sframes_t ma_snd_pcm_sframes_t;
typedef snd_pcm_stream_t ma_snd_pcm_stream_t;
typedef snd_pcm_format_t ma_snd_pcm_format_t;
typedef snd_pcm_access_t ma_snd_pcm_access_t;
typedef snd_pcm_t ma_snd_pcm_t;
typedef snd_pcm_hw_params_t ma_snd_pcm_hw_params_t;
typedef snd_pcm_sw_params_t ma_snd_pcm_sw_params_t;
typedef snd_pcm_format_mask_t ma_snd_pcm_format_mask_t;
typedef snd_pcm_info_t ma_snd_pcm_info_t;
typedef snd_pcm_channel_area_t ma_snd_pcm_channel_area_t;
typedef snd_pcm_chmap_t ma_snd_pcm_chmap_t;
typedef snd_pcm_state_t ma_snd_pcm_state_t;
/* snd_pcm_stream_t */
#define MA_SND_PCM_STREAM_PLAYBACK SND_PCM_STREAM_PLAYBACK
#define MA_SND_PCM_STREAM_CAPTURE SND_PCM_STREAM_CAPTURE
/* snd_pcm_format_t */
#define MA_SND_PCM_FORMAT_UNKNOWN SND_PCM_FORMAT_UNKNOWN
#define MA_SND_PCM_FORMAT_U8 SND_PCM_FORMAT_U8
#define MA_SND_PCM_FORMAT_S16_LE SND_PCM_FORMAT_S16_LE
#define MA_SND_PCM_FORMAT_S16_BE SND_PCM_FORMAT_S16_BE
#define MA_SND_PCM_FORMAT_S24_LE SND_PCM_FORMAT_S24_LE
#define MA_SND_PCM_FORMAT_S24_BE SND_PCM_FORMAT_S24_BE
#define MA_SND_PCM_FORMAT_S32_LE SND_PCM_FORMAT_S32_LE
#define MA_SND_PCM_FORMAT_S32_BE SND_PCM_FORMAT_S32_BE
#define MA_SND_PCM_FORMAT_FLOAT_LE SND_PCM_FORMAT_FLOAT_LE
#define MA_SND_PCM_FORMAT_FLOAT_BE SND_PCM_FORMAT_FLOAT_BE
#define MA_SND_PCM_FORMAT_FLOAT64_LE SND_PCM_FORMAT_FLOAT64_LE
#define MA_SND_PCM_FORMAT_FLOAT64_BE SND_PCM_FORMAT_FLOAT64_BE
#define MA_SND_PCM_FORMAT_MU_LAW SND_PCM_FORMAT_MU_LAW
#define MA_SND_PCM_FORMAT_A_LAW SND_PCM_FORMAT_A_LAW
#define MA_SND_PCM_FORMAT_S24_3LE SND_PCM_FORMAT_S24_3LE
#define MA_SND_PCM_FORMAT_S24_3BE SND_PCM_FORMAT_S24_3BE
/* ma_snd_pcm_access_t */
#define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED SND_PCM_ACCESS_MMAP_INTERLEAVED
#define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED SND_PCM_ACCESS_MMAP_NONINTERLEAVED
#define MA_SND_PCM_ACCESS_MMAP_COMPLEX SND_PCM_ACCESS_MMAP_COMPLEX
#define MA_SND_PCM_ACCESS_RW_INTERLEAVED SND_PCM_ACCESS_RW_INTERLEAVED
#define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED SND_PCM_ACCESS_RW_NONINTERLEAVED
/* Channel positions. */
#define MA_SND_CHMAP_UNKNOWN SND_CHMAP_UNKNOWN
#define MA_SND_CHMAP_NA SND_CHMAP_NA
#define MA_SND_CHMAP_MONO SND_CHMAP_MONO
#define MA_SND_CHMAP_FL SND_CHMAP_FL
#define MA_SND_CHMAP_FR SND_CHMAP_FR
#define MA_SND_CHMAP_RL SND_CHMAP_RL
#define MA_SND_CHMAP_RR SND_CHMAP_RR
#define MA_SND_CHMAP_FC SND_CHMAP_FC
#define MA_SND_CHMAP_LFE SND_CHMAP_LFE
#define MA_SND_CHMAP_SL SND_CHMAP_SL
#define MA_SND_CHMAP_SR SND_CHMAP_SR
#define MA_SND_CHMAP_RC SND_CHMAP_RC
#define MA_SND_CHMAP_FLC SND_CHMAP_FLC
#define MA_SND_CHMAP_FRC SND_CHMAP_FRC
#define MA_SND_CHMAP_RLC SND_CHMAP_RLC
#define MA_SND_CHMAP_RRC SND_CHMAP_RRC
#define MA_SND_CHMAP_FLW SND_CHMAP_FLW
#define MA_SND_CHMAP_FRW SND_CHMAP_FRW
#define MA_SND_CHMAP_FLH SND_CHMAP_FLH
#define MA_SND_CHMAP_FCH SND_CHMAP_FCH
#define MA_SND_CHMAP_FRH SND_CHMAP_FRH
#define MA_SND_CHMAP_TC SND_CHMAP_TC
#define MA_SND_CHMAP_TFL SND_CHMAP_TFL
#define MA_SND_CHMAP_TFR SND_CHMAP_TFR
#define MA_SND_CHMAP_TFC SND_CHMAP_TFC
#define MA_SND_CHMAP_TRL SND_CHMAP_TRL
#define MA_SND_CHMAP_TRR SND_CHMAP_TRR
#define MA_SND_CHMAP_TRC SND_CHMAP_TRC
#define MA_SND_CHMAP_TFLC SND_CHMAP_TFLC
#define MA_SND_CHMAP_TFRC SND_CHMAP_TFRC
#define MA_SND_CHMAP_TSL SND_CHMAP_TSL
#define MA_SND_CHMAP_TSR SND_CHMAP_TSR
#define MA_SND_CHMAP_LLFE SND_CHMAP_LLFE
#define MA_SND_CHMAP_RLFE SND_CHMAP_RLFE
#define MA_SND_CHMAP_BC SND_CHMAP_BC
#define MA_SND_CHMAP_BLC SND_CHMAP_BLC
#define MA_SND_CHMAP_BRC SND_CHMAP_BRC
/* Open mode flags. */
#define MA_SND_PCM_NO_AUTO_RESAMPLE SND_PCM_NO_AUTO_RESAMPLE
#define MA_SND_PCM_NO_AUTO_CHANNELS SND_PCM_NO_AUTO_CHANNELS
#define MA_SND_PCM_NO_AUTO_FORMAT SND_PCM_NO_AUTO_FORMAT
#else
#include /* For EPIPE, etc. */
typedef unsigned long ma_snd_pcm_uframes_t;
typedef long ma_snd_pcm_sframes_t;
typedef int ma_snd_pcm_stream_t;
typedef int ma_snd_pcm_format_t;
typedef int ma_snd_pcm_access_t;
typedef int ma_snd_pcm_state_t;
typedef struct ma_snd_pcm_t ma_snd_pcm_t;
typedef struct ma_snd_pcm_hw_params_t ma_snd_pcm_hw_params_t;
typedef struct ma_snd_pcm_sw_params_t ma_snd_pcm_sw_params_t;
typedef struct ma_snd_pcm_format_mask_t ma_snd_pcm_format_mask_t;
typedef struct ma_snd_pcm_info_t ma_snd_pcm_info_t;
typedef struct
{
void* addr;
unsigned int first;
unsigned int step;
} ma_snd_pcm_channel_area_t;
typedef struct
{
unsigned int channels;
unsigned int pos[1];
} ma_snd_pcm_chmap_t;
/* snd_pcm_state_t */
#define MA_SND_PCM_STATE_OPEN 0
#define MA_SND_PCM_STATE_SETUP 1
#define MA_SND_PCM_STATE_PREPARED 2
#define MA_SND_PCM_STATE_RUNNING 3
#define MA_SND_PCM_STATE_XRUN 4
#define MA_SND_PCM_STATE_DRAINING 5
#define MA_SND_PCM_STATE_PAUSED 6
#define MA_SND_PCM_STATE_SUSPENDED 7
#define MA_SND_PCM_STATE_DISCONNECTED 8
/* snd_pcm_stream_t */
#define MA_SND_PCM_STREAM_PLAYBACK 0
#define MA_SND_PCM_STREAM_CAPTURE 1
/* snd_pcm_format_t */
#define MA_SND_PCM_FORMAT_UNKNOWN -1
#define MA_SND_PCM_FORMAT_U8 1
#define MA_SND_PCM_FORMAT_S16_LE 2
#define MA_SND_PCM_FORMAT_S16_BE 3
#define MA_SND_PCM_FORMAT_S24_LE 6
#define MA_SND_PCM_FORMAT_S24_BE 7
#define MA_SND_PCM_FORMAT_S32_LE 10
#define MA_SND_PCM_FORMAT_S32_BE 11
#define MA_SND_PCM_FORMAT_FLOAT_LE 14
#define MA_SND_PCM_FORMAT_FLOAT_BE 15
#define MA_SND_PCM_FORMAT_FLOAT64_LE 16
#define MA_SND_PCM_FORMAT_FLOAT64_BE 17
#define MA_SND_PCM_FORMAT_MU_LAW 20
#define MA_SND_PCM_FORMAT_A_LAW 21
#define MA_SND_PCM_FORMAT_S24_3LE 32
#define MA_SND_PCM_FORMAT_S24_3BE 33
/* snd_pcm_access_t */
#define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED 0
#define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED 1
#define MA_SND_PCM_ACCESS_MMAP_COMPLEX 2
#define MA_SND_PCM_ACCESS_RW_INTERLEAVED 3
#define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED 4
/* Channel positions. */
#define MA_SND_CHMAP_UNKNOWN 0
#define MA_SND_CHMAP_NA 1
#define MA_SND_CHMAP_MONO 2
#define MA_SND_CHMAP_FL 3
#define MA_SND_CHMAP_FR 4
#define MA_SND_CHMAP_RL 5
#define MA_SND_CHMAP_RR 6
#define MA_SND_CHMAP_FC 7
#define MA_SND_CHMAP_LFE 8
#define MA_SND_CHMAP_SL 9
#define MA_SND_CHMAP_SR 10
#define MA_SND_CHMAP_RC 11
#define MA_SND_CHMAP_FLC 12
#define MA_SND_CHMAP_FRC 13
#define MA_SND_CHMAP_RLC 14
#define MA_SND_CHMAP_RRC 15
#define MA_SND_CHMAP_FLW 16
#define MA_SND_CHMAP_FRW 17
#define MA_SND_CHMAP_FLH 18
#define MA_SND_CHMAP_FCH 19
#define MA_SND_CHMAP_FRH 20
#define MA_SND_CHMAP_TC 21
#define MA_SND_CHMAP_TFL 22
#define MA_SND_CHMAP_TFR 23
#define MA_SND_CHMAP_TFC 24
#define MA_SND_CHMAP_TRL 25
#define MA_SND_CHMAP_TRR 26
#define MA_SND_CHMAP_TRC 27
#define MA_SND_CHMAP_TFLC 28
#define MA_SND_CHMAP_TFRC 29
#define MA_SND_CHMAP_TSL 30
#define MA_SND_CHMAP_TSR 31
#define MA_SND_CHMAP_LLFE 32
#define MA_SND_CHMAP_RLFE 33
#define MA_SND_CHMAP_BC 34
#define MA_SND_CHMAP_BLC 35
#define MA_SND_CHMAP_BRC 36
/* Open mode flags. */
#define MA_SND_PCM_NO_AUTO_RESAMPLE 0x00010000
#define MA_SND_PCM_NO_AUTO_CHANNELS 0x00020000
#define MA_SND_PCM_NO_AUTO_FORMAT 0x00040000
#endif
typedef int (* ma_snd_pcm_open_proc) (ma_snd_pcm_t **pcm, const char *name, ma_snd_pcm_stream_t stream, int mode);
typedef int (* ma_snd_pcm_close_proc) (ma_snd_pcm_t *pcm);
typedef size_t (* ma_snd_pcm_hw_params_sizeof_proc) (void);
typedef int (* ma_snd_pcm_hw_params_any_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params);
typedef int (* ma_snd_pcm_hw_params_set_format_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t val);
typedef int (* ma_snd_pcm_hw_params_set_format_first_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t *format);
typedef void (* ma_snd_pcm_hw_params_get_format_mask_proc) (ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_mask_t *mask);
typedef int (* ma_snd_pcm_hw_params_set_channels_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val);
typedef int (* ma_snd_pcm_hw_params_set_rate_resample_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int val);
typedef int (* ma_snd_pcm_hw_params_set_rate_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir);
typedef int (* ma_snd_pcm_hw_params_set_buffer_size_near_proc)(ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_uframes_t *val);
typedef int (* ma_snd_pcm_hw_params_set_periods_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir);
typedef int (* ma_snd_pcm_hw_params_set_access_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_access_t _access);
typedef int (* ma_snd_pcm_hw_params_get_format_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t *format);
typedef int (* ma_snd_pcm_hw_params_get_channels_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val);
typedef int (* ma_snd_pcm_hw_params_get_channels_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val);
typedef int (* ma_snd_pcm_hw_params_get_channels_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val);
typedef int (* ma_snd_pcm_hw_params_get_rate_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir);
typedef int (* ma_snd_pcm_hw_params_get_rate_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir);
typedef int (* ma_snd_pcm_hw_params_get_rate_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir);
typedef int (* ma_snd_pcm_hw_params_get_buffer_size_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_uframes_t *val);
typedef int (* ma_snd_pcm_hw_params_get_periods_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir);
typedef int (* ma_snd_pcm_hw_params_get_access_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_access_t *_access);
typedef int (* ma_snd_pcm_hw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params);
typedef size_t (* ma_snd_pcm_sw_params_sizeof_proc) (void);
typedef int (* ma_snd_pcm_sw_params_current_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params);
typedef int (* ma_snd_pcm_sw_params_get_boundary_proc) (const ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t* val);
typedef int (* ma_snd_pcm_sw_params_set_avail_min_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val);
typedef int (* ma_snd_pcm_sw_params_set_start_threshold_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val);
typedef int (* ma_snd_pcm_sw_params_set_stop_threshold_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val);
typedef int (* ma_snd_pcm_sw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params);
typedef size_t (* ma_snd_pcm_format_mask_sizeof_proc) (void);
typedef int (* ma_snd_pcm_format_mask_test_proc) (const ma_snd_pcm_format_mask_t *mask, ma_snd_pcm_format_t val);
typedef ma_snd_pcm_chmap_t * (* ma_snd_pcm_get_chmap_proc) (ma_snd_pcm_t *pcm);
typedef ma_snd_pcm_state_t (* ma_snd_pcm_state_proc) (ma_snd_pcm_t *pcm);
typedef int (* ma_snd_pcm_prepare_proc) (ma_snd_pcm_t *pcm);
typedef int (* ma_snd_pcm_start_proc) (ma_snd_pcm_t *pcm);
typedef int (* ma_snd_pcm_drop_proc) (ma_snd_pcm_t *pcm);
typedef int (* ma_snd_pcm_drain_proc) (ma_snd_pcm_t *pcm);
typedef int (* ma_snd_device_name_hint_proc) (int card, const char *iface, void ***hints);
typedef char * (* ma_snd_device_name_get_hint_proc) (const void *hint, const char *id);
typedef int (* ma_snd_card_get_index_proc) (const char *name);
typedef int (* ma_snd_device_name_free_hint_proc) (void **hints);
typedef int (* ma_snd_pcm_mmap_begin_proc) (ma_snd_pcm_t *pcm, const ma_snd_pcm_channel_area_t **areas, ma_snd_pcm_uframes_t *offset, ma_snd_pcm_uframes_t *frames);
typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_mmap_commit_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_uframes_t offset, ma_snd_pcm_uframes_t frames);
typedef int (* ma_snd_pcm_recover_proc) (ma_snd_pcm_t *pcm, int err, int silent);
typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_readi_proc) (ma_snd_pcm_t *pcm, void *buffer, ma_snd_pcm_uframes_t size);
typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_writei_proc) (ma_snd_pcm_t *pcm, const void *buffer, ma_snd_pcm_uframes_t size);
typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_avail_proc) (ma_snd_pcm_t *pcm);
typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_avail_update_proc) (ma_snd_pcm_t *pcm);
typedef int (* ma_snd_pcm_wait_proc) (ma_snd_pcm_t *pcm, int timeout);
typedef int (* ma_snd_pcm_info_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_info_t* info);
typedef size_t (* ma_snd_pcm_info_sizeof_proc) (void);
typedef const char* (* ma_snd_pcm_info_get_name_proc) (const ma_snd_pcm_info_t* info);
typedef int (* ma_snd_config_update_free_global_proc) (void);
/* This array specifies each of the common devices that can be used for both playback and capture. */
static const char* g_maCommonDeviceNamesALSA[] = {
"default",
"null",
"pulse",
"jack"
};
/* This array allows us to blacklist specific playback devices. */
static const char* g_maBlacklistedPlaybackDeviceNamesALSA[] = {
""
};
/* This array allows us to blacklist specific capture devices. */
static const char* g_maBlacklistedCaptureDeviceNamesALSA[] = {
""
};
/*
This array allows miniaudio to control device-specific default buffer sizes. This uses a scaling factor. Order is important. If
any part of the string is present in the device's name, the associated scale will be used.
*/
static struct
{
const char* name;
float scale;
} g_maDefaultBufferSizeScalesALSA[] = {
{"bcm2835 IEC958/HDMI", 2.0f},
{"bcm2835 ALSA", 2.0f}
};
static float ma_find_default_buffer_size_scale__alsa(const char* deviceName)
{
size_t i;
if (deviceName == NULL) {
return 1;
}
for (i = 0; i < ma_countof(g_maDefaultBufferSizeScalesALSA); ++i) {
if (strstr(g_maDefaultBufferSizeScalesALSA[i].name, deviceName) != NULL) {
return g_maDefaultBufferSizeScalesALSA[i].scale;
}
}
return 1;
}
static ma_snd_pcm_format_t ma_convert_ma_format_to_alsa_format(ma_format format)
{
ma_snd_pcm_format_t ALSAFormats[] = {
MA_SND_PCM_FORMAT_UNKNOWN, /* ma_format_unknown */
MA_SND_PCM_FORMAT_U8, /* ma_format_u8 */
MA_SND_PCM_FORMAT_S16_LE, /* ma_format_s16 */
MA_SND_PCM_FORMAT_S24_3LE, /* ma_format_s24 */
MA_SND_PCM_FORMAT_S32_LE, /* ma_format_s32 */
MA_SND_PCM_FORMAT_FLOAT_LE /* ma_format_f32 */
};
if (ma_is_big_endian()) {
ALSAFormats[0] = MA_SND_PCM_FORMAT_UNKNOWN;
ALSAFormats[1] = MA_SND_PCM_FORMAT_U8;
ALSAFormats[2] = MA_SND_PCM_FORMAT_S16_BE;
ALSAFormats[3] = MA_SND_PCM_FORMAT_S24_3BE;
ALSAFormats[4] = MA_SND_PCM_FORMAT_S32_BE;
ALSAFormats[5] = MA_SND_PCM_FORMAT_FLOAT_BE;
}
return ALSAFormats[format];
}
static ma_format ma_format_from_alsa(ma_snd_pcm_format_t formatALSA)
{
if (ma_is_little_endian()) {
switch (formatALSA) {
case MA_SND_PCM_FORMAT_S16_LE: return ma_format_s16;
case MA_SND_PCM_FORMAT_S24_3LE: return ma_format_s24;
case MA_SND_PCM_FORMAT_S32_LE: return ma_format_s32;
case MA_SND_PCM_FORMAT_FLOAT_LE: return ma_format_f32;
default: break;
}
} else {
switch (formatALSA) {
case MA_SND_PCM_FORMAT_S16_BE: return ma_format_s16;
case MA_SND_PCM_FORMAT_S24_3BE: return ma_format_s24;
case MA_SND_PCM_FORMAT_S32_BE: return ma_format_s32;
case MA_SND_PCM_FORMAT_FLOAT_BE: return ma_format_f32;
default: break;
}
}
/* Endian agnostic. */
switch (formatALSA) {
case MA_SND_PCM_FORMAT_U8: return ma_format_u8;
default: return ma_format_unknown;
}
}
static ma_channel ma_convert_alsa_channel_position_to_ma_channel(unsigned int alsaChannelPos)
{
switch (alsaChannelPos)
{
case MA_SND_CHMAP_MONO: return MA_CHANNEL_MONO;
case MA_SND_CHMAP_FL: return MA_CHANNEL_FRONT_LEFT;
case MA_SND_CHMAP_FR: return MA_CHANNEL_FRONT_RIGHT;
case MA_SND_CHMAP_RL: return MA_CHANNEL_BACK_LEFT;
case MA_SND_CHMAP_RR: return MA_CHANNEL_BACK_RIGHT;
case MA_SND_CHMAP_FC: return MA_CHANNEL_FRONT_CENTER;
case MA_SND_CHMAP_LFE: return MA_CHANNEL_LFE;
case MA_SND_CHMAP_SL: return MA_CHANNEL_SIDE_LEFT;
case MA_SND_CHMAP_SR: return MA_CHANNEL_SIDE_RIGHT;
case MA_SND_CHMAP_RC: return MA_CHANNEL_BACK_CENTER;
case MA_SND_CHMAP_FLC: return MA_CHANNEL_FRONT_LEFT_CENTER;
case MA_SND_CHMAP_FRC: return MA_CHANNEL_FRONT_RIGHT_CENTER;
case MA_SND_CHMAP_RLC: return 0;
case MA_SND_CHMAP_RRC: return 0;
case MA_SND_CHMAP_FLW: return 0;
case MA_SND_CHMAP_FRW: return 0;
case MA_SND_CHMAP_FLH: return 0;
case MA_SND_CHMAP_FCH: return 0;
case MA_SND_CHMAP_FRH: return 0;
case MA_SND_CHMAP_TC: return MA_CHANNEL_TOP_CENTER;
case MA_SND_CHMAP_TFL: return MA_CHANNEL_TOP_FRONT_LEFT;
case MA_SND_CHMAP_TFR: return MA_CHANNEL_TOP_FRONT_RIGHT;
case MA_SND_CHMAP_TFC: return MA_CHANNEL_TOP_FRONT_CENTER;
case MA_SND_CHMAP_TRL: return MA_CHANNEL_TOP_BACK_LEFT;
case MA_SND_CHMAP_TRR: return MA_CHANNEL_TOP_BACK_RIGHT;
case MA_SND_CHMAP_TRC: return MA_CHANNEL_TOP_BACK_CENTER;
default: break;
}
return 0;
}
static ma_bool32 ma_is_common_device_name__alsa(const char* name)
{
size_t iName;
for (iName = 0; iName < ma_countof(g_maCommonDeviceNamesALSA); ++iName) {
if (ma_strcmp(name, g_maCommonDeviceNamesALSA[iName]) == 0) {
return MA_TRUE;
}
}
return MA_FALSE;
}
static ma_bool32 ma_is_playback_device_blacklisted__alsa(const char* name)
{
size_t iName;
for (iName = 0; iName < ma_countof(g_maBlacklistedPlaybackDeviceNamesALSA); ++iName) {
if (ma_strcmp(name, g_maBlacklistedPlaybackDeviceNamesALSA[iName]) == 0) {
return MA_TRUE;
}
}
return MA_FALSE;
}
static ma_bool32 ma_is_capture_device_blacklisted__alsa(const char* name)
{
size_t iName;
for (iName = 0; iName < ma_countof(g_maBlacklistedCaptureDeviceNamesALSA); ++iName) {
if (ma_strcmp(name, g_maBlacklistedCaptureDeviceNamesALSA[iName]) == 0) {
return MA_TRUE;
}
}
return MA_FALSE;
}
static ma_bool32 ma_is_device_blacklisted__alsa(ma_device_type deviceType, const char* name)
{
if (deviceType == ma_device_type_playback) {
return ma_is_playback_device_blacklisted__alsa(name);
} else {
return ma_is_capture_device_blacklisted__alsa(name);
}
}
static const char* ma_find_char(const char* str, char c, int* index)
{
int i = 0;
for (;;) {
if (str[i] == '\0') {
if (index) *index = -1;
return NULL;
}
if (str[i] == c) {
if (index) *index = i;
return str + i;
}
i += 1;
}
/* Should never get here, but treat it as though the character was not found to make me feel better inside. */
if (index) *index = -1;
return NULL;
}
static ma_bool32 ma_is_device_name_in_hw_format__alsa(const char* hwid)
{
/* This function is just checking whether or not hwid is in "hw:%d,%d" format. */
int commaPos;
const char* dev;
int i;
if (hwid == NULL) {
return MA_FALSE;
}
if (hwid[0] != 'h' || hwid[1] != 'w' || hwid[2] != ':') {
return MA_FALSE;
}
hwid += 3;
dev = ma_find_char(hwid, ',', &commaPos);
if (dev == NULL) {
return MA_FALSE;
} else {
dev += 1; /* Skip past the ",". */
}
/* Check if the part between the ":" and the "," contains only numbers. If not, return false. */
for (i = 0; i < commaPos; ++i) {
if (hwid[i] < '0' || hwid[i] > '9') {
return MA_FALSE;
}
}
/* Check if everything after the "," is numeric. If not, return false. */
i = 0;
while (dev[i] != '\0') {
if (dev[i] < '0' || dev[i] > '9') {
return MA_FALSE;
}
i += 1;
}
return MA_TRUE;
}
static int ma_convert_device_name_to_hw_format__alsa(ma_context* pContext, char* dst, size_t dstSize, const char* src) /* Returns 0 on success, non-0 on error. */
{
/* src should look something like this: "hw:CARD=I82801AAICH,DEV=0" */
int colonPos;
int commaPos;
char card[256];
const char* dev;
int cardIndex;
if (dst == NULL) {
return -1;
}
if (dstSize < 7) {
return -1; /* Absolute minimum size of the output buffer is 7 bytes. */
}
*dst = '\0'; /* Safety. */
if (src == NULL) {
return -1;
}
/* If the input name is already in "hw:%d,%d" format, just return that verbatim. */
if (ma_is_device_name_in_hw_format__alsa(src)) {
return ma_strcpy_s(dst, dstSize, src);
}
src = ma_find_char(src, ':', &colonPos);
if (src == NULL) {
return -1; /* Couldn't find a colon */
}
dev = ma_find_char(src, ',', &commaPos);
if (dev == NULL) {
dev = "0";
ma_strncpy_s(card, sizeof(card), src+6, (size_t)-1); /* +6 = ":CARD=" */
} else {
dev = dev + 5; /* +5 = ",DEV=" */
ma_strncpy_s(card, sizeof(card), src+6, commaPos-6); /* +6 = ":CARD=" */
}
cardIndex = ((ma_snd_card_get_index_proc)pContext->alsa.snd_card_get_index)(card);
if (cardIndex < 0) {
return -2; /* Failed to retrieve the card index. */
}
/*printf("TESTING: CARD=%s,DEV=%s\n", card, dev); */
/* Construction. */
dst[0] = 'h'; dst[1] = 'w'; dst[2] = ':';
if (ma_itoa_s(cardIndex, dst+3, dstSize-3, 10) != 0) {
return -3;
}
if (ma_strcat_s(dst, dstSize, ",") != 0) {
return -3;
}
if (ma_strcat_s(dst, dstSize, dev) != 0) {
return -3;
}
return 0;
}
static ma_bool32 ma_does_id_exist_in_list__alsa(ma_device_id* pUniqueIDs, ma_uint32 count, const char* pHWID)
{
ma_uint32 i;
MA_ASSERT(pHWID != NULL);
for (i = 0; i < count; ++i) {
if (ma_strcmp(pUniqueIDs[i].alsa, pHWID) == 0) {
return MA_TRUE;
}
}
return MA_FALSE;
}
static ma_result ma_context_open_pcm__alsa(ma_context* pContext, ma_share_mode shareMode, ma_device_type deviceType, const ma_device_id* pDeviceID, int openMode, ma_snd_pcm_t** ppPCM)
{
ma_snd_pcm_t* pPCM;
ma_snd_pcm_stream_t stream;
MA_ASSERT(pContext != NULL);
MA_ASSERT(ppPCM != NULL);
*ppPCM = NULL;
pPCM = NULL;
stream = (deviceType == ma_device_type_playback) ? MA_SND_PCM_STREAM_PLAYBACK : MA_SND_PCM_STREAM_CAPTURE;
if (pDeviceID == NULL) {
ma_bool32 isDeviceOpen;
size_t i;
/*
We're opening the default device. I don't know if trying anything other than "default" is necessary, but it makes
me feel better to try as hard as we can get to get _something_ working.
*/
const char* defaultDeviceNames[] = {
"default",
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
};
if (shareMode == ma_share_mode_exclusive) {
defaultDeviceNames[1] = "hw";
defaultDeviceNames[2] = "hw:0";
defaultDeviceNames[3] = "hw:0,0";
} else {
if (deviceType == ma_device_type_playback) {
defaultDeviceNames[1] = "dmix";
defaultDeviceNames[2] = "dmix:0";
defaultDeviceNames[3] = "dmix:0,0";
} else {
defaultDeviceNames[1] = "dsnoop";
defaultDeviceNames[2] = "dsnoop:0";
defaultDeviceNames[3] = "dsnoop:0,0";
}
defaultDeviceNames[4] = "hw";
defaultDeviceNames[5] = "hw:0";
defaultDeviceNames[6] = "hw:0,0";
}
isDeviceOpen = MA_FALSE;
for (i = 0; i < ma_countof(defaultDeviceNames); ++i) {
if (defaultDeviceNames[i] != NULL && defaultDeviceNames[i][0] != '\0') {
if (((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, defaultDeviceNames[i], stream, openMode) == 0) {
isDeviceOpen = MA_TRUE;
break;
}
}
}
if (!isDeviceOpen) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed when trying to open an appropriate default device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
}
} else {
/*
We're trying to open a specific device. There's a few things to consider here:
miniaudio recongnizes a special format of device id that excludes the "hw", "dmix", etc. prefix. It looks like this: ":0,0", ":0,1", etc. When
an ID of this format is specified, it indicates to miniaudio that it can try different combinations of plugins ("hw", "dmix", etc.) until it
finds an appropriate one that works. This comes in very handy when trying to open a device in shared mode ("dmix"), vs exclusive mode ("hw").
*/
/* May end up needing to make small adjustments to the ID, so make a copy. */
ma_device_id deviceID = *pDeviceID;
int resultALSA = -ENODEV;
if (deviceID.alsa[0] != ':') {
/* The ID is not in ":0,0" format. Use the ID exactly as-is. */
resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, deviceID.alsa, stream, openMode);
} else {
char hwid[256];
/* The ID is in ":0,0" format. Try different plugins depending on the shared mode. */
if (deviceID.alsa[1] == '\0') {
deviceID.alsa[0] = '\0'; /* An ID of ":" should be converted to "". */
}
if (shareMode == ma_share_mode_shared) {
if (deviceType == ma_device_type_playback) {
ma_strcpy_s(hwid, sizeof(hwid), "dmix");
} else {
ma_strcpy_s(hwid, sizeof(hwid), "dsnoop");
}
if (ma_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) {
resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode);
}
}
/* If at this point we still don't have an open device it means we're either preferencing exclusive mode or opening with "dmix"/"dsnoop" failed. */
if (resultALSA != 0) {
ma_strcpy_s(hwid, sizeof(hwid), "hw");
if (ma_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) {
resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode);
}
}
}
if (resultALSA < 0) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed.", ma_result_from_errno(-resultALSA));
}
}
*ppPCM = pPCM;
return MA_SUCCESS;
}
static ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
{
int resultALSA;
ma_bool32 cbResult = MA_TRUE;
char** ppDeviceHints;
ma_device_id* pUniqueIDs = NULL;
ma_uint32 uniqueIDCount = 0;
char** ppNextDeviceHint;
MA_ASSERT(pContext != NULL);
MA_ASSERT(callback != NULL);
ma_mutex_lock(&pContext->alsa.internalDeviceEnumLock);
resultALSA = ((ma_snd_device_name_hint_proc)pContext->alsa.snd_device_name_hint)(-1, "pcm", (void***)&ppDeviceHints);
if (resultALSA < 0) {
ma_mutex_unlock(&pContext->alsa.internalDeviceEnumLock);
return ma_result_from_errno(-resultALSA);
}
ppNextDeviceHint = ppDeviceHints;
while (*ppNextDeviceHint != NULL) {
char* NAME = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "NAME");
char* DESC = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "DESC");
char* IOID = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "IOID");
ma_device_type deviceType = ma_device_type_playback;
ma_bool32 stopEnumeration = MA_FALSE;
char hwid[sizeof(pUniqueIDs->alsa)];
ma_device_info deviceInfo;
if ((IOID == NULL || ma_strcmp(IOID, "Output") == 0)) {
deviceType = ma_device_type_playback;
}
if ((IOID != NULL && ma_strcmp(IOID, "Input" ) == 0)) {
deviceType = ma_device_type_capture;
}
if (NAME != NULL) {
if (pContext->alsa.useVerboseDeviceEnumeration) {
/* Verbose mode. Use the name exactly as-is. */
ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1);
} else {
/* Simplified mode. Use ":%d,%d" format. */
if (ma_convert_device_name_to_hw_format__alsa(pContext, hwid, sizeof(hwid), NAME) == 0) {
/*
At this point, hwid looks like "hw:0,0". In simplified enumeration mode, we actually want to strip off the
plugin name so it looks like ":0,0". The reason for this is that this special format is detected at device
initialization time and is used as an indicator to try and use the most appropriate plugin depending on the
device type and sharing mode.
*/
char* dst = hwid;
char* src = hwid+2;
while ((*dst++ = *src++));
} else {
/* Conversion to "hw:%d,%d" failed. Just use the name as-is. */
ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1);
}
if (ma_does_id_exist_in_list__alsa(pUniqueIDs, uniqueIDCount, hwid)) {
goto next_device; /* The device has already been enumerated. Move on to the next one. */
} else {
/* The device has not yet been enumerated. Make sure it's added to our list so that it's not enumerated again. */
size_t oldCapacity = sizeof(*pUniqueIDs) * uniqueIDCount;
size_t newCapacity = sizeof(*pUniqueIDs) * (uniqueIDCount + 1);
ma_device_id* pNewUniqueIDs = (ma_device_id*)ma__realloc_from_callbacks(pUniqueIDs, newCapacity, oldCapacity, &pContext->allocationCallbacks);
if (pNewUniqueIDs == NULL) {
goto next_device; /* Failed to allocate memory. */
}
pUniqueIDs = pNewUniqueIDs;
MA_COPY_MEMORY(pUniqueIDs[uniqueIDCount].alsa, hwid, sizeof(hwid));
uniqueIDCount += 1;
}
}
} else {
MA_ZERO_MEMORY(hwid, sizeof(hwid));
}
MA_ZERO_OBJECT(&deviceInfo);
ma_strncpy_s(deviceInfo.id.alsa, sizeof(deviceInfo.id.alsa), hwid, (size_t)-1);
/*
There's no good way to determine whether or not a device is the default on Linux. We're just going to do something simple and
just use the name of "default" as the indicator.
*/
if (ma_strcmp(deviceInfo.id.alsa, "default") == 0) {
deviceInfo.isDefault = MA_TRUE;
}
/*
DESC is the friendly name. We treat this slightly differently depending on whether or not we are using verbose
device enumeration. In verbose mode we want to take the entire description so that the end-user can distinguish
between the subdevices of each card/dev pair. In simplified mode, however, we only want the first part of the
description.
The value in DESC seems to be split into two lines, with the first line being the name of the device and the
second line being a description of the device. I don't like having the description be across two lines because
it makes formatting ugly and annoying. I'm therefore deciding to put it all on a single line with the second line
being put into parentheses. In simplified mode I'm just stripping the second line entirely.
*/
if (DESC != NULL) {
int lfPos;
const char* line2 = ma_find_char(DESC, '\n', &lfPos);
if (line2 != NULL) {
line2 += 1; /* Skip past the new-line character. */
if (pContext->alsa.useVerboseDeviceEnumeration) {
/* Verbose mode. Put the second line in brackets. */
ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos);
ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), " (");
ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), line2);
ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), ")");
} else {
/* Simplified mode. Strip the second line entirely. */
ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos);
}
} else {
/* There's no second line. Just copy the whole description. */
ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, (size_t)-1);
}
}
if (!ma_is_device_blacklisted__alsa(deviceType, NAME)) {
cbResult = callback(pContext, deviceType, &deviceInfo, pUserData);
}
/*
Some devices are both playback and capture, but they are only enumerated by ALSA once. We need to fire the callback
again for the other device type in this case. We do this for known devices.
*/
if (cbResult) {
if (ma_is_common_device_name__alsa(NAME)) {
if (deviceType == ma_device_type_playback) {
if (!ma_is_capture_device_blacklisted__alsa(NAME)) {
cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
}
} else {
if (!ma_is_playback_device_blacklisted__alsa(NAME)) {
cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
}
}
}
}
if (cbResult == MA_FALSE) {
stopEnumeration = MA_TRUE;
}
next_device:
free(NAME);
free(DESC);
free(IOID);
ppNextDeviceHint += 1;
/* We need to stop enumeration if the callback returned false. */
if (stopEnumeration) {
break;
}
}
ma__free_from_callbacks(pUniqueIDs, &pContext->allocationCallbacks);
((ma_snd_device_name_free_hint_proc)pContext->alsa.snd_device_name_free_hint)((void**)ppDeviceHints);
ma_mutex_unlock(&pContext->alsa.internalDeviceEnumLock);
return MA_SUCCESS;
}
typedef struct
{
ma_device_type deviceType;
const ma_device_id* pDeviceID;
ma_share_mode shareMode;
ma_device_info* pDeviceInfo;
ma_bool32 foundDevice;
} ma_context_get_device_info_enum_callback_data__alsa;
static ma_bool32 ma_context_get_device_info_enum_callback__alsa(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pDeviceInfo, void* pUserData)
{
ma_context_get_device_info_enum_callback_data__alsa* pData = (ma_context_get_device_info_enum_callback_data__alsa*)pUserData;
MA_ASSERT(pData != NULL);
(void)pContext;
if (pData->pDeviceID == NULL && ma_strcmp(pDeviceInfo->id.alsa, "default") == 0) {
ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1);
pData->foundDevice = MA_TRUE;
} else {
if (pData->deviceType == deviceType && (pData->pDeviceID != NULL && ma_strcmp(pData->pDeviceID->alsa, pDeviceInfo->id.alsa) == 0)) {
ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1);
pData->foundDevice = MA_TRUE;
}
}
/* Keep enumerating until we have found the device. */
return !pData->foundDevice;
}
static ma_result ma_context_get_device_info__alsa(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo)
{
ma_context_get_device_info_enum_callback_data__alsa data;
ma_result result;
int resultALSA;
ma_snd_pcm_t* pPCM;
ma_snd_pcm_hw_params_t* pHWParams;
ma_snd_pcm_format_mask_t* pFormatMask;
int sampleRateDir = 0;
MA_ASSERT(pContext != NULL);
/* We just enumerate to find basic information about the device. */
data.deviceType = deviceType;
data.pDeviceID = pDeviceID;
data.shareMode = shareMode;
data.pDeviceInfo = pDeviceInfo;
data.foundDevice = MA_FALSE;
result = ma_context_enumerate_devices__alsa(pContext, ma_context_get_device_info_enum_callback__alsa, &data);
if (result != MA_SUCCESS) {
return result;
}
if (!data.foundDevice) {
return MA_NO_DEVICE;
}
if (ma_strcmp(pDeviceInfo->id.alsa, "default") == 0) {
pDeviceInfo->isDefault = MA_TRUE;
}
/* For detailed info we need to open the device. */
result = ma_context_open_pcm__alsa(pContext, shareMode, deviceType, pDeviceID, 0, &pPCM);
if (result != MA_SUCCESS) {
return result;
}
/* We need to initialize a HW parameters object in order to know what formats are supported. */
pHWParams = (ma_snd_pcm_hw_params_t*)ma__calloc_from_callbacks(((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)(), &pContext->allocationCallbacks);
if (pHWParams == NULL) {
((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
return MA_OUT_OF_MEMORY;
}
resultALSA = ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
if (resultALSA < 0) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.", ma_result_from_errno(-resultALSA));
}
((ma_snd_pcm_hw_params_get_channels_min_proc)pContext->alsa.snd_pcm_hw_params_get_channels_min)(pHWParams, &pDeviceInfo->minChannels);
((ma_snd_pcm_hw_params_get_channels_max_proc)pContext->alsa.snd_pcm_hw_params_get_channels_max)(pHWParams, &pDeviceInfo->maxChannels);
((ma_snd_pcm_hw_params_get_rate_min_proc)pContext->alsa.snd_pcm_hw_params_get_rate_min)(pHWParams, &pDeviceInfo->minSampleRate, &sampleRateDir);
((ma_snd_pcm_hw_params_get_rate_max_proc)pContext->alsa.snd_pcm_hw_params_get_rate_max)(pHWParams, &pDeviceInfo->maxSampleRate, &sampleRateDir);
/* Formats. */
pFormatMask = (ma_snd_pcm_format_mask_t*)ma__calloc_from_callbacks(((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)(), &pContext->allocationCallbacks);
if (pFormatMask == NULL) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
return MA_OUT_OF_MEMORY;
}
((ma_snd_pcm_hw_params_get_format_mask_proc)pContext->alsa.snd_pcm_hw_params_get_format_mask)(pHWParams, pFormatMask);
pDeviceInfo->formatCount = 0;
if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MA_SND_PCM_FORMAT_U8)) {
pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_u8;
}
if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MA_SND_PCM_FORMAT_S16_LE)) {
pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_s16;
}
if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MA_SND_PCM_FORMAT_S24_3LE)) {
pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_s24;
}
if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MA_SND_PCM_FORMAT_S32_LE)) {
pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_s32;
}
if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MA_SND_PCM_FORMAT_FLOAT_LE)) {
pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_f32;
}
ma__free_from_callbacks(pFormatMask, &pContext->allocationCallbacks);
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
return MA_SUCCESS;
}
#if 0
/*
Waits for a number of frames to become available for either capture or playback. The return
value is the number of frames available.
This will return early if the main loop is broken with ma_device__break_main_loop().
*/
static ma_uint32 ma_device__wait_for_frames__alsa(ma_device* pDevice, ma_bool32* pRequiresRestart)
{
MA_ASSERT(pDevice != NULL);
if (pRequiresRestart) *pRequiresRestart = MA_FALSE;
/* I want it so that this function returns the period size in frames. We just wait until that number of frames are available and then return. */
ma_uint32 periodSizeInFrames = pDevice->bufferSizeInFrames / pDevice->periods;
while (!pDevice->alsa.breakFromMainLoop) {
ma_snd_pcm_sframes_t framesAvailable = ((ma_snd_pcm_avail_update_proc)pDevice->pContext->alsa.snd_pcm_avail_update)((ma_snd_pcm_t*)pDevice->alsa.pPCM);
if (framesAvailable < 0) {
if (framesAvailable == -EPIPE) {
if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, framesAvailable, MA_TRUE) < 0) {
return 0;
}
/* A device recovery means a restart for mmap mode. */
if (pRequiresRestart) {
*pRequiresRestart = MA_TRUE;
}
/* Try again, but if it fails this time just return an error. */
framesAvailable = ((ma_snd_pcm_avail_update_proc)pDevice->pContext->alsa.snd_pcm_avail_update)((ma_snd_pcm_t*)pDevice->alsa.pPCM);
if (framesAvailable < 0) {
return 0;
}
}
}
if (framesAvailable >= periodSizeInFrames) {
return periodSizeInFrames;
}
if (framesAvailable < periodSizeInFrames) {
/* Less than a whole period is available so keep waiting. */
int waitResult = ((ma_snd_pcm_wait_proc)pDevice->pContext->alsa.snd_pcm_wait)((ma_snd_pcm_t*)pDevice->alsa.pPCM, -1);
if (waitResult < 0) {
if (waitResult == -EPIPE) {
if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, waitResult, MA_TRUE) < 0) {
return 0;
}
/* A device recovery means a restart for mmap mode. */
if (pRequiresRestart) {
*pRequiresRestart = MA_TRUE;
}
}
}
}
}
/* We'll get here if the loop was terminated. Just return whatever's available. */
ma_snd_pcm_sframes_t framesAvailable = ((ma_snd_pcm_avail_update_proc)pDevice->pContext->alsa.snd_pcm_avail_update)((ma_snd_pcm_t*)pDevice->alsa.pPCM);
if (framesAvailable < 0) {
return 0;
}
return framesAvailable;
}
static ma_bool32 ma_device_read_from_client_and_write__alsa(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
if (!ma_device_is_started(pDevice) && ma_device_get_state(pDevice) != MA_STATE_STARTING) {
return MA_FALSE;
}
if (pDevice->alsa.breakFromMainLoop) {
return MA_FALSE;
}
if (pDevice->alsa.isUsingMMap) {
/* mmap. */
ma_bool32 requiresRestart;
ma_uint32 framesAvailable = ma_device__wait_for_frames__alsa(pDevice, &requiresRestart);
if (framesAvailable == 0) {
return MA_FALSE;
}
/* Don't bother asking the client for more audio data if we're just stopping the device anyway. */
if (pDevice->alsa.breakFromMainLoop) {
return MA_FALSE;
}
const ma_snd_pcm_channel_area_t* pAreas;
ma_snd_pcm_uframes_t mappedOffset;
ma_snd_pcm_uframes_t mappedFrames = framesAvailable;
while (framesAvailable > 0) {
int result = ((ma_snd_pcm_mmap_begin_proc)pDevice->pContext->alsa.snd_pcm_mmap_begin)((ma_snd_pcm_t*)pDevice->alsa.pPCM, &pAreas, &mappedOffset, &mappedFrames);
if (result < 0) {
return MA_FALSE;
}
if (mappedFrames > 0) {
void* pBuffer = (ma_uint8*)pAreas[0].addr + ((pAreas[0].first + (mappedOffset * pAreas[0].step)) / 8);
ma_device__read_frames_from_client(pDevice, mappedFrames, pBuffer);
}
result = ((ma_snd_pcm_mmap_commit_proc)pDevice->pContext->alsa.snd_pcm_mmap_commit)((ma_snd_pcm_t*)pDevice->alsa.pPCM, mappedOffset, mappedFrames);
if (result < 0 || (ma_snd_pcm_uframes_t)result != mappedFrames) {
((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, result, MA_TRUE);
return MA_FALSE;
}
if (requiresRestart) {
if (((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCM) < 0) {
return MA_FALSE;
}
}
if (framesAvailable >= mappedFrames) {
framesAvailable -= mappedFrames;
} else {
framesAvailable = 0;
}
}
} else {
/* readi/writei. */
while (!pDevice->alsa.breakFromMainLoop) {
ma_uint32 framesAvailable = ma_device__wait_for_frames__alsa(pDevice, NULL);
if (framesAvailable == 0) {
continue;
}
/* Don't bother asking the client for more audio data if we're just stopping the device anyway. */
if (pDevice->alsa.breakFromMainLoop) {
return MA_FALSE;
}
ma_device__read_frames_from_client(pDevice, framesAvailable, pDevice->alsa.pIntermediaryBuffer);
ma_snd_pcm_sframes_t framesWritten = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable);
if (framesWritten < 0) {
if (framesWritten == -EAGAIN) {
continue; /* Just keep trying... */
} else if (framesWritten == -EPIPE) {
/* Underrun. Just recover and try writing again. */
if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, framesWritten, MA_TRUE) < 0) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after underrun.", MA_FAILED_TO_START_BACKEND_DEVICE);
return MA_FALSE;
}
framesWritten = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable);
if (framesWritten < 0) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to write data to the internal device.", ma_result_from_errno((int)-framesWritten));
return MA_FALSE;
}
break; /* Success. */
} else {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_writei() failed when writing initial data.", ma_result_from_errno((int)-framesWritten));
return MA_FALSE;
}
} else {
break; /* Success. */
}
}
}
return MA_TRUE;
}
static ma_bool32 ma_device_read_and_send_to_client__alsa(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
if (!ma_device_is_started(pDevice)) {
return MA_FALSE;
}
if (pDevice->alsa.breakFromMainLoop) {
return MA_FALSE;
}
ma_uint32 framesToSend = 0;
void* pBuffer = NULL;
if (pDevice->alsa.pIntermediaryBuffer == NULL) {
/* mmap. */
ma_bool32 requiresRestart;
ma_uint32 framesAvailable = ma_device__wait_for_frames__alsa(pDevice, &requiresRestart);
if (framesAvailable == 0) {
return MA_FALSE;
}
const ma_snd_pcm_channel_area_t* pAreas;
ma_snd_pcm_uframes_t mappedOffset;
ma_snd_pcm_uframes_t mappedFrames = framesAvailable;
while (framesAvailable > 0) {
int result = ((ma_snd_pcm_mmap_begin_proc)pDevice->pContext->alsa.snd_pcm_mmap_begin)((ma_snd_pcm_t*)pDevice->alsa.pPCM, &pAreas, &mappedOffset, &mappedFrames);
if (result < 0) {
return MA_FALSE;
}
if (mappedFrames > 0) {
void* pBuffer = (ma_uint8*)pAreas[0].addr + ((pAreas[0].first + (mappedOffset * pAreas[0].step)) / 8);
ma_device__send_frames_to_client(pDevice, mappedFrames, pBuffer);
}
result = ((ma_snd_pcm_mmap_commit_proc)pDevice->pContext->alsa.snd_pcm_mmap_commit)((ma_snd_pcm_t*)pDevice->alsa.pPCM, mappedOffset, mappedFrames);
if (result < 0 || (ma_snd_pcm_uframes_t)result != mappedFrames) {
((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, result, MA_TRUE);
return MA_FALSE;
}
if (requiresRestart) {
if (((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCM) < 0) {
return MA_FALSE;
}
}
if (framesAvailable >= mappedFrames) {
framesAvailable -= mappedFrames;
} else {
framesAvailable = 0;
}
}
} else {
/* readi/writei. */
ma_snd_pcm_sframes_t framesRead = 0;
while (!pDevice->alsa.breakFromMainLoop) {
ma_uint32 framesAvailable = ma_device__wait_for_frames__alsa(pDevice, NULL);
if (framesAvailable == 0) {
continue;
}
framesRead = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable);
if (framesRead < 0) {
if (framesRead == -EAGAIN) {
continue; /* Just keep trying... */
} else if (framesRead == -EPIPE) {
/* Overrun. Just recover and try reading again. */
if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, framesRead, MA_TRUE) < 0) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after overrun.", MA_FAILED_TO_START_BACKEND_DEVICE);
return MA_FALSE;
}
framesRead = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable);
if (framesRead < 0) {
ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to read data from the internal device.", ma_result_from_errno((int)-framesRead));
return MA_FALSE;
}
break; /* Success. */
} else {
return MA_FALSE;
}
} else {
break; /* Success. */
}
}
framesToSend = framesRead;
pBuffer = pDevice->alsa.pIntermediaryBuffer;
}
if (framesToSend > 0) {
ma_device__send_frames_to_client(pDevice, framesToSend, pBuffer);
}
return MA_TRUE;
}
#endif /* 0 */
static void ma_device_uninit__alsa(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
if ((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) {
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
}
if ((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback) {
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback);
}
}
static ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_config* pConfig, ma_device_type deviceType, ma_device* pDevice)
{
ma_result result;
int resultALSA;
ma_snd_pcm_t* pPCM;
ma_bool32 isUsingMMap;
ma_snd_pcm_format_t formatALSA;
ma_share_mode shareMode;
const ma_device_id* pDeviceID;
ma_format internalFormat;
ma_uint32 internalChannels;
ma_uint32 internalSampleRate;
ma_channel internalChannelMap[MA_MAX_CHANNELS];
ma_uint32 internalPeriodSizeInFrames;
ma_uint32 internalPeriods;
int openMode;
ma_snd_pcm_hw_params_t* pHWParams;
ma_snd_pcm_sw_params_t* pSWParams;
ma_snd_pcm_uframes_t bufferBoundary;
float bufferSizeScaleFactor;
MA_ASSERT(pContext != NULL);
MA_ASSERT(pConfig != NULL);
MA_ASSERT(deviceType != ma_device_type_duplex); /* This function should only be called for playback _or_ capture, never duplex. */
MA_ASSERT(pDevice != NULL);
formatALSA = ma_convert_ma_format_to_alsa_format((deviceType == ma_device_type_capture) ? pConfig->capture.format : pConfig->playback.format);
shareMode = (deviceType == ma_device_type_capture) ? pConfig->capture.shareMode : pConfig->playback.shareMode;
pDeviceID = (deviceType == ma_device_type_capture) ? pConfig->capture.pDeviceID : pConfig->playback.pDeviceID;
openMode = 0;
if (pConfig->alsa.noAutoResample) {
openMode |= MA_SND_PCM_NO_AUTO_RESAMPLE;
}
if (pConfig->alsa.noAutoChannels) {
openMode |= MA_SND_PCM_NO_AUTO_CHANNELS;
}
if (pConfig->alsa.noAutoFormat) {
openMode |= MA_SND_PCM_NO_AUTO_FORMAT;
}
result = ma_context_open_pcm__alsa(pContext, shareMode, deviceType, pDeviceID, openMode, &pPCM);
if (result != MA_SUCCESS) {
return result;
}
/* If using the default buffer size we may want to apply some device-specific scaling for known devices that have peculiar latency characteristics */
bufferSizeScaleFactor = 1;
if (pDevice->usingDefaultBufferSize) {
ma_snd_pcm_info_t* pInfo = (ma_snd_pcm_info_t*)ma__calloc_from_callbacks(((ma_snd_pcm_info_sizeof_proc)pContext->alsa.snd_pcm_info_sizeof)(), &pContext->allocationCallbacks);
if (pInfo == NULL) {
return MA_OUT_OF_MEMORY;
}
/* We may need to scale the size of the buffer depending on the device. */
if (((ma_snd_pcm_info_proc)pContext->alsa.snd_pcm_info)(pPCM, pInfo) == 0) {
const char* deviceName = ((ma_snd_pcm_info_get_name_proc)pContext->alsa.snd_pcm_info_get_name)(pInfo);
if (deviceName != NULL) {
if (ma_strcmp(deviceName, "default") == 0) {
char** ppDeviceHints;
char** ppNextDeviceHint;
/* It's the default device. We need to use DESC from snd_device_name_hint(). */
if (((ma_snd_device_name_hint_proc)pContext->alsa.snd_device_name_hint)(-1, "pcm", (void***)&ppDeviceHints) < 0) {
ma__free_from_callbacks(pInfo, &pContext->allocationCallbacks);
return MA_NO_BACKEND;
}
ppNextDeviceHint = ppDeviceHints;
while (*ppNextDeviceHint != NULL) {
char* NAME = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "NAME");
char* DESC = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "DESC");
char* IOID = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "IOID");
ma_bool32 foundDevice = MA_FALSE;
if ((deviceType == ma_device_type_playback && (IOID == NULL || ma_strcmp(IOID, "Output") == 0)) ||
(deviceType == ma_device_type_capture && (IOID != NULL && ma_strcmp(IOID, "Input" ) == 0))) {
if (ma_strcmp(NAME, deviceName) == 0) {
bufferSizeScaleFactor = ma_find_default_buffer_size_scale__alsa(DESC);
foundDevice = MA_TRUE;
}
}
free(NAME);
free(DESC);
free(IOID);
ppNextDeviceHint += 1;
if (foundDevice) {
break;
}
}
((ma_snd_device_name_free_hint_proc)pContext->alsa.snd_device_name_free_hint)((void**)ppDeviceHints);
} else {
bufferSizeScaleFactor = ma_find_default_buffer_size_scale__alsa(deviceName);
}
}
}
ma__free_from_callbacks(pInfo, &pContext->allocationCallbacks);
}
/* Hardware parameters. */
pHWParams = (ma_snd_pcm_hw_params_t*)ma__calloc_from_callbacks(((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)(), &pContext->allocationCallbacks);
if (pHWParams == NULL) {
return MA_OUT_OF_MEMORY;
}
resultALSA = ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
if (resultALSA < 0) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.", ma_result_from_errno(-resultALSA));
}
/* MMAP Mode. Try using interleaved MMAP access. If this fails, fall back to standard readi/writei. */
isUsingMMap = MA_FALSE;
#if 0 /* NOTE: MMAP mode temporarily disabled. */
if (deviceType != ma_device_type_capture) { /* <-- Disabling MMAP mode for capture devices because I apparently do not have a device that supports it which means I can't test it... Contributions welcome. */
if (!pConfig->alsa.noMMap && ma_device__is_async(pDevice)) {
if (((ma_snd_pcm_hw_params_set_access_proc)pContext->alsa.snd_pcm_hw_params_set_access)(pPCM, pHWParams, MA_SND_PCM_ACCESS_MMAP_INTERLEAVED) == 0) {
pDevice->alsa.isUsingMMap = MA_TRUE;
}
}
}
#endif
if (!isUsingMMap) {
resultALSA = ((ma_snd_pcm_hw_params_set_access_proc)pContext->alsa.snd_pcm_hw_params_set_access)(pPCM, pHWParams, MA_SND_PCM_ACCESS_RW_INTERLEAVED);
if (resultALSA < 0) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set access mode to neither SND_PCM_ACCESS_MMAP_INTERLEAVED nor SND_PCM_ACCESS_RW_INTERLEAVED. snd_pcm_hw_params_set_access() failed.", ma_result_from_errno(-resultALSA));
}
}
/*
Most important properties first. The documentation for OSS (yes, I know this is ALSA!) recommends format, channels, then sample rate. I can't
find any documentation for ALSA specifically, so I'm going to copy the recommendation for OSS.
*/
/* Format. */
{
ma_snd_pcm_format_mask_t* pFormatMask;
/* Try getting every supported format first. */
pFormatMask = (ma_snd_pcm_format_mask_t*)ma__calloc_from_callbacks(((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)(), &pContext->allocationCallbacks);
if (pFormatMask == NULL) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return MA_OUT_OF_MEMORY;
}
((ma_snd_pcm_hw_params_get_format_mask_proc)pContext->alsa.snd_pcm_hw_params_get_format_mask)(pHWParams, pFormatMask);
/*
At this point we should have a list of supported formats, so now we need to find the best one. We first check if the requested format is
supported, and if so, use that one. If it's not supported, we just run though a list of formats and try to find the best one.
*/
if (!((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, formatALSA)) {
size_t i;
/* The requested format is not supported so now try running through the list of formats and return the best one. */
ma_snd_pcm_format_t preferredFormatsALSA[] = {
MA_SND_PCM_FORMAT_S16_LE, /* ma_format_s16 */
MA_SND_PCM_FORMAT_FLOAT_LE, /* ma_format_f32 */
MA_SND_PCM_FORMAT_S32_LE, /* ma_format_s32 */
MA_SND_PCM_FORMAT_S24_3LE, /* ma_format_s24 */
MA_SND_PCM_FORMAT_U8 /* ma_format_u8 */
};
if (ma_is_big_endian()) {
preferredFormatsALSA[0] = MA_SND_PCM_FORMAT_S16_BE;
preferredFormatsALSA[1] = MA_SND_PCM_FORMAT_FLOAT_BE;
preferredFormatsALSA[2] = MA_SND_PCM_FORMAT_S32_BE;
preferredFormatsALSA[3] = MA_SND_PCM_FORMAT_S24_3BE;
preferredFormatsALSA[4] = MA_SND_PCM_FORMAT_U8;
}
formatALSA = MA_SND_PCM_FORMAT_UNKNOWN;
for (i = 0; i < (sizeof(preferredFormatsALSA) / sizeof(preferredFormatsALSA[0])); ++i) {
if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, preferredFormatsALSA[i])) {
formatALSA = preferredFormatsALSA[i];
break;
}
}
if (formatALSA == MA_SND_PCM_FORMAT_UNKNOWN) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. The device does not support any miniaudio formats.", MA_FORMAT_NOT_SUPPORTED);
}
}
ma__free_from_callbacks(pFormatMask, &pContext->allocationCallbacks);
pFormatMask = NULL;
resultALSA = ((ma_snd_pcm_hw_params_set_format_proc)pContext->alsa.snd_pcm_hw_params_set_format)(pPCM, pHWParams, formatALSA);
if (resultALSA < 0) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. snd_pcm_hw_params_set_format() failed.", ma_result_from_errno(-resultALSA));
}
internalFormat = ma_format_from_alsa(formatALSA);
if (internalFormat == ma_format_unknown) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] The chosen format is not supported by miniaudio.", MA_FORMAT_NOT_SUPPORTED);
}
}
/* Channels. */
{
unsigned int channels = (deviceType == ma_device_type_capture) ? pConfig->capture.channels : pConfig->playback.channels;
resultALSA = ((ma_snd_pcm_hw_params_set_channels_near_proc)pContext->alsa.snd_pcm_hw_params_set_channels_near)(pPCM, pHWParams, &channels);
if (resultALSA < 0) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set channel count. snd_pcm_hw_params_set_channels_near() failed.", ma_result_from_errno(-resultALSA));
}
internalChannels = (ma_uint32)channels;
}
/* Sample Rate */
{
unsigned int sampleRate;
/*
It appears there's either a bug in ALSA, a bug in some drivers, or I'm doing something silly; but having resampling enabled causes
problems with some device configurations when used in conjunction with MMAP access mode. To fix this problem we need to disable
resampling.
To reproduce this problem, open the "plug:dmix" device, and set the sample rate to 44100. Internally, it looks like dmix uses a
sample rate of 48000. The hardware parameters will get set correctly with no errors, but it looks like the 44100 -> 48000 resampling
doesn't work properly - but only with MMAP access mode. You will notice skipping/crackling in the audio, and it'll run at a slightly
faster rate.
miniaudio has built-in support for sample rate conversion (albeit low quality at the moment), so disabling resampling should be fine
for us. The only problem is that it won't be taking advantage of any kind of hardware-accelerated resampling and it won't be very
good quality until I get a chance to improve the quality of miniaudio's software sample rate conversion.
I don't currently know if the dmix plugin is the only one with this error. Indeed, this is the only one I've been able to reproduce
this error with. In the future, we may want to restrict the disabling of resampling to only known bad plugins.
*/
((ma_snd_pcm_hw_params_set_rate_resample_proc)pContext->alsa.snd_pcm_hw_params_set_rate_resample)(pPCM, pHWParams, 0);
sampleRate = pConfig->sampleRate;
resultALSA = ((ma_snd_pcm_hw_params_set_rate_near_proc)pContext->alsa.snd_pcm_hw_params_set_rate_near)(pPCM, pHWParams, &sampleRate, 0);
if (resultALSA < 0) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Sample rate not supported. snd_pcm_hw_params_set_rate_near() failed.", ma_result_from_errno(-resultALSA));
}
internalSampleRate = (ma_uint32)sampleRate;
}
/* Periods. */
{
ma_uint32 periods = pConfig->periods;
resultALSA = ((ma_snd_pcm_hw_params_set_periods_near_proc)pContext->alsa.snd_pcm_hw_params_set_periods_near)(pPCM, pHWParams, &periods, NULL);
if (resultALSA < 0) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set period count. snd_pcm_hw_params_set_periods_near() failed.", ma_result_from_errno(-resultALSA));
}
internalPeriods = periods;
}
/* Buffer Size */
{
ma_snd_pcm_uframes_t actualBufferSizeInFrames = pConfig->periodSizeInFrames * internalPeriods;
if (actualBufferSizeInFrames == 0) {
actualBufferSizeInFrames = ma_scale_buffer_size(ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, internalSampleRate), bufferSizeScaleFactor) * internalPeriods;
}
resultALSA = ((ma_snd_pcm_hw_params_set_buffer_size_near_proc)pContext->alsa.snd_pcm_hw_params_set_buffer_size_near)(pPCM, pHWParams, &actualBufferSizeInFrames);
if (resultALSA < 0) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set buffer size for device. snd_pcm_hw_params_set_buffer_size() failed.", ma_result_from_errno(-resultALSA));
}
internalPeriodSizeInFrames = actualBufferSizeInFrames / internalPeriods;
}
/* Apply hardware parameters. */
resultALSA = ((ma_snd_pcm_hw_params_proc)pContext->alsa.snd_pcm_hw_params)(pPCM, pHWParams);
if (resultALSA < 0) {
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set hardware parameters. snd_pcm_hw_params() failed.", ma_result_from_errno(-resultALSA));
}
ma__free_from_callbacks(pHWParams, &pContext->allocationCallbacks);
pHWParams = NULL;
/* Software parameters. */
pSWParams = (ma_snd_pcm_sw_params_t*)ma__calloc_from_callbacks(((ma_snd_pcm_sw_params_sizeof_proc)pContext->alsa.snd_pcm_sw_params_sizeof)(), &pContext->allocationCallbacks);
if (pSWParams == NULL) {
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return MA_OUT_OF_MEMORY;
}
resultALSA = ((ma_snd_pcm_sw_params_current_proc)pContext->alsa.snd_pcm_sw_params_current)(pPCM, pSWParams);
if (resultALSA < 0) {
ma__free_from_callbacks(pSWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize software parameters. snd_pcm_sw_params_current() failed.", ma_result_from_errno(-resultALSA));
}
resultALSA = ((ma_snd_pcm_sw_params_set_avail_min_proc)pContext->alsa.snd_pcm_sw_params_set_avail_min)(pPCM, pSWParams, ma_prev_power_of_2(internalPeriodSizeInFrames));
if (resultALSA < 0) {
ma__free_from_callbacks(pSWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_sw_params_set_avail_min() failed.", ma_result_from_errno(-resultALSA));
}
resultALSA = ((ma_snd_pcm_sw_params_get_boundary_proc)pContext->alsa.snd_pcm_sw_params_get_boundary)(pSWParams, &bufferBoundary);
if (resultALSA < 0) {
bufferBoundary = internalPeriodSizeInFrames * internalPeriods;
}
/*printf("TRACE: bufferBoundary=%ld\n", bufferBoundary);*/
if (deviceType == ma_device_type_playback && !isUsingMMap) { /* Only playback devices in writei/readi mode need a start threshold. */
/*
Subtle detail here with the start threshold. When in playback-only mode (no full-duplex) we can set the start threshold to
the size of a period. But for full-duplex we need to set it such that it is at least two periods.
*/
resultALSA = ((ma_snd_pcm_sw_params_set_start_threshold_proc)pContext->alsa.snd_pcm_sw_params_set_start_threshold)(pPCM, pSWParams, internalPeriodSizeInFrames*2);
if (resultALSA < 0) {
ma__free_from_callbacks(pSWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set start threshold for playback device. snd_pcm_sw_params_set_start_threshold() failed.", ma_result_from_errno(-resultALSA));
}
resultALSA = ((ma_snd_pcm_sw_params_set_stop_threshold_proc)pContext->alsa.snd_pcm_sw_params_set_stop_threshold)(pPCM, pSWParams, bufferBoundary);
if (resultALSA < 0) { /* Set to boundary to loop instead of stop in the event of an xrun. */
ma__free_from_callbacks(pSWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set stop threshold for playback device. snd_pcm_sw_params_set_stop_threshold() failed.", ma_result_from_errno(-resultALSA));
}
}
resultALSA = ((ma_snd_pcm_sw_params_proc)pContext->alsa.snd_pcm_sw_params)(pPCM, pSWParams);
if (resultALSA < 0) {
ma__free_from_callbacks(pSWParams, &pContext->allocationCallbacks);
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set software parameters. snd_pcm_sw_params() failed.", ma_result_from_errno(-resultALSA));
}
ma__free_from_callbacks(pSWParams, &pContext->allocationCallbacks);
pSWParams = NULL;
/* Grab the internal channel map. For now we're not going to bother trying to change the channel map and instead just do it ourselves. */
{
ma_snd_pcm_chmap_t* pChmap = ((ma_snd_pcm_get_chmap_proc)pContext->alsa.snd_pcm_get_chmap)(pPCM);
if (pChmap != NULL) {
ma_uint32 iChannel;
/* There are cases where the returned channel map can have a different channel count than was returned by snd_pcm_hw_params_set_channels_near(). */
if (pChmap->channels >= internalChannels) {
/* Drop excess channels. */
for (iChannel = 0; iChannel < internalChannels; ++iChannel) {
internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]);
}
} else {
ma_uint32 i;
/*
Excess channels use defaults. Do an initial fill with defaults, overwrite the first pChmap->channels, validate to ensure there are no duplicate
channels. If validation fails, fall back to defaults.
*/
ma_bool32 isValid = MA_TRUE;
/* Fill with defaults. */
ma_get_standard_channel_map(ma_standard_channel_map_alsa, internalChannels, internalChannelMap);
/* Overwrite first pChmap->channels channels. */
for (iChannel = 0; iChannel < pChmap->channels; ++iChannel) {
internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]);
}
/* Validate. */
for (i = 0; i < internalChannels && isValid; ++i) {
ma_uint32 j;
for (j = i+1; j < internalChannels; ++j) {
if (internalChannelMap[i] == internalChannelMap[j]) {
isValid = MA_FALSE;
break;
}
}
}
/* If our channel map is invalid, fall back to defaults. */
if (!isValid) {
ma_get_standard_channel_map(ma_standard_channel_map_alsa, internalChannels, internalChannelMap);
}
}
free(pChmap);
pChmap = NULL;
} else {
/* Could not retrieve the channel map. Fall back to a hard-coded assumption. */
ma_get_standard_channel_map(ma_standard_channel_map_alsa, internalChannels, internalChannelMap);
}
}
/* We're done. Prepare the device. */
resultALSA = ((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)(pPCM);
if (resultALSA < 0) {
((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to prepare device.", ma_result_from_errno(-resultALSA));
}
if (deviceType == ma_device_type_capture) {
pDevice->alsa.pPCMCapture = (ma_ptr)pPCM;
pDevice->alsa.isUsingMMapCapture = isUsingMMap;
pDevice->capture.internalFormat = internalFormat;
pDevice->capture.internalChannels = internalChannels;
pDevice->capture.internalSampleRate = internalSampleRate;
ma_channel_map_copy(pDevice->capture.internalChannelMap, internalChannelMap, ma_min(internalChannels, MA_MAX_CHANNELS));
pDevice->capture.internalPeriodSizeInFrames = internalPeriodSizeInFrames;
pDevice->capture.internalPeriods = internalPeriods;
} else {
pDevice->alsa.pPCMPlayback = (ma_ptr)pPCM;
pDevice->alsa.isUsingMMapPlayback = isUsingMMap;
pDevice->playback.internalFormat = internalFormat;
pDevice->playback.internalChannels = internalChannels;
pDevice->playback.internalSampleRate = internalSampleRate;
ma_channel_map_copy(pDevice->playback.internalChannelMap, internalChannelMap, ma_min(internalChannels, MA_MAX_CHANNELS));
pDevice->playback.internalPeriodSizeInFrames = internalPeriodSizeInFrames;
pDevice->playback.internalPeriods = internalPeriods;
}
return MA_SUCCESS;
}
static ma_result ma_device_init__alsa(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
MA_ZERO_OBJECT(&pDevice->alsa);
if (pConfig->deviceType == ma_device_type_loopback) {
return MA_DEVICE_TYPE_NOT_SUPPORTED;
}
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
ma_result result = ma_device_init_by_type__alsa(pContext, pConfig, ma_device_type_capture, pDevice);
if (result != MA_SUCCESS) {
return result;
}
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
ma_result result = ma_device_init_by_type__alsa(pContext, pConfig, ma_device_type_playback, pDevice);
if (result != MA_SUCCESS) {
return result;
}
}
return MA_SUCCESS;
}
static ma_result ma_device_read__alsa(ma_device* pDevice, void* pFramesOut, ma_uint32 frameCount, ma_uint32* pFramesRead)
{
ma_snd_pcm_sframes_t resultALSA;
MA_ASSERT(pDevice != NULL);
MA_ASSERT(pFramesOut != NULL);
if (pFramesRead != NULL) {
*pFramesRead = 0;
}
for (;;) {
resultALSA = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, pFramesOut, frameCount);
if (resultALSA >= 0) {
break; /* Success. */
} else {
if (resultALSA == -EAGAIN) {
/*printf("TRACE: EGAIN (read)\n");*/
continue; /* Try again. */
} else if (resultALSA == -EPIPE) {
#if defined(MA_DEBUG_OUTPUT)
printf("TRACE: EPIPE (read)\n");
#endif
/* Overrun. Recover and try again. If this fails we need to return an error. */
resultALSA = ((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, resultALSA, MA_TRUE);
if (resultALSA < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after overrun.", ma_result_from_errno((int)-resultALSA));
}
resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
if (resultALSA < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device after underrun.", ma_result_from_errno((int)-resultALSA));
}
resultALSA = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, pFramesOut, frameCount);
if (resultALSA < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to read data from the internal device.", ma_result_from_errno((int)-resultALSA));
}
}
}
}
if (pFramesRead != NULL) {
*pFramesRead = resultALSA;
}
return MA_SUCCESS;
}
static ma_result ma_device_write__alsa(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
{
ma_snd_pcm_sframes_t resultALSA;
MA_ASSERT(pDevice != NULL);
MA_ASSERT(pFrames != NULL);
if (pFramesWritten != NULL) {
*pFramesWritten = 0;
}
for (;;) {
resultALSA = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, pFrames, frameCount);
if (resultALSA >= 0) {
break; /* Success. */
} else {
if (resultALSA == -EAGAIN) {
/*printf("TRACE: EGAIN (write)\n");*/
continue; /* Try again. */
} else if (resultALSA == -EPIPE) {
#if defined(MA_DEBUG_OUTPUT)
printf("TRACE: EPIPE (write)\n");
#endif
/* Underrun. Recover and try again. If this fails we need to return an error. */
resultALSA = ((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, resultALSA, MA_TRUE);
if (resultALSA < 0) { /* MA_TRUE=silent (don't print anything on error). */
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after underrun.", ma_result_from_errno((int)-resultALSA));
}
/*
In my testing I have had a situation where writei() does not automatically restart the device even though I've set it
up as such in the software parameters. What will happen is writei() will block indefinitely even though the number of
frames is well beyond the auto-start threshold. To work around this I've needed to add an explicit start here. Not sure
if this is me just being stupid and not recovering the device properly, but this definitely feels like something isn't
quite right here.
*/
resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback);
if (resultALSA < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device after underrun.", ma_result_from_errno((int)-resultALSA));
}
resultALSA = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, pFrames, frameCount);
if (resultALSA < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to write data to device after underrun.", ma_result_from_errno((int)-resultALSA));
}
}
}
}
if (pFramesWritten != NULL) {
*pFramesWritten = resultALSA;
}
return MA_SUCCESS;
}
static ma_result ma_device_main_loop__alsa(ma_device* pDevice)
{
ma_result result = MA_SUCCESS;
int resultALSA;
ma_bool32 exitLoop = MA_FALSE;
MA_ASSERT(pDevice != NULL);
/* Capture devices need to be started immediately. */
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
if (resultALSA < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device in preparation for reading.", ma_result_from_errno(-resultALSA));
}
}
while (ma_device_get_state(pDevice) == MA_STATE_STARTED && !exitLoop) {
switch (pDevice->type)
{
case ma_device_type_duplex:
{
if (pDevice->alsa.isUsingMMapCapture || pDevice->alsa.isUsingMMapPlayback) {
/* MMAP */
return MA_INVALID_OPERATION; /* Not yet implemented. */
} else {
/* readi() and writei() */
/* The process is: device_read -> convert -> callback -> convert -> device_write */
ma_uint32 totalCapturedDeviceFramesProcessed = 0;
ma_uint32 capturedDevicePeriodSizeInFrames = ma_min(pDevice->capture.internalPeriodSizeInFrames, pDevice->playback.internalPeriodSizeInFrames);
while (totalCapturedDeviceFramesProcessed < capturedDevicePeriodSizeInFrames) {
ma_uint8 capturedDeviceData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint8 playbackDeviceData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 capturedDeviceDataCapInFrames = sizeof(capturedDeviceData) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
ma_uint32 playbackDeviceDataCapInFrames = sizeof(playbackDeviceData) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
ma_uint32 capturedDeviceFramesRemaining;
ma_uint32 capturedDeviceFramesProcessed;
ma_uint32 capturedDeviceFramesToProcess;
ma_uint32 capturedDeviceFramesToTryProcessing = capturedDevicePeriodSizeInFrames - totalCapturedDeviceFramesProcessed;
if (capturedDeviceFramesToTryProcessing > capturedDeviceDataCapInFrames) {
capturedDeviceFramesToTryProcessing = capturedDeviceDataCapInFrames;
}
result = ma_device_read__alsa(pDevice, capturedDeviceData, capturedDeviceFramesToTryProcessing, &capturedDeviceFramesToProcess);
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
capturedDeviceFramesRemaining = capturedDeviceFramesToProcess;
capturedDeviceFramesProcessed = 0;
for (;;) {
ma_uint8 capturedClientData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint8 playbackClientData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 capturedClientDataCapInFrames = sizeof(capturedClientData) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
ma_uint32 playbackClientDataCapInFrames = sizeof(playbackClientData) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
ma_uint64 capturedClientFramesToProcessThisIteration = ma_min(capturedClientDataCapInFrames, playbackClientDataCapInFrames);
ma_uint64 capturedDeviceFramesToProcessThisIteration = capturedDeviceFramesRemaining;
ma_uint8* pRunningCapturedDeviceFrames = ma_offset_ptr(capturedDeviceData, capturedDeviceFramesProcessed * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
/* Convert capture data from device format to client format. */
result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningCapturedDeviceFrames, &capturedDeviceFramesToProcessThisIteration, capturedClientData, &capturedClientFramesToProcessThisIteration);
if (result != MA_SUCCESS) {
break;
}
/*
If we weren't able to generate any output frames it must mean we've exhaused all of our input. The only time this would not be the case is if capturedClientData was too small
which should never be the case when it's of the size MA_DATA_CONVERTER_STACK_BUFFER_SIZE.
*/
if (capturedClientFramesToProcessThisIteration == 0) {
break;
}
ma_device__on_data(pDevice, playbackClientData, capturedClientData, (ma_uint32)capturedClientFramesToProcessThisIteration); /* Safe cast .*/
capturedDeviceFramesProcessed += (ma_uint32)capturedDeviceFramesToProcessThisIteration; /* Safe cast. */
capturedDeviceFramesRemaining -= (ma_uint32)capturedDeviceFramesToProcessThisIteration; /* Safe cast. */
/* At this point the playbackClientData buffer should be holding data that needs to be written to the device. */
for (;;) {
ma_uint64 convertedClientFrameCount = capturedClientFramesToProcessThisIteration;
ma_uint64 convertedDeviceFrameCount = playbackDeviceDataCapInFrames;
result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, playbackClientData, &convertedClientFrameCount, playbackDeviceData, &convertedDeviceFrameCount);
if (result != MA_SUCCESS) {
break;
}
result = ma_device_write__alsa(pDevice, playbackDeviceData, (ma_uint32)convertedDeviceFrameCount, NULL); /* Safe cast. */
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
capturedClientFramesToProcessThisIteration -= (ma_uint32)convertedClientFrameCount; /* Safe cast. */
if (capturedClientFramesToProcessThisIteration == 0) {
break;
}
}
/* In case an error happened from ma_device_write__alsa()... */
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
}
totalCapturedDeviceFramesProcessed += capturedDeviceFramesProcessed;
}
}
} break;
case ma_device_type_capture:
{
if (pDevice->alsa.isUsingMMapCapture) {
/* MMAP */
return MA_INVALID_OPERATION; /* Not yet implemented. */
} else {
/* readi() */
/* We read in chunks of the period size, but use a stack allocated buffer for the intermediary. */
ma_uint8 intermediaryBuffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 intermediaryBufferSizeInFrames = sizeof(intermediaryBuffer) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
ma_uint32 periodSizeInFrames = pDevice->capture.internalPeriodSizeInFrames;
ma_uint32 framesReadThisPeriod = 0;
while (framesReadThisPeriod < periodSizeInFrames) {
ma_uint32 framesRemainingInPeriod = periodSizeInFrames - framesReadThisPeriod;
ma_uint32 framesProcessed;
ma_uint32 framesToReadThisIteration = framesRemainingInPeriod;
if (framesToReadThisIteration > intermediaryBufferSizeInFrames) {
framesToReadThisIteration = intermediaryBufferSizeInFrames;
}
result = ma_device_read__alsa(pDevice, intermediaryBuffer, framesToReadThisIteration, &framesProcessed);
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
ma_device__send_frames_to_client(pDevice, framesProcessed, intermediaryBuffer);
framesReadThisPeriod += framesProcessed;
}
}
} break;
case ma_device_type_playback:
{
if (pDevice->alsa.isUsingMMapPlayback) {
/* MMAP */
return MA_INVALID_OPERATION; /* Not yet implemented. */
} else {
/* writei() */
/* We write in chunks of the period size, but use a stack allocated buffer for the intermediary. */
ma_uint8 intermediaryBuffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 intermediaryBufferSizeInFrames = sizeof(intermediaryBuffer) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
ma_uint32 periodSizeInFrames = pDevice->playback.internalPeriodSizeInFrames;
ma_uint32 framesWrittenThisPeriod = 0;
while (framesWrittenThisPeriod < periodSizeInFrames) {
ma_uint32 framesRemainingInPeriod = periodSizeInFrames - framesWrittenThisPeriod;
ma_uint32 framesProcessed;
ma_uint32 framesToWriteThisIteration = framesRemainingInPeriod;
if (framesToWriteThisIteration > intermediaryBufferSizeInFrames) {
framesToWriteThisIteration = intermediaryBufferSizeInFrames;
}
ma_device__read_frames_from_client(pDevice, framesToWriteThisIteration, intermediaryBuffer);
result = ma_device_write__alsa(pDevice, intermediaryBuffer, framesToWriteThisIteration, &framesProcessed);
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
framesWrittenThisPeriod += framesProcessed;
}
}
} break;
/* To silence a warning. Will never hit this. */
case ma_device_type_loopback:
default: break;
}
}
/* Here is where the device needs to be stopped. */
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
((ma_snd_pcm_drain_proc)pDevice->pContext->alsa.snd_pcm_drain)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
/* We need to prepare the device again, otherwise we won't be able to restart the device. */
if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) < 0) {
#ifdef MA_DEBUG_OUTPUT
printf("[ALSA] Failed to prepare capture device after stopping.\n");
#endif
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
((ma_snd_pcm_drain_proc)pDevice->pContext->alsa.snd_pcm_drain)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback);
/* We need to prepare the device again, otherwise we won't be able to restart the device. */
if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback) < 0) {
#ifdef MA_DEBUG_OUTPUT
printf("[ALSA] Failed to prepare playback device after stopping.\n");
#endif
}
}
return result;
}
static ma_result ma_context_uninit__alsa(ma_context* pContext)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pContext->backend == ma_backend_alsa);
/* Clean up memory for memory leak checkers. */
((ma_snd_config_update_free_global_proc)pContext->alsa.snd_config_update_free_global)();
#ifndef MA_NO_RUNTIME_LINKING
ma_dlclose(pContext, pContext->alsa.asoundSO);
#endif
ma_mutex_uninit(&pContext->alsa.internalDeviceEnumLock);
return MA_SUCCESS;
}
static ma_result ma_context_init__alsa(const ma_context_config* pConfig, ma_context* pContext)
{
#ifndef MA_NO_RUNTIME_LINKING
const char* libasoundNames[] = {
"libasound.so.2",
"libasound.so"
};
size_t i;
for (i = 0; i < ma_countof(libasoundNames); ++i) {
pContext->alsa.asoundSO = ma_dlopen(pContext, libasoundNames[i]);
if (pContext->alsa.asoundSO != NULL) {
break;
}
}
if (pContext->alsa.asoundSO == NULL) {
#ifdef MA_DEBUG_OUTPUT
printf("[ALSA] Failed to open shared object.\n");
#endif
return MA_NO_BACKEND;
}
pContext->alsa.snd_pcm_open = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_open");
pContext->alsa.snd_pcm_close = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_close");
pContext->alsa.snd_pcm_hw_params_sizeof = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_sizeof");
pContext->alsa.snd_pcm_hw_params_any = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_any");
pContext->alsa.snd_pcm_hw_params_set_format = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format");
pContext->alsa.snd_pcm_hw_params_set_format_first = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format_first");
pContext->alsa.snd_pcm_hw_params_get_format_mask = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format_mask");
pContext->alsa.snd_pcm_hw_params_set_channels_near = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels_near");
pContext->alsa.snd_pcm_hw_params_set_rate_resample = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_resample");
pContext->alsa.snd_pcm_hw_params_set_rate_near = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_near");
pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_buffer_size_near");
pContext->alsa.snd_pcm_hw_params_set_periods_near = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_periods_near");
pContext->alsa.snd_pcm_hw_params_set_access = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_access");
pContext->alsa.snd_pcm_hw_params_get_format = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format");
pContext->alsa.snd_pcm_hw_params_get_channels = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels");
pContext->alsa.snd_pcm_hw_params_get_channels_min = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_min");
pContext->alsa.snd_pcm_hw_params_get_channels_max = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_max");
pContext->alsa.snd_pcm_hw_params_get_rate = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate");
pContext->alsa.snd_pcm_hw_params_get_rate_min = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_min");
pContext->alsa.snd_pcm_hw_params_get_rate_max = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_max");
pContext->alsa.snd_pcm_hw_params_get_buffer_size = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_buffer_size");
pContext->alsa.snd_pcm_hw_params_get_periods = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_periods");
pContext->alsa.snd_pcm_hw_params_get_access = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_access");
pContext->alsa.snd_pcm_hw_params = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params");
pContext->alsa.snd_pcm_sw_params_sizeof = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_sizeof");
pContext->alsa.snd_pcm_sw_params_current = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_current");
pContext->alsa.snd_pcm_sw_params_get_boundary = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_get_boundary");
pContext->alsa.snd_pcm_sw_params_set_avail_min = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_set_avail_min");
pContext->alsa.snd_pcm_sw_params_set_start_threshold = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_set_start_threshold");
pContext->alsa.snd_pcm_sw_params_set_stop_threshold = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_set_stop_threshold");
pContext->alsa.snd_pcm_sw_params = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params");
pContext->alsa.snd_pcm_format_mask_sizeof = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_format_mask_sizeof");
pContext->alsa.snd_pcm_format_mask_test = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_format_mask_test");
pContext->alsa.snd_pcm_get_chmap = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_get_chmap");
pContext->alsa.snd_pcm_state = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_state");
pContext->alsa.snd_pcm_prepare = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_prepare");
pContext->alsa.snd_pcm_start = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_start");
pContext->alsa.snd_pcm_drop = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_drop");
pContext->alsa.snd_pcm_drain = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_drain");
pContext->alsa.snd_device_name_hint = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_device_name_hint");
pContext->alsa.snd_device_name_get_hint = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_device_name_get_hint");
pContext->alsa.snd_card_get_index = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_card_get_index");
pContext->alsa.snd_device_name_free_hint = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_device_name_free_hint");
pContext->alsa.snd_pcm_mmap_begin = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_mmap_begin");
pContext->alsa.snd_pcm_mmap_commit = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_mmap_commit");
pContext->alsa.snd_pcm_recover = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_recover");
pContext->alsa.snd_pcm_readi = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_readi");
pContext->alsa.snd_pcm_writei = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_writei");
pContext->alsa.snd_pcm_avail = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_avail");
pContext->alsa.snd_pcm_avail_update = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_avail_update");
pContext->alsa.snd_pcm_wait = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_wait");
pContext->alsa.snd_pcm_info = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_info");
pContext->alsa.snd_pcm_info_sizeof = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_info_sizeof");
pContext->alsa.snd_pcm_info_get_name = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_info_get_name");
pContext->alsa.snd_config_update_free_global = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_config_update_free_global");
#else
/* The system below is just for type safety. */
ma_snd_pcm_open_proc _snd_pcm_open = snd_pcm_open;
ma_snd_pcm_close_proc _snd_pcm_close = snd_pcm_close;
ma_snd_pcm_hw_params_sizeof_proc _snd_pcm_hw_params_sizeof = snd_pcm_hw_params_sizeof;
ma_snd_pcm_hw_params_any_proc _snd_pcm_hw_params_any = snd_pcm_hw_params_any;
ma_snd_pcm_hw_params_set_format_proc _snd_pcm_hw_params_set_format = snd_pcm_hw_params_set_format;
ma_snd_pcm_hw_params_set_format_first_proc _snd_pcm_hw_params_set_format_first = snd_pcm_hw_params_set_format_first;
ma_snd_pcm_hw_params_get_format_mask_proc _snd_pcm_hw_params_get_format_mask = snd_pcm_hw_params_get_format_mask;
ma_snd_pcm_hw_params_set_channels_near_proc _snd_pcm_hw_params_set_channels_near = snd_pcm_hw_params_set_channels_near;
ma_snd_pcm_hw_params_set_rate_resample_proc _snd_pcm_hw_params_set_rate_resample = snd_pcm_hw_params_set_rate_resample;
ma_snd_pcm_hw_params_set_rate_near_proc _snd_pcm_hw_params_set_rate_near = snd_pcm_hw_params_set_rate_near;
ma_snd_pcm_hw_params_set_buffer_size_near_proc _snd_pcm_hw_params_set_buffer_size_near = snd_pcm_hw_params_set_buffer_size_near;
ma_snd_pcm_hw_params_set_periods_near_proc _snd_pcm_hw_params_set_periods_near = snd_pcm_hw_params_set_periods_near;
ma_snd_pcm_hw_params_set_access_proc _snd_pcm_hw_params_set_access = snd_pcm_hw_params_set_access;
ma_snd_pcm_hw_params_get_format_proc _snd_pcm_hw_params_get_format = snd_pcm_hw_params_get_format;
ma_snd_pcm_hw_params_get_channels_proc _snd_pcm_hw_params_get_channels = snd_pcm_hw_params_get_channels;
ma_snd_pcm_hw_params_get_channels_min_proc _snd_pcm_hw_params_get_channels_min = snd_pcm_hw_params_get_channels_min;
ma_snd_pcm_hw_params_get_channels_max_proc _snd_pcm_hw_params_get_channels_max = snd_pcm_hw_params_get_channels_max;
ma_snd_pcm_hw_params_get_rate_proc _snd_pcm_hw_params_get_rate = snd_pcm_hw_params_get_rate;
ma_snd_pcm_hw_params_get_rate_min_proc _snd_pcm_hw_params_get_rate_min = snd_pcm_hw_params_get_rate_min;
ma_snd_pcm_hw_params_get_rate_max_proc _snd_pcm_hw_params_get_rate_max = snd_pcm_hw_params_get_rate_max;
ma_snd_pcm_hw_params_get_buffer_size_proc _snd_pcm_hw_params_get_buffer_size = snd_pcm_hw_params_get_buffer_size;
ma_snd_pcm_hw_params_get_periods_proc _snd_pcm_hw_params_get_periods = snd_pcm_hw_params_get_periods;
ma_snd_pcm_hw_params_get_access_proc _snd_pcm_hw_params_get_access = snd_pcm_hw_params_get_access;
ma_snd_pcm_hw_params_proc _snd_pcm_hw_params = snd_pcm_hw_params;
ma_snd_pcm_sw_params_sizeof_proc _snd_pcm_sw_params_sizeof = snd_pcm_sw_params_sizeof;
ma_snd_pcm_sw_params_current_proc _snd_pcm_sw_params_current = snd_pcm_sw_params_current;
ma_snd_pcm_sw_params_get_boundary_proc _snd_pcm_sw_params_get_boundary = snd_pcm_sw_params_get_boundary;
ma_snd_pcm_sw_params_set_avail_min_proc _snd_pcm_sw_params_set_avail_min = snd_pcm_sw_params_set_avail_min;
ma_snd_pcm_sw_params_set_start_threshold_proc _snd_pcm_sw_params_set_start_threshold = snd_pcm_sw_params_set_start_threshold;
ma_snd_pcm_sw_params_set_stop_threshold_proc _snd_pcm_sw_params_set_stop_threshold = snd_pcm_sw_params_set_stop_threshold;
ma_snd_pcm_sw_params_proc _snd_pcm_sw_params = snd_pcm_sw_params;
ma_snd_pcm_format_mask_sizeof_proc _snd_pcm_format_mask_sizeof = snd_pcm_format_mask_sizeof;
ma_snd_pcm_format_mask_test_proc _snd_pcm_format_mask_test = snd_pcm_format_mask_test;
ma_snd_pcm_get_chmap_proc _snd_pcm_get_chmap = snd_pcm_get_chmap;
ma_snd_pcm_state_proc _snd_pcm_state = snd_pcm_state;
ma_snd_pcm_prepare_proc _snd_pcm_prepare = snd_pcm_prepare;
ma_snd_pcm_start_proc _snd_pcm_start = snd_pcm_start;
ma_snd_pcm_drop_proc _snd_pcm_drop = snd_pcm_drop;
ma_snd_pcm_drain_proc _snd_pcm_drain = snd_pcm_drain;
ma_snd_device_name_hint_proc _snd_device_name_hint = snd_device_name_hint;
ma_snd_device_name_get_hint_proc _snd_device_name_get_hint = snd_device_name_get_hint;
ma_snd_card_get_index_proc _snd_card_get_index = snd_card_get_index;
ma_snd_device_name_free_hint_proc _snd_device_name_free_hint = snd_device_name_free_hint;
ma_snd_pcm_mmap_begin_proc _snd_pcm_mmap_begin = snd_pcm_mmap_begin;
ma_snd_pcm_mmap_commit_proc _snd_pcm_mmap_commit = snd_pcm_mmap_commit;
ma_snd_pcm_recover_proc _snd_pcm_recover = snd_pcm_recover;
ma_snd_pcm_readi_proc _snd_pcm_readi = snd_pcm_readi;
ma_snd_pcm_writei_proc _snd_pcm_writei = snd_pcm_writei;
ma_snd_pcm_avail_proc _snd_pcm_avail = snd_pcm_avail;
ma_snd_pcm_avail_update_proc _snd_pcm_avail_update = snd_pcm_avail_update;
ma_snd_pcm_wait_proc _snd_pcm_wait = snd_pcm_wait;
ma_snd_pcm_info_proc _snd_pcm_info = snd_pcm_info;
ma_snd_pcm_info_sizeof_proc _snd_pcm_info_sizeof = snd_pcm_info_sizeof;
ma_snd_pcm_info_get_name_proc _snd_pcm_info_get_name = snd_pcm_info_get_name;
ma_snd_config_update_free_global_proc _snd_config_update_free_global = snd_config_update_free_global;
pContext->alsa.snd_pcm_open = (ma_proc)_snd_pcm_open;
pContext->alsa.snd_pcm_close = (ma_proc)_snd_pcm_close;
pContext->alsa.snd_pcm_hw_params_sizeof = (ma_proc)_snd_pcm_hw_params_sizeof;
pContext->alsa.snd_pcm_hw_params_any = (ma_proc)_snd_pcm_hw_params_any;
pContext->alsa.snd_pcm_hw_params_set_format = (ma_proc)_snd_pcm_hw_params_set_format;
pContext->alsa.snd_pcm_hw_params_set_format_first = (ma_proc)_snd_pcm_hw_params_set_format_first;
pContext->alsa.snd_pcm_hw_params_get_format_mask = (ma_proc)_snd_pcm_hw_params_get_format_mask;
pContext->alsa.snd_pcm_hw_params_set_channels_near = (ma_proc)_snd_pcm_hw_params_set_channels_near;
pContext->alsa.snd_pcm_hw_params_set_rate_resample = (ma_proc)_snd_pcm_hw_params_set_rate_resample;
pContext->alsa.snd_pcm_hw_params_set_rate_near = (ma_proc)_snd_pcm_hw_params_set_rate_near;
pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (ma_proc)_snd_pcm_hw_params_set_buffer_size_near;
pContext->alsa.snd_pcm_hw_params_set_periods_near = (ma_proc)_snd_pcm_hw_params_set_periods_near;
pContext->alsa.snd_pcm_hw_params_set_access = (ma_proc)_snd_pcm_hw_params_set_access;
pContext->alsa.snd_pcm_hw_params_get_format = (ma_proc)_snd_pcm_hw_params_get_format;
pContext->alsa.snd_pcm_hw_params_get_channels = (ma_proc)_snd_pcm_hw_params_get_channels;
pContext->alsa.snd_pcm_hw_params_get_channels_min = (ma_proc)_snd_pcm_hw_params_get_channels_min;
pContext->alsa.snd_pcm_hw_params_get_channels_max = (ma_proc)_snd_pcm_hw_params_get_channels_max;
pContext->alsa.snd_pcm_hw_params_get_rate = (ma_proc)_snd_pcm_hw_params_get_rate;
pContext->alsa.snd_pcm_hw_params_get_rate_min = (ma_proc)_snd_pcm_hw_params_get_rate_min;
pContext->alsa.snd_pcm_hw_params_get_rate_max = (ma_proc)_snd_pcm_hw_params_get_rate_max;
pContext->alsa.snd_pcm_hw_params_get_buffer_size = (ma_proc)_snd_pcm_hw_params_get_buffer_size;
pContext->alsa.snd_pcm_hw_params_get_periods = (ma_proc)_snd_pcm_hw_params_get_periods;
pContext->alsa.snd_pcm_hw_params_get_access = (ma_proc)_snd_pcm_hw_params_get_access;
pContext->alsa.snd_pcm_hw_params = (ma_proc)_snd_pcm_hw_params;
pContext->alsa.snd_pcm_sw_params_sizeof = (ma_proc)_snd_pcm_sw_params_sizeof;
pContext->alsa.snd_pcm_sw_params_current = (ma_proc)_snd_pcm_sw_params_current;
pContext->alsa.snd_pcm_sw_params_get_boundary = (ma_proc)_snd_pcm_sw_params_get_boundary;
pContext->alsa.snd_pcm_sw_params_set_avail_min = (ma_proc)_snd_pcm_sw_params_set_avail_min;
pContext->alsa.snd_pcm_sw_params_set_start_threshold = (ma_proc)_snd_pcm_sw_params_set_start_threshold;
pContext->alsa.snd_pcm_sw_params_set_stop_threshold = (ma_proc)_snd_pcm_sw_params_set_stop_threshold;
pContext->alsa.snd_pcm_sw_params = (ma_proc)_snd_pcm_sw_params;
pContext->alsa.snd_pcm_format_mask_sizeof = (ma_proc)_snd_pcm_format_mask_sizeof;
pContext->alsa.snd_pcm_format_mask_test = (ma_proc)_snd_pcm_format_mask_test;
pContext->alsa.snd_pcm_get_chmap = (ma_proc)_snd_pcm_get_chmap;
pContext->alsa.snd_pcm_state = (ma_proc)_snd_pcm_state;
pContext->alsa.snd_pcm_prepare = (ma_proc)_snd_pcm_prepare;
pContext->alsa.snd_pcm_start = (ma_proc)_snd_pcm_start;
pContext->alsa.snd_pcm_drop = (ma_proc)_snd_pcm_drop;
pContext->alsa.snd_pcm_drain = (ma_proc)_snd_pcm_drain;
pContext->alsa.snd_device_name_hint = (ma_proc)_snd_device_name_hint;
pContext->alsa.snd_device_name_get_hint = (ma_proc)_snd_device_name_get_hint;
pContext->alsa.snd_card_get_index = (ma_proc)_snd_card_get_index;
pContext->alsa.snd_device_name_free_hint = (ma_proc)_snd_device_name_free_hint;
pContext->alsa.snd_pcm_mmap_begin = (ma_proc)_snd_pcm_mmap_begin;
pContext->alsa.snd_pcm_mmap_commit = (ma_proc)_snd_pcm_mmap_commit;
pContext->alsa.snd_pcm_recover = (ma_proc)_snd_pcm_recover;
pContext->alsa.snd_pcm_readi = (ma_proc)_snd_pcm_readi;
pContext->alsa.snd_pcm_writei = (ma_proc)_snd_pcm_writei;
pContext->alsa.snd_pcm_avail = (ma_proc)_snd_pcm_avail;
pContext->alsa.snd_pcm_avail_update = (ma_proc)_snd_pcm_avail_update;
pContext->alsa.snd_pcm_wait = (ma_proc)_snd_pcm_wait;
pContext->alsa.snd_pcm_info = (ma_proc)_snd_pcm_info;
pContext->alsa.snd_pcm_info_sizeof = (ma_proc)_snd_pcm_info_sizeof;
pContext->alsa.snd_pcm_info_get_name = (ma_proc)_snd_pcm_info_get_name;
pContext->alsa.snd_config_update_free_global = (ma_proc)_snd_config_update_free_global;
#endif
pContext->alsa.useVerboseDeviceEnumeration = pConfig->alsa.useVerboseDeviceEnumeration;
if (ma_mutex_init(&pContext->alsa.internalDeviceEnumLock) != MA_SUCCESS) {
ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[ALSA] WARNING: Failed to initialize mutex for internal device enumeration.", MA_ERROR);
}
pContext->onUninit = ma_context_uninit__alsa;
pContext->onEnumDevices = ma_context_enumerate_devices__alsa;
pContext->onGetDeviceInfo = ma_context_get_device_info__alsa;
pContext->onDeviceInit = ma_device_init__alsa;
pContext->onDeviceUninit = ma_device_uninit__alsa;
pContext->onDeviceStart = NULL; /* Not used. Started in the main loop. */
pContext->onDeviceStop = NULL; /* Not used. Started in the main loop. */
pContext->onDeviceMainLoop = ma_device_main_loop__alsa;
return MA_SUCCESS;
}
#endif /* ALSA */
/******************************************************************************
PulseAudio Backend
******************************************************************************/
#ifdef MA_HAS_PULSEAUDIO
/*
The PulseAudio API, along with Apple's Core Audio, is the worst of the maintream audio APIs. This is a brief description of what's going on
in the PulseAudio backend. I apologize if this gets a bit ranty for your liking - you might want to skip this discussion.
PulseAudio has something they call the "Simple API", which unfortunately isn't suitable for miniaudio. I've not seen anywhere where it
allows you to enumerate over devices, nor does it seem to support the ability to stop and start streams. Looking at the documentation, it
appears as though the stream is constantly running and you prevent sound from being emitted or captured by simply not calling the read or
write functions. This is not a professional solution as it would be much better to *actually* stop the underlying stream. Perhaps the
simple API has some smarts to do this automatically, but I'm not sure. Another limitation with the simple API is that it seems inefficient
when you want to have multiple streams to a single context. For these reasons, miniaudio is not using the simple API.
Since we're not using the simple API, we're left with the asynchronous API as our only other option. And boy, is this where it starts to
get fun, and I don't mean that in a good way...
The problems start with the very name of the API - "asynchronous". Yes, this is an asynchronous oriented API which means your commands
don't immediately take effect. You instead need to issue your commands, and then wait for them to complete. The waiting mechanism is
enabled through the use of a "main loop". In the asychronous API you cannot get away from the main loop, and the main loop is where almost
all of PulseAudio's problems stem from.
When you first initialize PulseAudio you need an object referred to as "main loop". You can implement this yourself by defining your own
vtable, but it's much easier to just use one of the built-in main loop implementations. There's two generic implementations called
pa_mainloop and pa_threaded_mainloop, and another implementation specific to GLib called pa_glib_mainloop. We're using pa_threaded_mainloop
because it simplifies management of the worker thread. The idea of the main loop object is pretty self explanatory - you're supposed to use
it to implement a worker thread which runs in a loop. The main loop is where operations are actually executed.
To initialize the main loop, you just use `pa_threaded_mainloop_new()`. This is the first function you'll call. You can then get a pointer
to the vtable with `pa_threaded_mainloop_get_api()` (the main loop vtable is called `pa_mainloop_api`). Again, you can bypass the threaded
main loop object entirely and just implement `pa_mainloop_api` directly, but there's no need for it unless you're doing something extremely
specialized such as if you want to integrate it into your application's existing main loop infrastructure.
Once you have your main loop vtable (the `pa_mainloop_api` object) you can create the PulseAudio context. This is very similar to
miniaudio's context and they map to each other quite well. You have one context to many streams, which is basically the same as miniaudio's
one `ma_context` to many `ma_device`s. Here's where it starts to get annoying, however. When you first create the PulseAudio context, which
is done with `pa_context_new()`, it's not actually connected to anything. When you connect, you call `pa_context_connect()`. However, if
you remember, PulseAudio is an asynchronous API. That means you cannot just assume the context is connected after `pa_context_context()`
has returned. You instead need to wait for it to connect. To do this, you need to either wait for a callback to get fired, which you can
set with `pa_context_set_state_callback()`, or you can continuously poll the context's state. Either way, you need to run this in a loop.
All objects from here out are created from the context, and, I believe, you can't be creating these objects until the context is connected.
This waiting loop is therefore unavoidable. In order for the waiting to ever complete, however, the main loop needs to be running. Before
attempting to connect the context, the main loop needs to be started with `pa_threaded_mainloop_start()`.
The reason for this asynchronous design is to support cases where you're connecting to a remote server, say through a local network or an
internet connection. However, the *VAST* majority of cases don't involve this at all - they just connect to a local "server" running on the
host machine. The fact that this would be the default rather than making `pa_context_connect()` synchronous tends to boggle the mind.
Once the context has been created and connected you can start creating a stream. A PulseAudio stream is analogous to miniaudio's device.
The initialization of a stream is fairly standard - you configure some attributes (analogous to miniaudio's device config) and then call
`pa_stream_new()` to actually create it. Here is where we start to get into "operations". When configuring the stream, you can get
information about the source (such as sample format, sample rate, etc.), however it's not synchronous. Instead, a `pa_operation` object
is returned from `pa_context_get_source_info_by_name()` (capture) or `pa_context_get_sink_info_by_name()` (playback). Then, you need to
run a loop (again!) to wait for the operation to complete which you can determine via a callback or polling, just like we did with the
context. Then, as an added bonus, you need to decrement the reference counter of the `pa_operation` object to ensure memory is cleaned up.
All of that just to retrieve basic information about a device!
Once the basic information about the device has been retrieved, miniaudio can now create the stream with `ma_stream_new()`. Like the
context, this needs to be connected. But we need to be careful here, because we're now about to introduce one of the most horrific design
choices in PulseAudio.
PulseAudio allows you to specify a callback that is fired when data can be written to or read from a stream. The language is important here
because PulseAudio takes it literally, specifically the "can be". You would think these callbacks would be appropriate as the place for
writing and reading data to and from the stream, and that would be right, except when it's not. When you initialize the stream, you can
set a flag that tells PulseAudio to not start the stream automatically. This is required because miniaudio does not auto-start devices
straight after initialization - you need to call `ma_device_start()` manually. The problem is that even when this flag is specified,
PulseAudio will immediately fire it's write or read callback. This is *technically* correct (based on the wording in the documentation)
because indeed, data *can* be written at this point. The problem is that it's not *practical*. It makes sense that the write/read callback
would be where a program will want to write or read data to or from the stream, but when it's called before the application has even
requested that the stream be started, it's just not practical because the program probably isn't ready for any kind of data delivery at
that point (it may still need to load files or whatnot). Instead, this callback should only be fired when the application requests the
stream be started which is how it works with literally *every* other callback-based audio API. Since miniaudio forbids firing of the data
callback until the device has been started (as it should be with *all* callback based APIs), logic needs to be added to ensure miniaudio
doesn't just blindly fire the application-defined data callback from within the PulseAudio callback before the stream has actually been
started. The device state is used for this - if the state is anything other than `MA_STATE_STARTING` or `MA_STATE_STARTED`, the main data
callback is not fired.
This, unfortunately, is not the end of the problems with the PulseAudio write callback. Any normal callback based audio API will
continuously fire the callback at regular intervals based on the size of the internal buffer. This will only ever be fired when the device
is running, and will be fired regardless of whether or not the user actually wrote anything to the device/stream. This not the case in
PulseAudio. In PulseAudio, the data callback will *only* be called if you wrote something to it previously. That means, if you don't call
`pa_stream_write()`, the callback will not get fired. On the surface you wouldn't think this would matter because you should be always
writing data, and if you don't have anything to write, just write silence. That's fine until you want to drain the stream. You see, if
you're continuously writing data to the stream, the stream will never get drained! That means in order to drain the stream, you need to
*not* write data to it! But remember, when you don't write data to the stream, the callback won't get fired again! Why is draining
important? Because that's how we've defined stopping to work in miniaudio. In miniaudio, stopping the device requires it to be drained
before returning from ma_device_stop(). So we've stopped the device, which requires us to drain, but draining requires us to *not* write
data to the stream (or else it won't ever complete draining), but not writing to the stream means the callback won't get fired again!
This becomes a problem when stopping and then restarting the device. When the device is stopped, it's drained, which requires us to *not*
write anything to the stream. But then, since we didn't write anything to it, the write callback will *never* get called again if we just
resume the stream naively. This means that starting the stream requires us to write data to the stream from outside the callback. This
disconnect is something PulseAudio has got seriously wrong - there should only ever be a single source of data delivery, that being the
callback. (I have tried using `pa_stream_flush()` to trigger the write callback to fire, but this just doesn't work for some reason.)
Once you've created the stream, you need to connect it which involves the whole waiting procedure. This is the same process as the context,
only this time you'll poll for the state with `pa_stream_get_status()`. The starting and stopping of a streaming is referred to as
"corking" in PulseAudio. The analogy is corking a barrel. To start the stream, you uncork it, to stop it you cork it. Personally I think
it's silly - why would you not just call it "starting" and "stopping" like any other normal audio API? Anyway, the act of corking is, you
guessed it, asynchronous. This means you'll need our waiting loop as usual. Again, why this asynchronous design is the default is
absolutely beyond me. Would it really be that hard to just make it run synchronously?
Teardown is pretty simple (what?!). It's just a matter of calling the relevant `_unref()` function on each object in reverse order that
they were initialized in.
That's about it from the PulseAudio side. A bit ranty, I know, but they really need to fix that main loop and callback system. They're
embarrassingly unpractical. The main loop thing is an easy fix - have synchronous versions of all APIs. If an application wants these to
run asynchronously, they can execute them in a separate thread themselves. The desire to run these asynchronously is such a niche
requirement - it makes no sense to make it the default. The stream write callback needs to be change, or an alternative provided, that is
constantly fired, regardless of whether or not `pa_stream_write()` has been called, and it needs to take a pointer to a buffer as a
parameter which the program just writes to directly rather than having to call `pa_stream_writable_size()` and `pa_stream_write()`. These
changes alone will change PulseAudio from one of the worst audio APIs to one of the best.
*/
/*
It is assumed pulseaudio.h is available when linking at compile time. When linking at compile time, we use the declarations in the header
to check for type safety. We cannot do this when linking at run time because the header might not be available.
*/
#ifdef MA_NO_RUNTIME_LINKING
/* pulseaudio.h marks some functions with "inline" which isn't always supported. Need to emulate it. */
#if !defined(__cplusplus)
#if defined(__STRICT_ANSI__)
#if !defined(inline)
#define inline __inline__ __attribute__((always_inline))
#define MA_INLINE_DEFINED
#endif
#endif
#endif
#include
#if defined(MA_INLINE_DEFINED)
#undef inline
#undef MA_INLINE_DEFINED
#endif
#define MA_PA_OK PA_OK
#define MA_PA_ERR_ACCESS PA_ERR_ACCESS
#define MA_PA_ERR_INVALID PA_ERR_INVALID
#define MA_PA_ERR_NOENTITY PA_ERR_NOENTITY
#define MA_PA_CHANNELS_MAX PA_CHANNELS_MAX
#define MA_PA_RATE_MAX PA_RATE_MAX
typedef pa_context_flags_t ma_pa_context_flags_t;
#define MA_PA_CONTEXT_NOFLAGS PA_CONTEXT_NOFLAGS
#define MA_PA_CONTEXT_NOAUTOSPAWN PA_CONTEXT_NOAUTOSPAWN
#define MA_PA_CONTEXT_NOFAIL PA_CONTEXT_NOFAIL
typedef pa_stream_flags_t ma_pa_stream_flags_t;
#define MA_PA_STREAM_NOFLAGS PA_STREAM_NOFLAGS
#define MA_PA_STREAM_START_CORKED PA_STREAM_START_CORKED
#define MA_PA_STREAM_INTERPOLATE_TIMING PA_STREAM_INTERPOLATE_TIMING
#define MA_PA_STREAM_NOT_MONOTONIC PA_STREAM_NOT_MONOTONIC
#define MA_PA_STREAM_AUTO_TIMING_UPDATE PA_STREAM_AUTO_TIMING_UPDATE
#define MA_PA_STREAM_NO_REMAP_CHANNELS PA_STREAM_NO_REMAP_CHANNELS
#define MA_PA_STREAM_NO_REMIX_CHANNELS PA_STREAM_NO_REMIX_CHANNELS
#define MA_PA_STREAM_FIX_FORMAT PA_STREAM_FIX_FORMAT
#define MA_PA_STREAM_FIX_RATE PA_STREAM_FIX_RATE
#define MA_PA_STREAM_FIX_CHANNELS PA_STREAM_FIX_CHANNELS
#define MA_PA_STREAM_DONT_MOVE PA_STREAM_DONT_MOVE
#define MA_PA_STREAM_VARIABLE_RATE PA_STREAM_VARIABLE_RATE
#define MA_PA_STREAM_PEAK_DETECT PA_STREAM_PEAK_DETECT
#define MA_PA_STREAM_START_MUTED PA_STREAM_START_MUTED
#define MA_PA_STREAM_ADJUST_LATENCY PA_STREAM_ADJUST_LATENCY
#define MA_PA_STREAM_EARLY_REQUESTS PA_STREAM_EARLY_REQUESTS
#define MA_PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND
#define MA_PA_STREAM_START_UNMUTED PA_STREAM_START_UNMUTED
#define MA_PA_STREAM_FAIL_ON_SUSPEND PA_STREAM_FAIL_ON_SUSPEND
#define MA_PA_STREAM_RELATIVE_VOLUME PA_STREAM_RELATIVE_VOLUME
#define MA_PA_STREAM_PASSTHROUGH PA_STREAM_PASSTHROUGH
typedef pa_sink_flags_t ma_pa_sink_flags_t;
#define MA_PA_SINK_NOFLAGS PA_SINK_NOFLAGS
#define MA_PA_SINK_HW_VOLUME_CTRL PA_SINK_HW_VOLUME_CTRL
#define MA_PA_SINK_LATENCY PA_SINK_LATENCY
#define MA_PA_SINK_HARDWARE PA_SINK_HARDWARE
#define MA_PA_SINK_NETWORK PA_SINK_NETWORK
#define MA_PA_SINK_HW_MUTE_CTRL PA_SINK_HW_MUTE_CTRL
#define MA_PA_SINK_DECIBEL_VOLUME PA_SINK_DECIBEL_VOLUME
#define MA_PA_SINK_FLAT_VOLUME PA_SINK_FLAT_VOLUME
#define MA_PA_SINK_DYNAMIC_LATENCY PA_SINK_DYNAMIC_LATENCY
#define MA_PA_SINK_SET_FORMATS PA_SINK_SET_FORMATS
typedef pa_source_flags_t ma_pa_source_flags_t;
#define MA_PA_SOURCE_NOFLAGS PA_SOURCE_NOFLAGS
#define MA_PA_SOURCE_HW_VOLUME_CTRL PA_SOURCE_HW_VOLUME_CTRL
#define MA_PA_SOURCE_LATENCY PA_SOURCE_LATENCY
#define MA_PA_SOURCE_HARDWARE PA_SOURCE_HARDWARE
#define MA_PA_SOURCE_NETWORK PA_SOURCE_NETWORK
#define MA_PA_SOURCE_HW_MUTE_CTRL PA_SOURCE_HW_MUTE_CTRL
#define MA_PA_SOURCE_DECIBEL_VOLUME PA_SOURCE_DECIBEL_VOLUME
#define MA_PA_SOURCE_DYNAMIC_LATENCY PA_SOURCE_DYNAMIC_LATENCY
#define MA_PA_SOURCE_FLAT_VOLUME PA_SOURCE_FLAT_VOLUME
typedef pa_context_state_t ma_pa_context_state_t;
#define MA_PA_CONTEXT_UNCONNECTED PA_CONTEXT_UNCONNECTED
#define MA_PA_CONTEXT_CONNECTING PA_CONTEXT_CONNECTING
#define MA_PA_CONTEXT_AUTHORIZING PA_CONTEXT_AUTHORIZING
#define MA_PA_CONTEXT_SETTING_NAME PA_CONTEXT_SETTING_NAME
#define MA_PA_CONTEXT_READY PA_CONTEXT_READY
#define MA_PA_CONTEXT_FAILED PA_CONTEXT_FAILED
#define MA_PA_CONTEXT_TERMINATED PA_CONTEXT_TERMINATED
typedef pa_stream_state_t ma_pa_stream_state_t;
#define MA_PA_STREAM_UNCONNECTED PA_STREAM_UNCONNECTED
#define MA_PA_STREAM_CREATING PA_STREAM_CREATING
#define MA_PA_STREAM_READY PA_STREAM_READY
#define MA_PA_STREAM_FAILED PA_STREAM_FAILED
#define MA_PA_STREAM_TERMINATED PA_STREAM_TERMINATED
typedef pa_operation_state_t ma_pa_operation_state_t;
#define MA_PA_OPERATION_RUNNING PA_OPERATION_RUNNING
#define MA_PA_OPERATION_DONE PA_OPERATION_DONE
#define MA_PA_OPERATION_CANCELLED PA_OPERATION_CANCELLED
typedef pa_sink_state_t ma_pa_sink_state_t;
#define MA_PA_SINK_INVALID_STATE PA_SINK_INVALID_STATE
#define MA_PA_SINK_RUNNING PA_SINK_RUNNING
#define MA_PA_SINK_IDLE PA_SINK_IDLE
#define MA_PA_SINK_SUSPENDED PA_SINK_SUSPENDED
typedef pa_source_state_t ma_pa_source_state_t;
#define MA_PA_SOURCE_INVALID_STATE PA_SOURCE_INVALID_STATE
#define MA_PA_SOURCE_RUNNING PA_SOURCE_RUNNING
#define MA_PA_SOURCE_IDLE PA_SOURCE_IDLE
#define MA_PA_SOURCE_SUSPENDED PA_SOURCE_SUSPENDED
typedef pa_seek_mode_t ma_pa_seek_mode_t;
#define MA_PA_SEEK_RELATIVE PA_SEEK_RELATIVE
#define MA_PA_SEEK_ABSOLUTE PA_SEEK_ABSOLUTE
#define MA_PA_SEEK_RELATIVE_ON_READ PA_SEEK_RELATIVE_ON_READ
#define MA_PA_SEEK_RELATIVE_END PA_SEEK_RELATIVE_END
typedef pa_channel_position_t ma_pa_channel_position_t;
#define MA_PA_CHANNEL_POSITION_INVALID PA_CHANNEL_POSITION_INVALID
#define MA_PA_CHANNEL_POSITION_MONO PA_CHANNEL_POSITION_MONO
#define MA_PA_CHANNEL_POSITION_FRONT_LEFT PA_CHANNEL_POSITION_FRONT_LEFT
#define MA_PA_CHANNEL_POSITION_FRONT_RIGHT PA_CHANNEL_POSITION_FRONT_RIGHT
#define MA_PA_CHANNEL_POSITION_FRONT_CENTER PA_CHANNEL_POSITION_FRONT_CENTER
#define MA_PA_CHANNEL_POSITION_REAR_CENTER PA_CHANNEL_POSITION_REAR_CENTER
#define MA_PA_CHANNEL_POSITION_REAR_LEFT PA_CHANNEL_POSITION_REAR_LEFT
#define MA_PA_CHANNEL_POSITION_REAR_RIGHT PA_CHANNEL_POSITION_REAR_RIGHT
#define MA_PA_CHANNEL_POSITION_LFE PA_CHANNEL_POSITION_LFE
#define MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER
#define MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER
#define MA_PA_CHANNEL_POSITION_SIDE_LEFT PA_CHANNEL_POSITION_SIDE_LEFT
#define MA_PA_CHANNEL_POSITION_SIDE_RIGHT PA_CHANNEL_POSITION_SIDE_RIGHT
#define MA_PA_CHANNEL_POSITION_AUX0 PA_CHANNEL_POSITION_AUX0
#define MA_PA_CHANNEL_POSITION_AUX1 PA_CHANNEL_POSITION_AUX1
#define MA_PA_CHANNEL_POSITION_AUX2 PA_CHANNEL_POSITION_AUX2
#define MA_PA_CHANNEL_POSITION_AUX3 PA_CHANNEL_POSITION_AUX3
#define MA_PA_CHANNEL_POSITION_AUX4 PA_CHANNEL_POSITION_AUX4
#define MA_PA_CHANNEL_POSITION_AUX5 PA_CHANNEL_POSITION_AUX5
#define MA_PA_CHANNEL_POSITION_AUX6 PA_CHANNEL_POSITION_AUX6
#define MA_PA_CHANNEL_POSITION_AUX7 PA_CHANNEL_POSITION_AUX7
#define MA_PA_CHANNEL_POSITION_AUX8 PA_CHANNEL_POSITION_AUX8
#define MA_PA_CHANNEL_POSITION_AUX9 PA_CHANNEL_POSITION_AUX9
#define MA_PA_CHANNEL_POSITION_AUX10 PA_CHANNEL_POSITION_AUX10
#define MA_PA_CHANNEL_POSITION_AUX11 PA_CHANNEL_POSITION_AUX11
#define MA_PA_CHANNEL_POSITION_AUX12 PA_CHANNEL_POSITION_AUX12
#define MA_PA_CHANNEL_POSITION_AUX13 PA_CHANNEL_POSITION_AUX13
#define MA_PA_CHANNEL_POSITION_AUX14 PA_CHANNEL_POSITION_AUX14
#define MA_PA_CHANNEL_POSITION_AUX15 PA_CHANNEL_POSITION_AUX15
#define MA_PA_CHANNEL_POSITION_AUX16 PA_CHANNEL_POSITION_AUX16
#define MA_PA_CHANNEL_POSITION_AUX17 PA_CHANNEL_POSITION_AUX17
#define MA_PA_CHANNEL_POSITION_AUX18 PA_CHANNEL_POSITION_AUX18
#define MA_PA_CHANNEL_POSITION_AUX19 PA_CHANNEL_POSITION_AUX19
#define MA_PA_CHANNEL_POSITION_AUX20 PA_CHANNEL_POSITION_AUX20
#define MA_PA_CHANNEL_POSITION_AUX21 PA_CHANNEL_POSITION_AUX21
#define MA_PA_CHANNEL_POSITION_AUX22 PA_CHANNEL_POSITION_AUX22
#define MA_PA_CHANNEL_POSITION_AUX23 PA_CHANNEL_POSITION_AUX23
#define MA_PA_CHANNEL_POSITION_AUX24 PA_CHANNEL_POSITION_AUX24
#define MA_PA_CHANNEL_POSITION_AUX25 PA_CHANNEL_POSITION_AUX25
#define MA_PA_CHANNEL_POSITION_AUX26 PA_CHANNEL_POSITION_AUX26
#define MA_PA_CHANNEL_POSITION_AUX27 PA_CHANNEL_POSITION_AUX27
#define MA_PA_CHANNEL_POSITION_AUX28 PA_CHANNEL_POSITION_AUX28
#define MA_PA_CHANNEL_POSITION_AUX29 PA_CHANNEL_POSITION_AUX29
#define MA_PA_CHANNEL_POSITION_AUX30 PA_CHANNEL_POSITION_AUX30
#define MA_PA_CHANNEL_POSITION_AUX31 PA_CHANNEL_POSITION_AUX31
#define MA_PA_CHANNEL_POSITION_TOP_CENTER PA_CHANNEL_POSITION_TOP_CENTER
#define MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT PA_CHANNEL_POSITION_TOP_FRONT_LEFT
#define MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT PA_CHANNEL_POSITION_TOP_FRONT_RIGHT
#define MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER PA_CHANNEL_POSITION_TOP_FRONT_CENTER
#define MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT PA_CHANNEL_POSITION_TOP_REAR_LEFT
#define MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT PA_CHANNEL_POSITION_TOP_REAR_RIGHT
#define MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER PA_CHANNEL_POSITION_TOP_REAR_CENTER
#define MA_PA_CHANNEL_POSITION_LEFT PA_CHANNEL_POSITION_LEFT
#define MA_PA_CHANNEL_POSITION_RIGHT PA_CHANNEL_POSITION_RIGHT
#define MA_PA_CHANNEL_POSITION_CENTER PA_CHANNEL_POSITION_CENTER
#define MA_PA_CHANNEL_POSITION_SUBWOOFER PA_CHANNEL_POSITION_SUBWOOFER
typedef pa_channel_map_def_t ma_pa_channel_map_def_t;
#define MA_PA_CHANNEL_MAP_AIFF PA_CHANNEL_MAP_AIFF
#define MA_PA_CHANNEL_MAP_ALSA PA_CHANNEL_MAP_ALSA
#define MA_PA_CHANNEL_MAP_AUX PA_CHANNEL_MAP_AUX
#define MA_PA_CHANNEL_MAP_WAVEEX PA_CHANNEL_MAP_WAVEEX
#define MA_PA_CHANNEL_MAP_OSS PA_CHANNEL_MAP_OSS
#define MA_PA_CHANNEL_MAP_DEFAULT PA_CHANNEL_MAP_DEFAULT
typedef pa_sample_format_t ma_pa_sample_format_t;
#define MA_PA_SAMPLE_INVALID PA_SAMPLE_INVALID
#define MA_PA_SAMPLE_U8 PA_SAMPLE_U8
#define MA_PA_SAMPLE_ALAW PA_SAMPLE_ALAW
#define MA_PA_SAMPLE_ULAW PA_SAMPLE_ULAW
#define MA_PA_SAMPLE_S16LE PA_SAMPLE_S16LE
#define MA_PA_SAMPLE_S16BE PA_SAMPLE_S16BE
#define MA_PA_SAMPLE_FLOAT32LE PA_SAMPLE_FLOAT32LE
#define MA_PA_SAMPLE_FLOAT32BE PA_SAMPLE_FLOAT32BE
#define MA_PA_SAMPLE_S32LE PA_SAMPLE_S32LE
#define MA_PA_SAMPLE_S32BE PA_SAMPLE_S32BE
#define MA_PA_SAMPLE_S24LE PA_SAMPLE_S24LE
#define MA_PA_SAMPLE_S24BE PA_SAMPLE_S24BE
#define MA_PA_SAMPLE_S24_32LE PA_SAMPLE_S24_32LE
#define MA_PA_SAMPLE_S24_32BE PA_SAMPLE_S24_32BE
typedef pa_mainloop ma_pa_mainloop;
typedef pa_threaded_mainloop ma_pa_threaded_mainloop;
typedef pa_mainloop_api ma_pa_mainloop_api;
typedef pa_context ma_pa_context;
typedef pa_operation ma_pa_operation;
typedef pa_stream ma_pa_stream;
typedef pa_spawn_api ma_pa_spawn_api;
typedef pa_buffer_attr ma_pa_buffer_attr;
typedef pa_channel_map ma_pa_channel_map;
typedef pa_cvolume ma_pa_cvolume;
typedef pa_sample_spec ma_pa_sample_spec;
typedef pa_sink_info ma_pa_sink_info;
typedef pa_source_info ma_pa_source_info;
typedef pa_context_notify_cb_t ma_pa_context_notify_cb_t;
typedef pa_sink_info_cb_t ma_pa_sink_info_cb_t;
typedef pa_source_info_cb_t ma_pa_source_info_cb_t;
typedef pa_stream_success_cb_t ma_pa_stream_success_cb_t;
typedef pa_stream_request_cb_t ma_pa_stream_request_cb_t;
typedef pa_free_cb_t ma_pa_free_cb_t;
#else
#define MA_PA_OK 0
#define MA_PA_ERR_ACCESS 1
#define MA_PA_ERR_INVALID 2
#define MA_PA_ERR_NOENTITY 5
#define MA_PA_CHANNELS_MAX 32
#define MA_PA_RATE_MAX 384000
typedef int ma_pa_context_flags_t;
#define MA_PA_CONTEXT_NOFLAGS 0x00000000
#define MA_PA_CONTEXT_NOAUTOSPAWN 0x00000001
#define MA_PA_CONTEXT_NOFAIL 0x00000002
typedef int ma_pa_stream_flags_t;
#define MA_PA_STREAM_NOFLAGS 0x00000000
#define MA_PA_STREAM_START_CORKED 0x00000001
#define MA_PA_STREAM_INTERPOLATE_TIMING 0x00000002
#define MA_PA_STREAM_NOT_MONOTONIC 0x00000004
#define MA_PA_STREAM_AUTO_TIMING_UPDATE 0x00000008
#define MA_PA_STREAM_NO_REMAP_CHANNELS 0x00000010
#define MA_PA_STREAM_NO_REMIX_CHANNELS 0x00000020
#define MA_PA_STREAM_FIX_FORMAT 0x00000040
#define MA_PA_STREAM_FIX_RATE 0x00000080
#define MA_PA_STREAM_FIX_CHANNELS 0x00000100
#define MA_PA_STREAM_DONT_MOVE 0x00000200
#define MA_PA_STREAM_VARIABLE_RATE 0x00000400
#define MA_PA_STREAM_PEAK_DETECT 0x00000800
#define MA_PA_STREAM_START_MUTED 0x00001000
#define MA_PA_STREAM_ADJUST_LATENCY 0x00002000
#define MA_PA_STREAM_EARLY_REQUESTS 0x00004000
#define MA_PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND 0x00008000
#define MA_PA_STREAM_START_UNMUTED 0x00010000
#define MA_PA_STREAM_FAIL_ON_SUSPEND 0x00020000
#define MA_PA_STREAM_RELATIVE_VOLUME 0x00040000
#define MA_PA_STREAM_PASSTHROUGH 0x00080000
typedef int ma_pa_sink_flags_t;
#define MA_PA_SINK_NOFLAGS 0x00000000
#define MA_PA_SINK_HW_VOLUME_CTRL 0x00000001
#define MA_PA_SINK_LATENCY 0x00000002
#define MA_PA_SINK_HARDWARE 0x00000004
#define MA_PA_SINK_NETWORK 0x00000008
#define MA_PA_SINK_HW_MUTE_CTRL 0x00000010
#define MA_PA_SINK_DECIBEL_VOLUME 0x00000020
#define MA_PA_SINK_FLAT_VOLUME 0x00000040
#define MA_PA_SINK_DYNAMIC_LATENCY 0x00000080
#define MA_PA_SINK_SET_FORMATS 0x00000100
typedef int ma_pa_source_flags_t;
#define MA_PA_SOURCE_NOFLAGS 0x00000000
#define MA_PA_SOURCE_HW_VOLUME_CTRL 0x00000001
#define MA_PA_SOURCE_LATENCY 0x00000002
#define MA_PA_SOURCE_HARDWARE 0x00000004
#define MA_PA_SOURCE_NETWORK 0x00000008
#define MA_PA_SOURCE_HW_MUTE_CTRL 0x00000010
#define MA_PA_SOURCE_DECIBEL_VOLUME 0x00000020
#define MA_PA_SOURCE_DYNAMIC_LATENCY 0x00000040
#define MA_PA_SOURCE_FLAT_VOLUME 0x00000080
typedef int ma_pa_context_state_t;
#define MA_PA_CONTEXT_UNCONNECTED 0
#define MA_PA_CONTEXT_CONNECTING 1
#define MA_PA_CONTEXT_AUTHORIZING 2
#define MA_PA_CONTEXT_SETTING_NAME 3
#define MA_PA_CONTEXT_READY 4
#define MA_PA_CONTEXT_FAILED 5
#define MA_PA_CONTEXT_TERMINATED 6
typedef int ma_pa_stream_state_t;
#define MA_PA_STREAM_UNCONNECTED 0
#define MA_PA_STREAM_CREATING 1
#define MA_PA_STREAM_READY 2
#define MA_PA_STREAM_FAILED 3
#define MA_PA_STREAM_TERMINATED 4
typedef int ma_pa_operation_state_t;
#define MA_PA_OPERATION_RUNNING 0
#define MA_PA_OPERATION_DONE 1
#define MA_PA_OPERATION_CANCELLED 2
typedef int ma_pa_sink_state_t;
#define MA_PA_SINK_INVALID_STATE -1
#define MA_PA_SINK_RUNNING 0
#define MA_PA_SINK_IDLE 1
#define MA_PA_SINK_SUSPENDED 2
typedef int ma_pa_source_state_t;
#define MA_PA_SOURCE_INVALID_STATE -1
#define MA_PA_SOURCE_RUNNING 0
#define MA_PA_SOURCE_IDLE 1
#define MA_PA_SOURCE_SUSPENDED 2
typedef int ma_pa_seek_mode_t;
#define MA_PA_SEEK_RELATIVE 0
#define MA_PA_SEEK_ABSOLUTE 1
#define MA_PA_SEEK_RELATIVE_ON_READ 2
#define MA_PA_SEEK_RELATIVE_END 3
typedef int ma_pa_channel_position_t;
#define MA_PA_CHANNEL_POSITION_INVALID -1
#define MA_PA_CHANNEL_POSITION_MONO 0
#define MA_PA_CHANNEL_POSITION_FRONT_LEFT 1
#define MA_PA_CHANNEL_POSITION_FRONT_RIGHT 2
#define MA_PA_CHANNEL_POSITION_FRONT_CENTER 3
#define MA_PA_CHANNEL_POSITION_REAR_CENTER 4
#define MA_PA_CHANNEL_POSITION_REAR_LEFT 5
#define MA_PA_CHANNEL_POSITION_REAR_RIGHT 6
#define MA_PA_CHANNEL_POSITION_LFE 7
#define MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER 8
#define MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER 9
#define MA_PA_CHANNEL_POSITION_SIDE_LEFT 10
#define MA_PA_CHANNEL_POSITION_SIDE_RIGHT 11
#define MA_PA_CHANNEL_POSITION_AUX0 12
#define MA_PA_CHANNEL_POSITION_AUX1 13
#define MA_PA_CHANNEL_POSITION_AUX2 14
#define MA_PA_CHANNEL_POSITION_AUX3 15
#define MA_PA_CHANNEL_POSITION_AUX4 16
#define MA_PA_CHANNEL_POSITION_AUX5 17
#define MA_PA_CHANNEL_POSITION_AUX6 18
#define MA_PA_CHANNEL_POSITION_AUX7 19
#define MA_PA_CHANNEL_POSITION_AUX8 20
#define MA_PA_CHANNEL_POSITION_AUX9 21
#define MA_PA_CHANNEL_POSITION_AUX10 22
#define MA_PA_CHANNEL_POSITION_AUX11 23
#define MA_PA_CHANNEL_POSITION_AUX12 24
#define MA_PA_CHANNEL_POSITION_AUX13 25
#define MA_PA_CHANNEL_POSITION_AUX14 26
#define MA_PA_CHANNEL_POSITION_AUX15 27
#define MA_PA_CHANNEL_POSITION_AUX16 28
#define MA_PA_CHANNEL_POSITION_AUX17 29
#define MA_PA_CHANNEL_POSITION_AUX18 30
#define MA_PA_CHANNEL_POSITION_AUX19 31
#define MA_PA_CHANNEL_POSITION_AUX20 32
#define MA_PA_CHANNEL_POSITION_AUX21 33
#define MA_PA_CHANNEL_POSITION_AUX22 34
#define MA_PA_CHANNEL_POSITION_AUX23 35
#define MA_PA_CHANNEL_POSITION_AUX24 36
#define MA_PA_CHANNEL_POSITION_AUX25 37
#define MA_PA_CHANNEL_POSITION_AUX26 38
#define MA_PA_CHANNEL_POSITION_AUX27 39
#define MA_PA_CHANNEL_POSITION_AUX28 40
#define MA_PA_CHANNEL_POSITION_AUX29 41
#define MA_PA_CHANNEL_POSITION_AUX30 42
#define MA_PA_CHANNEL_POSITION_AUX31 43
#define MA_PA_CHANNEL_POSITION_TOP_CENTER 44
#define MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT 45
#define MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT 46
#define MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER 47
#define MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT 48
#define MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT 49
#define MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER 50
#define MA_PA_CHANNEL_POSITION_LEFT MA_PA_CHANNEL_POSITION_FRONT_LEFT
#define MA_PA_CHANNEL_POSITION_RIGHT MA_PA_CHANNEL_POSITION_FRONT_RIGHT
#define MA_PA_CHANNEL_POSITION_CENTER MA_PA_CHANNEL_POSITION_FRONT_CENTER
#define MA_PA_CHANNEL_POSITION_SUBWOOFER MA_PA_CHANNEL_POSITION_LFE
typedef int ma_pa_channel_map_def_t;
#define MA_PA_CHANNEL_MAP_AIFF 0
#define MA_PA_CHANNEL_MAP_ALSA 1
#define MA_PA_CHANNEL_MAP_AUX 2
#define MA_PA_CHANNEL_MAP_WAVEEX 3
#define MA_PA_CHANNEL_MAP_OSS 4
#define MA_PA_CHANNEL_MAP_DEFAULT MA_PA_CHANNEL_MAP_AIFF
typedef int ma_pa_sample_format_t;
#define MA_PA_SAMPLE_INVALID -1
#define MA_PA_SAMPLE_U8 0
#define MA_PA_SAMPLE_ALAW 1
#define MA_PA_SAMPLE_ULAW 2
#define MA_PA_SAMPLE_S16LE 3
#define MA_PA_SAMPLE_S16BE 4
#define MA_PA_SAMPLE_FLOAT32LE 5
#define MA_PA_SAMPLE_FLOAT32BE 6
#define MA_PA_SAMPLE_S32LE 7
#define MA_PA_SAMPLE_S32BE 8
#define MA_PA_SAMPLE_S24LE 9
#define MA_PA_SAMPLE_S24BE 10
#define MA_PA_SAMPLE_S24_32LE 11
#define MA_PA_SAMPLE_S24_32BE 12
typedef struct ma_pa_mainloop ma_pa_mainloop;
typedef struct ma_pa_threaded_mainloop ma_pa_threaded_mainloop;
typedef struct ma_pa_mainloop_api ma_pa_mainloop_api;
typedef struct ma_pa_context ma_pa_context;
typedef struct ma_pa_operation ma_pa_operation;
typedef struct ma_pa_stream ma_pa_stream;
typedef struct ma_pa_spawn_api ma_pa_spawn_api;
typedef struct
{
ma_uint32 maxlength;
ma_uint32 tlength;
ma_uint32 prebuf;
ma_uint32 minreq;
ma_uint32 fragsize;
} ma_pa_buffer_attr;
typedef struct
{
ma_uint8 channels;
ma_pa_channel_position_t map[MA_PA_CHANNELS_MAX];
} ma_pa_channel_map;
typedef struct
{
ma_uint8 channels;
ma_uint32 values[MA_PA_CHANNELS_MAX];
} ma_pa_cvolume;
typedef struct
{
ma_pa_sample_format_t format;
ma_uint32 rate;
ma_uint8 channels;
} ma_pa_sample_spec;
typedef struct
{
const char* name;
ma_uint32 index;
const char* description;
ma_pa_sample_spec sample_spec;
ma_pa_channel_map channel_map;
ma_uint32 owner_module;
ma_pa_cvolume volume;
int mute;
ma_uint32 monitor_source;
const char* monitor_source_name;
ma_uint64 latency;
const char* driver;
ma_pa_sink_flags_t flags;
void* proplist;
ma_uint64 configured_latency;
ma_uint32 base_volume;
ma_pa_sink_state_t state;
ma_uint32 n_volume_steps;
ma_uint32 card;
ma_uint32 n_ports;
void** ports;
void* active_port;
ma_uint8 n_formats;
void** formats;
} ma_pa_sink_info;
typedef struct
{
const char *name;
ma_uint32 index;
const char *description;
ma_pa_sample_spec sample_spec;
ma_pa_channel_map channel_map;
ma_uint32 owner_module;
ma_pa_cvolume volume;
int mute;
ma_uint32 monitor_of_sink;
const char *monitor_of_sink_name;
ma_uint64 latency;
const char *driver;
ma_pa_source_flags_t flags;
void* proplist;
ma_uint64 configured_latency;
ma_uint32 base_volume;
ma_pa_source_state_t state;
ma_uint32 n_volume_steps;
ma_uint32 card;
ma_uint32 n_ports;
void** ports;
void* active_port;
ma_uint8 n_formats;
void** formats;
} ma_pa_source_info;
typedef void (* ma_pa_context_notify_cb_t)(ma_pa_context* c, void* userdata);
typedef void (* ma_pa_sink_info_cb_t) (ma_pa_context* c, const ma_pa_sink_info* i, int eol, void* userdata);
typedef void (* ma_pa_source_info_cb_t) (ma_pa_context* c, const ma_pa_source_info* i, int eol, void* userdata);
typedef void (* ma_pa_stream_success_cb_t)(ma_pa_stream* s, int success, void* userdata);
typedef void (* ma_pa_stream_request_cb_t)(ma_pa_stream* s, size_t nbytes, void* userdata);
typedef void (* ma_pa_free_cb_t) (void* p);
#endif
typedef ma_pa_mainloop* (* ma_pa_mainloop_new_proc) (void);
typedef void (* ma_pa_mainloop_free_proc) (ma_pa_mainloop* m);
typedef void (* ma_pa_mainloop_quit_proc) (ma_pa_mainloop* m, int retval);
typedef ma_pa_mainloop_api* (* ma_pa_mainloop_get_api_proc) (ma_pa_mainloop* m);
typedef int (* ma_pa_mainloop_iterate_proc) (ma_pa_mainloop* m, int block, int* retval);
typedef void (* ma_pa_mainloop_wakeup_proc) (ma_pa_mainloop* m);
typedef ma_pa_threaded_mainloop* (* ma_pa_threaded_mainloop_new_proc) (void);
typedef void (* ma_pa_threaded_mainloop_free_proc) (ma_pa_threaded_mainloop* m);
typedef int (* ma_pa_threaded_mainloop_start_proc) (ma_pa_threaded_mainloop* m);
typedef void (* ma_pa_threaded_mainloop_stop_proc) (ma_pa_threaded_mainloop* m);
typedef void (* ma_pa_threaded_mainloop_lock_proc) (ma_pa_threaded_mainloop* m);
typedef void (* ma_pa_threaded_mainloop_unlock_proc) (ma_pa_threaded_mainloop* m);
typedef void (* ma_pa_threaded_mainloop_wait_proc) (ma_pa_threaded_mainloop* m);
typedef void (* ma_pa_threaded_mainloop_signal_proc) (ma_pa_threaded_mainloop* m, int wait_for_accept);
typedef void (* ma_pa_threaded_mainloop_accept_proc) (ma_pa_threaded_mainloop* m);
typedef int (* ma_pa_threaded_mainloop_get_retval_proc) (ma_pa_threaded_mainloop* m);
typedef ma_pa_mainloop_api* (* ma_pa_threaded_mainloop_get_api_proc) (ma_pa_threaded_mainloop* m);
typedef int (* ma_pa_threaded_mainloop_in_thread_proc) (ma_pa_threaded_mainloop* m);
typedef void (* ma_pa_threaded_mainloop_set_name_proc) (ma_pa_threaded_mainloop* m, const char* name);
typedef ma_pa_context* (* ma_pa_context_new_proc) (ma_pa_mainloop_api* mainloop, const char* name);
typedef void (* ma_pa_context_unref_proc) (ma_pa_context* c);
typedef int (* ma_pa_context_connect_proc) (ma_pa_context* c, const char* server, ma_pa_context_flags_t flags, const ma_pa_spawn_api* api);
typedef void (* ma_pa_context_disconnect_proc) (ma_pa_context* c);
typedef void (* ma_pa_context_set_state_callback_proc) (ma_pa_context* c, ma_pa_context_notify_cb_t cb, void* userdata);
typedef ma_pa_context_state_t (* ma_pa_context_get_state_proc) (ma_pa_context* c);
typedef ma_pa_operation* (* ma_pa_context_get_sink_info_list_proc) (ma_pa_context* c, ma_pa_sink_info_cb_t cb, void* userdata);
typedef ma_pa_operation* (* ma_pa_context_get_source_info_list_proc) (ma_pa_context* c, ma_pa_source_info_cb_t cb, void* userdata);
typedef ma_pa_operation* (* ma_pa_context_get_sink_info_by_name_proc) (ma_pa_context* c, const char* name, ma_pa_sink_info_cb_t cb, void* userdata);
typedef ma_pa_operation* (* ma_pa_context_get_source_info_by_name_proc)(ma_pa_context* c, const char* name, ma_pa_source_info_cb_t cb, void* userdata);
typedef void (* ma_pa_operation_unref_proc) (ma_pa_operation* o);
typedef ma_pa_operation_state_t (* ma_pa_operation_get_state_proc) (ma_pa_operation* o);
typedef ma_pa_channel_map* (* ma_pa_channel_map_init_extend_proc) (ma_pa_channel_map* m, unsigned channels, ma_pa_channel_map_def_t def);
typedef int (* ma_pa_channel_map_valid_proc) (const ma_pa_channel_map* m);
typedef int (* ma_pa_channel_map_compatible_proc) (const ma_pa_channel_map* m, const ma_pa_sample_spec* ss);
typedef ma_pa_stream* (* ma_pa_stream_new_proc) (ma_pa_context* c, const char* name, const ma_pa_sample_spec* ss, const ma_pa_channel_map* map);
typedef void (* ma_pa_stream_unref_proc) (ma_pa_stream* s);
typedef int (* ma_pa_stream_connect_playback_proc) (ma_pa_stream* s, const char* dev, const ma_pa_buffer_attr* attr, ma_pa_stream_flags_t flags, const ma_pa_cvolume* volume, ma_pa_stream* sync_stream);
typedef int (* ma_pa_stream_connect_record_proc) (ma_pa_stream* s, const char* dev, const ma_pa_buffer_attr* attr, ma_pa_stream_flags_t flags);
typedef int (* ma_pa_stream_disconnect_proc) (ma_pa_stream* s);
typedef ma_pa_stream_state_t (* ma_pa_stream_get_state_proc) (ma_pa_stream* s);
typedef const ma_pa_sample_spec* (* ma_pa_stream_get_sample_spec_proc) (ma_pa_stream* s);
typedef const ma_pa_channel_map* (* ma_pa_stream_get_channel_map_proc) (ma_pa_stream* s);
typedef const ma_pa_buffer_attr* (* ma_pa_stream_get_buffer_attr_proc) (ma_pa_stream* s);
typedef ma_pa_operation* (* ma_pa_stream_set_buffer_attr_proc) (ma_pa_stream* s, const ma_pa_buffer_attr* attr, ma_pa_stream_success_cb_t cb, void* userdata);
typedef const char* (* ma_pa_stream_get_device_name_proc) (ma_pa_stream* s);
typedef void (* ma_pa_stream_set_write_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata);
typedef void (* ma_pa_stream_set_read_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata);
typedef ma_pa_operation* (* ma_pa_stream_flush_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata);
typedef ma_pa_operation* (* ma_pa_stream_drain_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata);
typedef int (* ma_pa_stream_is_corked_proc) (ma_pa_stream* s);
typedef ma_pa_operation* (* ma_pa_stream_cork_proc) (ma_pa_stream* s, int b, ma_pa_stream_success_cb_t cb, void* userdata);
typedef ma_pa_operation* (* ma_pa_stream_trigger_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata);
typedef int (* ma_pa_stream_begin_write_proc) (ma_pa_stream* s, void** data, size_t* nbytes);
typedef int (* ma_pa_stream_write_proc) (ma_pa_stream* s, const void* data, size_t nbytes, ma_pa_free_cb_t free_cb, int64_t offset, ma_pa_seek_mode_t seek);
typedef int (* ma_pa_stream_peek_proc) (ma_pa_stream* s, const void** data, size_t* nbytes);
typedef int (* ma_pa_stream_drop_proc) (ma_pa_stream* s);
typedef size_t (* ma_pa_stream_writable_size_proc) (ma_pa_stream* s);
typedef size_t (* ma_pa_stream_readable_size_proc) (ma_pa_stream* s);
typedef struct
{
ma_uint32 count;
ma_uint32 capacity;
ma_device_info* pInfo;
} ma_pulse_device_enum_data;
static ma_result ma_result_from_pulse(int result)
{
if (result < 0) {
return MA_ERROR;
}
switch (result) {
case MA_PA_OK: return MA_SUCCESS;
case MA_PA_ERR_ACCESS: return MA_ACCESS_DENIED;
case MA_PA_ERR_INVALID: return MA_INVALID_ARGS;
case MA_PA_ERR_NOENTITY: return MA_NO_DEVICE;
default: return MA_ERROR;
}
}
#if 0
static ma_pa_sample_format_t ma_format_to_pulse(ma_format format)
{
if (ma_is_little_endian()) {
switch (format) {
case ma_format_s16: return MA_PA_SAMPLE_S16LE;
case ma_format_s24: return MA_PA_SAMPLE_S24LE;
case ma_format_s32: return MA_PA_SAMPLE_S32LE;
case ma_format_f32: return MA_PA_SAMPLE_FLOAT32LE;
default: break;
}
} else {
switch (format) {
case ma_format_s16: return MA_PA_SAMPLE_S16BE;
case ma_format_s24: return MA_PA_SAMPLE_S24BE;
case ma_format_s32: return MA_PA_SAMPLE_S32BE;
case ma_format_f32: return MA_PA_SAMPLE_FLOAT32BE;
default: break;
}
}
/* Endian agnostic. */
switch (format) {
case ma_format_u8: return MA_PA_SAMPLE_U8;
default: return MA_PA_SAMPLE_INVALID;
}
}
#endif
static ma_format ma_format_from_pulse(ma_pa_sample_format_t format)
{
if (ma_is_little_endian()) {
switch (format) {
case MA_PA_SAMPLE_S16LE: return ma_format_s16;
case MA_PA_SAMPLE_S24LE: return ma_format_s24;
case MA_PA_SAMPLE_S32LE: return ma_format_s32;
case MA_PA_SAMPLE_FLOAT32LE: return ma_format_f32;
default: break;
}
} else {
switch (format) {
case MA_PA_SAMPLE_S16BE: return ma_format_s16;
case MA_PA_SAMPLE_S24BE: return ma_format_s24;
case MA_PA_SAMPLE_S32BE: return ma_format_s32;
case MA_PA_SAMPLE_FLOAT32BE: return ma_format_f32;
default: break;
}
}
/* Endian agnostic. */
switch (format) {
case MA_PA_SAMPLE_U8: return ma_format_u8;
default: return ma_format_unknown;
}
}
static ma_channel ma_channel_position_from_pulse(ma_pa_channel_position_t position)
{
switch (position)
{
case MA_PA_CHANNEL_POSITION_INVALID: return MA_CHANNEL_NONE;
case MA_PA_CHANNEL_POSITION_MONO: return MA_CHANNEL_MONO;
case MA_PA_CHANNEL_POSITION_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT;
case MA_PA_CHANNEL_POSITION_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT;
case MA_PA_CHANNEL_POSITION_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER;
case MA_PA_CHANNEL_POSITION_REAR_CENTER: return MA_CHANNEL_BACK_CENTER;
case MA_PA_CHANNEL_POSITION_REAR_LEFT: return MA_CHANNEL_BACK_LEFT;
case MA_PA_CHANNEL_POSITION_REAR_RIGHT: return MA_CHANNEL_BACK_RIGHT;
case MA_PA_CHANNEL_POSITION_LFE: return MA_CHANNEL_LFE;
case MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER;
case MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER;
case MA_PA_CHANNEL_POSITION_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT;
case MA_PA_CHANNEL_POSITION_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT;
case MA_PA_CHANNEL_POSITION_AUX0: return MA_CHANNEL_AUX_0;
case MA_PA_CHANNEL_POSITION_AUX1: return MA_CHANNEL_AUX_1;
case MA_PA_CHANNEL_POSITION_AUX2: return MA_CHANNEL_AUX_2;
case MA_PA_CHANNEL_POSITION_AUX3: return MA_CHANNEL_AUX_3;
case MA_PA_CHANNEL_POSITION_AUX4: return MA_CHANNEL_AUX_4;
case MA_PA_CHANNEL_POSITION_AUX5: return MA_CHANNEL_AUX_5;
case MA_PA_CHANNEL_POSITION_AUX6: return MA_CHANNEL_AUX_6;
case MA_PA_CHANNEL_POSITION_AUX7: return MA_CHANNEL_AUX_7;
case MA_PA_CHANNEL_POSITION_AUX8: return MA_CHANNEL_AUX_8;
case MA_PA_CHANNEL_POSITION_AUX9: return MA_CHANNEL_AUX_9;
case MA_PA_CHANNEL_POSITION_AUX10: return MA_CHANNEL_AUX_10;
case MA_PA_CHANNEL_POSITION_AUX11: return MA_CHANNEL_AUX_11;
case MA_PA_CHANNEL_POSITION_AUX12: return MA_CHANNEL_AUX_12;
case MA_PA_CHANNEL_POSITION_AUX13: return MA_CHANNEL_AUX_13;
case MA_PA_CHANNEL_POSITION_AUX14: return MA_CHANNEL_AUX_14;
case MA_PA_CHANNEL_POSITION_AUX15: return MA_CHANNEL_AUX_15;
case MA_PA_CHANNEL_POSITION_AUX16: return MA_CHANNEL_AUX_16;
case MA_PA_CHANNEL_POSITION_AUX17: return MA_CHANNEL_AUX_17;
case MA_PA_CHANNEL_POSITION_AUX18: return MA_CHANNEL_AUX_18;
case MA_PA_CHANNEL_POSITION_AUX19: return MA_CHANNEL_AUX_19;
case MA_PA_CHANNEL_POSITION_AUX20: return MA_CHANNEL_AUX_20;
case MA_PA_CHANNEL_POSITION_AUX21: return MA_CHANNEL_AUX_21;
case MA_PA_CHANNEL_POSITION_AUX22: return MA_CHANNEL_AUX_22;
case MA_PA_CHANNEL_POSITION_AUX23: return MA_CHANNEL_AUX_23;
case MA_PA_CHANNEL_POSITION_AUX24: return MA_CHANNEL_AUX_24;
case MA_PA_CHANNEL_POSITION_AUX25: return MA_CHANNEL_AUX_25;
case MA_PA_CHANNEL_POSITION_AUX26: return MA_CHANNEL_AUX_26;
case MA_PA_CHANNEL_POSITION_AUX27: return MA_CHANNEL_AUX_27;
case MA_PA_CHANNEL_POSITION_AUX28: return MA_CHANNEL_AUX_28;
case MA_PA_CHANNEL_POSITION_AUX29: return MA_CHANNEL_AUX_29;
case MA_PA_CHANNEL_POSITION_AUX30: return MA_CHANNEL_AUX_30;
case MA_PA_CHANNEL_POSITION_AUX31: return MA_CHANNEL_AUX_31;
case MA_PA_CHANNEL_POSITION_TOP_CENTER: return MA_CHANNEL_TOP_CENTER;
case MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT;
case MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT;
case MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER;
case MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT: return MA_CHANNEL_TOP_BACK_LEFT;
case MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT;
case MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER: return MA_CHANNEL_TOP_BACK_CENTER;
default: return MA_CHANNEL_NONE;
}
}
#if 0
static ma_pa_channel_position_t ma_channel_position_to_pulse(ma_channel position)
{
switch (position)
{
case MA_CHANNEL_NONE: return MA_PA_CHANNEL_POSITION_INVALID;
case MA_CHANNEL_FRONT_LEFT: return MA_PA_CHANNEL_POSITION_FRONT_LEFT;
case MA_CHANNEL_FRONT_RIGHT: return MA_PA_CHANNEL_POSITION_FRONT_RIGHT;
case MA_CHANNEL_FRONT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_CENTER;
case MA_CHANNEL_LFE: return MA_PA_CHANNEL_POSITION_LFE;
case MA_CHANNEL_BACK_LEFT: return MA_PA_CHANNEL_POSITION_REAR_LEFT;
case MA_CHANNEL_BACK_RIGHT: return MA_PA_CHANNEL_POSITION_REAR_RIGHT;
case MA_CHANNEL_FRONT_LEFT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER;
case MA_CHANNEL_FRONT_RIGHT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;
case MA_CHANNEL_BACK_CENTER: return MA_PA_CHANNEL_POSITION_REAR_CENTER;
case MA_CHANNEL_SIDE_LEFT: return MA_PA_CHANNEL_POSITION_SIDE_LEFT;
case MA_CHANNEL_SIDE_RIGHT: return MA_PA_CHANNEL_POSITION_SIDE_RIGHT;
case MA_CHANNEL_TOP_CENTER: return MA_PA_CHANNEL_POSITION_TOP_CENTER;
case MA_CHANNEL_TOP_FRONT_LEFT: return MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT;
case MA_CHANNEL_TOP_FRONT_CENTER: return MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER;
case MA_CHANNEL_TOP_FRONT_RIGHT: return MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT;
case MA_CHANNEL_TOP_BACK_LEFT: return MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT;
case MA_CHANNEL_TOP_BACK_CENTER: return MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER;
case MA_CHANNEL_TOP_BACK_RIGHT: return MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT;
case MA_CHANNEL_19: return MA_PA_CHANNEL_POSITION_AUX18;
case MA_CHANNEL_20: return MA_PA_CHANNEL_POSITION_AUX19;
case MA_CHANNEL_21: return MA_PA_CHANNEL_POSITION_AUX20;
case MA_CHANNEL_22: return MA_PA_CHANNEL_POSITION_AUX21;
case MA_CHANNEL_23: return MA_PA_CHANNEL_POSITION_AUX22;
case MA_CHANNEL_24: return MA_PA_CHANNEL_POSITION_AUX23;
case MA_CHANNEL_25: return MA_PA_CHANNEL_POSITION_AUX24;
case MA_CHANNEL_26: return MA_PA_CHANNEL_POSITION_AUX25;
case MA_CHANNEL_27: return MA_PA_CHANNEL_POSITION_AUX26;
case MA_CHANNEL_28: return MA_PA_CHANNEL_POSITION_AUX27;
case MA_CHANNEL_29: return MA_PA_CHANNEL_POSITION_AUX28;
case MA_CHANNEL_30: return MA_PA_CHANNEL_POSITION_AUX29;
case MA_CHANNEL_31: return MA_PA_CHANNEL_POSITION_AUX30;
case MA_CHANNEL_32: return MA_PA_CHANNEL_POSITION_AUX31;
default: return (ma_pa_channel_position_t)position;
}
}
#endif
static void ma_mainloop_lock__pulse(ma_context* pContext, const char* what)
{
(void)what;
MA_ASSERT(pContext != NULL);
/*printf("locking mainloop by %s\n", what);*/
((ma_pa_threaded_mainloop_lock_proc)pContext->pulse.pa_threaded_mainloop_lock)((ma_pa_threaded_mainloop*)pContext->pulse.pMainLoop);
}
static void ma_mainloop_unlock__pulse(ma_context* pContext, const char* what)
{
(void)what;
MA_ASSERT(pContext != NULL);
/*printf("unlocking mainloop by %s\n", what);*/
((ma_pa_threaded_mainloop_unlock_proc)pContext->pulse.pa_threaded_mainloop_unlock)((ma_pa_threaded_mainloop*)pContext->pulse.pMainLoop);
}
static ma_result ma_wait_for_operation__pulse(ma_context* pContext, ma_pa_operation* pOP)
{
ma_pa_operation_state_t state;
MA_ASSERT(pContext != NULL);
MA_ASSERT(pOP != NULL);
for (;;) {
ma_mainloop_lock__pulse(pContext, "ma_wait_for_operation__pulse");
state = ((ma_pa_operation_get_state_proc)pContext->pulse.pa_operation_get_state)(pOP);
ma_mainloop_unlock__pulse(pContext, "ma_wait_for_operation__pulse");
if (state != MA_PA_OPERATION_RUNNING) {
break; /* Done. */
}
ma_yield();
}
return MA_SUCCESS;
}
static ma_result ma_wait_for_operation_and_unref__pulse(ma_context* pContext, ma_pa_operation* pOP)
{
ma_result result;
if (pOP == NULL) {
return MA_INVALID_ARGS;
}
result = ma_wait_for_operation__pulse(pContext, pOP);
((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
return result;
}
static ma_result ma_context_wait_for_pa_context_to_connect__pulse(ma_context* pContext)
{
ma_pa_context_state_t state;
for (;;) {
ma_mainloop_lock__pulse(pContext, "ma_context_wait_for_pa_context_to_connect__pulse");
state = ((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)((ma_pa_context*)pContext->pulse.pPulseContext);
ma_mainloop_unlock__pulse(pContext, "ma_context_wait_for_pa_context_to_connect__pulse");
if (state == MA_PA_CONTEXT_READY) {
break; /* Done. */
}
if (state == MA_PA_CONTEXT_FAILED || state == MA_PA_CONTEXT_TERMINATED) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio context.", MA_ERROR);
}
ma_yield();
}
/* Should never get here. */
return MA_SUCCESS;
}
static ma_result ma_context_wait_for_pa_stream_to_connect__pulse(ma_context* pContext, ma_pa_stream* pStream)
{
ma_pa_stream_state_t state;
for (;;) {
ma_mainloop_lock__pulse(pContext, "ma_context_wait_for_pa_stream_to_connect__pulse");
state = ((ma_pa_stream_get_state_proc)pContext->pulse.pa_stream_get_state)(pStream);
ma_mainloop_unlock__pulse(pContext, "ma_context_wait_for_pa_stream_to_connect__pulse");
if (state == MA_PA_STREAM_READY) {
break; /* Done. */
}
if (state == MA_PA_STREAM_FAILED || state == MA_PA_STREAM_TERMINATED) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio stream.", MA_ERROR);
}
ma_yield();
}
return MA_SUCCESS;
}
static void ma_device_sink_info_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData)
{
ma_pa_sink_info* pInfoOut;
if (endOfList > 0) {
return;
}
pInfoOut = (ma_pa_sink_info*)pUserData;
MA_ASSERT(pInfoOut != NULL);
*pInfoOut = *pInfo;
(void)pPulseContext; /* Unused. */
}
static void ma_device_source_info_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData)
{
ma_pa_source_info* pInfoOut;
if (endOfList > 0) {
return;
}
pInfoOut = (ma_pa_source_info*)pUserData;
MA_ASSERT(pInfoOut != NULL);
*pInfoOut = *pInfo;
(void)pPulseContext; /* Unused. */
}
static void ma_device_sink_name_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData)
{
ma_device* pDevice;
if (endOfList > 0) {
return;
}
pDevice = (ma_device*)pUserData;
MA_ASSERT(pDevice != NULL);
ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), pInfo->description, (size_t)-1);
(void)pPulseContext; /* Unused. */
}
static void ma_device_source_name_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData)
{
ma_device* pDevice;
if (endOfList > 0) {
return;
}
pDevice = (ma_device*)pUserData;
MA_ASSERT(pDevice != NULL);
ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), pInfo->description, (size_t)-1);
(void)pPulseContext; /* Unused. */
}
static ma_result ma_context_get_sink_info__pulse(ma_context* pContext, const char* pDeviceName, ma_pa_sink_info* pSinkInfo)
{
ma_pa_operation* pOP;
ma_mainloop_lock__pulse(pContext, "ma_context_get_sin