Files
miniaudio/examples/custom_backend.c
T
David Reid 8890eac6aa One Big Beautiful Commit with refactoring to the device backend system.
This includes API changes that affect custom backends.

`ma_backend_callbacks` has been renamed to `ma_device_backend_vtable`.
The reason for this change is to to be consistent with the naming
convention used in other parts of the library. In addition, using the
term "device backend" rather than just "backend" removes ambiguity with
decoding backends.

A change has been made to the way backends manage their internal state,
and some functions in the vtable have been updated to reflect this.
Previously internal state for stock backends were located directly in
the `ma_device` structure. This works fine if stock backends are the
only backends to be concerned about, but it falls apart when you need
to consider how to manage the internal state of custom backends since
they cannot modify the `ma_device` structure. In order to simplify and
unify state management between stock and custom backends, the decision
was made to change the backend system such that backends now manage
their own internal state.

When the context is initialized with `onContextInit`, the backend must
now allocate an internal state object and output a pointer to it via
an output parameter. Typically you would do something like this:

    ma_result custom_context_init(..., void** ppContextState)
    {
        ctx_state_t* state = malloc(...);

        ...

        *ppContextState = state;
        return MA_SUCCESS;
    }

miniaudio will store a pointer to the state object internally. When you
need to access this later in other backend callbacks, you can retrieve
it straight from the context with `ma_context_get_backend_state()`:

    state = (ctx_state_t*)ma_context_get_backend_state(pContext);

The same idea applies to devices and `onDeviceInit`. You can use
`ma_device_get_backend_state()` to get a pointer to the internal state
object.

When a context and device is initialized, backend-specific
configurations can be supplied. The way these configs are provided to
`onContextInit` and `onDeviceInit` has been changed. Previously, these
callbacks would take a `ma_context/device_config` object. These have
been replaced with a `const void*` which points to a backend-specific
config object which is defined by the backend. All stock backends have
their own backend-specific config object:

    struct ma_context_config_wasapi
    struct ma_context_config_pulseaudio
    etc.

    struct ma_device_config_wasapi
    struct ma_device_config_pulseaudio
    etc.

You can cast the config object inside the relevant callbacks:

    ma_result custom_context_init(..., const void* pBackendConfig, ...)
    {
        ctx_config_t* pCustomConfig = (ctx_config_t*)pBackendConfig;
    }

The backend itself defines whether or not a config is required. None of
the stock backends require a config. If the config is NULL, it'll use
defaults. It's recommended custom backends follow this convention.

In addition to the above, `onContextUninit` and `onDeviceUninit` have
been updated to return void instead of `ma_result`.

The last change to the backend vtable is a new callback called
`onBackendInfo`. This is used to fill the `ma_device_backend_info`
structure.

In addition to the backend vtable, some changes have been made to the
public API to make it much easier to support plugging in custom
backends.

Previously, plugging in more than one custom backend was a complete
mess. It was possible, but you had to use a stupid wrapper thing to
make it work, and you had no control over prioritization. The entire
thing was just aweful, so it's now been stripped out and replaced with
a brand new system.

When a context or device is initialized, it is done so with a config
which is standard across the entire library. A complication to this is
that backends can sometimes require their own backend-specific configs.
But since miniaudio cannot possibly know about custom backends, it
cannot put their config options inside `ma_context/device_config`. The
functions for initializing a context and device have been updated to
allow plugging in backend-specific configs.

When initializing a context, instead of passing in an array of
`ma_backend` enums, an array of `ma_device_backend_config` objects is
passed in instead. This object has two members: A pointer to a backend
vtable, and a pointer to a config object. It can be initialized
something like this:

    ma_context_config_custom customContextConfig;
    ... initialize the custom backend config if necessary ...

    ma_device_backend_config backends[] =
    {
        { ma_device_backend_custom,     &customContextConfig },
        { ma_device_backend_wasapi,     NULL },
        { ma_device_backend_pulseaudio, NULL }
    };

    ma_context_init(backends, backendCount, ...);

Here `ma_device_backend_custom` is our custom backend. You can see how
the config is mapped to the backend. For stock backends (WASAPI and
PulseAudio in this example), you can pass in NULL and just set the
relevant config options straight in `ma_context_config` exactly how it
was done before:

    ma_context_config contextConfig = ma_context_config_init();
    contextConfig.pulseaudio.pApplicationName = "My App";

Here we are just using the standard `ma_context_config` object for
configuring the stock PulseAudio backend. This is possible for all
stock backends, but for custom backends an explicit config object will
be required. You can still use a separate explicit config object for
stock backends if you prefer that style:

    ma_context_config_pulseaudio paContextConfig;
    paContextConfig = ma_context_config_pulseaudio_init();
    paContextConfig.pApplicationName = "My App";

    ma_device_backend_config backends[] =
    {
        { ma_device_backend_pulseaudio, &paContextConfig }
    };

Note that if you do not use custom backends, you can still pass in NULL
for the backends in which case defaults will be used like how it's
always worked in the past.

As with contexts, devices can also have their own backend-specific
configs associated with them. These work exactly the same way, except
these configs are passed into the main `ma_device_config` object. (A
future commit may make this consistent between contexts and devices).

    ma_device_backend_config deviceBackendConfigs[] =
    {
        { ma_device_backend_custom, &customDeviceConfig }
    };

    deviceConfig.pBackendConfigs    = deviceBackendConfigs;
    deviceConfig.backendConfigCount = backendCount;

    ma_device_init(&deviceConfig, &device);

This commit is just the start of many backend related changes. Future
commits will be cleaning up a lot of residual code from the old system,
such as removing `ma_backend`.
2025-07-14 18:05:55 +10:00

150 lines
5.4 KiB
C

/*
This example shows how to plug in custom backends.
To use a custom backend you need to plug in a `ma_device_backend_vtable` pointer into the context config. You can plug in multiple
custom backends, but for this example we're just using the SDL backend which you can find in the extras folder in the miniaudio
repository. If your custom backend requires it, you can also plug in a user data pointer which will be passed to the backend callbacks.
Custom backends are identified with the `ma_backend_custom` backend type. For the purpose of demonstration, this example only uses the
`ma_backend_custom` backend type because otherwise the built-in backends would always get chosen first and none of the code for the custom
backends would actually get hit. By default, the `ma_backend_custom` backend is the second-lowest priority backend, sitting just above
`ma_backend_null`.
*/
#include "../miniaudio.c"
/* We're using SDL for this example. To use this in your own program, you need to include backend_sdl.h after miniaudio.h. */
#include "../extras/backends/sdl/backend_sdl.h"
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
void main_loop__em()
{
}
#endif
/*
Main program starts here.
*/
#define DEVICE_FORMAT ma_format_f32
#define DEVICE_CHANNELS 2
#define DEVICE_SAMPLE_RATE 48000
void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
{
if (pDevice->type == ma_device_type_playback) {
ma_waveform_read_pcm_frames((ma_waveform*)pDevice->pUserData, pOutput, frameCount, NULL);
}
if (pDevice->type == ma_device_type_duplex) {
ma_copy_pcm_frames(pOutput, pInput, frameCount, pDevice->playback.format, pDevice->playback.channels);
}
}
int main(int argc, char** argv)
{
ma_result result;
ma_context context;
ma_device_config deviceConfig;
ma_device device;
ma_waveform_config sineWaveConfig;
ma_waveform sineWave;
char name[256];
/*
Here is where we would set up the SDL-specific context-level config. The custom SDL backend allows this to be null, but we're
defining it here just for the sake of demonstration. Whether or not this is required depends on the backend. If you're not sure,
check the documentation for the backend.
*/
ma_context_config_sdl sdlContextConfig = ma_context_config_sdl_init();
sdlContextConfig._unused = 0;
/*
You must include an entry for each backend you're using, even if the config is NULL. This is how miniaudio knows about
your custom backend.
For stock backends, you can just leave the config pointer as NULL and fill out any backend-specific config options in
the ma_context_config structure. Same with device configs.
*/
ma_device_backend_config backends[] =
{
{ ma_device_backend_sdl, &sdlContextConfig },
{ ma_device_backend_wasapi, NULL },
{ ma_device_backend_pulseaudio, NULL }
};
result = ma_context_init(backends, sizeof(backends)/sizeof(backends[0]), NULL, &context);
if (result != MA_SUCCESS) {
return -1;
}
/* In playback mode we're just going to play a sine wave. */
sineWaveConfig = ma_waveform_config_init(DEVICE_FORMAT, DEVICE_CHANNELS, DEVICE_SAMPLE_RATE, ma_waveform_type_sine, 0.2, 220);
ma_waveform_init(&sineWaveConfig, &sineWave);
/*
Just like with context configs, we can define some device-level configs as well. It works the same way, except you will pass in
a backend-specific device-level config. If the backend doesn't require a device-level config, you can set this to NULL.
*/
ma_device_config_sdl sdlDeviceConfig = ma_device_config_sdl_init();
sdlDeviceConfig._unused = 0;
/*
Unlike with contexts, if your backend does not require a device-level config, you can just leave it out of this list entirely.
*/
ma_device_backend_config pBackendDeviceConfigs[] =
{
{ ma_device_backend_sdl, &sdlDeviceConfig },
{ ma_device_backend_wasapi, NULL },
{ ma_device_backend_pulseaudio, NULL }
};
deviceConfig = ma_device_config_init(ma_device_type_playback);
deviceConfig.playback.format = DEVICE_FORMAT;
deviceConfig.playback.channels = DEVICE_CHANNELS;
deviceConfig.capture.format = DEVICE_FORMAT;
deviceConfig.capture.channels = DEVICE_CHANNELS;
deviceConfig.sampleRate = DEVICE_SAMPLE_RATE;
deviceConfig.dataCallback = data_callback;
deviceConfig.pUserData = &sineWave;
deviceConfig.pBackendConfigs = pBackendDeviceConfigs;
deviceConfig.backendConfigCount = sizeof(pBackendDeviceConfigs) / sizeof(pBackendDeviceConfigs[0]);
result = ma_device_init(&context, &deviceConfig, &device);
if (result != MA_SUCCESS) {
ma_context_uninit(&context);
return -1;
}
ma_device_get_name(&device, ma_device_type_playback, name, sizeof(name), NULL);
printf("Device Name: %s\n", name);
if (ma_device_start(&device) != MA_SUCCESS) {
ma_device_uninit(&device);
ma_context_uninit(&context);
return -5;
}
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(main_loop__em, 0, 1);
#else
printf("Press Enter to quit...\n");
getchar();
#endif
ma_device_uninit(&device);
ma_context_uninit(&context);
(void)argc;
(void)argv;
return 0;
}
/* We put the SDL implementation here just to simplify the compilation process. This way you need only compile custom_backend.c. */
#include "../extras/backends/sdl/backend_sdl.c"