view release on metacpan or search on metacpan
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
/*
Audio playback and capture library. Choice of public domain or MIT-0. See license statements at the end of this file.
miniaudio - v0.10.21 - 2020-10-30
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:
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
// 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:
```
<key>com.apple.security.cs.allow-dyld-environment-variables</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
```
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+.
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. |
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
+----------------------+----------------------------------------------------------------------------------------------------------------------------------+
| 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_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. Defaults to `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. 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 <br> |
| | 1: MA_CHANNEL_FRONT_RIGHT |
+---------------+---------------------------------+
| 3 | 0: MA_CHANNEL_FRONT_LEFT <br> |
| | 1: MA_CHANNEL_FRONT_RIGHT <br> |
| | 2: MA_CHANNEL_FRONT_CENTER |
+---------------+---------------------------------+
| 4 (Surround) | 0: MA_CHANNEL_FRONT_LEFT <br> |
| | 1: MA_CHANNEL_FRONT_RIGHT <br> |
| | 2: MA_CHANNEL_FRONT_CENTER <br> |
| | 3: MA_CHANNEL_BACK_CENTER |
+---------------+---------------------------------+
| 5 | 0: MA_CHANNEL_FRONT_LEFT <br> |
| | 1: MA_CHANNEL_FRONT_RIGHT <br> |
| | 2: MA_CHANNEL_FRONT_CENTER <br> |
| | 3: MA_CHANNEL_BACK_LEFT <br> |
| | 4: MA_CHANNEL_BACK_RIGHT |
+---------------+---------------------------------+
| 6 (5.1) | 0: MA_CHANNEL_FRONT_LEFT <br> |
| | 1: MA_CHANNEL_FRONT_RIGHT <br> |
| | 2: MA_CHANNEL_FRONT_CENTER <br> |
| | 3: MA_CHANNEL_LFE <br> |
| | 4: MA_CHANNEL_SIDE_LEFT <br> |
| | 5: MA_CHANNEL_SIDE_RIGHT |
+---------------+---------------------------------+
| 7 | 0: MA_CHANNEL_FRONT_LEFT <br> |
| | 1: MA_CHANNEL_FRONT_RIGHT <br> |
| | 2: MA_CHANNEL_FRONT_CENTER <br> |
| | 3: MA_CHANNEL_LFE <br> |
| | 4: MA_CHANNEL_BACK_CENTER <br> |
| | 4: MA_CHANNEL_SIDE_LEFT <br> |
| | 5: MA_CHANNEL_SIDE_RIGHT |
+---------------+---------------------------------+
| 8 (7.1) | 0: MA_CHANNEL_FRONT_LEFT <br> |
| | 1: MA_CHANNEL_FRONT_RIGHT <br> |
| | 2: MA_CHANNEL_FRONT_CENTER <br> |
| | 3: MA_CHANNEL_LFE <br> |
| | 4: MA_CHANNEL_BACK_LEFT <br> |
| | 5: MA_CHANNEL_BACK_RIGHT <br> |
| | 6: MA_CHANNEL_SIDE_LEFT <br> |
| | 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:
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
+----------+------------------------------------------+
| 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 and sample rate can be changed dynamically with `ma_waveform_set_amplitude()`, `ma_waveform_set_frequency()` 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.
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.
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) |
| 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: `<uses-permission android:name="android.permission.RECORD_AUDIO" />`
- 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):
```
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
#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(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(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(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(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(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(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(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(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(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(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(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(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(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(ma_linear_resampler* pResampler, ma_uint64 outputFrameCount);
MA_API ma_uint64 ma_linear_resampler_get_expected_output_frame_count(ma_linear_resampler* pResampler, ma_uint64 inputFrameCount);
MA_API ma_uint64 ma_linear_resampler_get_input_latency(ma_linear_resampler* pResampler);
MA_API ma_uint64 ma_linear_resampler_get_output_latency(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(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(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(ma_resampler* pResampler);
/*
Retrieves the latency introduced by the resampler in output frames.
*/
MA_API ma_uint64 ma_resampler_get_output_latency(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_bool32 isPassthrough : 1;
ma_bool32 isSimpleShuffle : 1;
ma_bool32 isSimpleMonoExpansion : 1;
ma_bool32 isStereoToMono : 1;
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_bool32 hasPreFormatConversion : 1;
ma_bool32 hasPostFormatConversion : 1;
ma_bool32 hasChannelConverter : 1;
ma_bool32 hasResampler : 1;
ma_bool32 isPassthrough : 1;
} 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(ma_data_converter* pConverter, ma_uint64 outputFrameCount);
MA_API ma_uint64 ma_data_converter_get_expected_output_frame_count(ma_data_converter* pConverter, ma_uint64 inputFrameCount);
MA_API ma_uint64 ma_data_converter_get_input_latency(ma_data_converter* pConverter);
MA_API ma_uint64 ma_data_converter_get_output_latency(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
************************************************************************************************************************************************************/
/*
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;
volatile ma_uint32 encodedReadOffset; /* Most significant bit is the loop flag. Lower 31 bits contains the actual offset in bytes. */
volatile ma_uint32 encodedWriteOffset; /* Most significant bit is the loop flag. Lower 31 bits contains the actual offset in bytes. */
ma_bool32 ownsBuffer : 1; /* Used to know whether or not miniaudio is responsible for free()-ing the buffer. */
ma_bool32 clearOnWriteAcquire : 1; /* 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 hi...
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* pAllocationCallba...
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);
/************************************************************************************************************************************************************
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
/* Explicitly disable the Null backend for Emscripten because it uses a background thread which is not properly supported right now. */
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
#define MA_ENABLE_COREAUDIO
#endif
#if !defined(MA_NO_SNDIO) && defined(MA_SUPPORT_SNDIO)
#define MA_ENABLE_SNDIO
#endif
#if !defined(MA_NO_AUDIO4) && defined(MA_SUPPORT_AUDIO4)
#define MA_ENABLE_AUDIO4
#endif
#if !defined(MA_NO_OSS) && defined(MA_SUPPORT_OSS)
#define MA_ENABLE_OSS
#endif
#if !defined(MA_NO_AAUDIO) && defined(MA_SUPPORT_AAUDIO)
#define MA_ENABLE_AAUDIO
#endif
#if !defined(MA_NO_OPENSL) && defined(MA_SUPPORT_OPENSL)
#define MA_ENABLE_OPENSL
#endif
#if !defined(MA_NO_WEBAUDIO) && defined(MA_SUPPORT_WEBAUDIO)
#define MA_ENABLE_WEBAUDIO
#endif
#if !defined(MA_NO_NULL) && defined(MA_SUPPORT_NULL)
#define MA_ENABLE_NULL
#endif
#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_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
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
ma_format internalFormat;
ma_uint32 internalChannels;
ma_uint32 internalSampleRate;
ma_channel internalChannelMap[MA_MAX_CHANNELS];
ma_uint32 internalPeriodSizeInFrames;
ma_uint32 internalPeriods;
ma_data_converter converter;
} 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_bool32 hasDefaultPlaybackDeviceChanged; /* <-- Make sure this is always a whole 32-bits because we use atomic assignments. */
ma_bool32 hasDefaultCaptureDeviceChanged; /* <-- Make sure this is always a whole 32-bits because we use atomic assignments. */
ma_uint32 periodSizeInFramesPlayback;
ma_uint32 periodSizeInFramesCapture;
ma_bool32 isStartedCapture; /* <-- Make sure this is always a whole 32-bits because we use atomic assignments. */
ma_bool32 isStartedPlayback; /* <-- Make sure this is always a whole 32-bits because we use atomic assignments. */
ma_bool32 noAutoConvertSRC : 1; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */
ma_bool32 noDefaultQualitySRC : 1; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */
ma_bool32 noHardwareOffloading : 1;
ma_bool32 allowCaptureAutoStreamRouting : 1;
ma_bool32 allowPlaybackAutoStreamRouting : 1;
} 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_bool32 isUsingMMapPlayback : 1;
ma_bool32 isUsingMMapCapture : 1;
} alsa;
#endif
#ifdef MA_SUPPORT_PULSEAUDIO
struct
{
/*pa_mainloop**/ ma_ptr pMainLoop;
/*pa_mainloop_api**/ ma_ptr pAPI;
/*pa_context**/ ma_ptr pPulseContext;
/*pa_stream**/ ma_ptr pStreamPlayback;
/*pa_stream**/ ma_ptr pStreamCapture;
/*pa_context_state*/ ma_uint32 pulseContextState;
void* pMappedBufferPlayback;
const void* pMappedBufferCapture;
ma_uint32 mappedBufferFramesRemainingPlayback;
ma_uint32 mappedBufferFramesRemainingCapture;
ma_uint32 mappedBufferFramesCapacityPlayback;
ma_uint32 mappedBufferFramesCapacityCapture;
ma_bool32 breakFromMainLoop : 1;
} 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;
ma_pcm_rb duplexRB;
} 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_event stopEvent;
ma_uint32 originalPeriodSizeInFrames;
ma_uint32 originalPeriodSizeInMilliseconds;
ma_uint32 originalPeriods;
ma_bool32 isDefaultPlaybackDevice;
ma_bool32 isDefaultCaptureDevice;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
| 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
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
/*
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);
/*
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_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_data_source_callbacks ds;
ma_format format;
ma_uint32 channels;
ma_uint64 cursor;
ma_uint64 sizeInFrames;
const void* pData;
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_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);
#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 <assert.h>
#include <limits.h> /* For INT_MAX */
#include <math.h> /* sin(), etc. */
#include <stdarg.h>
#include <stdio.h>
#if !defined(_MSC_VER) && !defined(__DMC__)
#include <strings.h> /* For strcasecmp(). */
#include <wchar.h> /* For wcslen(), wcsrtombs() */
#endif
#ifdef MA_WIN32
#include <windows.h>
#else
#include <stdlib.h> /* For malloc(), free(), wcstombs(). */
#include <string.h> /* For memset() */
#include <sched.h>
#include <sys/time.h> /* select() (used for ma_sleep()). */
#endif
#include <sys/stat.h> /* For fstat(), etc. */
#ifdef MA_EMSCRIPTEN
#include <emscripten/emscripten.h>
#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__
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
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
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
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(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) {
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
#endif
#ifdef _WIN32
proc = (ma_proc)GetProcAddress((HMODULE)handle, symbol);
#else
#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
#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__ >= 6))
#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;
masterVolumeFactor = pDevice->masterVolumeFactor;
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. */
}
}
}
}
/* We only want to expose ma_device__handle_duplex_callback_capture() and ma_device__handle_duplex_callback_playback() if we have an asynchronous backend enabled. */
#if defined(MA_HAS_JACK) || \
defined(MA_HAS_COREAUDIO) || \
defined(MA_HAS_AAUDIO) || \
defined(MA_HAS_OPENSL) || \
defined(MA_HAS_WEBAUDIO)
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;
}
#endif /* Asynchronous backends. */
/* 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);
}
/* A helper for getting the state of the device. */
static MA_INLINE ma_uint32 ma_device__get_state(ma_device* pDevice)
{
return pDevice->state;
}
#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
typedef struct
{
ma_device_type deviceType;
const ma_device_id* pDeviceID;
char* pName;
size_t nameBufferSize;
ma_bool32 foundDevice;
} ma_context__try_get_device_name_by_id__enum_callback_data;
static ma_bool32 ma_context__try_get_device_name_by_id__enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pDeviceInfo, void* pUserData)
{
ma_context__try_get_device_name_by_id__enum_callback_data* pData = (ma_context__try_get_device_name_by_id__enum_callback_data*)pUserData;
MA_ASSERT(pData != NULL);
if (pData->deviceType == deviceType) {
if (pContext->onDeviceIDEqual(pContext, pData->pDeviceID, &pDeviceInfo->id)) {
ma_strncpy_s(pData->pName, pData->nameBufferSize, pDeviceInfo->name, (size_t)-1);
pData->foundDevice = MA_TRUE;
}
}
return !pData->foundDevice;
}
/*
Generic function for retrieving the name of a device by it's ID.
This function simply enumerates every device and then retrieves the name of the first device that has the same ID.
*/
static ma_result ma_context__try_get_device_name_by_id(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, char* pName, size_t nameBufferSize)
{
ma_result result;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
/* Keep looping until an operation has been requested. */
while (pDevice->null_device.operation != MA_DEVICE_OP_NONE__NULL && pDevice->null_device.operation != MA_DEVICE_OP_START__NULL) {
ma_sleep(10); /* Don't hog the CPU. */
}
/* Getting here means a suspend or kill operation has been requested. */
c89atomic_exchange_32((c89atomic_uint32*)&pDevice->null_device.operationResult, MA_SUCCESS);
ma_event_signal(&pDevice->null_device.operationCompletionEvent);
continue;
}
/* Suspending the device means we need to stop the timer and just continue the loop. */
if (pDevice->null_device.operation == MA_DEVICE_OP_SUSPEND__NULL) {
c89atomic_exchange_32(&pDevice->null_device.operation, MA_DEVICE_OP_NONE__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. */
c89atomic_exchange_32((c89atomic_uint32*)&pDevice->null_device.operationResult, MA_SUCCESS);
ma_event_signal(&pDevice->null_device.operationCompletionEvent);
continue;
}
/* Killing the device means we need to get out of this loop so that this thread can terminate. */
if (pDevice->null_device.operation == MA_DEVICE_OP_KILL__NULL) {
c89atomic_exchange_32(&pDevice->null_device.operation, MA_DEVICE_OP_NONE__NULL);
c89atomic_exchange_32((c89atomic_uint32*)&pDevice->null_device.operationResult, MA_SUCCESS);
ma_event_signal(&pDevice->null_device.operationCompletionEvent);
break;
}
/* Getting a signal on a "none" operation probably means an error. Return invalid operation. */
if (pDevice->null_device.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). */
c89atomic_exchange_32((c89atomic_uint32*)&pDevice->null_device.operationResult, (c89atomic_uint32)MA_INVALID_OPERATION);
ma_event_signal(&pDevice->null_device.operationCompletionEvent);
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)
{
c89atomic_exchange_32(&pDevice->null_device.operation, operation);
if (ma_event_signal(&pDevice->null_device.operationEvent) != MA_SUCCESS) {
return MA_ERROR;
}
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_bool32 ma_context_is_device_id_equal__null(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pID0 != NULL);
MA_ASSERT(pID1 != NULL);
(void)pContext;
return pID0->nullbackend == pID1->nullbackend;
}
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);
}
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_share_mode shareMode, ma_device_info* pDeviceInfo)
{
ma_uint32 iFormat;
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->formatCount = ma_format_count - 1; /* Minus one because we don't want to include ma_format_unknown. */
for (iFormat = 0; iFormat < pDeviceInfo->formatCount; ++iFormat) {
pDeviceInfo->formats[iFormat] = (ma_format)(iFormat + 1); /* +1 to skip over ma_format_unknown. */
}
pDeviceInfo->minChannels = 1;
pDeviceInfo->maxChannels = MA_MAX_CHANNELS;
pDeviceInfo->minSampleRate = MA_SAMPLE_RATE_8000;
pDeviceInfo->maxSampleRate = MA_SAMPLE_RATE_384000;
(void)pContext;
(void)shareMode;
return MA_SUCCESS;
}
static void 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);
/* At this point the loop in the device thread is as good as terminated so we can uninitialize our events. */
ma_event_uninit(&pDevice->null_device.operationCompletionEvent);
ma_event_uninit(&pDevice->null_device.operationEvent);
}
static ma_result ma_device_init__null(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
{
ma_result result;
ma_uint32 periodSizeInFrames;
MA_ASSERT(pDevice != NULL);
MA_ZERO_OBJECT(&pDevice->null_device);
if (pConfig->deviceType == ma_device_type_loopback) {
return MA_DEVICE_TYPE_NOT_SUPPORTED;
}
periodSizeInFrames = pConfig->periodSizeInFrames;
if (periodSizeInFrames == 0) {
periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, pConfig->sampleRate);
}
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), "NULL Capture Device", (size_t)-1);
pDevice->capture.internalFormat = pConfig->capture.format;
pDevice->capture.internalChannels = pConfig->capture.channels;
ma_channel_map_copy(pDevice->capture.internalChannelMap, pConfig->capture.channelMap, ma_min(pConfig->capture.channels, MA_MAX_CHANNELS));
pDevice->capture.internalPeriodSizeInFrames = periodSizeInFrames;
pDevice->capture.internalPeriods = pConfig->periods;
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), "NULL Playback Device", (size_t)-1);
pDevice->playback.internalFormat = pConfig->playback.format;
pDevice->playback.internalChannels = pConfig->playback.channels;
ma_channel_map_copy(pDevice->playback.internalChannelMap, pConfig->playback.channelMap, ma_min(pConfig->playback.channels, MA_MAX_CHANNELS));
pDevice->playback.internalPeriodSizeInFrames = periodSizeInFrames;
pDevice->playback.internalPeriods = pConfig->periods;
}
/*
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_thread_create(&pDevice->thread, 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_32(&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_32(&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 = 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 (!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 (!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 (!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_device_main_loop__null(ma_device* pDevice)
{
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);
/* The capture device needs to be started immediately. */
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
result = ma_device_start__null(pDevice);
if (result != MA_SUCCESS) {
return result;
}
}
while (ma_device__get_state(pDevice) == MA_STATE_STARTED && !exitLoop) {
switch (pDevice->type)
{
case ma_device_type_duplex:
{
/* 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_uint32 capturedDeviceFramesRemaining;
ma_uint32 capturedDeviceFramesProcessed;
ma_uint32 capturedDeviceFramesToProcess;
ma_uint32 capturedDeviceFramesToTryProcessing = capturedDevicePeriodSizeInFrames - totalCapturedDeviceFramesProcessed;
if (capturedDeviceFramesToTryProcessing > capturedDeviceDataCapInFrames) {
capturedDeviceFramesToTryProcessing = capturedDeviceDataCapInFrames;
}
result = ma_device_read__null(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 = ma_device_write__null(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:
{
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 = ma_device_read__null(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 = ma_device_write__null(pDevice, playbackDeviceData, 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 is started. */
ma_device_stop__null(pDevice);
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(const ma_context_config* pConfig, ma_context* pContext)
{
MA_ASSERT(pContext != NULL);
(void)pConfig;
pContext->onUninit = ma_context_uninit__null;
pContext->onDeviceIDEqual = ma_context_is_device_id_equal__null;
pContext->onEnumDevices = ma_context_enumerate_devices__null;
pContext->onGetDeviceInfo = ma_context_get_device_info__null;
pContext->onDeviceInit = ma_device_init__null;
pContext->onDeviceUninit = ma_device_uninit__null;
pContext->onDeviceStart = NULL; /* Not required for synchronous backends. */
pContext->onDeviceStop = NULL; /* Not required for synchronous backends. */
pContext->onDeviceMainLoop = ma_device_main_loop__null;
/* 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)
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
} 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;
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_share_mode_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;
pData->periodSizeInFramesOut = pData->periodSizeInFramesIn;
if (pData->periodSizeInFramesOut == 0) {
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 {
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
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);
}
/*
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(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_32(&pDevice->wasapi.isStartedCapture, MA_FALSE);
c89atomic_exchange_32(&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 pDevice->wasapi.hasDefaultPlaybackDeviceChanged;
}
if (deviceType == ma_device_type_capture || deviceType == ma_device_type_loopback) {
return 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_32(&pDevice->wasapi.hasDefaultPlaybackDeviceChanged, MA_FALSE);
}
if (deviceType == ma_device_type_capture || deviceType == ma_device_type_loopback) {
c89atomic_exchange_32(&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_main_loop__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_32(&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 (!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_32(&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 (!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_32(&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_32(&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 (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_32(&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(const ma_context_config* pConfig, ma_context* pContext)
{
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 lin 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");
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
if (pDevice->dsound.pPlayback != NULL) {
ma_IDirectSound_Release((ma_IDirectSound*)pDevice->dsound.pPlayback);
}
}
static ma_result ma_config_to_WAVEFORMATEXTENSIBLE(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const ma_channel* pChannelMap, WAVEFORMATEXTENSIBLE* pWF)
{
GUID subformat;
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_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
{
ma_result result;
HRESULT hr;
ma_uint32 periodSizeInMilliseconds;
MA_ASSERT(pDevice != NULL);
MA_ZERO_OBJECT(&pDevice->dsound);
if (pConfig->deviceType == ma_device_type_loopback) {
return MA_DEVICE_TYPE_NOT_SUPPORTED;
}
periodSizeInMilliseconds = pConfig->periodSizeInMilliseconds;
if (periodSizeInMilliseconds == 0) {
periodSizeInMilliseconds = ma_calculate_buffer_size_in_milliseconds_from_frames(pConfig->periodSizeInFrames, pConfig->sampleRate);
}
/* DirectSound should use a latency of about 20ms per period for low latency mode. */
if (pDevice->usingDefaultBufferSize) {
if (pConfig->performanceProfile == ma_performance_profile_low_latency) {
periodSizeInMilliseconds = 20;
} else {
periodSizeInMilliseconds = 200;
}
}
/* DirectSound breaks down with tiny buffer sizes (bad glitching and silent output). I am therefore restricting the size of the buffer to a minimum of 20 milliseconds. */
if (periodSizeInMilliseconds < 20) {
periodSizeInMilliseconds = 20;
}
/*
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;
char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */
WAVEFORMATEXTENSIBLE* pActualFormat;
result = ma_config_to_WAVEFORMATEXTENSIBLE(pConfig->capture.format, pConfig->capture.channels, pConfig->sampleRate, pConfig->capture.channelMap, &wf);
if (result != MA_SUCCESS) {
return result;
}
result = ma_context_create_IDirectSoundCapture__dsound(pContext, pConfig->capture.shareMode, pConfig->capture.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(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_buffer_size_in_frames_from_milliseconds(periodSizeInMilliseconds, wf.Format.nSamplesPerSec);
MA_ZERO_OBJECT(&descDS);
descDS.dwSize = sizeof(descDS);
descDS.dwFlags = 0;
descDS.dwBufferBytes = periodSizeInFrames * pConfig->periods * ma_get_bytes_per_frame(pDevice->capture.internalFormat, wf.Format.nChannels);
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));
}
pDevice->capture.internalFormat = ma_format_from_WAVEFORMATEX((WAVEFORMATEX*)pActualFormat);
pDevice->capture.internalChannels = pActualFormat->Format.nChannels;
pDevice->capture.internalSampleRate = 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, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap);
} else {
ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap);
}
/*
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(pDevice->capture.internalFormat, pDevice->capture.internalChannels) / pConfig->periods)) {
descDS.dwBufferBytes = periodSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, wf.Format.nChannels) * pConfig->periods;
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. */
pDevice->capture.internalPeriodSizeInFrames = periodSizeInFrames;
pDevice->capture.internalPeriods = pConfig->periods;
}
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_DSBUFFERDESC descDS;
result = ma_config_to_WAVEFORMATEXTENSIBLE(pConfig->playback.format, pConfig->playback.channels, pConfig->sampleRate, pConfig->playback.channelMap, &wf);
if (result != MA_SUCCESS) {
return result;
}
result = ma_context_create_IDirectSound__dsound(pContext, pConfig->playback.shareMode, pConfig->playback.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 (pDevice->playback.usingDefaultChannels) {
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 (pDevice->usingDefaultSampleRate) {
/* 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));
}
pDevice->playback.internalFormat = ma_format_from_WAVEFORMATEX((WAVEFORMATEX*)pActualFormat);
pDevice->playback.internalChannels = pActualFormat->Format.nChannels;
pDevice->playback.internalSampleRate = 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, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap);
} else {
ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap);
}
/* The size of the buffer must be a clean multiple of the period count. */
periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(periodSizeInMilliseconds, pDevice->playback.internalSampleRate);
/*
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 * pConfig->periods * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
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. */
pDevice->playback.internalPeriodSizeInFrames = periodSizeInFrames;
pDevice->playback.internalPeriods = pConfig->periods;
}
(void)pContext;
return MA_SUCCESS;
}
static ma_result ma_device_main_loop__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, v...
#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, v...
#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, virtualWriteCurs...
#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, virtualWriteCurs...
#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)) {
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
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) {
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
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 void 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. */
}
static ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
{
const char* errorMsg = "";
ma_result errorCode = MA_ERROR;
ma_result result = MA_SUCCESS;
ma_uint32 heapSize;
UINT winMMDeviceIDPlayback = 0;
UINT winMMDeviceIDCapture = 0;
ma_uint32 periodSizeInMilliseconds;
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) && pConfig->playback.shareMode == ma_share_mode_exclusive) ||
((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) {
return MA_SHARE_MODE_NOT_SUPPORTED;
}
periodSizeInMilliseconds = pConfig->periodSizeInMilliseconds;
if (periodSizeInMilliseconds == 0) {
periodSizeInMilliseconds = ma_calculate_buffer_size_in_milliseconds_from_frames(pConfig->periodSizeInFrames, pConfig->sampleRate);
}
/* WinMM has horrible latency. */
if (pDevice->usingDefaultBufferSize) {
if (pConfig->performanceProfile == ma_performance_profile_low_latency) {
periodSizeInMilliseconds = 40;
} else {
periodSizeInMilliseconds = 400;
}
}
if (pConfig->playback.pDeviceID != NULL) {
winMMDeviceIDPlayback = (UINT)pConfig->playback.pDeviceID->winmm;
}
if (pConfig->capture.pDeviceID != NULL) {
winMMDeviceIDCapture = (UINT)pConfig->capture.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)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;
}
pDevice->capture.internalFormat = ma_format_from_WAVEFORMATEX(&wf);
pDevice->capture.internalChannels = wf.nChannels;
pDevice->capture.internalSampleRate = wf.nSamplesPerSec;
ma_get_standard_channel_map(ma_standard_channel_map_microsoft, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap);
pDevice->capture.internalPeriods = pConfig->periods;
pDevice->capture.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(periodSizeInMilliseconds, pDevice->capture.internalSampleRate);
}
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)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)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;
}
pDevice->playback.internalFormat = ma_format_from_WAVEFORMATEX(&wf);
pDevice->playback.internalChannels = wf.nChannels;
pDevice->playback.internalSampleRate = wf.nSamplesPerSec;
ma_get_standard_channel_map(ma_standard_channel_map_microsoft, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap);
pDevice->playback.internalPeriods = pConfig->periods;
pDevice->playback.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(periodSizeInMilliseconds, pDevice->playback.internalSampleRate);
}
/*
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)*pDevice->capture.internalPeriods + (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
heapSize += sizeof(WAVEHDR)*pDevice->playback.internalPeriods + (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
}
pDevice->winmm._pHeapData = (ma_uint8*)ma__calloc_from_callbacks(heapSize, &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)*(pDevice->capture.internalPeriods));
} else {
pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData;
pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDevice->capture.internalPeriods + pDevice->playback.internalPeriods));
}
/* Prepare headers. */
for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) {
ma_uint32 periodSizeInBytes = ma_get_period_size_in_bytes(pDevice->capture.internalPeriodSizeInFrames, pDevice->capture.internalFormat, pDevice->capture.internalChannels);
((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)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)*pDevice->playback.internalPeriods);
} else {
pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDevice->capture.internalPeriods));
pDevice->winmm.pIntermediaryBufferPlayback = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDevice->capture.internalPeriods + pDevice->playback.internalPeriods)) + (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeri...
}
/* Prepare headers. */
for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) {
ma_uint32 periodSizeInBytes = ma_get_period_size_in_bytes(pDevice->playback.internalPeriodSizeInFrames, pDevice->playback.internalFormat, pDevice->playback.internalChannels);
((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)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 < pDevice->capture.internalPeriods; ++iPeriod) {
((MA_PFN_waveInUnprepareHeader)pContext->winmm.waveInUnprepareHeader)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(WAVEHDR));
}
}
((MA_PFN_waveInClose)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 < pDevice->playback.internalPeriods; ++iPeriod) {
((MA_PFN_waveOutUnprepareHeader)pContext->winmm.waveOutUnprepareHeader)((HWAVEOUT)pDevice->winmm.hDevicePlayback, &((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(WAVEHDR));
}
}
((MA_PFN_waveOutClose)pContext->winmm.waveOutClose)((HWAVEOUT)pDevice->winmm.hDevicePlayback);
}
ma__free_from_callbacks(pDevice->winmm._pHeapData, &pContext->allocationCallbacks);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, errorMsg, errorCode);
}
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_device_main_loop__winmm(ma_device* pDevice)
{
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);
/* The capture device needs to be started immediately. */
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));
}
}
while (ma_device__get_state(pDevice) == MA_STATE_STARTED && !exitLoop) {
switch (pDevice->type)
{
case ma_device_type_duplex:
{
/* 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_uint32 capturedDeviceFramesRemaining;
ma_uint32 capturedDeviceFramesProcessed;
ma_uint32 capturedDeviceFramesToProcess;
ma_uint32 capturedDeviceFramesToTryProcessing = capturedDevicePeriodSizeInFrames - totalCapturedDeviceFramesProcessed;
if (capturedDeviceFramesToTryProcessing > capturedDeviceDataCapInFrames) {
capturedDeviceFramesToTryProcessing = capturedDeviceDataCapInFrames;
}
result = ma_device_read__winmm(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__winmm(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__winmm()... */
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
}
totalCapturedDeviceFramesProcessed += capturedDeviceFramesProcessed;
}
} break;
case ma_device_type_capture:
{
/* We read in chunks of the period size, but use a stack allocated buffer for the intermediary. */
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 = ma_device_read__winmm(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 = ma_device_write__winmm(pDevice, playbackDeviceData, 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 is started. */
ma_device_stop__winmm(pDevice);
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(const ma_context_config* pConfig, ma_context* pContext)
{
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");
pContext->onUninit = ma_context_uninit__winmm;
pContext->onDeviceIDEqual = ma_context_is_device_id_equal__winmm;
pContext->onEnumDevices = ma_context_enumerate_devices__winmm;
pContext->onGetDeviceInfo = ma_context_get_device_info__winmm;
pContext->onDeviceInit = ma_device_init__winmm;
pContext->onDeviceUninit = ma_device_uninit__winmm;
pContext->onDeviceStart = NULL; /* Not used with synchronous backends. */
pContext->onDeviceStop = NULL; /* Not used with synchronous backends. */
pContext->onDeviceMainLoop = ma_device_main_loop__winmm;
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 <alsa/asoundlib.h>
#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 <errno.h> /* 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 */
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
/* 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) {
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);
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);
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);
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
/* 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);
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
/* 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"
};
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
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 void ma_device_uninit__pulse(ma_device* pDevice)
{
ma_context* pContext;
MA_ASSERT(pDevice != NULL);
pContext = pDevice->pContext;
MA_ASSERT(pContext != NULL);
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
}
((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((ma_pa_context*)pDevice->pulse.pPulseContext);
((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)((ma_pa_context*)pDevice->pulse.pPulseContext);
((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)pDevice->pulse.pMainLoop);
}
static ma_pa_buffer_attr ma_device__pa_buffer_attr_new(ma_uint32 periodSizeInFrames, ma_uint32 periods, const ma_pa_sample_spec* ss)
{
ma_pa_buffer_attr attr;
attr.maxlength = periodSizeInFrames * periods * ma_get_bytes_per_frame(ma_format_from_pulse(ss->format), ss->channels);
attr.tlength = attr.maxlength / periods;
attr.prebuf = (ma_uint32)-1;
attr.minreq = (ma_uint32)-1;
attr.fragsize = attr.maxlength / periods;
return attr;
}
static ma_pa_stream* ma_device__pa_stream_new__pulse(ma_device* pDevice, const char* pStreamName, const ma_pa_sample_spec* ss, const ma_pa_channel_map* cmap)
{
static int g_StreamCounter = 0;
char actualStreamName[256];
if (pStreamName != NULL) {
ma_strncpy_s(actualStreamName, sizeof(actualStreamName), pStreamName, (size_t)-1);
} else {
ma_strcpy_s(actualStreamName, sizeof(actualStreamName), "miniaudio:");
ma_itoa_s(g_StreamCounter, actualStreamName + 8, sizeof(actualStreamName)-8, 10); /* 8 = strlen("miniaudio:") */
}
g_StreamCounter += 1;
return ((ma_pa_stream_new_proc)pDevice->pContext->pulse.pa_stream_new)((ma_pa_context*)pDevice->pulse.pPulseContext, actualStreamName, ss, cmap);
}
static ma_result ma_device_init__pulse(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
{
ma_result result = MA_SUCCESS;
int error = 0;
const char* devPlayback = NULL;
const char* devCapture = NULL;
ma_uint32 periodSizeInMilliseconds;
ma_pa_sink_info sinkInfo;
ma_pa_source_info sourceInfo;
ma_pa_operation* pOP = NULL;
ma_pa_sample_spec ss;
ma_pa_channel_map cmap;
ma_pa_buffer_attr attr;
const ma_pa_sample_spec* pActualSS = NULL;
const ma_pa_channel_map* pActualCMap = NULL;
const ma_pa_buffer_attr* pActualAttr = NULL;
ma_uint32 iChannel;
ma_pa_stream_flags_t streamFlags;
MA_ASSERT(pDevice != NULL);
MA_ZERO_OBJECT(&pDevice->pulse);
if (pConfig->deviceType == ma_device_type_loopback) {
return MA_DEVICE_TYPE_NOT_SUPPORTED;
}
/* No exclusive mode with the PulseAudio backend. */
if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) ||
((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) {
return MA_SHARE_MODE_NOT_SUPPORTED;
}
if ((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.pDeviceID != NULL) {
devPlayback = pConfig->playback.pDeviceID->pulse;
}
if ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.pDeviceID != NULL) {
devCapture = pConfig->capture.pDeviceID->pulse;
}
periodSizeInMilliseconds = pConfig->periodSizeInMilliseconds;
if (periodSizeInMilliseconds == 0) {
periodSizeInMilliseconds = ma_calculate_buffer_size_in_milliseconds_from_frames(pConfig->periodSizeInFrames, pConfig->sampleRate);
}
pDevice->pulse.pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)();
if (pDevice->pulse.pMainLoop == NULL) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create main loop for device.", MA_FAILED_TO_INIT_BACKEND);
goto on_error0;
}
pDevice->pulse.pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)((ma_pa_mainloop*)pDevice->pulse.pMainLoop);
if (pDevice->pulse.pAPI == NULL) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve PulseAudio main loop.", MA_FAILED_TO_INIT_BACKEND);
goto on_error1;
}
pDevice->pulse.pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)((ma_pa_mainloop_api*)pDevice->pulse.pAPI, pContext->pulse.pApplicationName);
if (pDevice->pulse.pPulseContext == NULL) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio context for device.", MA_FAILED_TO_INIT_BACKEND);
goto on_error1;
}
error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)((ma_pa_context*)pDevice->pulse.pPulseContext, pContext->pulse.pServerName, (pContext->pulse.tryAutoSpawn) ? 0 : MA_PA_CONTEXT_NOAUTOSPAWN, NULL);
if (error != MA_PA_OK) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio context.", ma_result_from_pulse(error));
goto on_error2;
}
pDevice->pulse.pulseContextState = MA_PA_CONTEXT_UNCONNECTED;
((ma_pa_context_set_state_callback_proc)pContext->pulse.pa_context_set_state_callback)((ma_pa_context*)pDevice->pulse.pPulseContext, ma_pulse_device_state_callback, pDevice);
/* Wait for PulseAudio to get itself ready before returning. */
for (;;) {
if (pDevice->pulse.pulseContextState == MA_PA_CONTEXT_READY) {
break;
}
/* An error may have occurred. */
if (pDevice->pulse.pulseContextState == MA_PA_CONTEXT_FAILED || pDevice->pulse.pulseContextState == MA_PA_CONTEXT_TERMINATED) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio context.", MA_ERROR);
goto on_error3;
}
error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL);
if (error < 0) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] The PulseAudio main loop returned an error while connecting the PulseAudio context.", ma_result_from_pulse(error));
goto on_error3;
}
}
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
pOP = ((ma_pa_context_get_source_info_by_name_proc)pContext->pulse.pa_context_get_source_info_by_name)((ma_pa_context*)pDevice->pulse.pPulseContext, devCapture, ma_device_source_info_callback, &sourceInfo);
if (pOP != NULL) {
ma_device__wait_for_operation__pulse(pDevice, pOP);
((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
} else {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve source info for capture device.", ma_result_from_pulse(error));
goto on_error3;
}
ss = sourceInfo.sample_spec;
cmap = sourceInfo.channel_map;
pDevice->capture.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(periodSizeInMilliseconds, ss.rate);
pDevice->capture.internalPeriods = pConfig->periods;
attr = ma_device__pa_buffer_attr_new(pDevice->capture.internalPeriodSizeInFrames, pConfig->periods, &ss);
#ifdef MA_DEBUG_OUTPUT
printf("[PulseAudio] Capture attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalPeriodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->capture.internalPeriodSizeInFram...
#endif
pDevice->pulse.pStreamCapture = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNameCapture, &ss, &cmap);
if (pDevice->pulse.pStreamCapture == NULL) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio capture stream.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
goto on_error3;
}
streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS;
if (devCapture != NULL) {
streamFlags |= MA_PA_STREAM_DONT_MOVE;
}
error = ((ma_pa_stream_connect_record_proc)pContext->pulse.pa_stream_connect_record)((ma_pa_stream*)pDevice->pulse.pStreamCapture, devCapture, &attr, streamFlags);
if (error != MA_PA_OK) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio capture stream.", ma_result_from_pulse(error));
goto on_error4;
}
while (((ma_pa_stream_get_state_proc)pContext->pulse.pa_stream_get_state)((ma_pa_stream*)pDevice->pulse.pStreamCapture) != MA_PA_STREAM_READY) {
error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL);
if (error < 0) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] The PulseAudio main loop returned an error while connecting the PulseAudio capture stream.", ma_result_from_pulse(error));
goto on_error5;
}
}
/* Internal format. */
pActualSS = ((ma_pa_stream_get_sample_spec_proc)pContext->pulse.pa_stream_get_sample_spec)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
if (pActualSS != NULL) {
/* If anything has changed between the requested and the actual sample spec, we need to update the buffer. */
if (ss.format != pActualSS->format || ss.channels != pActualSS->channels || ss.rate != pActualSS->rate) {
attr = ma_device__pa_buffer_attr_new(pDevice->capture.internalPeriodSizeInFrames, pConfig->periods, pActualSS);
pOP = ((ma_pa_stream_set_buffer_attr_proc)pContext->pulse.pa_stream_set_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamCapture, &attr, NULL, NULL);
if (pOP != NULL) {
ma_device__wait_for_operation__pulse(pDevice, pOP);
((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
}
}
ss = *pActualSS;
}
pDevice->capture.internalFormat = ma_format_from_pulse(ss.format);
pDevice->capture.internalChannels = ss.channels;
pDevice->capture.internalSampleRate = ss.rate;
/* Internal channel map. */
pActualCMap = ((ma_pa_stream_get_channel_map_proc)pContext->pulse.pa_stream_get_channel_map)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
if (pActualCMap != NULL) {
cmap = *pActualCMap;
}
for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) {
pDevice->capture.internalChannelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]);
}
/* Buffer. */
pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
if (pActualAttr != NULL) {
attr = *pActualAttr;
}
pDevice->capture.internalPeriods = attr.maxlength / attr.fragsize;
pDevice->capture.internalPeriodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels) / pDevice->capture.internalPeriods;
#ifdef MA_DEBUG_OUTPUT
printf("[PulseAudio] Capture actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalPeriodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->capture.internalPeriodSiz...
#endif
/* Name. */
devCapture = ((ma_pa_stream_get_device_name_proc)pContext->pulse.pa_stream_get_device_name)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
if (devCapture != NULL) {
ma_pa_operation* pOP = ((ma_pa_context_get_source_info_by_name_proc)pContext->pulse.pa_context_get_source_info_by_name)((ma_pa_context*)pDevice->pulse.pPulseContext, devCapture, ma_device_source_name_callback, pDevice);
if (pOP != NULL) {
ma_device__wait_for_operation__pulse(pDevice, pOP);
((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
}
}
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
pOP = ((ma_pa_context_get_sink_info_by_name_proc)pContext->pulse.pa_context_get_sink_info_by_name)((ma_pa_context*)pDevice->pulse.pPulseContext, devPlayback, ma_device_sink_info_callback, &sinkInfo);
if (pOP != NULL) {
ma_device__wait_for_operation__pulse(pDevice, pOP);
((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
} else {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve sink info for playback device.", ma_result_from_pulse(error));
goto on_error3;
}
ss = sinkInfo.sample_spec;
cmap = sinkInfo.channel_map;
pDevice->playback.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(periodSizeInMilliseconds, ss.rate);
pDevice->playback.internalPeriods = pConfig->periods;
attr = ma_device__pa_buffer_attr_new(pDevice->playback.internalPeriodSizeInFrames, pConfig->periods, &ss);
#ifdef MA_DEBUG_OUTPUT
printf("[PulseAudio] Playback attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalPeriodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->playback.internalPeriodSizeInFr...
#endif
pDevice->pulse.pStreamPlayback = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNamePlayback, &ss, &cmap);
if (pDevice->pulse.pStreamPlayback == NULL) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio playback stream.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
goto on_error3;
}
streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS;
if (devPlayback != NULL) {
streamFlags |= MA_PA_STREAM_DONT_MOVE;
}
error = ((ma_pa_stream_connect_playback_proc)pContext->pulse.pa_stream_connect_playback)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, devPlayback, &attr, streamFlags, NULL, NULL);
if (error != MA_PA_OK) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio playback stream.", ma_result_from_pulse(error));
goto on_error6;
}
while (((ma_pa_stream_get_state_proc)pContext->pulse.pa_stream_get_state)((ma_pa_stream*)pDevice->pulse.pStreamPlayback) != MA_PA_STREAM_READY) {
error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL);
if (error < 0) {
result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] The PulseAudio main loop returned an error while connecting the PulseAudio playback stream.", ma_result_from_pulse(error));
goto on_error7;
}
}
/* Internal format. */
pActualSS = ((ma_pa_stream_get_sample_spec_proc)pContext->pulse.pa_stream_get_sample_spec)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
if (pActualSS != NULL) {
/* If anything has changed between the requested and the actual sample spec, we need to update the buffer. */
if (ss.format != pActualSS->format || ss.channels != pActualSS->channels || ss.rate != pActualSS->rate) {
attr = ma_device__pa_buffer_attr_new(pDevice->playback.internalPeriodSizeInFrames, pConfig->periods, pActualSS);
pOP = ((ma_pa_stream_set_buffer_attr_proc)pContext->pulse.pa_stream_set_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, &attr, NULL, NULL);
if (pOP != NULL) {
ma_device__wait_for_operation__pulse(pDevice, pOP);
((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
}
}
ss = *pActualSS;
}
pDevice->playback.internalFormat = ma_format_from_pulse(ss.format);
pDevice->playback.internalChannels = ss.channels;
pDevice->playback.internalSampleRate = ss.rate;
/* Internal channel map. */
pActualCMap = ((ma_pa_stream_get_channel_map_proc)pContext->pulse.pa_stream_get_channel_map)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
if (pActualCMap != NULL) {
cmap = *pActualCMap;
}
for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) {
pDevice->playback.internalChannelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]);
}
/* Buffer. */
pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
if (pActualAttr != NULL) {
attr = *pActualAttr;
}
pDevice->playback.internalPeriods = attr.maxlength / attr.tlength;
pDevice->playback.internalPeriodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels) / pDevice->playback.internalPeriods;
#ifdef MA_DEBUG_OUTPUT
printf("[PulseAudio] Playback actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalPeriodSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->playback.internalPeriodS...
#endif
/* Name. */
devPlayback = ((ma_pa_stream_get_device_name_proc)pContext->pulse.pa_stream_get_device_name)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
if (devPlayback != NULL) {
ma_pa_operation* pOP = ((ma_pa_context_get_sink_info_by_name_proc)pContext->pulse.pa_context_get_sink_info_by_name)((ma_pa_context*)pDevice->pulse.pPulseContext, devPlayback, ma_device_sink_name_callback, pDevice);
if (pOP != NULL) {
ma_device__wait_for_operation__pulse(pDevice, pOP);
((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
}
}
}
return MA_SUCCESS;
on_error7:
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
}
on_error6:
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
}
on_error5:
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
}
on_error4:
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
}
on_error3: ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((ma_pa_context*)pDevice->pulse.pPulseContext);
on_error2: ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)((ma_pa_context*)pDevice->pulse.pPulseContext);
on_error1: ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)pDevice->pulse.pMainLoop);
on_error0:
return result;
}
static void ma_pulse_operation_complete_callback(ma_pa_stream* pStream, int success, void* pUserData)
{
ma_bool32* pIsSuccessful = (ma_bool32*)pUserData;
MA_ASSERT(pIsSuccessful != NULL);
*pIsSuccessful = (ma_bool32)success;
(void)pStream; /* Unused. */
}
static ma_result ma_device__cork_stream__pulse(ma_device* pDevice, ma_device_type deviceType, int cork)
{
ma_context* pContext = pDevice->pContext;
ma_bool32 wasSuccessful;
ma_pa_stream* pStream;
ma_pa_operation* pOP;
ma_result result;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
wasSuccessful = MA_FALSE;
pStream = (ma_pa_stream*)((deviceType == ma_device_type_capture) ? pDevice->pulse.pStreamCapture : pDevice->pulse.pStreamPlayback);
MA_ASSERT(pStream != NULL);
pOP = ((ma_pa_stream_cork_proc)pContext->pulse.pa_stream_cork)(pStream, cork, ma_pulse_operation_complete_callback, &wasSuccessful);
if (pOP == NULL) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to cork PulseAudio stream.", (cork == 0) ? MA_FAILED_TO_START_BACKEND_DEVICE : MA_FAILED_TO_STOP_BACKEND_DEVICE);
}
result = ma_device__wait_for_operation__pulse(pDevice, pOP);
((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
if (result != MA_SUCCESS) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while waiting for the PulseAudio stream to cork.", result);
}
if (!wasSuccessful) {
if (cork) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to stop PulseAudio stream.", MA_FAILED_TO_STOP_BACKEND_DEVICE);
} else {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to start PulseAudio stream.", MA_FAILED_TO_START_BACKEND_DEVICE);
}
}
return MA_SUCCESS;
}
static ma_result ma_device_stop__pulse(ma_device* pDevice)
{
ma_result result;
ma_bool32 wasSuccessful;
ma_pa_operation* pOP;
MA_ASSERT(pDevice != NULL);
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
result = ma_device__cork_stream__pulse(pDevice, ma_device_type_capture, 1);
if (result != MA_SUCCESS) {
return result;
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
/* The stream needs to be drained if it's a playback device. */
pOP = ((ma_pa_stream_drain_proc)pDevice->pContext->pulse.pa_stream_drain)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, ma_pulse_operation_complete_callback, &wasSuccessful);
if (pOP != NULL) {
ma_device__wait_for_operation__pulse(pDevice, pOP);
((ma_pa_operation_unref_proc)pDevice->pContext->pulse.pa_operation_unref)(pOP);
}
result = ma_device__cork_stream__pulse(pDevice, ma_device_type_playback, 1);
if (result != MA_SUCCESS) {
return result;
}
}
return MA_SUCCESS;
}
static ma_result ma_device_write__pulse(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
{
ma_uint32 totalFramesWritten;
MA_ASSERT(pDevice != NULL);
MA_ASSERT(pPCMFrames != NULL);
MA_ASSERT(frameCount > 0);
if (pFramesWritten != NULL) {
*pFramesWritten = 0;
}
totalFramesWritten = 0;
while (totalFramesWritten < frameCount) {
if (ma_device__get_state(pDevice) != MA_STATE_STARTED) {
return MA_DEVICE_NOT_STARTED;
}
/* Place the data into the mapped buffer if we have one. */
if (pDevice->pulse.pMappedBufferPlayback != NULL && pDevice->pulse.mappedBufferFramesRemainingPlayback > 0) {
ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
ma_uint32 mappedBufferFramesConsumed = pDevice->pulse.mappedBufferFramesCapacityPlayback - pDevice->pulse.mappedBufferFramesRemainingPlayback;
void* pDst = (ma_uint8*)pDevice->pulse.pMappedBufferPlayback + (mappedBufferFramesConsumed * bpf);
const void* pSrc = (const ma_uint8*)pPCMFrames + (totalFramesWritten * bpf);
ma_uint32 framesToCopy = ma_min(pDevice->pulse.mappedBufferFramesRemainingPlayback, (frameCount - totalFramesWritten));
MA_COPY_MEMORY(pDst, pSrc, framesToCopy * bpf);
pDevice->pulse.mappedBufferFramesRemainingPlayback -= framesToCopy;
totalFramesWritten += framesToCopy;
}
/*
Getting here means we've run out of data in the currently mapped chunk. We need to write this to the device and then try
mapping another chunk. If this fails we need to wait for space to become available.
*/
if (pDevice->pulse.mappedBufferFramesCapacityPlayback > 0 && pDevice->pulse.mappedBufferFramesRemainingPlayback == 0) {
size_t nbytes = pDevice->pulse.mappedBufferFramesCapacityPlayback * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
int error = ((ma_pa_stream_write_proc)pDevice->pContext->pulse.pa_stream_write)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, pDevice->pulse.pMappedBufferPlayback, nbytes, NULL, 0, MA_PA_SEEK_RELATIVE);
if (error < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to write data to the PulseAudio stream.", ma_result_from_pulse(error));
}
pDevice->pulse.pMappedBufferPlayback = NULL;
pDevice->pulse.mappedBufferFramesRemainingPlayback = 0;
pDevice->pulse.mappedBufferFramesCapacityPlayback = 0;
}
MA_ASSERT(totalFramesWritten <= frameCount);
if (totalFramesWritten == frameCount) {
break;
}
/* Getting here means we need to map a new buffer. If we don't have enough space we need to wait for more. */
for (;;) {
size_t writableSizeInBytes;
/* If the device has been corked, don't try to continue. */
if (((ma_pa_stream_is_corked_proc)pDevice->pContext->pulse.pa_stream_is_corked)((ma_pa_stream*)pDevice->pulse.pStreamPlayback)) {
break;
}
writableSizeInBytes = ((ma_pa_stream_writable_size_proc)pDevice->pContext->pulse.pa_stream_writable_size)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
if (writableSizeInBytes != (size_t)-1) {
if (writableSizeInBytes > 0) {
/* Data is avaialable. */
size_t bytesToMap = writableSizeInBytes;
int error = ((ma_pa_stream_begin_write_proc)pDevice->pContext->pulse.pa_stream_begin_write)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, &pDevice->pulse.pMappedBufferPlayback, &bytesToMap);
if (error < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to map write buffer.", ma_result_from_pulse(error));
}
pDevice->pulse.mappedBufferFramesCapacityPlayback = bytesToMap / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
pDevice->pulse.mappedBufferFramesRemainingPlayback = pDevice->pulse.mappedBufferFramesCapacityPlayback;
break;
} else {
/* No data available. Need to wait for more. */
int error = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL);
if (error < 0) {
return ma_result_from_pulse(error);
}
continue;
}
} else {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to query the stream's writable size.", MA_ERROR);
}
}
}
if (pFramesWritten != NULL) {
*pFramesWritten = totalFramesWritten;
}
return MA_SUCCESS;
}
static ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
{
ma_uint32 totalFramesRead;
MA_ASSERT(pDevice != NULL);
MA_ASSERT(pPCMFrames != NULL);
MA_ASSERT(frameCount > 0);
if (pFramesRead != NULL) {
*pFramesRead = 0;
}
totalFramesRead = 0;
while (totalFramesRead < frameCount) {
if (ma_device__get_state(pDevice) != MA_STATE_STARTED) {
return MA_DEVICE_NOT_STARTED;
}
/*
If a buffer is mapped we need to read from that first. Once it's consumed we need to drop it. Note that pDevice->pulse.pMappedBufferCapture can be null in which
case it could be a hole. In this case we just write zeros into the output buffer.
*/
if (pDevice->pulse.mappedBufferFramesRemainingCapture > 0) {
ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
ma_uint32 mappedBufferFramesConsumed = pDevice->pulse.mappedBufferFramesCapacityCapture - pDevice->pulse.mappedBufferFramesRemainingCapture;
ma_uint32 framesToCopy = ma_min(pDevice->pulse.mappedBufferFramesRemainingCapture, (frameCount - totalFramesRead));
void* pDst = (ma_uint8*)pPCMFrames + (totalFramesRead * bpf);
/*
This little bit of logic here is specifically for PulseAudio and it's hole management. The buffer pointer will be set to NULL
when the current fragment is a hole. For a hole we just output silence.
*/
if (pDevice->pulse.pMappedBufferCapture != NULL) {
const void* pSrc = (const ma_uint8*)pDevice->pulse.pMappedBufferCapture + (mappedBufferFramesConsumed * bpf);
MA_COPY_MEMORY(pDst, pSrc, framesToCopy * bpf);
} else {
MA_ZERO_MEMORY(pDst, framesToCopy * bpf);
#if defined(MA_DEBUG_OUTPUT)
printf("[PulseAudio] ma_device_read__pulse: Filling hole with silence.\n");
#endif
}
pDevice->pulse.mappedBufferFramesRemainingCapture -= framesToCopy;
totalFramesRead += framesToCopy;
}
/*
Getting here means we've run out of data in the currently mapped chunk. We need to drop this from the device and then try
mapping another chunk. If this fails we need to wait for data to become available.
*/
if (pDevice->pulse.mappedBufferFramesCapacityCapture > 0 && pDevice->pulse.mappedBufferFramesRemainingCapture == 0) {
int error;
#if defined(MA_DEBUG_OUTPUT)
printf("[PulseAudio] ma_device_read__pulse: Call pa_stream_drop()\n");
#endif
error = ((ma_pa_stream_drop_proc)pDevice->pContext->pulse.pa_stream_drop)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
if (error != 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to drop fragment.", ma_result_from_pulse(error));
}
pDevice->pulse.pMappedBufferCapture = NULL;
pDevice->pulse.mappedBufferFramesRemainingCapture = 0;
pDevice->pulse.mappedBufferFramesCapacityCapture = 0;
}
MA_ASSERT(totalFramesRead <= frameCount);
if (totalFramesRead == frameCount) {
break;
}
/* Getting here means we need to map a new buffer. If we don't have enough data we wait for more. */
for (;;) {
int error;
size_t bytesMapped;
if (ma_device__get_state(pDevice) != MA_STATE_STARTED) {
break;
}
/* If the device has been corked, don't try to continue. */
if (((ma_pa_stream_is_corked_proc)pDevice->pContext->pulse.pa_stream_is_corked)((ma_pa_stream*)pDevice->pulse.pStreamCapture)) {
#if defined(MA_DEBUG_OUTPUT)
printf("[PulseAudio] ma_device_read__pulse: Corked.\n");
#endif
break;
}
MA_ASSERT(pDevice->pulse.pMappedBufferCapture == NULL); /* <-- We're about to map a buffer which means we shouldn't have an existing mapping. */
error = ((ma_pa_stream_peek_proc)pDevice->pContext->pulse.pa_stream_peek)((ma_pa_stream*)pDevice->pulse.pStreamCapture, &pDevice->pulse.pMappedBufferCapture, &bytesMapped);
if (error < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to peek capture buffer.", ma_result_from_pulse(error));
}
if (bytesMapped > 0) {
pDevice->pulse.mappedBufferFramesCapacityCapture = bytesMapped / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
pDevice->pulse.mappedBufferFramesRemainingCapture = pDevice->pulse.mappedBufferFramesCapacityCapture;
#if defined(MA_DEBUG_OUTPUT)
printf("[PulseAudio] ma_device_read__pulse: Mapped. mappedBufferFramesCapacityCapture=%d, mappedBufferFramesRemainingCapture=%d\n", pDevice->pulse.mappedBufferFramesCapacityCapture, pDevice->pulse.mappedBufferFramesRemainingCaptur...
#endif
if (pDevice->pulse.pMappedBufferCapture == NULL) {
/* It's a hole. */
#if defined(MA_DEBUG_OUTPUT)
printf("[PulseAudio] ma_device_read__pulse: Call pa_stream_peek(). Hole.\n");
#endif
}
break;
} else {
if (pDevice->pulse.pMappedBufferCapture == NULL) {
/* Nothing available yet. Need to wait for more. */
/*
I have had reports of a deadlock in this part of the code. I have reproduced this when using the "Built-in Audio Analogue Stereo" device without
an actual microphone connected. I'm experimenting here by not blocking in pa_mainloop_iterate() and instead sleep for a bit when there are no
dispatches.
*/
error = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 0, NULL);
if (error < 0) {
return ma_result_from_pulse(error);
}
/* Sleep for a bit if nothing was dispatched. */
if (error == 0) {
ma_sleep(1);
}
#if defined(MA_DEBUG_OUTPUT)
printf("[PulseAudio] ma_device_read__pulse: No data available. Waiting. mappedBufferFramesCapacityCapture=%d, mappedBufferFramesRemainingCapture=%d\n", pDevice->pulse.mappedBufferFramesCapacityCapture, pDevice->pulse.mappedBufferF...
#endif
} else {
/* Getting here means we mapped 0 bytes, but have a non-NULL buffer. I don't think this should ever happen. */
MA_ASSERT(MA_FALSE);
}
}
}
}
if (pFramesRead != NULL) {
*pFramesRead = totalFramesRead;
}
return MA_SUCCESS;
}
static ma_result ma_device_main_loop__pulse(ma_device* pDevice)
{
ma_result result = MA_SUCCESS;
ma_bool32 exitLoop = MA_FALSE;
MA_ASSERT(pDevice != NULL);
/* The stream needs to be uncorked first. We do this at the top for both capture and playback for PulseAudio. */
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
result = ma_device__cork_stream__pulse(pDevice, ma_device_type_capture, 0);
if (result != MA_SUCCESS) {
return result;
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
result = ma_device__cork_stream__pulse(pDevice, ma_device_type_playback, 0);
if (result != MA_SUCCESS) {
return result;
}
}
while (ma_device__get_state(pDevice) == MA_STATE_STARTED && !exitLoop) {
switch (pDevice->type)
{
case ma_device_type_duplex:
{
/* 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__pulse(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__pulse(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__pulse()... */
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
}
totalCapturedDeviceFramesProcessed += capturedDeviceFramesProcessed;
}
} break;
case ma_device_type_capture:
{
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__pulse(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:
{
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__pulse(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. */
ma_device_stop__pulse(pDevice);
return result;
}
static ma_result ma_context_uninit__pulse(ma_context* pContext)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pContext->backend == ma_backend_pulseaudio);
ma_free(pContext->pulse.pServerName, &pContext->allocationCallbacks);
pContext->pulse.pServerName = NULL;
ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
pContext->pulse.pApplicationName = NULL;
#ifndef MA_NO_RUNTIME_LINKING
ma_dlclose(pContext, pContext->pulse.pulseSO);
#endif
return MA_SUCCESS;
}
static ma_result ma_context_init__pulse(const ma_context_config* pConfig, ma_context* pContext)
{
#ifndef MA_NO_RUNTIME_LINKING
const char* libpulseNames[] = {
"libpulse.so",
"libpulse.so.0"
};
size_t i;
for (i = 0; i < ma_countof(libpulseNames); ++i) {
pContext->pulse.pulseSO = ma_dlopen(pContext, libpulseNames[i]);
if (pContext->pulse.pulseSO != NULL) {
break;
}
}
if (pContext->pulse.pulseSO == NULL) {
return MA_NO_BACKEND;
}
pContext->pulse.pa_mainloop_new = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_new");
pContext->pulse.pa_mainloop_free = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_free");
pContext->pulse.pa_mainloop_get_api = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_get_api");
pContext->pulse.pa_mainloop_iterate = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_iterate");
pContext->pulse.pa_mainloop_wakeup = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_wakeup");
pContext->pulse.pa_context_new = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_new");
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
ma_dlclose(pContext, pContext->pulse.pulseSO);
#endif
return MA_NO_BACKEND;
}
pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop);
if (pAPI == NULL) {
ma_free(pContext->pulse.pServerName, &pContext->allocationCallbacks);
ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop);
#ifndef MA_NO_RUNTIME_LINKING
ma_dlclose(pContext, pContext->pulse.pulseSO);
#endif
return MA_NO_BACKEND;
}
pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->pulse.pApplicationName);
if (pPulseContext == NULL) {
ma_free(pContext->pulse.pServerName, &pContext->allocationCallbacks);
ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop);
#ifndef MA_NO_RUNTIME_LINKING
ma_dlclose(pContext, pContext->pulse.pulseSO);
#endif
return MA_NO_BACKEND;
}
error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->pulse.pServerName, 0, NULL);
if (error != MA_PA_OK) {
ma_free(pContext->pulse.pServerName, &pContext->allocationCallbacks);
ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext);
((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop);
#ifndef MA_NO_RUNTIME_LINKING
ma_dlclose(pContext, pContext->pulse.pulseSO);
#endif
return MA_NO_BACKEND;
}
((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)(pPulseContext);
((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext);
((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop);
}
return MA_SUCCESS;
}
#endif
/******************************************************************************
JACK Backend
******************************************************************************/
#ifdef MA_HAS_JACK
/* It is assumed jack.h is available when compile-time linking is being used. */
#ifdef MA_NO_RUNTIME_LINKING
#include <jack/jack.h>
typedef jack_nframes_t ma_jack_nframes_t;
typedef jack_options_t ma_jack_options_t;
typedef jack_status_t ma_jack_status_t;
typedef jack_client_t ma_jack_client_t;
typedef jack_port_t ma_jack_port_t;
typedef JackProcessCallback ma_JackProcessCallback;
typedef JackBufferSizeCallback ma_JackBufferSizeCallback;
typedef JackShutdownCallback ma_JackShutdownCallback;
#define MA_JACK_DEFAULT_AUDIO_TYPE JACK_DEFAULT_AUDIO_TYPE
#define ma_JackNoStartServer JackNoStartServer
#define ma_JackPortIsInput JackPortIsInput
#define ma_JackPortIsOutput JackPortIsOutput
#define ma_JackPortIsPhysical JackPortIsPhysical
#else
typedef ma_uint32 ma_jack_nframes_t;
typedef int ma_jack_options_t;
typedef int ma_jack_status_t;
typedef struct ma_jack_client_t ma_jack_client_t;
typedef struct ma_jack_port_t ma_jack_port_t;
typedef int (* ma_JackProcessCallback) (ma_jack_nframes_t nframes, void* arg);
typedef int (* ma_JackBufferSizeCallback)(ma_jack_nframes_t nframes, void* arg);
typedef void (* ma_JackShutdownCallback) (void* arg);
#define MA_JACK_DEFAULT_AUDIO_TYPE "32 bit float mono audio"
#define ma_JackNoStartServer 1
#define ma_JackPortIsInput 1
#define ma_JackPortIsOutput 2
#define ma_JackPortIsPhysical 4
#endif
typedef ma_jack_client_t* (* ma_jack_client_open_proc) (const char* client_name, ma_jack_options_t options, ma_jack_status_t* status, ...);
typedef int (* ma_jack_client_close_proc) (ma_jack_client_t* client);
typedef int (* ma_jack_client_name_size_proc) (void);
typedef int (* ma_jack_set_process_callback_proc) (ma_jack_client_t* client, ma_JackProcessCallback process_callback, void* arg);
typedef int (* ma_jack_set_buffer_size_callback_proc)(ma_jack_client_t* client, ma_JackBufferSizeCallback bufsize_callback, void* arg);
typedef void (* ma_jack_on_shutdown_proc) (ma_jack_client_t* client, ma_JackShutdownCallback function, void* arg);
typedef ma_jack_nframes_t (* ma_jack_get_sample_rate_proc) (ma_jack_client_t* client);
typedef ma_jack_nframes_t (* ma_jack_get_buffer_size_proc) (ma_jack_client_t* client);
typedef const char** (* ma_jack_get_ports_proc) (ma_jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags);
typedef int (* ma_jack_activate_proc) (ma_jack_client_t* client);
typedef int (* ma_jack_deactivate_proc) (ma_jack_client_t* client);
typedef int (* ma_jack_connect_proc) (ma_jack_client_t* client, const char* source_port, const char* destination_port);
typedef ma_jack_port_t* (* ma_jack_port_register_proc) (ma_jack_client_t* client, const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size);
typedef const char* (* ma_jack_port_name_proc) (const ma_jack_port_t* port);
typedef void* (* ma_jack_port_get_buffer_proc) (ma_jack_port_t* port, ma_jack_nframes_t nframes);
typedef void (* ma_jack_free_proc) (void* ptr);
static ma_result ma_context_open_client__jack(ma_context* pContext, ma_jack_client_t** ppClient)
{
size_t maxClientNameSize;
char clientName[256];
ma_jack_status_t status;
ma_jack_client_t* pClient;
MA_ASSERT(pContext != NULL);
MA_ASSERT(ppClient != NULL);
if (ppClient) {
*ppClient = NULL;
}
maxClientNameSize = ((ma_jack_client_name_size_proc)pContext->jack.jack_client_name_size)(); /* Includes null terminator. */
ma_strncpy_s(clientName, ma_min(sizeof(clientName), maxClientNameSize), (pContext->jack.pClientName != NULL) ? pContext->jack.pClientName : "miniaudio", (size_t)-1);
pClient = ((ma_jack_client_open_proc)pContext->jack.jack_client_open)(clientName, (pContext->jack.tryStartServer) ? 0 : ma_JackNoStartServer, &status, NULL);
if (pClient == NULL) {
return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
}
if (ppClient) {
*ppClient = pClient;
}
return MA_SUCCESS;
}
static ma_bool32 ma_context_is_device_id_equal__jack(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pID0 != NULL);
MA_ASSERT(pID1 != NULL);
(void)pContext;
return pID0->jack == pID1->jack;
}
static ma_result ma_context_enumerate_devices__jack(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), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
}
/* Capture. */
if (cbResult) {
ma_device_info deviceInfo;
MA_ZERO_OBJECT(&deviceInfo);
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
pDeviceInfo->minSampleRate = ((ma_jack_get_sample_rate_proc)pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pClient);
pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate;
pDeviceInfo->minChannels = 0;
pDeviceInfo->maxChannels = 0;
ppPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ((deviceType == ma_device_type_playback) ? ma_JackPortIsInput : ma_JackPortIsOutput));
if (ppPorts == NULL) {
((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pClient);
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
}
while (ppPorts[pDeviceInfo->minChannels] != NULL) {
pDeviceInfo->minChannels += 1;
pDeviceInfo->maxChannels += 1;
}
((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts);
((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pClient);
(void)pContext;
return MA_SUCCESS;
}
static void ma_device_uninit__jack(ma_device* pDevice)
{
ma_context* pContext;
MA_ASSERT(pDevice != NULL);
pContext = pDevice->pContext;
MA_ASSERT(pContext != NULL);
if (pDevice->jack.pClient != NULL) {
((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pDevice->jack.pClient);
}
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
ma__free_from_callbacks(pDevice->jack.pIntermediaryBufferCapture, &pDevice->pContext->allocationCallbacks);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
ma__free_from_callbacks(pDevice->jack.pIntermediaryBufferPlayback, &pDevice->pContext->allocationCallbacks);
}
if (pDevice->type == ma_device_type_duplex) {
ma_pcm_rb_uninit(&pDevice->jack.duplexRB);
}
}
static void ma_device__jack_shutdown_callback(void* pUserData)
{
/* JACK died. Stop the device. */
ma_device* pDevice = (ma_device*)pUserData;
MA_ASSERT(pDevice != NULL);
ma_device_stop(pDevice);
}
static int ma_device__jack_buffer_size_callback(ma_jack_nframes_t frameCount, void* pUserData)
{
ma_device* pDevice = (ma_device*)pUserData;
MA_ASSERT(pDevice != NULL);
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
size_t newBufferSize = frameCount * (pDevice->capture.internalChannels * ma_get_bytes_per_sample(pDevice->capture.internalFormat));
float* pNewBuffer = (float*)ma__calloc_from_callbacks(newBufferSize, &pDevice->pContext->allocationCallbacks);
if (pNewBuffer == NULL) {
return MA_OUT_OF_MEMORY;
}
ma__free_from_callbacks(pDevice->jack.pIntermediaryBufferCapture, &pDevice->pContext->allocationCallbacks);
pDevice->jack.pIntermediaryBufferCapture = pNewBuffer;
pDevice->playback.internalPeriodSizeInFrames = frameCount;
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
size_t newBufferSize = frameCount * (pDevice->playback.internalChannels * ma_get_bytes_per_sample(pDevice->playback.internalFormat));
float* pNewBuffer = (float*)ma__calloc_from_callbacks(newBufferSize, &pDevice->pContext->allocationCallbacks);
if (pNewBuffer == NULL) {
return MA_OUT_OF_MEMORY;
}
ma__free_from_callbacks(pDevice->jack.pIntermediaryBufferPlayback, &pDevice->pContext->allocationCallbacks);
pDevice->jack.pIntermediaryBufferPlayback = pNewBuffer;
pDevice->playback.internalPeriodSizeInFrames = frameCount;
}
return 0;
}
static int ma_device__jack_process_callback(ma_jack_nframes_t frameCount, void* pUserData)
{
ma_device* pDevice;
ma_context* pContext;
ma_uint32 iChannel;
pDevice = (ma_device*)pUserData;
MA_ASSERT(pDevice != NULL);
pContext = pDevice->pContext;
MA_ASSERT(pContext != NULL);
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
/* Channels need to be interleaved. */
for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) {
const float* pSrc = (const float*)((ma_jack_port_get_buffer_proc)pContext->jack.jack_port_get_buffer)((ma_jack_port_t*)pDevice->jack.pPortsCapture[iChannel], frameCount);
if (pSrc != NULL) {
float* pDst = pDevice->jack.pIntermediaryBufferCapture + iChannel;
ma_jack_nframes_t iFrame;
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
*pDst = *pSrc;
pDst += pDevice->capture.internalChannels;
pSrc += 1;
}
}
}
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_capture(pDevice, frameCount, pDevice->jack.pIntermediaryBufferCapture, &pDevice->jack.duplexRB);
} else {
ma_device__send_frames_to_client(pDevice, frameCount, pDevice->jack.pIntermediaryBufferCapture);
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_playback(pDevice, frameCount, pDevice->jack.pIntermediaryBufferPlayback, &pDevice->jack.duplexRB);
} else {
ma_device__read_frames_from_client(pDevice, frameCount, pDevice->jack.pIntermediaryBufferPlayback);
}
/* Channels need to be deinterleaved. */
for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) {
float* pDst = (float*)((ma_jack_port_get_buffer_proc)pContext->jack.jack_port_get_buffer)((ma_jack_port_t*)pDevice->jack.pPortsPlayback[iChannel], frameCount);
if (pDst != NULL) {
const float* pSrc = pDevice->jack.pIntermediaryBufferPlayback + iChannel;
ma_jack_nframes_t iFrame;
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
*pDst = *pSrc;
pDst += 1;
pSrc += pDevice->playback.internalChannels;
}
}
}
}
return 0;
}
static ma_result ma_device_init__jack(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
{
ma_result result;
ma_uint32 periods;
ma_uint32 periodSizeInFrames;
MA_ASSERT(pContext != NULL);
MA_ASSERT(pConfig != NULL);
MA_ASSERT(pDevice != NULL);
if (pConfig->deviceType == ma_device_type_loopback) {
return MA_DEVICE_TYPE_NOT_SUPPORTED;
}
/* Only supporting default devices with JACK. */
if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.pDeviceID != NULL && pConfig->playback.pDeviceID->jack != 0) ||
((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.pDeviceID != NULL && pConfig->capture.pDeviceID->jack != 0)) {
return MA_NO_DEVICE;
}
/* No exclusive mode with the JACK backend. */
if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) ||
((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) {
return MA_SHARE_MODE_NOT_SUPPORTED;
}
/* Open the client. */
result = ma_context_open_client__jack(pContext, (ma_jack_client_t**)&pDevice->jack.pClient);
if (result != MA_SUCCESS) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client.", result);
}
/* Callbacks. */
if (((ma_jack_set_process_callback_proc)pContext->jack.jack_set_process_callback)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_process_callback, pDevice) != 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to set process callback.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
}
if (((ma_jack_set_buffer_size_callback_proc)pContext->jack.jack_set_buffer_size_callback)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_buffer_size_callback, pDevice) != 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to set buffer size callback.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
}
((ma_jack_on_shutdown_proc)pContext->jack.jack_on_shutdown)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_shutdown_callback, pDevice);
/* The buffer size in frames can change. */
periods = pConfig->periods;
periodSizeInFrames = ((ma_jack_get_buffer_size_proc)pContext->jack.jack_get_buffer_size)((ma_jack_client_t*)pDevice->jack.pClient);
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
const char** ppPorts;
pDevice->capture.internalFormat = ma_format_f32;
pDevice->capture.internalChannels = 0;
pDevice->capture.internalSampleRate = ((ma_jack_get_sample_rate_proc)pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pDevice->jack.pClient);
ma_get_standard_channel_map(ma_standard_channel_map_alsa, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap);
ppPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ma_JackPortIsOutput);
if (ppPorts == NULL) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
}
while (ppPorts[pDevice->capture.internalChannels] != NULL) {
char name[64];
ma_strcpy_s(name, sizeof(name), "capture");
ma_itoa_s((int)pDevice->capture.internalChannels, name+7, sizeof(name)-7, 10); /* 7 = length of "capture" */
pDevice->jack.pPortsCapture[pDevice->capture.internalChannels] = ((ma_jack_port_register_proc)pContext->jack.jack_port_register)((ma_jack_client_t*)pDevice->jack.pClient, name, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsInput, 0);
if (pDevice->jack.pPortsCapture[pDevice->capture.internalChannels] == NULL) {
((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts);
ma_device_uninit__jack(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to register ports.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
}
pDevice->capture.internalChannels += 1;
}
((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts);
pDevice->capture.internalPeriodSizeInFrames = periodSizeInFrames;
pDevice->capture.internalPeriods = periods;
pDevice->jack.pIntermediaryBufferCapture = (float*)ma__calloc_from_callbacks(pDevice->capture.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels), &pContext->allocationCallba...
if (pDevice->jack.pIntermediaryBufferCapture == NULL) {
ma_device_uninit__jack(pDevice);
return MA_OUT_OF_MEMORY;
}
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
const char** ppPorts;
pDevice->playback.internalFormat = ma_format_f32;
pDevice->playback.internalChannels = 0;
pDevice->playback.internalSampleRate = ((ma_jack_get_sample_rate_proc)pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pDevice->jack.pClient);
ma_get_standard_channel_map(ma_standard_channel_map_alsa, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap);
ppPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ma_JackPortIsInput);
if (ppPorts == NULL) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
}
while (ppPorts[pDevice->playback.internalChannels] != NULL) {
char name[64];
ma_strcpy_s(name, sizeof(name), "playback");
ma_itoa_s((int)pDevice->playback.internalChannels, name+8, sizeof(name)-8, 10); /* 8 = length of "playback" */
pDevice->jack.pPortsPlayback[pDevice->playback.internalChannels] = ((ma_jack_port_register_proc)pContext->jack.jack_port_register)((ma_jack_client_t*)pDevice->jack.pClient, name, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsOutput, 0);
if (pDevice->jack.pPortsPlayback[pDevice->playback.internalChannels] == NULL) {
((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts);
ma_device_uninit__jack(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to register ports.", MA_FAILED_TO_OPEN_BACKEND_DEVICE);
}
pDevice->playback.internalChannels += 1;
}
((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts);
pDevice->playback.internalPeriodSizeInFrames = periodSizeInFrames;
pDevice->playback.internalPeriods = periods;
pDevice->jack.pIntermediaryBufferPlayback = (float*)ma__calloc_from_callbacks(pDevice->playback.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels), &pContext->allocationCa...
if (pDevice->jack.pIntermediaryBufferPlayback == NULL) {
ma_device_uninit__jack(pDevice);
return MA_OUT_OF_MEMORY;
}
}
if (pDevice->type == ma_device_type_duplex) {
ma_uint32 rbSizeInFrames = (ma_uint32)ma_calculate_frame_count_after_resampling(pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalPeriodSizeInFrames * pDevice->capture.internalPeriods);
result = ma_pcm_rb_init(pDevice->capture.format, pDevice->capture.channels, rbSizeInFrames, NULL, &pDevice->pContext->allocationCallbacks, &pDevice->jack.duplexRB);
if (result != MA_SUCCESS) {
ma_device_uninit__jack(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to initialize ring buffer.", result);
}
/* We need a period to act as a buffer for cases where the playback and capture device's end up desyncing. */
{
ma_uint32 marginSizeInFrames = rbSizeInFrames / pDevice->capture.internalPeriods;
void* pMarginData;
ma_pcm_rb_acquire_write(&pDevice->jack.duplexRB, &marginSizeInFrames, &pMarginData);
{
MA_ZERO_MEMORY(pMarginData, marginSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels));
}
ma_pcm_rb_commit_write(&pDevice->jack.duplexRB, marginSizeInFrames, pMarginData);
}
}
return MA_SUCCESS;
}
static ma_result ma_device_start__jack(ma_device* pDevice)
{
ma_context* pContext = pDevice->pContext;
int resultJACK;
size_t i;
resultJACK = ((ma_jack_activate_proc)pContext->jack.jack_activate)((ma_jack_client_t*)pDevice->jack.pClient);
if (resultJACK != 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to activate the JACK client.", MA_FAILED_TO_START_BACKEND_DEVICE);
}
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
const char** ppServerPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ma_JackPortIsOutput);
if (ppServerPorts == NULL) {
((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.", MA_ERROR);
}
for (i = 0; ppServerPorts[i] != NULL; ++i) {
const char* pServerPort = ppServerPorts[i];
const char* pClientPort = ((ma_jack_port_name_proc)pContext->jack.jack_port_name)((ma_jack_port_t*)pDevice->jack.pPortsCapture[i]);
resultJACK = ((ma_jack_connect_proc)pContext->jack.jack_connect)((ma_jack_client_t*)pDevice->jack.pClient, pServerPort, pClientPort);
if (resultJACK != 0) {
((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports.", MA_ERROR);
}
}
((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
const char** ppServerPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsPhysical | ma_JackPortIsInput);
if (ppServerPorts == NULL) {
((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.", MA_ERROR);
}
for (i = 0; ppServerPorts[i] != NULL; ++i) {
const char* pServerPort = ppServerPorts[i];
const char* pClientPort = ((ma_jack_port_name_proc)pContext->jack.jack_port_name)((ma_jack_port_t*)pDevice->jack.pPortsPlayback[i]);
resultJACK = ((ma_jack_connect_proc)pContext->jack.jack_connect)((ma_jack_client_t*)pDevice->jack.pClient, pClientPort, pServerPort);
if (resultJACK != 0) {
((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports.", MA_ERROR);
}
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
for (iMALSampleRate = 0; iMALSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iMALSampleRate) {
ma_uint32 malSampleRate = g_maStandardSampleRatePriorities[iMALSampleRate];
UInt32 iCASampleRate;
for (iCASampleRate = 0; iCASampleRate < sampleRateRangeCount; ++iCASampleRate) {
AudioValueRange caSampleRate = pSampleRateRanges[iCASampleRate];
if (caSampleRate.mMinimum <= malSampleRate && caSampleRate.mMaximum >= malSampleRate) {
*pSampleRateOut = malSampleRate;
ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
return MA_SUCCESS;
}
}
}
/*
If we get here it means none of miniaudio's standard sample rates matched any of the supported sample rates from the device. In this
case we just fall back to the first one reported by Core Audio.
*/
MA_ASSERT(sampleRateRangeCount > 0);
*pSampleRateOut = pSampleRateRanges[0].mMinimum;
ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
return MA_SUCCESS;
} else {
/* Find the closest match to this sample rate. */
UInt32 currentAbsoluteDifference = INT32_MAX;
UInt32 iCurrentClosestRange = (UInt32)-1;
UInt32 iRange;
for (iRange = 0; iRange < sampleRateRangeCount; ++iRange) {
if (pSampleRateRanges[iRange].mMinimum <= sampleRateIn && pSampleRateRanges[iRange].mMaximum >= sampleRateIn) {
*pSampleRateOut = sampleRateIn;
ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
return MA_SUCCESS;
} else {
UInt32 absoluteDifference;
if (pSampleRateRanges[iRange].mMinimum > sampleRateIn) {
absoluteDifference = pSampleRateRanges[iRange].mMinimum - sampleRateIn;
} else {
absoluteDifference = sampleRateIn - pSampleRateRanges[iRange].mMaximum;
}
if (currentAbsoluteDifference > absoluteDifference) {
currentAbsoluteDifference = absoluteDifference;
iCurrentClosestRange = iRange;
}
}
}
MA_ASSERT(iCurrentClosestRange != (UInt32)-1);
*pSampleRateOut = pSampleRateRanges[iCurrentClosestRange].mMinimum;
ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
return MA_SUCCESS;
}
/* Should never get here, but it would mean we weren't able to find any suitable sample rates. */
/*ma_free(pSampleRateRanges, &pContext->allocationCallbacks);*/
/*return MA_ERROR;*/
}
#endif
static ma_result ma_get_AudioObject_closest_buffer_size_in_frames(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32 bufferSizeInFramesIn, ma_uint32* pBufferSizeInFramesOut)
{
AudioObjectPropertyAddress propAddress;
AudioValueRange bufferSizeRange;
UInt32 dataSize;
OSStatus status;
MA_ASSERT(pContext != NULL);
MA_ASSERT(pBufferSizeInFramesOut != NULL);
*pBufferSizeInFramesOut = 0; /* Safety. */
propAddress.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
propAddress.mElement = kAudioObjectPropertyElementMaster;
dataSize = sizeof(bufferSizeRange);
status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &bufferSizeRange);
if (status != noErr) {
return ma_result_from_OSStatus(status);
}
/* This is just a clamp. */
if (bufferSizeInFramesIn < bufferSizeRange.mMinimum) {
*pBufferSizeInFramesOut = (ma_uint32)bufferSizeRange.mMinimum;
} else if (bufferSizeInFramesIn > bufferSizeRange.mMaximum) {
*pBufferSizeInFramesOut = (ma_uint32)bufferSizeRange.mMaximum;
} else {
*pBufferSizeInFramesOut = bufferSizeInFramesIn;
}
return MA_SUCCESS;
}
static ma_result ma_set_AudioObject_buffer_size_in_frames(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32* pPeriodSizeInOut)
{
ma_result result;
ma_uint32 chosenBufferSizeInFrames;
AudioObjectPropertyAddress propAddress;
UInt32 dataSize;
OSStatus status;
MA_ASSERT(pContext != NULL);
result = ma_get_AudioObject_closest_buffer_size_in_frames(pContext, deviceObjectID, deviceType, *pPeriodSizeInOut, &chosenBufferSizeInFrames);
if (result != MA_SUCCESS) {
return result;
}
/* Try setting the size of the buffer... If this fails we just use whatever is currently set. */
propAddress.mSelector = kAudioDevicePropertyBufferFrameSize;
propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
propAddress.mElement = kAudioObjectPropertyElementMaster;
((ma_AudioObjectSetPropertyData_proc)pContext->coreaudio.AudioObjectSetPropertyData)(deviceObjectID, &propAddress, 0, NULL, sizeof(chosenBufferSizeInFrames), &chosenBufferSizeInFrames);
/* Get the actual size of the buffer. */
dataSize = sizeof(*pPeriodSizeInOut);
status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &chosenBufferSizeInFrames);
if (status != noErr) {
return ma_result_from_OSStatus(status);
}
*pPeriodSizeInOut = chosenBufferSizeInFrames;
return MA_SUCCESS;
}
static ma_result ma_find_AudioObjectID(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, AudioObjectID* pDeviceObjectID)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pDeviceObjectID != NULL);
/* Safety. */
*pDeviceObjectID = 0;
if (pDeviceID == NULL) {
/* Default device. */
AudioObjectPropertyAddress propAddressDefaultDevice;
UInt32 defaultDeviceObjectIDSize = sizeof(AudioObjectID);
AudioObjectID defaultDeviceObjectID;
OSStatus status;
propAddressDefaultDevice.mScope = kAudioObjectPropertyScopeGlobal;
propAddressDefaultDevice.mElement = kAudioObjectPropertyElementMaster;
if (deviceType == ma_device_type_playback) {
propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
} else {
propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultInputDevice;
}
defaultDeviceObjectIDSize = sizeof(AudioObjectID);
status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDefaultDevice, 0, NULL, &defaultDeviceObjectIDSize, &defaultDeviceObjectID);
if (status == noErr) {
*pDeviceObjectID = defaultDeviceObjectID;
return MA_SUCCESS;
}
} else {
/* Explicit device. */
UInt32 deviceCount;
AudioObjectID* pDeviceObjectIDs;
ma_result result;
UInt32 iDevice;
result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs);
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
retrieve from the AVAudioSession shared instance.
*/
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_RemoteIO;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc);
if (component == NULL) {
return MA_FAILED_TO_INIT_BACKEND;
}
status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)(component, &audioUnit);
if (status != noErr) {
return ma_result_from_OSStatus(status);
}
formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output;
formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS;
propSize = sizeof(bestFormat);
status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, &propSize);
if (status != noErr) {
((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit);
return ma_result_from_OSStatus(status);
}
((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit);
audioUnit = NULL;
pDeviceInfo->minChannels = bestFormat.mChannelsPerFrame;
pDeviceInfo->maxChannels = bestFormat.mChannelsPerFrame;
pDeviceInfo->formatCount = 1;
result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pDeviceInfo->formats[0]);
if (result != MA_SUCCESS) {
return result;
}
/*
It looks like Apple are wanting to push the whole AVAudioSession thing. Thus, we need to use that to determine device settings. To do
this we just get the shared instance and inspect.
*/
@autoreleasepool {
AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
MA_ASSERT(pAudioSession != NULL);
pDeviceInfo->minSampleRate = (ma_uint32)pAudioSession.sampleRate;
pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate;
}
}
#endif
(void)pDeviceInfo; /* Unused. */
return MA_SUCCESS;
}
static OSStatus ma_on_output__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pBufferList)
{
ma_device* pDevice = (ma_device*)pUserData;
ma_stream_layout layout;
MA_ASSERT(pDevice != NULL);
#if defined(MA_DEBUG_OUTPUT)
printf("INFO: Output Callback: busNumber=%d, frameCount=%d, mNumberBuffers=%d\n", busNumber, frameCount, pBufferList->mNumberBuffers);
#endif
/* We need to check whether or not we are outputting interleaved or non-interleaved samples. The way we do this is slightly different for each type. */
layout = ma_stream_layout_interleaved;
if (pBufferList->mBuffers[0].mNumberChannels != pDevice->playback.internalChannels) {
layout = ma_stream_layout_deinterleaved;
}
if (layout == ma_stream_layout_interleaved) {
/* For now we can assume everything is interleaved. */
UInt32 iBuffer;
for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) {
if (pBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->playback.internalChannels) {
ma_uint32 frameCountForThisBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
if (frameCountForThisBuffer > 0) {
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_playback(pDevice, frameCountForThisBuffer, pBufferList->mBuffers[iBuffer].mData, &pDevice->coreaudio.duplexRB);
} else {
ma_device__read_frames_from_client(pDevice, frameCountForThisBuffer, pBufferList->mBuffers[iBuffer].mData);
}
}
#if defined(MA_DEBUG_OUTPUT)
printf(" frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", frameCount, pBufferList->mBuffers[iBuffer].mNumberChannels, pBufferList->mBuffers[iBuffer].mDataByteSize);
#endif
} else {
/*
This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's
not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams. We just
output silence here.
*/
MA_ZERO_MEMORY(pBufferList->mBuffers[iBuffer].mData, pBufferList->mBuffers[iBuffer].mDataByteSize);
#if defined(MA_DEBUG_OUTPUT)
printf(" WARNING: Outputting silence. frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", frameCount, pBufferList->mBuffers[iBuffer].mNumberChannels, pBufferList->mBuffers[iBuffer].mDataByteSize);
#endif
}
}
} else {
/* This is the deinterleaved case. We need to update each buffer in groups of internalChannels. This assumes each buffer is the same size. */
MA_ASSERT(pDevice->playback.internalChannels <= MA_MAX_CHANNELS); /* This should heve been validated at initialization time. */
/*
For safety we'll check that the internal channels is a multiple of the buffer count. If it's not it means something
very strange has happened and we're not going to support it.
*/
if ((pBufferList->mNumberBuffers % pDevice->playback.internalChannels) == 0) {
ma_uint8 tempBuffer[4096];
UInt32 iBuffer;
for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; iBuffer += pDevice->playback.internalChannels) {
ma_uint32 frameCountPerBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / ma_get_bytes_per_sample(pDevice->playback.internalFormat);
ma_uint32 framesRemaining = frameCountPerBuffer;
while (framesRemaining > 0) {
void* ppDeinterleavedBuffers[MA_MAX_CHANNELS];
ma_uint32 iChannel;
ma_uint32 framesToRead = sizeof(tempBuffer) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
if (framesToRead > framesRemaining) {
framesToRead = framesRemaining;
}
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_playback(pDevice, framesToRead, tempBuffer, &pDevice->coreaudio.duplexRB);
} else {
ma_device__read_frames_from_client(pDevice, framesToRead, tempBuffer);
}
for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) {
ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pBufferList->mBuffers[iBuffer+iChannel].mData, (frameCountPerBuffer - framesRemaining) * ma_get_bytes_per_sample(pDevice->playback.internalFormat));
}
ma_deinterleave_pcm_frames(pDevice->playback.internalFormat, pDevice->playback.internalChannels, framesToRead, tempBuffer, ppDeinterleavedBuffers);
framesRemaining -= framesToRead;
}
}
}
}
(void)pActionFlags;
(void)pTimeStamp;
(void)busNumber;
(void)frameCount;
return noErr;
}
static OSStatus ma_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pUnusedBufferList)
{
ma_device* pDevice = (ma_device*)pUserData;
AudioBufferList* pRenderedBufferList;
ma_stream_layout layout;
OSStatus status;
MA_ASSERT(pDevice != NULL);
pRenderedBufferList = (AudioBufferList*)pDevice->coreaudio.pAudioBufferList;
MA_ASSERT(pRenderedBufferList);
/* We need to check whether or not we are outputting interleaved or non-interleaved samples. The way we do this is slightly different for each type. */
layout = ma_stream_layout_interleaved;
if (pRenderedBufferList->mBuffers[0].mNumberChannels != pDevice->capture.internalChannels) {
layout = ma_stream_layout_deinterleaved;
}
#if defined(MA_DEBUG_OUTPUT)
printf("INFO: Input Callback: busNumber=%d, frameCount=%d, mNumberBuffers=%d\n", busNumber, frameCount, pRenderedBufferList->mNumberBuffers);
#endif
status = ((ma_AudioUnitRender_proc)pDevice->pContext->coreaudio.AudioUnitRender)((AudioUnit)pDevice->coreaudio.audioUnitCapture, pActionFlags, pTimeStamp, busNumber, frameCount, pRenderedBufferList);
if (status != noErr) {
#if defined(MA_DEBUG_OUTPUT)
printf(" ERROR: AudioUnitRender() failed with %d\n", status);
#endif
return status;
}
if (layout == ma_stream_layout_interleaved) {
UInt32 iBuffer;
for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) {
if (pRenderedBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->capture.internalChannels) {
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_capture(pDevice, frameCount, pRenderedBufferList->mBuffers[iBuffer].mData, &pDevice->coreaudio.duplexRB);
} else {
ma_device__send_frames_to_client(pDevice, frameCount, pRenderedBufferList->mBuffers[iBuffer].mData);
}
#if defined(MA_DEBUG_OUTPUT)
printf(" mDataByteSize=%d\n", pRenderedBufferList->mBuffers[iBuffer].mDataByteSize);
#endif
} else {
/*
This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's
not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams.
*/
ma_uint8 silentBuffer[4096];
ma_uint32 framesRemaining;
MA_ZERO_MEMORY(silentBuffer, sizeof(silentBuffer));
framesRemaining = frameCount;
while (framesRemaining > 0) {
ma_uint32 framesToSend = sizeof(silentBuffer) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
if (framesToSend > framesRemaining) {
framesToSend = framesRemaining;
}
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_capture(pDevice, framesToSend, silentBuffer, &pDevice->coreaudio.duplexRB);
} else {
ma_device__send_frames_to_client(pDevice, framesToSend, silentBuffer);
}
framesRemaining -= framesToSend;
}
#if defined(MA_DEBUG_OUTPUT)
printf(" WARNING: Outputting silence. frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", frameCount, pRenderedBufferList->mBuffers[iBuffer].mNumberChannels, pRenderedBufferList->mBuffers[iBuffer].mDataByteSize);
#endif
}
}
} else {
/* This is the deinterleaved case. We need to interleave the audio data before sending it to the client. This assumes each buffer is the same size. */
MA_ASSERT(pDevice->capture.internalChannels <= MA_MAX_CHANNELS); /* This should have been validated at initialization time. */
/*
For safety we'll check that the internal channels is a multiple of the buffer count. If it's not it means something
very strange has happened and we're not going to support it.
*/
if ((pRenderedBufferList->mNumberBuffers % pDevice->capture.internalChannels) == 0) {
ma_uint8 tempBuffer[4096];
UInt32 iBuffer;
for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; iBuffer += pDevice->capture.internalChannels) {
ma_uint32 framesRemaining = frameCount;
while (framesRemaining > 0) {
void* ppDeinterleavedBuffers[MA_MAX_CHANNELS];
ma_uint32 iChannel;
ma_uint32 framesToSend = sizeof(tempBuffer) / ma_get_bytes_per_sample(pDevice->capture.internalFormat);
if (framesToSend > framesRemaining) {
framesToSend = framesRemaining;
}
for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) {
ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pRenderedBufferList->mBuffers[iBuffer+iChannel].mData, (frameCount - framesRemaining) * ma_get_bytes_per_sample(pDevice->capture.internalFormat));
}
ma_interleave_pcm_frames(pDevice->capture.internalFormat, pDevice->capture.internalChannels, framesToSend, (const void**)ppDeinterleavedBuffers, tempBuffer);
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_capture(pDevice, framesToSend, tempBuffer, &pDevice->coreaudio.duplexRB);
} else {
ma_device__send_frames_to_client(pDevice, framesToSend, tempBuffer);
}
framesRemaining -= framesToSend;
}
}
}
}
(void)pActionFlags;
(void)pTimeStamp;
(void)busNumber;
(void)frameCount;
(void)pUnusedBufferList;
return noErr;
}
static void on_start_stop__coreaudio(void* pUserData, AudioUnit audioUnit, AudioUnitPropertyID propertyID, AudioUnitScope scope, AudioUnitElement element)
{
ma_device* pDevice = (ma_device*)pUserData;
MA_ASSERT(pDevice != NULL);
/*
There's been a report of a deadlock here when triggered by ma_device_uninit(). It looks like
AudioUnitGetProprty (called below) and AudioComponentInstanceDispose (called in ma_device_uninit)
can try waiting on the same lock. I'm going to try working around this by not calling any Core
Audio APIs in the callback when the device has been stopped or uninitialized.
*/
if (ma_device__get_state(pDevice) == MA_STATE_UNINITIALIZED || ma_device__get_state(pDevice) == MA_STATE_STOPPING || ma_device__get_state(pDevice) == MA_STATE_STOPPED) {
ma_stop_proc onStop = pDevice->onStop;
if (onStop) {
onStop(pDevice);
}
ma_event_signal(&pDevice->coreaudio.stopEvent);
} else {
UInt32 isRunning;
UInt32 isRunningSize = sizeof(isRunning);
OSStatus status = ((ma_AudioUnitGetProperty_proc)pDevice->pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioOutputUnitProperty_IsRunning, scope, element, &isRunning, &isRunningSize);
if (status != noErr) {
return; /* Don't really know what to do in this case... just ignore it, I suppose... */
}
if (!isRunning) {
ma_stop_proc onStop;
/*
The stop event is a bit annoying in Core Audio because it will be called when we automatically switch the default device. Some scenarios to consider:
1) When the device is unplugged, this will be called _before_ the default device change notification.
2) When the device is changed via the default device change notification, this will be called _after_ the switch.
For case #1, we just check if there's a new default device available. If so, we just ignore the stop event. For case #2 we check a flag.
*/
if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isDefaultPlaybackDevice) ||
((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isDefaultCaptureDevice)) {
/*
It looks like the device is switching through an external event, such as the user unplugging the device or changing the default device
via the operating system's sound settings. If we're re-initializing the device, we just terminate because we want the stopping of the
device to be seamless to the client (we don't want them receiving the onStop event and thinking that the device has stopped when it
hasn't!).
*/
if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isSwitchingPlaybackDevice) ||
((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isSwitchingCaptureDevice)) {
return;
}
/*
Getting here means the device is not reinitializing which means it may have been unplugged. From what I can see, it looks like Core Audio
will try switching to the new default device seamlessly. We need to somehow find a way to determine whether or not Core Audio will most
likely be successful in switching to the new device.
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, sizeof(bestFormat));
if (status != noErr) {
((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
return ma_result_from_OSStatus(status);
}
#endif
result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pData->formatOut);
if (result != MA_SUCCESS) {
((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
return result;
}
if (pData->formatOut == ma_format_unknown) {
((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
return MA_FORMAT_NOT_SUPPORTED;
}
pData->channelsOut = bestFormat.mChannelsPerFrame;
pData->sampleRateOut = bestFormat.mSampleRate;
}
/* Clamp the channel count for safety. */
if (pData->channelsOut > MA_MAX_CHANNELS) {
pData->channelsOut = MA_MAX_CHANNELS;
}
/*
Internal channel map. This is weird in my testing. If I use the AudioObject to get the
channel map, the channel descriptions are set to "Unknown" for some reason. To work around
this it looks like retrieving it from the AudioUnit will work. However, and this is where
it gets weird, it doesn't seem to work with capture devices, nor at all on iOS... Therefore
I'm going to fall back to a default assumption in these cases.
*/
#if defined(MA_APPLE_DESKTOP)
result = ma_get_AudioUnit_channel_map(pContext, pData->audioUnit, deviceType, pData->channelMapOut, pData->channelsOut);
if (result != MA_SUCCESS) {
#if 0
/* Try falling back to the channel map from the AudioObject. */
result = ma_get_AudioObject_channel_map(pContext, deviceObjectID, deviceType, pData->channelMapOut, pData->channelsOut);
if (result != MA_SUCCESS) {
return result;
}
#else
/* Fall back to default assumptions. */
ma_get_standard_channel_map(ma_standard_channel_map_default, pData->channelsOut, pData->channelMapOut);
#endif
}
#else
/* TODO: Figure out how to get the channel map using AVAudioSession. */
ma_get_standard_channel_map(ma_standard_channel_map_default, pData->channelsOut, pData->channelMapOut);
#endif
/* Buffer size. Not allowing this to be configurable on iOS. */
actualPeriodSizeInFrames = pData->periodSizeInFramesIn;
#if defined(MA_APPLE_DESKTOP)
if (actualPeriodSizeInFrames == 0) {
actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pData->periodSizeInMillisecondsIn, pData->sampleRateOut);
}
result = ma_set_AudioObject_buffer_size_in_frames(pContext, deviceObjectID, deviceType, &actualPeriodSizeInFrames);
if (result != MA_SUCCESS) {
return result;
}
pData->periodSizeInFramesOut = actualPeriodSizeInFrames;
#else
actualPeriodSizeInFrames = 2048;
pData->periodSizeInFramesOut = actualPeriodSizeInFrames;
#endif
/*
During testing I discovered that the buffer size can be too big. You'll get an error like this:
kAudioUnitErr_TooManyFramesToProcess : inFramesToProcess=4096, mMaxFramesPerSlice=512
Note how inFramesToProcess is smaller than mMaxFramesPerSlice. To fix, we need to set kAudioUnitProperty_MaximumFramesPerSlice to that
of the size of our buffer, or do it the other way around and set our buffer size to the kAudioUnitProperty_MaximumFramesPerSlice.
*/
{
/*AudioUnitScope propScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output;
AudioUnitElement propBus = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS;
status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_MaximumFramesPerSlice, propScope, propBus, &actualBufferSizeInFrames, sizeof(actualBufferSizeInFrames));
if (status != noErr) {
((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
return ma_result_from_OSStatus(status);
}*/
status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &actualPeriodSizeInFrames, sizeof(actualPeriodSizeInFrames));
if (status != noErr) {
((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
return ma_result_from_OSStatus(status);
}
}
/* We need a buffer list if this is an input device. We render into this in the input callback. */
if (deviceType == ma_device_type_capture) {
ma_bool32 isInterleaved = (bestFormat.mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0;
size_t allocationSize;
AudioBufferList* pBufferList;
allocationSize = sizeof(AudioBufferList) - sizeof(AudioBuffer); /* Subtract sizeof(AudioBuffer) because that part is dynamically sized. */
if (isInterleaved) {
/* Interleaved case. This is the simple case because we just have one buffer. */
allocationSize += sizeof(AudioBuffer) * 1;
allocationSize += actualPeriodSizeInFrames * ma_get_bytes_per_frame(pData->formatOut, pData->channelsOut);
} else {
/* Non-interleaved case. This is the more complex case because there's more than one buffer. */
allocationSize += sizeof(AudioBuffer) * pData->channelsOut;
allocationSize += actualPeriodSizeInFrames * ma_get_bytes_per_sample(pData->formatOut) * pData->channelsOut;
}
pBufferList = (AudioBufferList*)ma__malloc_from_callbacks(allocationSize, &pContext->allocationCallbacks);
if (pBufferList == NULL) {
((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
return MA_OUT_OF_MEMORY;
}
if (isInterleaved) {
pBufferList->mNumberBuffers = 1;
pBufferList->mBuffers[0].mNumberChannels = pData->channelsOut;
pBufferList->mBuffers[0].mDataByteSize = actualPeriodSizeInFrames * ma_get_bytes_per_frame(pData->formatOut, pData->channelsOut);
pBufferList->mBuffers[0].mData = (ma_uint8*)pBufferList + sizeof(AudioBufferList);
} else {
ma_uint32 iBuffer;
pBufferList->mNumberBuffers = pData->channelsOut;
for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) {
pBufferList->mBuffers[iBuffer].mNumberChannels = 1;
pBufferList->mBuffers[iBuffer].mDataByteSize = actualPeriodSizeInFrames * ma_get_bytes_per_sample(pData->formatOut);
pBufferList->mBuffers[iBuffer].mData = (ma_uint8*)pBufferList + ((sizeof(AudioBufferList) - sizeof(AudioBuffer)) + (sizeof(AudioBuffer) * pData->channelsOut)) + (actualPeriodSizeInFrames * ma_get_bytes_per_sample(pData->form...
}
}
pData->pAudioBufferList = pBufferList;
}
/* Callbacks. */
callbackInfo.inputProcRefCon = pDevice_DoNotReference;
if (deviceType == ma_device_type_playback) {
callbackInfo.inputProc = ma_on_output__coreaudio;
status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Global, MA_COREAUDIO_OUTPUT_BUS, &callbackInfo, sizeof(callbackInfo));
if (status != noErr) {
((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
return ma_result_from_OSStatus(status);
}
} else {
callbackInfo.inputProc = ma_on_input__coreaudio;
status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, MA_COREAUDIO_INPUT_BUS, &callbackInfo, sizeof(callbackInfo));
if (status != noErr) {
((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
return ma_result_from_OSStatus(status);
}
}
/* We need to listen for stop events. */
if (pData->registerStopEvent) {
status = ((ma_AudioUnitAddPropertyListener_proc)pContext->coreaudio.AudioUnitAddPropertyListener)(pData->audioUnit, kAudioOutputUnitProperty_IsRunning, on_start_stop__coreaudio, pDevice_DoNotReference);
if (status != noErr) {
((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
return ma_result_from_OSStatus(status);
}
}
/* Initialize the audio unit. */
status = ((ma_AudioUnitInitialize_proc)pContext->coreaudio.AudioUnitInitialize)(pData->audioUnit);
if (status != noErr) {
ma__free_from_callbacks(pData->pAudioBufferList, &pContext->allocationCallbacks);
pData->pAudioBufferList = NULL;
((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
return ma_result_from_OSStatus(status);
}
/* Grab the name. */
#if defined(MA_APPLE_DESKTOP)
ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(pData->deviceName), pData->deviceName);
#else
if (deviceType == ma_device_type_playback) {
ma_strcpy_s(pData->deviceName, sizeof(pData->deviceName), MA_DEFAULT_PLAYBACK_DEVICE_NAME);
} else {
ma_strcpy_s(pData->deviceName, sizeof(pData->deviceName), MA_DEFAULT_CAPTURE_DEVICE_NAME);
}
#endif
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
/* In full-duplex mode we want the playback buffer to be the same size as the capture buffer. */
if (pConfig->deviceType == ma_device_type_duplex) {
data.periodSizeInFramesIn = pDevice->capture.internalPeriodSizeInFrames;
data.periodsIn = pDevice->capture.internalPeriods;
data.registerStopEvent = MA_FALSE;
} else {
data.periodSizeInFramesIn = pConfig->periodSizeInFrames;
data.periodSizeInMillisecondsIn = pConfig->periodSizeInMilliseconds;
data.periodsIn = pConfig->periods;
data.registerStopEvent = MA_TRUE;
}
result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_playback, pConfig->playback.pDeviceID, &data, (void*)pDevice);
if (result != MA_SUCCESS) {
if (pConfig->deviceType == ma_device_type_duplex) {
((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
if (pDevice->coreaudio.pAudioBufferList) {
ma__free_from_callbacks(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
}
}
return result;
}
pDevice->coreaudio.isDefaultPlaybackDevice = (pConfig->playback.pDeviceID == NULL);
#if defined(MA_APPLE_DESKTOP)
pDevice->coreaudio.deviceObjectIDPlayback = (ma_uint32)data.deviceObjectID;
#endif
pDevice->coreaudio.audioUnitPlayback = (ma_ptr)data.audioUnit;
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;
#if defined(MA_APPLE_DESKTOP)
/*
If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly
switch the device in the background.
*/
if (pConfig->playback.pDeviceID == NULL && (pConfig->deviceType != ma_device_type_duplex || pConfig->capture.pDeviceID != NULL)) {
ma_device__track__coreaudio(pDevice);
}
#endif
}
pDevice->coreaudio.originalPeriodSizeInFrames = pConfig->periodSizeInFrames;
pDevice->coreaudio.originalPeriodSizeInMilliseconds = pConfig->periodSizeInMilliseconds;
pDevice->coreaudio.originalPeriods = pConfig->periods;
/*
When stopping the device, a callback is called on another thread. We need to wait for this callback
before returning from ma_device_stop(). This event is used for this.
*/
ma_event_init(&pDevice->coreaudio.stopEvent);
/* Need a ring buffer for duplex mode. */
if (pConfig->deviceType == ma_device_type_duplex) {
ma_uint32 rbSizeInFrames = (ma_uint32)ma_calculate_frame_count_after_resampling(pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalPeriodSizeInFrames * pDevice->capture.internalPeriods);
ma_result result = ma_pcm_rb_init(pDevice->capture.format, pDevice->capture.channels, rbSizeInFrames, NULL, &pDevice->pContext->allocationCallbacks, &pDevice->coreaudio.duplexRB);
if (result != MA_SUCCESS) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[Core Audio] Failed to initialize ring buffer.", result);
}
/* We need a period to act as a buffer for cases where the playback and capture device's end up desyncing. */
{
ma_uint32 bufferSizeInFrames = rbSizeInFrames / pDevice->capture.internalPeriods;
void* pBufferData;
ma_pcm_rb_acquire_write(&pDevice->coreaudio.duplexRB, &bufferSizeInFrames, &pBufferData);
{
MA_ZERO_MEMORY(pBufferData, bufferSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels));
}
ma_pcm_rb_commit_write(&pDevice->coreaudio.duplexRB, bufferSizeInFrames, pBufferData);
}
}
/*
We need to detect when a route has changed so we can update the data conversion pipeline accordingly. This is done
differently on non-Desktop Apple platforms.
*/
#if defined(MA_APPLE_MOBILE)
pDevice->coreaudio.pRouteChangeHandler = (__bridge_retained void*)[[ma_router_change_handler alloc] init:pDevice];
#endif
return MA_SUCCESS;
}
static ma_result ma_device_start__coreaudio(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
if (status != noErr) {
return ma_result_from_OSStatus(status);
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
if (status != noErr) {
if (pDevice->type == ma_device_type_duplex) {
((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
}
return ma_result_from_OSStatus(status);
}
}
return MA_SUCCESS;
}
static ma_result ma_device_stop__coreaudio(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
/* It's not clear from the documentation whether or not AudioOutputUnitStop() actually drains the device or not. */
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
OSStatus status = ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
if (status != noErr) {
return ma_result_from_OSStatus(status);
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
OSStatus status = ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
if (status != noErr) {
return ma_result_from_OSStatus(status);
}
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
case ma_ios_session_category_play_and_record: return AVAudioSessionCategoryPlayAndRecord;
case ma_ios_session_category_multi_route: return AVAudioSessionCategoryMultiRoute;
case ma_ios_session_category_none: return AVAudioSessionCategoryAmbient;
case ma_ios_session_category_default: return AVAudioSessionCategoryAmbient;
default: return AVAudioSessionCategoryAmbient;
}
}
#endif
static ma_result ma_context_init__coreaudio(const ma_context_config* pConfig, ma_context* pContext)
{
#if !defined(MA_APPLE_MOBILE)
ma_result result;
#endif
MA_ASSERT(pConfig != NULL);
MA_ASSERT(pContext != NULL);
#if defined(MA_APPLE_MOBILE)
@autoreleasepool {
AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
AVAudioSessionCategoryOptions options = pConfig->coreaudio.sessionCategoryOptions;
MA_ASSERT(pAudioSession != NULL);
if (pConfig->coreaudio.sessionCategory == ma_ios_session_category_default) {
/*
I'm going to use trial and error to determine our default session category. First we'll try PlayAndRecord. If that fails
we'll try Playback and if that fails we'll try record. If all of these fail we'll just not set the category.
*/
#if !defined(MA_APPLE_TV) && !defined(MA_APPLE_WATCH)
options |= AVAudioSessionCategoryOptionDefaultToSpeaker;
#endif
if ([pAudioSession setCategory: AVAudioSessionCategoryPlayAndRecord withOptions:options error:nil]) {
/* Using PlayAndRecord */
} else if ([pAudioSession setCategory: AVAudioSessionCategoryPlayback withOptions:options error:nil]) {
/* Using Playback */
} else if ([pAudioSession setCategory: AVAudioSessionCategoryRecord withOptions:options error:nil]) {
/* Using Record */
} else {
/* Leave as default? */
}
} else {
if (pConfig->coreaudio.sessionCategory != ma_ios_session_category_none) {
if (![pAudioSession setCategory: ma_to_AVAudioSessionCategory(pConfig->coreaudio.sessionCategory) withOptions:options error:nil]) {
return MA_INVALID_OPERATION; /* Failed to set session category. */
}
}
}
if (!pConfig->coreaudio.noAudioSessionActivate) {
if (![pAudioSession setActive:true error:nil]) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "Failed to activate audio session.", MA_FAILED_TO_INIT_BACKEND);
}
}
}
#endif
#if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
pContext->coreaudio.hCoreFoundation = ma_dlopen(pContext, "CoreFoundation.framework/CoreFoundation");
if (pContext->coreaudio.hCoreFoundation == NULL) {
return MA_API_NOT_FOUND;
}
pContext->coreaudio.CFStringGetCString = ma_dlsym(pContext, pContext->coreaudio.hCoreFoundation, "CFStringGetCString");
pContext->coreaudio.CFRelease = ma_dlsym(pContext, pContext->coreaudio.hCoreFoundation, "CFRelease");
pContext->coreaudio.hCoreAudio = ma_dlopen(pContext, "CoreAudio.framework/CoreAudio");
if (pContext->coreaudio.hCoreAudio == NULL) {
ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
return MA_API_NOT_FOUND;
}
pContext->coreaudio.AudioObjectGetPropertyData = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyData");
pContext->coreaudio.AudioObjectGetPropertyDataSize = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyDataSize");
pContext->coreaudio.AudioObjectSetPropertyData = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectSetPropertyData");
pContext->coreaudio.AudioObjectAddPropertyListener = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectAddPropertyListener");
pContext->coreaudio.AudioObjectRemovePropertyListener = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectRemovePropertyListener");
/*
It looks like Apple has moved some APIs from AudioUnit into AudioToolbox on more recent versions of macOS. They are still
defined in AudioUnit, but just in case they decide to remove them from there entirely I'm going to implement a fallback.
The way it'll work is that it'll first try AudioUnit, and if the required symbols are not present there we'll fall back to
AudioToolbox.
*/
pContext->coreaudio.hAudioUnit = ma_dlopen(pContext, "AudioUnit.framework/AudioUnit");
if (pContext->coreaudio.hAudioUnit == NULL) {
ma_dlclose(pContext, pContext->coreaudio.hCoreAudio);
ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
return MA_API_NOT_FOUND;
}
if (ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioComponentFindNext") == NULL) {
/* Couldn't find the required symbols in AudioUnit, so fall back to AudioToolbox. */
ma_dlclose(pContext, pContext->coreaudio.hAudioUnit);
pContext->coreaudio.hAudioUnit = ma_dlopen(pContext, "AudioToolbox.framework/AudioToolbox");
if (pContext->coreaudio.hAudioUnit == NULL) {
ma_dlclose(pContext, pContext->coreaudio.hCoreAudio);
ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
return MA_API_NOT_FOUND;
}
}
pContext->coreaudio.AudioComponentFindNext = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioComponentFindNext");
pContext->coreaudio.AudioComponentInstanceDispose = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioComponentInstanceDispose");
pContext->coreaudio.AudioComponentInstanceNew = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioComponentInstanceNew");
pContext->coreaudio.AudioOutputUnitStart = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioOutputUnitStart");
pContext->coreaudio.AudioOutputUnitStop = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioOutputUnitStop");
pContext->coreaudio.AudioUnitAddPropertyListener = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitAddPropertyListener");
pContext->coreaudio.AudioUnitGetPropertyInfo = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitGetPropertyInfo");
pContext->coreaudio.AudioUnitGetProperty = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitGetProperty");
pContext->coreaudio.AudioUnitSetProperty = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitSetProperty");
pContext->coreaudio.AudioUnitInitialize = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitInitialize");
pContext->coreaudio.AudioUnitRender = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitRender");
#else
pContext->coreaudio.CFStringGetCString = (ma_proc)CFStringGetCString;
pContext->coreaudio.CFRelease = (ma_proc)CFRelease;
#if defined(MA_APPLE_DESKTOP)
pContext->coreaudio.AudioObjectGetPropertyData = (ma_proc)AudioObjectGetPropertyData;
pContext->coreaudio.AudioObjectGetPropertyDataSize = (ma_proc)AudioObjectGetPropertyDataSize;
pContext->coreaudio.AudioObjectSetPropertyData = (ma_proc)AudioObjectSetPropertyData;
pContext->coreaudio.AudioObjectAddPropertyListener = (ma_proc)AudioObjectAddPropertyListener;
pContext->coreaudio.AudioObjectRemovePropertyListener = (ma_proc)AudioObjectRemovePropertyListener;
#endif
pContext->coreaudio.AudioComponentFindNext = (ma_proc)AudioComponentFindNext;
pContext->coreaudio.AudioComponentInstanceDispose = (ma_proc)AudioComponentInstanceDispose;
pContext->coreaudio.AudioComponentInstanceNew = (ma_proc)AudioComponentInstanceNew;
pContext->coreaudio.AudioOutputUnitStart = (ma_proc)AudioOutputUnitStart;
pContext->coreaudio.AudioOutputUnitStop = (ma_proc)AudioOutputUnitStop;
pContext->coreaudio.AudioUnitAddPropertyListener = (ma_proc)AudioUnitAddPropertyListener;
pContext->coreaudio.AudioUnitGetPropertyInfo = (ma_proc)AudioUnitGetPropertyInfo;
pContext->coreaudio.AudioUnitGetProperty = (ma_proc)AudioUnitGetProperty;
pContext->coreaudio.AudioUnitSetProperty = (ma_proc)AudioUnitSetProperty;
pContext->coreaudio.AudioUnitInitialize = (ma_proc)AudioUnitInitialize;
pContext->coreaudio.AudioUnitRender = (ma_proc)AudioUnitRender;
#endif
pContext->isBackendAsynchronous = MA_TRUE;
pContext->onUninit = ma_context_uninit__coreaudio;
pContext->onDeviceIDEqual = ma_context_is_device_id_equal__coreaudio;
pContext->onEnumDevices = ma_context_enumerate_devices__coreaudio;
pContext->onGetDeviceInfo = ma_context_get_device_info__coreaudio;
pContext->onDeviceInit = ma_device_init__coreaudio;
pContext->onDeviceUninit = ma_device_uninit__coreaudio;
pContext->onDeviceStart = ma_device_start__coreaudio;
pContext->onDeviceStop = ma_device_stop__coreaudio;
/* Audio component. */
{
AudioComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
#if defined(MA_APPLE_DESKTOP)
desc.componentSubType = kAudioUnitSubType_HALOutput;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
format = ma_find_best_format_from_sio_cap__sndio(&caps);
}
if (pDevice->playback.usingDefaultChannels) {
if (strlen(pDeviceName) > strlen("rsnd/") && strncmp(pDeviceName, "rsnd/", strlen("rsnd/")) == 0) {
channels = ma_find_best_channels_from_sio_cap__sndio(&caps, deviceType, format);
}
}
}
if (pDevice->usingDefaultSampleRate) {
sampleRate = ma_find_best_sample_rate_from_sio_cap__sndio(&caps, pConfig->deviceType, format, channels);
}
((ma_sio_initpar_proc)pDevice->pContext->sndio.sio_initpar)(&par);
par.msb = 0;
par.le = ma_is_little_endian();
switch (format) {
case ma_format_u8:
{
par.bits = 8;
par.bps = 1;
par.sig = 0;
} break;
case ma_format_s24:
{
par.bits = 24;
par.bps = 3;
par.sig = 1;
} break;
case ma_format_s32:
{
par.bits = 32;
par.bps = 4;
par.sig = 1;
} break;
case ma_format_s16:
case ma_format_f32:
default:
{
par.bits = 16;
par.bps = 2;
par.sig = 1;
} break;
}
if (deviceType == ma_device_type_capture) {
par.rchan = channels;
} else {
par.pchan = channels;
}
par.rate = sampleRate;
internalPeriodSizeInFrames = pConfig->periodSizeInFrames;
if (internalPeriodSizeInFrames == 0) {
internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, par.rate);
}
par.round = internalPeriodSizeInFrames;
par.appbufsz = par.round * pConfig->periods;
if (((ma_sio_setpar_proc)pContext->sndio.sio_setpar)((struct ma_sio_hdl*)handle, &par) == 0) {
((ma_sio_close_proc)pContext->sndio.sio_close)((struct ma_sio_hdl*)handle);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[sndio] Failed to set buffer size.", MA_FORMAT_NOT_SUPPORTED);
}
if (((ma_sio_getpar_proc)pContext->sndio.sio_getpar)((struct ma_sio_hdl*)handle, &par) == 0) {
((ma_sio_close_proc)pContext->sndio.sio_close)((struct ma_sio_hdl*)handle);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve buffer size.", MA_FORMAT_NOT_SUPPORTED);
}
internalFormat = ma_format_from_sio_enc__sndio(par.bits, par.bps, par.sig, par.le, par.msb);
internalChannels = (deviceType == ma_device_type_capture) ? par.rchan : par.pchan;
internalSampleRate = par.rate;
internalPeriods = par.appbufsz / par.round;
internalPeriodSizeInFrames = par.round;
if (deviceType == ma_device_type_capture) {
pDevice->sndio.handleCapture = handle;
pDevice->capture.internalFormat = internalFormat;
pDevice->capture.internalChannels = internalChannels;
pDevice->capture.internalSampleRate = internalSampleRate;
ma_get_standard_channel_map(ma_standard_channel_map_sndio, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap);
pDevice->capture.internalPeriodSizeInFrames = internalPeriodSizeInFrames;
pDevice->capture.internalPeriods = internalPeriods;
} else {
pDevice->sndio.handlePlayback = handle;
pDevice->playback.internalFormat = internalFormat;
pDevice->playback.internalChannels = internalChannels;
pDevice->playback.internalSampleRate = internalSampleRate;
ma_get_standard_channel_map(ma_standard_channel_map_sndio, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap);
pDevice->playback.internalPeriodSizeInFrames = internalPeriodSizeInFrames;
pDevice->playback.internalPeriods = internalPeriods;
}
#ifdef MA_DEBUG_OUTPUT
printf("DEVICE INFO\n");
printf(" Format: %s\n", ma_get_format_name(internalFormat));
printf(" Channels: %d\n", internalChannels);
printf(" Sample Rate: %d\n", internalSampleRate);
printf(" Period Size: %d\n", internalPeriodSizeInFrames);
printf(" Periods: %d\n", internalPeriods);
printf(" appbufsz: %d\n", par.appbufsz);
printf(" round: %d\n", par.round);
#endif
return MA_SUCCESS;
}
static ma_result ma_device_init__sndio(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
MA_ZERO_OBJECT(&pDevice->sndio);
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_handle__sndio(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_handle__sndio(pContext, pConfig, ma_device_type_playback, pDevice);
if (result != MA_SUCCESS) {
return result;
}
}
return MA_SUCCESS;
}
static ma_result ma_device_stop__sndio(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
/*
From the documentation:
The sio_stop() function puts the audio subsystem in the same state as before sio_start() is called. It stops recording, drains the play buffer and then
stops playback. If samples to play are queued but playback hasn't started yet then playback is forced immediately; playback will actually stop once the
buffer is drained. In no case are samples in the play buffer discarded.
Therefore, sio_stop() performs all of the necessary draining for us.
*/
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
((ma_sio_stop_proc)pDevice->pContext->sndio.sio_stop)((struct ma_sio_hdl*)pDevice->sndio.handleCapture);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
((ma_sio_stop_proc)pDevice->pContext->sndio.sio_stop)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback);
}
return MA_SUCCESS;
}
static ma_result ma_device_write__sndio(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
{
int result;
if (pFramesWritten != NULL) {
*pFramesWritten = 0;
}
result = ((ma_sio_write_proc)pDevice->pContext->sndio.sio_write)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
if (result == 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[sndio] Failed to send data from the client to the device.", MA_IO_ERROR);
}
if (pFramesWritten != NULL) {
*pFramesWritten = frameCount;
}
return MA_SUCCESS;
}
static ma_result ma_device_read__sndio(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
{
int result;
if (pFramesRead != NULL) {
*pFramesRead = 0;
}
result = ((ma_sio_read_proc)pDevice->pContext->sndio.sio_read)((struct ma_sio_hdl*)pDevice->sndio.handleCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
if (result == 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[sndio] Failed to read data from the device to be sent to the device.", MA_IO_ERROR);
}
if (pFramesRead != NULL) {
*pFramesRead = frameCount;
}
return MA_SUCCESS;
}
static ma_result ma_device_main_loop__sndio(ma_device* pDevice)
{
ma_result result = MA_SUCCESS;
ma_bool32 exitLoop = MA_FALSE;
/* Devices need to be started here. */
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
((ma_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct ma_sio_hdl*)pDevice->sndio.handleCapture);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
((ma_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback); /* <-- Doesn't actually playback until data is written. */
}
while (ma_device__get_state(pDevice) == MA_STATE_STARTED && !exitLoop) {
switch (pDevice->type)
{
case ma_device_type_duplex:
{
/* 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__sndio(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__sndio(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__sndio()... */
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
}
totalCapturedDeviceFramesProcessed += capturedDeviceFramesProcessed;
}
} break;
case ma_device_type_capture:
{
/* We read in chunks of the period size, but use a stack allocated buffer for the intermediary. */
ma_uint8 intermediaryBuffer[8192];
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__sndio(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:
{
/* We write in chunks of the period size, but use a stack allocated buffer for the intermediary. */
ma_uint8 intermediaryBuffer[8192];
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__sndio(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 is stopped. */
ma_device_stop__sndio(pDevice);
return result;
}
static ma_result ma_context_uninit__sndio(ma_context* pContext)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pContext->backend == ma_backend_sndio);
(void)pContext;
return MA_SUCCESS;
}
static ma_result ma_context_init__sndio(const ma_context_config* pConfig, ma_context* pContext)
{
#ifndef MA_NO_RUNTIME_LINKING
const char* libsndioNames[] = {
"libsndio.so"
};
size_t i;
for (i = 0; i < ma_countof(libsndioNames); ++i) {
pContext->sndio.sndioSO = ma_dlopen(pContext, libsndioNames[i]);
if (pContext->sndio.sndioSO != NULL) {
break;
}
}
if (pContext->sndio.sndioSO == NULL) {
return MA_NO_BACKEND;
}
pContext->sndio.sio_open = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_open");
pContext->sndio.sio_close = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_close");
pContext->sndio.sio_setpar = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_setpar");
pContext->sndio.sio_getpar = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_getpar");
pContext->sndio.sio_getcap = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_getcap");
pContext->sndio.sio_write = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_write");
pContext->sndio.sio_read = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_read");
pContext->sndio.sio_start = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_start");
pContext->sndio.sio_stop = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_stop");
pContext->sndio.sio_initpar = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_initpar");
#else
pContext->sndio.sio_open = sio_open;
pContext->sndio.sio_close = sio_close;
pContext->sndio.sio_setpar = sio_setpar;
pContext->sndio.sio_getpar = sio_getpar;
pContext->sndio.sio_getcap = sio_getcap;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
if (fd != -1) {
break;
}
}
} else {
/* Specific device. */
fd = open((deviceType == ma_device_type_capture) ? pConfig->capture.pDeviceID->audio4 : pConfig->playback.pDeviceID->audio4, fdFlags, 0);
}
if (fd == -1) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to open device.", ma_result_from_errno(errno));
}
#if !defined(MA_AUDIO4_USE_NEW_API) /* Old API */
AUDIO_INITINFO(&fdInfo);
/* We get the driver to do as much of the data conversion as possible. */
if (deviceType == ma_device_type_capture) {
fdInfo.mode = AUMODE_RECORD;
ma_encoding_from_format__audio4(pConfig->capture.format, &fdInfo.record.encoding, &fdInfo.record.precision);
fdInfo.record.channels = pConfig->capture.channels;
fdInfo.record.sample_rate = pConfig->sampleRate;
} else {
fdInfo.mode = AUMODE_PLAY;
ma_encoding_from_format__audio4(pConfig->playback.format, &fdInfo.play.encoding, &fdInfo.play.precision);
fdInfo.play.channels = pConfig->playback.channels;
fdInfo.play.sample_rate = pConfig->sampleRate;
}
if (ioctl(fd, AUDIO_SETINFO, &fdInfo) < 0) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to set device format. AUDIO_SETINFO failed.", MA_FORMAT_NOT_SUPPORTED);
}
if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] AUDIO_GETINFO failed.", MA_FORMAT_NOT_SUPPORTED);
}
if (deviceType == ma_device_type_capture) {
internalFormat = ma_format_from_prinfo__audio4(&fdInfo.record);
internalChannels = fdInfo.record.channels;
internalSampleRate = fdInfo.record.sample_rate;
} else {
internalFormat = ma_format_from_prinfo__audio4(&fdInfo.play);
internalChannels = fdInfo.play.channels;
internalSampleRate = fdInfo.play.sample_rate;
}
if (internalFormat == ma_format_unknown) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by miniaudio. The device is unusable.", MA_FORMAT_NOT_SUPPORTED);
}
/* Buffer. */
{
ma_uint32 internalPeriodSizeInBytes;
internalPeriodSizeInFrames = pConfig->periodSizeInFrames;
if (internalPeriodSizeInFrames == 0) {
internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, internalSampleRate);
}
internalPeriodSizeInBytes = internalPeriodSizeInFrames * ma_get_bytes_per_frame(internalFormat, internalChannels);
if (internalPeriodSizeInBytes < 16) {
internalPeriodSizeInBytes = 16;
}
internalPeriods = pConfig->periods;
if (internalPeriods < 2) {
internalPeriods = 2;
}
/* What miniaudio calls a period, audio4 calls a block. */
AUDIO_INITINFO(&fdInfo);
fdInfo.hiwat = internalPeriods;
fdInfo.lowat = internalPeriods-1;
fdInfo.blocksize = internalPeriodSizeInBytes;
if (ioctl(fd, AUDIO_SETINFO, &fdInfo) < 0) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to set internal buffer size. AUDIO_SETINFO failed.", MA_FORMAT_NOT_SUPPORTED);
}
internalPeriods = fdInfo.hiwat;
internalPeriodSizeInFrames = fdInfo.blocksize / ma_get_bytes_per_frame(internalFormat, internalChannels);
}
#else
/* We need to retrieve the format of the device so we can know the channel count and sample rate. Then we can calculate the buffer size. */
if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve initial device parameters.", MA_FORMAT_NOT_SUPPORTED);
}
internalFormat = ma_format_from_swpar__audio4(&fdPar);
internalChannels = (deviceType == ma_device_type_capture) ? fdPar.rchan : fdPar.pchan;
internalSampleRate = fdPar.rate;
if (internalFormat == ma_format_unknown) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by miniaudio. The device is unusable.", MA_FORMAT_NOT_SUPPORTED);
}
/* Buffer. */
{
ma_uint32 internalPeriodSizeInBytes;
internalPeriodSizeInFrames = pConfig->periodSizeInFrames;
if (internalPeriodSizeInFrames == 0) {
internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, internalSampleRate);
}
/* What miniaudio calls a period, audio4 calls a block. */
internalPeriodSizeInBytes = internalPeriodSizeInFrames * ma_get_bytes_per_frame(internalFormat, internalChannels);
if (internalPeriodSizeInBytes < 16) {
internalPeriodSizeInBytes = 16;
}
fdPar.nblks = pConfig->periods;
fdPar.round = internalPeriodSizeInBytes;
if (ioctl(fd, AUDIO_SETPAR, &fdPar) < 0) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to set device parameters.", MA_FORMAT_NOT_SUPPORTED);
}
if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve actual device parameters.", MA_FORMAT_NOT_SUPPORTED);
}
}
internalFormat = ma_format_from_swpar__audio4(&fdPar);
internalChannels = (deviceType == ma_device_type_capture) ? fdPar.rchan : fdPar.pchan;
internalSampleRate = fdPar.rate;
internalPeriods = fdPar.nblks;
internalPeriodSizeInFrames = fdPar.round / ma_get_bytes_per_frame(internalFormat, internalChannels);
#endif
if (internalFormat == ma_format_unknown) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by miniaudio. The device is unusable.", MA_FORMAT_NOT_SUPPORTED);
}
if (deviceType == ma_device_type_capture) {
pDevice->audio4.fdCapture = fd;
pDevice->capture.internalFormat = internalFormat;
pDevice->capture.internalChannels = internalChannels;
pDevice->capture.internalSampleRate = internalSampleRate;
ma_get_standard_channel_map(ma_standard_channel_map_sound4, internalChannels, pDevice->capture.internalChannelMap);
pDevice->capture.internalPeriodSizeInFrames = internalPeriodSizeInFrames;
pDevice->capture.internalPeriods = internalPeriods;
} else {
pDevice->audio4.fdPlayback = fd;
pDevice->playback.internalFormat = internalFormat;
pDevice->playback.internalChannels = internalChannels;
pDevice->playback.internalSampleRate = internalSampleRate;
ma_get_standard_channel_map(ma_standard_channel_map_sound4, internalChannels, pDevice->playback.internalChannelMap);
pDevice->playback.internalPeriodSizeInFrames = internalPeriodSizeInFrames;
pDevice->playback.internalPeriods = internalPeriods;
}
return MA_SUCCESS;
}
static ma_result ma_device_init__audio4(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
MA_ZERO_OBJECT(&pDevice->audio4);
if (pConfig->deviceType == ma_device_type_loopback) {
return MA_DEVICE_TYPE_NOT_SUPPORTED;
}
pDevice->audio4.fdCapture = -1;
pDevice->audio4.fdPlayback = -1;
/*
The version of the operating system dictates whether or not the device is exclusive or shared. NetBSD
introduced in-kernel mixing which means it's shared. All other BSD flavours are exclusive as far as
I'm aware.
*/
#if defined(__NetBSD_Version__) && __NetBSD_Version__ >= 800000000
/* NetBSD 8.0+ */
if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) ||
((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) {
return MA_SHARE_MODE_NOT_SUPPORTED;
}
#else
/* All other flavors. */
#endif
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
ma_result result = ma_device_init_fd__audio4(pContext, pConfig, ma_device_type_capture, pDevice);
if (result != MA_SUCCESS) {
return result;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
if (pDevice->audio4.fdPlayback == -1) {
return MA_INVALID_ARGS;
}
}
return MA_SUCCESS;
}
#endif
static ma_result ma_device_stop_fd__audio4(ma_device* pDevice, int fd)
{
if (fd == -1) {
return MA_INVALID_ARGS;
}
#if !defined(MA_AUDIO4_USE_NEW_API)
if (ioctl(fd, AUDIO_FLUSH, 0) < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_FLUSH failed.", ma_result_from_errno(errno));
}
#else
if (ioctl(fd, AUDIO_STOP, 0) < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_STOP failed.", ma_result_from_errno(errno));
}
#endif
return MA_SUCCESS;
}
static ma_result ma_device_stop__audio4(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
ma_result result;
result = ma_device_stop_fd__audio4(pDevice, pDevice->audio4.fdCapture);
if (result != MA_SUCCESS) {
return result;
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
ma_result result;
/* Drain the device first. If this fails we'll just need to flush without draining. Unfortunately draining isn't available on newer version of OpenBSD. */
#if !defined(MA_AUDIO4_USE_NEW_API)
ioctl(pDevice->audio4.fdPlayback, AUDIO_DRAIN, 0);
#endif
/* Here is where the device is stopped immediately. */
result = ma_device_stop_fd__audio4(pDevice, pDevice->audio4.fdPlayback);
if (result != MA_SUCCESS) {
return result;
}
}
return MA_SUCCESS;
}
static ma_result ma_device_write__audio4(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
{
int result;
if (pFramesWritten != NULL) {
*pFramesWritten = 0;
}
result = write(pDevice->audio4.fdPlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
if (result < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to write data to the device.", ma_result_from_errno(errno));
}
if (pFramesWritten != NULL) {
*pFramesWritten = (ma_uint32)result / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
}
return MA_SUCCESS;
}
static ma_result ma_device_read__audio4(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
{
int result;
if (pFramesRead != NULL) {
*pFramesRead = 0;
}
result = read(pDevice->audio4.fdCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
if (result < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to read data from the device.", ma_result_from_errno(errno));
}
if (pFramesRead != NULL) {
*pFramesRead = (ma_uint32)result / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
}
return MA_SUCCESS;
}
static ma_result ma_device_main_loop__audio4(ma_device* pDevice)
{
ma_result result = MA_SUCCESS;
ma_bool32 exitLoop = MA_FALSE;
/* No need to explicitly start the device like the other backends. */
while (ma_device__get_state(pDevice) == MA_STATE_STARTED && !exitLoop) {
switch (pDevice->type)
{
case ma_device_type_duplex:
{
/* 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__audio4(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__audio4(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__audio4()... */
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
}
totalCapturedDeviceFramesProcessed += capturedDeviceFramesProcessed;
}
} break;
case ma_device_type_capture:
{
/* We read in chunks of the period size, but use a stack allocated buffer for the intermediary. */
ma_uint8 intermediaryBuffer[8192];
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__audio4(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:
{
/* We write in chunks of the period size, but use a stack allocated buffer for the intermediary. */
ma_uint8 intermediaryBuffer[8192];
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__audio4(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 is stopped. */
ma_device_stop__audio4(pDevice);
return result;
}
static ma_result ma_context_uninit__audio4(ma_context* pContext)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pContext->backend == ma_backend_audio4);
(void)pContext;
return MA_SUCCESS;
}
static ma_result ma_context_init__audio4(const ma_context_config* pConfig, ma_context* pContext)
{
MA_ASSERT(pContext != NULL);
(void)pConfig;
pContext->onUninit = ma_context_uninit__audio4;
pContext->onDeviceIDEqual = ma_context_is_device_id_equal__audio4;
pContext->onEnumDevices = ma_context_enumerate_devices__audio4;
pContext->onGetDeviceInfo = ma_context_get_device_info__audio4;
pContext->onDeviceInit = ma_device_init__audio4;
pContext->onDeviceUninit = ma_device_uninit__audio4;
pContext->onDeviceStart = NULL; /* Not required for synchronous backends. */
pContext->onDeviceStop = NULL; /* Not required for synchronous backends. */
pContext->onDeviceMainLoop = ma_device_main_loop__audio4;
return MA_SUCCESS;
}
#endif /* audio4 */
/******************************************************************************
OSS Backend
******************************************************************************/
#ifdef MA_HAS_OSS
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/soundcard.h>
#ifndef SNDCTL_DSP_HALT
#define SNDCTL_DSP_HALT SNDCTL_DSP_RESET
#endif
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
ossFormat = ma_format_to_oss(pConfig->capture.format);
ossChannels = (int)pConfig->capture.channels;
ossSampleRate = (int)pConfig->sampleRate;
} else {
pDeviceID = pConfig->playback.pDeviceID;
shareMode = pConfig->playback.shareMode;
ossFormat = ma_format_to_oss(pConfig->playback.format);
ossChannels = (int)pConfig->playback.channels;
ossSampleRate = (int)pConfig->sampleRate;
}
result = ma_context_open_device__oss(pContext, deviceType, pDeviceID, shareMode, &fd);
if (result != MA_SUCCESS) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.", result);
}
/*
The OSS documantation is very clear about the order we should be initializing the device's properties:
1) Format
2) Channels
3) Sample rate.
*/
/* Format. */
ossResult = ioctl(fd, SNDCTL_DSP_SETFMT, &ossFormat);
if (ossResult == -1) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to set format.", MA_FORMAT_NOT_SUPPORTED);
}
/* Channels. */
ossResult = ioctl(fd, SNDCTL_DSP_CHANNELS, &ossChannels);
if (ossResult == -1) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to set channel count.", MA_FORMAT_NOT_SUPPORTED);
}
/* Sample Rate. */
ossResult = ioctl(fd, SNDCTL_DSP_SPEED, &ossSampleRate);
if (ossResult == -1) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to set sample rate.", MA_FORMAT_NOT_SUPPORTED);
}
/*
Buffer.
The documentation says that the fragment settings should be set as soon as possible, but I'm not sure if
it should be done before or after format/channels/rate.
OSS wants the fragment size in bytes and a power of 2. When setting, we specify the power, not the actual
value.
*/
{
ma_uint32 periodSizeInFrames;
ma_uint32 periodSizeInBytes;
ma_uint32 ossFragmentSizePower;
periodSizeInFrames = pConfig->periodSizeInFrames;
if (periodSizeInFrames == 0) {
periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, (ma_uint32)ossSampleRate);
}
periodSizeInBytes = ma_round_to_power_of_2(periodSizeInFrames * ma_get_bytes_per_frame(ma_format_from_oss(ossFormat), ossChannels));
if (periodSizeInBytes < 16) {
periodSizeInBytes = 16;
}
ossFragmentSizePower = 4;
periodSizeInBytes >>= 4;
while (periodSizeInBytes >>= 1) {
ossFragmentSizePower += 1;
}
ossFragment = (int)((pConfig->periods << 16) | ossFragmentSizePower);
ossResult = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ossFragment);
if (ossResult == -1) {
close(fd);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to set fragment size and period count.", MA_FORMAT_NOT_SUPPORTED);
}
}
/* Internal settings. */
if (deviceType == ma_device_type_capture) {
pDevice->oss.fdCapture = fd;
pDevice->capture.internalFormat = ma_format_from_oss(ossFormat);
pDevice->capture.internalChannels = ossChannels;
pDevice->capture.internalSampleRate = ossSampleRate;
ma_get_standard_channel_map(ma_standard_channel_map_sound4, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap);
pDevice->capture.internalPeriods = (ma_uint32)(ossFragment >> 16);
pDevice->capture.internalPeriodSizeInFrames = (ma_uint32)(1 << (ossFragment & 0xFFFF)) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
if (pDevice->capture.internalFormat == ma_format_unknown) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] The device's internal format is not supported by miniaudio.", MA_FORMAT_NOT_SUPPORTED);
}
} else {
pDevice->oss.fdPlayback = fd;
pDevice->playback.internalFormat = ma_format_from_oss(ossFormat);
pDevice->playback.internalChannels = ossChannels;
pDevice->playback.internalSampleRate = ossSampleRate;
ma_get_standard_channel_map(ma_standard_channel_map_sound4, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap);
pDevice->playback.internalPeriods = (ma_uint32)(ossFragment >> 16);
pDevice->playback.internalPeriodSizeInFrames = (ma_uint32)(1 << (ossFragment & 0xFFFF)) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
if (pDevice->playback.internalFormat == ma_format_unknown) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] The device's internal format is not supported by miniaudio.", MA_FORMAT_NOT_SUPPORTED);
}
}
return MA_SUCCESS;
}
static ma_result ma_device_init__oss(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pConfig != NULL);
MA_ASSERT(pDevice != NULL);
MA_ZERO_OBJECT(&pDevice->oss);
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_fd__oss(pContext, pConfig, ma_device_type_capture, pDevice);
if (result != MA_SUCCESS) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.", result);
}
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
ma_result result = ma_device_init_fd__oss(pContext, pConfig, ma_device_type_playback, pDevice);
if (result != MA_SUCCESS) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.", result);
}
}
return MA_SUCCESS;
}
static ma_result ma_device_stop__oss(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
/*
We want to use SNDCTL_DSP_HALT. From the documentation:
In multithreaded applications SNDCTL_DSP_HALT (SNDCTL_DSP_RESET) must only be called by the thread
that actually reads/writes the audio device. It must not be called by some master thread to kill the
audio thread. The audio thread will not stop or get any kind of notification that the device was
stopped by the master thread. The device gets stopped but the next read or write call will silently
restart the device.
This is actually safe in our case, because this function is only ever called from within our worker
thread anyway. Just keep this in mind, though...
*/
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
int result = ioctl(pDevice->oss.fdCapture, SNDCTL_DSP_HALT, 0);
if (result == -1) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to stop device. SNDCTL_DSP_HALT failed.", ma_result_from_errno(errno));
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
int result = ioctl(pDevice->oss.fdPlayback, SNDCTL_DSP_HALT, 0);
if (result == -1) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to stop device. SNDCTL_DSP_HALT failed.", ma_result_from_errno(errno));
}
}
return MA_SUCCESS;
}
static ma_result ma_device_write__oss(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
{
int resultOSS;
if (pFramesWritten != NULL) {
*pFramesWritten = 0;
}
resultOSS = write(pDevice->oss.fdPlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
if (resultOSS < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to send data from the client to the device.", ma_result_from_errno(errno));
}
if (pFramesWritten != NULL) {
*pFramesWritten = (ma_uint32)resultOSS / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
}
return MA_SUCCESS;
}
static ma_result ma_device_read__oss(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
{
int resultOSS;
if (pFramesRead != NULL) {
*pFramesRead = 0;
}
resultOSS = read(pDevice->oss.fdCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
if (resultOSS < 0) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to read data from the device to be sent to the client.", ma_result_from_errno(errno));
}
if (pFramesRead != NULL) {
*pFramesRead = (ma_uint32)resultOSS / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
}
return MA_SUCCESS;
}
static ma_result ma_device_main_loop__oss(ma_device* pDevice)
{
ma_result result = MA_SUCCESS;
ma_bool32 exitLoop = MA_FALSE;
/* No need to explicitly start the device like the other backends. */
while (ma_device__get_state(pDevice) == MA_STATE_STARTED && !exitLoop) {
switch (pDevice->type)
{
case ma_device_type_duplex:
{
/* 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__oss(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__oss(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__oss()... */
if (result != MA_SUCCESS) {
exitLoop = MA_TRUE;
break;
}
}
totalCapturedDeviceFramesProcessed += capturedDeviceFramesProcessed;
}
} break;
case ma_device_type_capture:
{
/* 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__oss(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:
{
/* 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__oss(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 is stopped. */
ma_device_stop__oss(pDevice);
return result;
}
static ma_result ma_context_uninit__oss(ma_context* pContext)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pContext->backend == ma_backend_oss);
(void)pContext;
return MA_SUCCESS;
}
static ma_result ma_context_init__oss(const ma_context_config* pConfig, ma_context* pContext)
{
int fd;
int ossVersion;
int result;
MA_ASSERT(pContext != NULL);
(void)pConfig;
/* Try opening a temporary device first so we can get version information. This is closed at the end. */
fd = ma_open_temp_device__oss();
if (fd == -1) {
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open temporary device for retrieving system properties.", MA_NO_BACKEND); /* Looks liks OSS isn't installed, or there are no available devices. */
}
/* Grab the OSS version. */
ossVersion = 0;
result = ioctl(fd, OSS_GETVERSION, &ossVersion);
if (result == -1) {
close(fd);
return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve OSS version.", MA_NO_BACKEND);
}
pContext->oss.versionMajor = ((ossVersion & 0xFF0000) >> 16);
pContext->oss.versionMinor = ((ossVersion & 0x00FF00) >> 8);
pContext->onUninit = ma_context_uninit__oss;
pContext->onDeviceIDEqual = ma_context_is_device_id_equal__oss;
pContext->onEnumDevices = ma_context_enumerate_devices__oss;
pContext->onGetDeviceInfo = ma_context_get_device_info__oss;
pContext->onDeviceInit = ma_device_init__oss;
pContext->onDeviceUninit = ma_device_uninit__oss;
pContext->onDeviceStart = NULL; /* Not required for synchronous backends. */
pContext->onDeviceStop = NULL; /* Not required for synchronous backends. */
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
typedef ma_aaudio_result_t (* MA_PFN_AAudio_createStreamBuilder) (ma_AAudioStreamBuilder** ppBuilder);
typedef ma_aaudio_result_t (* MA_PFN_AAudioStreamBuilder_delete) (ma_AAudioStreamBuilder* pBuilder);
typedef void (* MA_PFN_AAudioStreamBuilder_setDeviceId) (ma_AAudioStreamBuilder* pBuilder, int32_t deviceId);
typedef void (* MA_PFN_AAudioStreamBuilder_setDirection) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_direction_t direction);
typedef void (* MA_PFN_AAudioStreamBuilder_setSharingMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_sharing_mode_t sharingMode);
typedef void (* MA_PFN_AAudioStreamBuilder_setFormat) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_format_t format);
typedef void (* MA_PFN_AAudioStreamBuilder_setChannelCount) (ma_AAudioStreamBuilder* pBuilder, int32_t channelCount);
typedef void (* MA_PFN_AAudioStreamBuilder_setSampleRate) (ma_AAudioStreamBuilder* pBuilder, int32_t sampleRate);
typedef void (* MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)(ma_AAudioStreamBuilder* pBuilder, int32_t numFrames);
typedef void (* MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback) (ma_AAudioStreamBuilder* pBuilder, int32_t numFrames);
typedef void (* MA_PFN_AAudioStreamBuilder_setDataCallback) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream_dataCallback callback, void* pUserData);
typedef void (* MA_PFN_AAudioStreamBuilder_setErrorCallback) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream_errorCallback callback, void* pUserData);
typedef void (* MA_PFN_AAudioStreamBuilder_setPerformanceMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_performance_mode_t mode);
typedef ma_aaudio_result_t (* MA_PFN_AAudioStreamBuilder_openStream) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream** ppStream);
typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_close) (ma_AAudioStream* pStream);
typedef ma_aaudio_stream_state_t (* MA_PFN_AAudioStream_getState) (ma_AAudioStream* pStream);
typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_waitForStateChange) (ma_AAudioStream* pStream, ma_aaudio_stream_state_t inputState, ma_aaudio_stream_state_t* pNextState, int64_t timeoutInNanoseconds);
typedef ma_aaudio_format_t (* MA_PFN_AAudioStream_getFormat) (ma_AAudioStream* pStream);
typedef int32_t (* MA_PFN_AAudioStream_getChannelCount) (ma_AAudioStream* pStream);
typedef int32_t (* MA_PFN_AAudioStream_getSampleRate) (ma_AAudioStream* pStream);
typedef int32_t (* MA_PFN_AAudioStream_getBufferCapacityInFrames) (ma_AAudioStream* pStream);
typedef int32_t (* MA_PFN_AAudioStream_getFramesPerDataCallback) (ma_AAudioStream* pStream);
typedef int32_t (* MA_PFN_AAudioStream_getFramesPerBurst) (ma_AAudioStream* pStream);
typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_requestStart) (ma_AAudioStream* pStream);
typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_requestStop) (ma_AAudioStream* pStream);
static ma_result ma_result_from_aaudio(ma_aaudio_result_t resultAA)
{
switch (resultAA)
{
case MA_AAUDIO_OK: return MA_SUCCESS;
default: break;
}
return MA_ERROR;
}
static void ma_stream_error_callback__aaudio(ma_AAudioStream* pStream, void* pUserData, ma_aaudio_result_t error)
{
ma_device* pDevice = (ma_device*)pUserData;
MA_ASSERT(pDevice != NULL);
(void)error;
#if defined(MA_DEBUG_OUTPUT)
printf("[AAudio] ERROR CALLBACK: error=%d, AAudioStream_getState()=%d\n", error, ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream));
#endif
/*
From the documentation for AAudio, when a device is disconnected all we can do is stop it. However, we cannot stop it from the callback - we need
to do it from another thread. Therefore we are going to use an event thread for the AAudio backend to do this cleanly and safely.
*/
if (((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream) == MA_AAUDIO_STREAM_STATE_DISCONNECTED) {
#if defined(MA_DEBUG_OUTPUT)
printf("[AAudio] Device Disconnected.\n");
#endif
}
}
static ma_aaudio_data_callback_result_t ma_stream_data_callback_capture__aaudio(ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t frameCount)
{
ma_device* pDevice = (ma_device*)pUserData;
MA_ASSERT(pDevice != NULL);
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_capture(pDevice, frameCount, pAudioData, &pDevice->aaudio.duplexRB);
} else {
ma_device__send_frames_to_client(pDevice, frameCount, pAudioData); /* Send directly to the client. */
}
(void)pStream;
return MA_AAUDIO_CALLBACK_RESULT_CONTINUE;
}
static ma_aaudio_data_callback_result_t ma_stream_data_callback_playback__aaudio(ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t frameCount)
{
ma_device* pDevice = (ma_device*)pUserData;
MA_ASSERT(pDevice != NULL);
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_playback(pDevice, frameCount, pAudioData, &pDevice->aaudio.duplexRB);
} else {
ma_device__read_frames_from_client(pDevice, frameCount, pAudioData); /* Read directly from the client. */
}
(void)pStream;
return MA_AAUDIO_CALLBACK_RESULT_CONTINUE;
}
static ma_result ma_open_stream__aaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, const ma_device_config* pConfig, const ma_device* pDevice, ma_AAudioStream** ppStream)
{
ma_AAudioStreamBuilder* pBuilder;
ma_aaudio_result_t resultAA;
MA_ASSERT(deviceType != ma_device_type_duplex); /* This function should not be called for a full-duplex device type. */
*ppStream = NULL;
resultAA = ((MA_PFN_AAudio_createStreamBuilder)pContext->aaudio.AAudio_createStreamBuilder)(&pBuilder);
if (resultAA != MA_AAUDIO_OK) {
return ma_result_from_aaudio(resultAA);
}
if (pDeviceID != NULL) {
((MA_PFN_AAudioStreamBuilder_setDeviceId)pContext->aaudio.AAudioStreamBuilder_setDeviceId)(pBuilder, pDeviceID->aaudio);
}
((MA_PFN_AAudioStreamBuilder_setDirection)pContext->aaudio.AAudioStreamBuilder_setDirection)(pBuilder, (deviceType == ma_device_type_playback) ? MA_AAUDIO_DIRECTION_OUTPUT : MA_AAUDIO_DIRECTION_INPUT);
((MA_PFN_AAudioStreamBuilder_setSharingMode)pContext->aaudio.AAudioStreamBuilder_setSharingMode)(pBuilder, (shareMode == ma_share_mode_shared) ? MA_AAUDIO_SHARING_MODE_SHARED : MA_AAUDIO_SHARING_MODE_EXCLUSIVE);
if (pConfig != NULL) {
ma_uint32 bufferCapacityInFrames;
if (pDevice == NULL || !pDevice->usingDefaultSampleRate) {
((MA_PFN_AAudioStreamBuilder_setSampleRate)pContext->aaudio.AAudioStreamBuilder_setSampleRate)(pBuilder, pConfig->sampleRate);
}
if (deviceType == ma_device_type_capture) {
if (pDevice == NULL || !pDevice->capture.usingDefaultChannels) {
((MA_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pConfig->capture.channels);
}
if (pDevice == NULL || !pDevice->capture.usingDefaultFormat) {
((MA_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pConfig->capture.format == ma_format_s16) ? MA_AAUDIO_FORMAT_PCM_I16 : MA_AAUDIO_FORMAT_PCM_FLOAT);
}
} else {
if (pDevice == NULL || !pDevice->playback.usingDefaultChannels) {
((MA_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pConfig->playback.channels);
}
if (pDevice == NULL || !pDevice->playback.usingDefaultFormat) {
((MA_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pConfig->playback.format == ma_format_s16) ? MA_AAUDIO_FORMAT_PCM_I16 : MA_AAUDIO_FORMAT_PCM_FLOAT);
}
}
bufferCapacityInFrames = pConfig->periodSizeInFrames * pConfig->periods;
if (bufferCapacityInFrames == 0) {
bufferCapacityInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, pConfig->sampleRate) * pConfig->periods;
}
((MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames)(pBuilder, bufferCapacityInFrames);
((MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback)pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback)(pBuilder, bufferCapacityInFrames / pConfig->periods);
if (deviceType == ma_device_type_capture) {
((MA_PFN_AAudioStreamBuilder_setDataCallback)pContext->aaudio.AAudioStreamBuilder_setDataCallback)(pBuilder, ma_stream_data_callback_capture__aaudio, (void*)pDevice);
} else {
((MA_PFN_AAudioStreamBuilder_setDataCallback)pContext->aaudio.AAudioStreamBuilder_setDataCallback)(pBuilder, ma_stream_data_callback_playback__aaudio, (void*)pDevice);
}
/* Not sure how this affects things, but since there's a mapping between miniaudio's performance profiles and AAudio's performance modes, let go ahead and set it. */
((MA_PFN_AAudioStreamBuilder_setPerformanceMode)pContext->aaudio.AAudioStreamBuilder_setPerformanceMode)(pBuilder, (pConfig->performanceProfile == ma_performance_profile_low_latency) ? MA_AAUDIO_PERFORMANCE_MODE_LOW_LATENCY : MA_AAUDIO_PERFOR...
}
((MA_PFN_AAudioStreamBuilder_setErrorCallback)pContext->aaudio.AAudioStreamBuilder_setErrorCallback)(pBuilder, ma_stream_error_callback__aaudio, (void*)pDevice);
resultAA = ((MA_PFN_AAudioStreamBuilder_openStream)pContext->aaudio.AAudioStreamBuilder_openStream)(pBuilder, ppStream);
if (resultAA != MA_AAUDIO_OK) {
*ppStream = NULL;
((MA_PFN_AAudioStreamBuilder_delete)pContext->aaudio.AAudioStreamBuilder_delete)(pBuilder);
return ma_result_from_aaudio(resultAA);
}
((MA_PFN_AAudioStreamBuilder_delete)pContext->aaudio.AAudioStreamBuilder_delete)(pBuilder);
return MA_SUCCESS;
}
static ma_result ma_close_stream__aaudio(ma_context* pContext, ma_AAudioStream* pStream)
{
return ma_result_from_aaudio(((MA_PFN_AAudioStream_close)pContext->aaudio.AAudioStream_close)(pStream));
}
static ma_bool32 ma_has_default_device__aaudio(ma_context* pContext, ma_device_type deviceType)
{
/* The only way to know this is to try creating a stream. */
ma_AAudioStream* pStream;
ma_result result = ma_open_stream__aaudio(pContext, deviceType, NULL, ma_share_mode_shared, NULL, NULL, &pStream);
if (result != MA_SUCCESS) {
return MA_FALSE;
}
ma_close_stream__aaudio(pContext, pStream);
return MA_TRUE;
}
static ma_result ma_wait_for_simple_state_transition__aaudio(ma_context* pContext, ma_AAudioStream* pStream, ma_aaudio_stream_state_t oldState, ma_aaudio_stream_state_t newState)
{
ma_aaudio_stream_state_t actualNewState;
ma_aaudio_result_t resultAA = ((MA_PFN_AAudioStream_waitForStateChange)pContext->aaudio.AAudioStream_waitForStateChange)(pStream, oldState, &actualNewState, 5000000000); /* 5 second timeout. */
if (resultAA != MA_AAUDIO_OK) {
return ma_result_from_aaudio(resultAA);
}
if (newState != actualNewState) {
return MA_ERROR; /* Failed to transition into the expected state. */
}
return MA_SUCCESS;
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
if (result != MA_SUCCESS) {
return result;
}
pDeviceInfo->minChannels = ((MA_PFN_AAudioStream_getChannelCount)pContext->aaudio.AAudioStream_getChannelCount)(pStream);
pDeviceInfo->maxChannels = pDeviceInfo->minChannels;
pDeviceInfo->minSampleRate = ((MA_PFN_AAudioStream_getSampleRate)pContext->aaudio.AAudioStream_getSampleRate)(pStream);
pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate;
ma_close_stream__aaudio(pContext, pStream);
pStream = NULL;
/* AAudio supports s16 and f32. */
pDeviceInfo->formatCount = 2;
pDeviceInfo->formats[0] = ma_format_s16;
pDeviceInfo->formats[1] = ma_format_f32;
return MA_SUCCESS;
}
static void ma_device_uninit__aaudio(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
pDevice->aaudio.pStreamCapture = NULL;
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
pDevice->aaudio.pStreamPlayback = NULL;
}
if (pDevice->type == ma_device_type_duplex) {
ma_pcm_rb_uninit(&pDevice->aaudio.duplexRB);
}
}
static ma_result ma_device_init__aaudio(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
{
ma_result result;
MA_ASSERT(pDevice != NULL);
if (pConfig->deviceType == ma_device_type_loopback) {
return MA_DEVICE_TYPE_NOT_SUPPORTED;
}
/* No exclusive mode with AAudio. */
if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) ||
((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) {
return MA_SHARE_MODE_NOT_SUPPORTED;
}
/* We first need to try opening the stream. */
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
int32_t bufferCapacityInFrames;
int32_t framesPerDataCallback;
result = ma_open_stream__aaudio(pContext, ma_device_type_capture, pConfig->capture.pDeviceID, pConfig->capture.shareMode, pConfig, pDevice, (ma_AAudioStream**)&pDevice->aaudio.pStreamCapture);
if (result != MA_SUCCESS) {
return result; /* Failed to open the AAudio stream. */
}
pDevice->capture.internalFormat = (((MA_PFN_AAudioStream_getFormat)pContext->aaudio.AAudioStream_getFormat)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture) == MA_AAUDIO_FORMAT_PCM_I16) ? ma_format_s16 : ma_format_f32;
pDevice->capture.internalChannels = ((MA_PFN_AAudioStream_getChannelCount)pContext->aaudio.AAudioStream_getChannelCount)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
pDevice->capture.internalSampleRate = ((MA_PFN_AAudioStream_getSampleRate)pContext->aaudio.AAudioStream_getSampleRate)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
ma_get_standard_channel_map(ma_standard_channel_map_default, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap); /* <-- Cannot find info on channel order, so assuming a default. */
bufferCapacityInFrames = ((MA_PFN_AAudioStream_getBufferCapacityInFrames)pContext->aaudio.AAudioStream_getBufferCapacityInFrames)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
framesPerDataCallback = ((MA_PFN_AAudioStream_getFramesPerDataCallback)pContext->aaudio.AAudioStream_getFramesPerDataCallback)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
if (framesPerDataCallback > 0) {
pDevice->capture.internalPeriodSizeInFrames = framesPerDataCallback;
pDevice->capture.internalPeriods = bufferCapacityInFrames / framesPerDataCallback;
} else {
pDevice->capture.internalPeriodSizeInFrames = bufferCapacityInFrames;
pDevice->capture.internalPeriods = 1;
}
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
int32_t bufferCapacityInFrames;
int32_t framesPerDataCallback;
result = ma_open_stream__aaudio(pContext, ma_device_type_playback, pConfig->playback.pDeviceID, pConfig->playback.shareMode, pConfig, pDevice, (ma_AAudioStream**)&pDevice->aaudio.pStreamPlayback);
if (result != MA_SUCCESS) {
return result; /* Failed to open the AAudio stream. */
}
pDevice->playback.internalFormat = (((MA_PFN_AAudioStream_getFormat)pContext->aaudio.AAudioStream_getFormat)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback) == MA_AAUDIO_FORMAT_PCM_I16) ? ma_format_s16 : ma_format_f32;
pDevice->playback.internalChannels = ((MA_PFN_AAudioStream_getChannelCount)pContext->aaudio.AAudioStream_getChannelCount)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
pDevice->playback.internalSampleRate = ((MA_PFN_AAudioStream_getSampleRate)pContext->aaudio.AAudioStream_getSampleRate)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
ma_get_standard_channel_map(ma_standard_channel_map_default, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap); /* <-- Cannot find info on channel order, so assuming a default. */
bufferCapacityInFrames = ((MA_PFN_AAudioStream_getBufferCapacityInFrames)pContext->aaudio.AAudioStream_getBufferCapacityInFrames)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
framesPerDataCallback = ((MA_PFN_AAudioStream_getFramesPerDataCallback)pContext->aaudio.AAudioStream_getFramesPerDataCallback)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
if (framesPerDataCallback > 0) {
pDevice->playback.internalPeriodSizeInFrames = framesPerDataCallback;
pDevice->playback.internalPeriods = bufferCapacityInFrames / framesPerDataCallback;
} else {
pDevice->playback.internalPeriodSizeInFrames = bufferCapacityInFrames;
pDevice->playback.internalPeriods = 1;
}
}
if (pConfig->deviceType == ma_device_type_duplex) {
ma_uint32 rbSizeInFrames = (ma_uint32)ma_calculate_frame_count_after_resampling(pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalPeriodSizeInFrames) * pDevice->capture.internalPeriods;
ma_result result = ma_pcm_rb_init(pDevice->capture.format, pDevice->capture.channels, rbSizeInFrames, NULL, &pDevice->pContext->allocationCallbacks, &pDevice->aaudio.duplexRB);
if (result != MA_SUCCESS) {
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
}
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[AAudio] Failed to initialize ring buffer.", result);
}
/* We need a period to act as a buffer for cases where the playback and capture device's end up desyncing. */
{
ma_uint32 marginSizeInFrames = rbSizeInFrames / pDevice->capture.internalPeriods;
void* pMarginData;
ma_pcm_rb_acquire_write(&pDevice->aaudio.duplexRB, &marginSizeInFrames, &pMarginData);
{
MA_ZERO_MEMORY(pMarginData, marginSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels));
}
ma_pcm_rb_commit_write(&pDevice->aaudio.duplexRB, marginSizeInFrames, pMarginData);
}
}
return MA_SUCCESS;
}
static ma_result ma_device_start_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pStream)
{
ma_aaudio_result_t resultAA;
ma_aaudio_stream_state_t currentState;
MA_ASSERT(pDevice != NULL);
resultAA = ((MA_PFN_AAudioStream_requestStart)pDevice->pContext->aaudio.AAudioStream_requestStart)(pStream);
if (resultAA != MA_AAUDIO_OK) {
return ma_result_from_aaudio(resultAA);
}
/* Do we actually need to wait for the device to transition into it's started state? */
/* The device should be in either a starting or started state. If it's not set to started we need to wait for it to transition. It should go from starting to started. */
currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream);
if (currentState != MA_AAUDIO_STREAM_STATE_STARTED) {
ma_result result;
if (currentState != MA_AAUDIO_STREAM_STATE_STARTING) {
return MA_ERROR; /* Expecting the stream to be a starting or started state. */
}
result = ma_wait_for_simple_state_transition__aaudio(pDevice->pContext, pStream, currentState, MA_AAUDIO_STREAM_STATE_STARTED);
if (result != MA_SUCCESS) {
return result;
}
}
return MA_SUCCESS;
}
static ma_result ma_device_stop_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pStream)
{
ma_aaudio_result_t resultAA;
ma_aaudio_stream_state_t currentState;
MA_ASSERT(pDevice != NULL);
/*
From the AAudio documentation:
The stream will stop after all of the data currently buffered has been played.
This maps with miniaudio's requirement that device's be drained which means we don't need to implement any draining logic.
*/
resultAA = ((MA_PFN_AAudioStream_requestStop)pDevice->pContext->aaudio.AAudioStream_requestStop)(pStream);
if (resultAA != MA_AAUDIO_OK) {
return ma_result_from_aaudio(resultAA);
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
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);
}
goto return_detailed_info;
return_detailed_info:
/*
For now we're just outputting a set of values that are supported by the API but not necessarily supported
by the device natively. Later on we should work on this so that it more closely reflects the device's
actual native format.
*/
pDeviceInfo->minChannels = 1;
pDeviceInfo->maxChannels = 2;
pDeviceInfo->minSampleRate = 8000;
pDeviceInfo->maxSampleRate = 48000;
pDeviceInfo->formatCount = 2;
pDeviceInfo->formats[0] = ma_format_u8;
pDeviceInfo->formats[1] = ma_format_s16;
#if defined(MA_ANDROID) && __ANDROID_API__ >= 21
pDeviceInfo->formats[pDeviceInfo->formatCount] = ma_format_f32;
pDeviceInfo->formatCount += 1;
#endif
return MA_SUCCESS;
}
#ifdef MA_ANDROID
/*void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, SLuint32 eventFlags, const void* pBuffer, SLuint32 bufferSize, SLuint32 dataUsed, void* pContext)*/
static void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData)
{
ma_device* pDevice = (ma_device*)pUserData;
size_t periodSizeInBytes;
ma_uint8* pBuffer;
SLresult resultSL;
MA_ASSERT(pDevice != NULL);
(void)pBufferQueue;
/*
For now, don't do anything unless the buffer was fully processed. From what I can tell, it looks like
OpenSL|ES 1.1 improves on buffer queues to the point that we could much more intelligently handle this,
but unfortunately it looks like Android is only supporting OpenSL|ES 1.0.1 for now :(
*/
/* Don't do anything if the device is not started. */
if (pDevice->state != MA_STATE_STARTED) {
return;
}
/* Don't do anything if the device is being drained. */
if (pDevice->opensl.isDrainingCapture) {
return;
}
periodSizeInBytes = pDevice->capture.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
pBuffer = pDevice->opensl.pBufferCapture + (pDevice->opensl.currentBufferIndexCapture * periodSizeInBytes);
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_capture(pDevice, pDevice->capture.internalPeriodSizeInFrames, pBuffer, &pDevice->opensl.duplexRB);
} else {
ma_device__send_frames_to_client(pDevice, pDevice->capture.internalPeriodSizeInFrames, pBuffer);
}
resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pBuffer, periodSizeInBytes);
if (resultSL != SL_RESULT_SUCCESS) {
return;
}
pDevice->opensl.currentBufferIndexCapture = (pDevice->opensl.currentBufferIndexCapture + 1) % pDevice->capture.internalPeriods;
}
static void ma_buffer_queue_callback_playback__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData)
{
ma_device* pDevice = (ma_device*)pUserData;
size_t periodSizeInBytes;
ma_uint8* pBuffer;
SLresult resultSL;
MA_ASSERT(pDevice != NULL);
(void)pBufferQueue;
/* Don't do anything if the device is not started. */
if (pDevice->state != MA_STATE_STARTED) {
return;
}
/* Don't do anything if the device is being drained. */
if (pDevice->opensl.isDrainingPlayback) {
return;
}
periodSizeInBytes = pDevice->playback.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
pBuffer = pDevice->opensl.pBufferPlayback + (pDevice->opensl.currentBufferIndexPlayback * periodSizeInBytes);
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_playback(pDevice, pDevice->playback.internalPeriodSizeInFrames, pBuffer, &pDevice->opensl.duplexRB);
} else {
ma_device__read_frames_from_client(pDevice, pDevice->playback.internalPeriodSizeInFrames, pBuffer);
}
resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pBuffer, periodSizeInBytes);
if (resultSL != SL_RESULT_SUCCESS) {
return;
}
pDevice->opensl.currentBufferIndexPlayback = (pDevice->opensl.currentBufferIndexPlayback + 1) % pDevice->playback.internalPeriods;
}
#endif
static void ma_device_uninit__opensl(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
MA_ASSERT(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it before uninitializing the device. */
if (g_maOpenSLInitCounter == 0) {
return;
}
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
if (pDevice->opensl.pAudioRecorderObj) {
MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Destroy((SLObjectItf)pDevice->opensl.pAudioRecorderObj);
}
ma__free_from_callbacks(pDevice->opensl.pBufferCapture, &pDevice->pContext->allocationCallbacks);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
if (pDevice->opensl.pAudioPlayerObj) {
MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Destroy((SLObjectItf)pDevice->opensl.pAudioPlayerObj);
}
if (pDevice->opensl.pOutputMixObj) {
MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Destroy((SLObjectItf)pDevice->opensl.pOutputMixObj);
}
ma__free_from_callbacks(pDevice->opensl.pBufferPlayback, &pDevice->pContext->allocationCallbacks);
}
if (pDevice->type == ma_device_type_duplex) {
ma_pcm_rb_uninit(&pDevice->opensl.duplexRB);
}
}
#if defined(MA_ANDROID) && __ANDROID_API__ >= 21
typedef SLAndroidDataFormat_PCM_EX ma_SLDataFormat_PCM;
#else
typedef SLDataFormat_PCM ma_SLDataFormat_PCM;
#endif
static ma_result ma_SLDataFormat_PCM_init__opensl(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const ma_channel* channelMap, ma_SLDataFormat_PCM* pDataFormat)
{
#if defined(MA_ANDROID) && __ANDROID_API__ >= 21
if (format == ma_format_f32) {
pDataFormat->formatType = SL_ANDROID_DATAFORMAT_PCM_EX;
pDataFormat->representation = SL_ANDROID_PCM_REPRESENTATION_FLOAT;
} else {
pDataFormat->formatType = SL_DATAFORMAT_PCM;
}
#else
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
ma_SLDataFormat_PCM_init__opensl(pConfig->capture.format, pConfig->capture.channels, pConfig->sampleRate, pConfig->capture.channelMap, &pcm);
locatorDevice.locatorType = SL_DATALOCATOR_IODEVICE;
locatorDevice.deviceType = SL_IODEVICE_AUDIOINPUT;
locatorDevice.deviceID = (pConfig->capture.pDeviceID == NULL) ? SL_DEFAULTDEVICEID_AUDIOINPUT : pConfig->capture.pDeviceID->opensl;
locatorDevice.device = NULL;
source.pLocator = &locatorDevice;
source.pFormat = NULL;
sink.pLocator = &queue;
sink.pFormat = (SLDataFormat_PCM*)&pcm;
resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, 1, itfIDs1, itfIDsRequired1);
if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED) {
/* Unsupported format. Fall back to something safer and try again. If this fails, just abort. */
pcm.formatType = SL_DATAFORMAT_PCM;
pcm.numChannels = 1;
((SLDataFormat_PCM*)&pcm)->samplesPerSec = SL_SAMPLINGRATE_16; /* The name of the sample rate variable is different between SLAndroidDataFormat_PCM_EX and SLDataFormat_PCM. */
pcm.bitsPerSample = 16;
pcm.containerSize = pcm.bitsPerSample; /* Always tightly packed for now. */
pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, 1, itfIDs1, itfIDsRequired1);
}
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio recorder.", ma_result_from_OpenSL(resultSL));
}
resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Realize((SLObjectItf)pDevice->opensl.pAudioRecorderObj, SL_BOOLEAN_FALSE);
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio recorder.", ma_result_from_OpenSL(resultSL));
}
resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pContext->opensl.SL_IID_RECORD, &pDevice->opensl.pAudioRecorder);
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_RECORD interface.", ma_result_from_OpenSL(resultSL));
}
resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueueCapture);
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface.", ma_result_from_OpenSL(resultSL));
}
resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, ma_buffer_queue_callback_capture__opensl_android, pDevice);
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback.", ma_result_from_OpenSL(resultSL));
}
/* The internal format is determined by the "pcm" object. */
ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDevice->capture.internalFormat, &pDevice->capture.internalChannels, &pDevice->capture.internalSampleRate, pDevice->capture.internalChannelMap, ma_countof(pDevice->capture.internalChannelMap));
/* Buffer. */
periodSizeInFrames = pConfig->periodSizeInFrames;
if (periodSizeInFrames == 0) {
periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, pDevice->capture.internalSampleRate);
}
pDevice->capture.internalPeriods = pConfig->periods;
pDevice->capture.internalPeriodSizeInFrames = periodSizeInFrames;
pDevice->opensl.currentBufferIndexCapture = 0;
bufferSizeInBytes = pDevice->capture.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels) * pDevice->capture.internalPeriods;
pDevice->opensl.pBufferCapture = (ma_uint8*)ma__calloc_from_callbacks(bufferSizeInBytes, &pContext->allocationCallbacks);
if (pDevice->opensl.pBufferCapture == NULL) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer.", MA_OUT_OF_MEMORY);
}
MA_ZERO_MEMORY(pDevice->opensl.pBufferCapture, bufferSizeInBytes);
}
if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
ma_SLDataFormat_PCM pcm;
SLDataSource source;
SLDataLocator_OutputMix outmixLocator;
SLDataSink sink;
ma_SLDataFormat_PCM_init__opensl(pConfig->playback.format, pConfig->playback.channels, pConfig->sampleRate, pConfig->playback.channelMap, &pcm);
resultSL = (*g_maEngineSL)->CreateOutputMix(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pOutputMixObj, 0, NULL, NULL);
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create output mix.", ma_result_from_OpenSL(resultSL));
}
resultSL = MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Realize((SLObjectItf)pDevice->opensl.pOutputMixObj, SL_BOOLEAN_FALSE);
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize output mix object.", ma_result_from_OpenSL(resultSL));
}
resultSL = MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->GetInterface((SLObjectItf)pDevice->opensl.pOutputMixObj, (SLInterfaceID)pContext->opensl.SL_IID_OUTPUTMIX, &pDevice->opensl.pOutputMix);
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_OUTPUTMIX interface.", ma_result_from_OpenSL(resultSL));
}
/* Set the output device. */
if (pConfig->playback.pDeviceID != NULL) {
SLuint32 deviceID_OpenSL = pConfig->playback.pDeviceID->opensl;
MA_OPENSL_OUTPUTMIX(pDevice->opensl.pOutputMix)->ReRoute((SLOutputMixItf)pDevice->opensl.pOutputMix, 1, &deviceID_OpenSL);
}
source.pLocator = &queue;
source.pFormat = (SLDataFormat_PCM*)&pcm;
outmixLocator.locatorType = SL_DATALOCATOR_OUTPUTMIX;
outmixLocator.outputMix = (SLObjectItf)pDevice->opensl.pOutputMixObj;
sink.pLocator = &outmixLocator;
sink.pFormat = NULL;
resultSL = (*g_maEngineSL)->CreateAudioPlayer(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, 1, itfIDs1, itfIDsRequired1);
if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED) {
/* Unsupported format. Fall back to something safer and try again. If this fails, just abort. */
pcm.formatType = SL_DATAFORMAT_PCM;
pcm.numChannels = 2;
((SLDataFormat_PCM*)&pcm)->samplesPerSec = SL_SAMPLINGRATE_16;
pcm.bitsPerSample = 16;
pcm.containerSize = pcm.bitsPerSample; /* Always tightly packed for now. */
pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
resultSL = (*g_maEngineSL)->CreateAudioPlayer(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, 1, itfIDs1, itfIDsRequired1);
}
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio player.", ma_result_from_OpenSL(resultSL));
}
resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Realize((SLObjectItf)pDevice->opensl.pAudioPlayerObj, SL_BOOLEAN_FALSE);
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio player.", ma_result_from_OpenSL(resultSL));
}
resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pContext->opensl.SL_IID_PLAY, &pDevice->opensl.pAudioPlayer);
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_PLAY interface.", ma_result_from_OpenSL(resultSL));
}
resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueuePlayback);
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface.", ma_result_from_OpenSL(resultSL));
}
resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, ma_buffer_queue_callback_playback__opensl_android, pDevice);
if (resultSL != SL_RESULT_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback.", ma_result_from_OpenSL(resultSL));
}
/* The internal format is determined by the "pcm" object. */
ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDevice->playback.internalFormat, &pDevice->playback.internalChannels, &pDevice->playback.internalSampleRate, pDevice->playback.internalChannelMap, ma_countof(pDevice->playback.internalChannelMap...
/* Buffer. */
periodSizeInFrames = pConfig->periodSizeInFrames;
if (periodSizeInFrames == 0) {
periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, pDevice->playback.internalSampleRate);
}
pDevice->playback.internalPeriods = pConfig->periods;
pDevice->playback.internalPeriodSizeInFrames = periodSizeInFrames;
pDevice->opensl.currentBufferIndexPlayback = 0;
bufferSizeInBytes = pDevice->playback.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels) * pDevice->playback.internalPeriods;
pDevice->opensl.pBufferPlayback = (ma_uint8*)ma__calloc_from_callbacks(bufferSizeInBytes, &pContext->allocationCallbacks);
if (pDevice->opensl.pBufferPlayback == NULL) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer.", MA_OUT_OF_MEMORY);
}
MA_ZERO_MEMORY(pDevice->opensl.pBufferPlayback, bufferSizeInBytes);
}
if (pConfig->deviceType == ma_device_type_duplex) {
ma_uint32 rbSizeInFrames = (ma_uint32)ma_calculate_frame_count_after_resampling(pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalPeriodSizeInFrames) * pDevice->capture.internalPeriods;
ma_result result = ma_pcm_rb_init(pDevice->capture.format, pDevice->capture.channels, rbSizeInFrames, NULL, &pDevice->pContext->allocationCallbacks, &pDevice->opensl.duplexRB);
if (result != MA_SUCCESS) {
ma_device_uninit__opensl(pDevice);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to initialize ring buffer.", result);
}
/* We need a period to act as a buffer for cases where the playback and capture device's end up desyncing. */
{
ma_uint32 marginSizeInFrames = rbSizeInFrames / pDevice->capture.internalPeriods;
void* pMarginData;
ma_pcm_rb_acquire_write(&pDevice->opensl.duplexRB, &marginSizeInFrames, &pMarginData);
{
MA_ZERO_MEMORY(pMarginData, marginSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels));
}
ma_pcm_rb_commit_write(&pDevice->opensl.duplexRB, marginSizeInFrames, pMarginData);
}
}
return MA_SUCCESS;
#else
return MA_NO_BACKEND; /* Non-Android implementations are not supported. */
#endif
}
static ma_result ma_device_start__opensl(ma_device* pDevice)
{
SLresult resultSL;
size_t periodSizeInBytes;
ma_uint32 iPeriod;
MA_ASSERT(pDevice != NULL);
MA_ASSERT(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to start the device. */
if (g_maOpenSLInitCounter == 0) {
return MA_INVALID_OPERATION;
}
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_RECORDING);
if (resultSL != SL_RESULT_SUCCESS) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal capture device.", ma_result_from_OpenSL(resultSL));
}
periodSizeInBytes = pDevice->capture.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) {
resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pDevice->opensl.pBufferCapture + (periodSizeInBytes * iPeriod), periodSizeInBytes);
if (resultSL != SL_RESULT_SUCCESS) {
MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for capture device.", ma_result_from_OpenSL(resultSL));
}
}
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_PLAYING);
if (resultSL != SL_RESULT_SUCCESS) {
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal playback device.", ma_result_from_OpenSL(resultSL));
}
/* In playback mode (no duplex) we need to load some initial buffers. In duplex mode we need to enqueu silent buffers. */
if (pDevice->type == ma_device_type_duplex) {
MA_ZERO_MEMORY(pDevice->opensl.pBufferPlayback, pDevice->playback.internalPeriodSizeInFrames * pDevice->playback.internalPeriods * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
} else {
ma_device__read_frames_from_client(pDevice, pDevice->playback.internalPeriodSizeInFrames * pDevice->playback.internalPeriods, pDevice->opensl.pBufferPlayback);
}
periodSizeInBytes = pDevice->playback.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) {
resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pDevice->opensl.pBufferPlayback + (periodSizeInBytes * iPeriod), periodSizeInBytes);
if (resultSL != SL_RESULT_SUCCESS) {
MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED);
return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for playback device.", ma_result_from_OpenSL(resultSL));
}
}
}
return MA_SUCCESS;
}
static ma_result ma_device_drain__opensl(ma_device* pDevice, ma_device_type deviceType)
{
SLAndroidSimpleBufferQueueItf pBufferQueue;
MA_ASSERT(deviceType == ma_device_type_capture || deviceType == ma_device_type_playback);
if (pDevice->type == ma_device_type_capture) {
pBufferQueue = (SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture;
pDevice->opensl.isDrainingCapture = MA_TRUE;
} else {
pBufferQueue = (SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback;
pDevice->opensl.isDrainingPlayback = MA_TRUE;
}
for (;;) {
SLAndroidSimpleBufferQueueState state;
MA_OPENSL_BUFFERQUEUE(pBufferQueue)->GetState(pBufferQueue, &state);
if (state.count == 0) {
break;
}
ma_sleep(10);
}
if (pDevice->type == ma_device_type_capture) {
pDevice->opensl.isDrainingCapture = MA_FALSE;
} else {
pDevice->opensl.isDrainingPlayback = MA_FALSE;
}
return MA_SUCCESS;
}
static ma_result ma_device_stop__opensl(ma_device* pDevice)
{
SLresult resultSL;
ma_stop_proc onStop;
MA_ASSERT(pDevice != NULL);
MA_ASSERT(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it before stopping/uninitializing the device. */
if (g_maOpenSLInitCounter == 0) {
return MA_INVALID_OPERATION;
}
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
ma_device_drain__opensl(pDevice, ma_device_type_capture);
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_OUTPUTMIX", &pContext->opensl.SL_IID_OUTPUTMIX);
if (result != MA_SUCCESS) {
return result;
}
pContext->opensl.slCreateEngine = (ma_proc)ma_dlsym(pContext, pContext->opensl.libOpenSLES, "slCreateEngine");
if (pContext->opensl.slCreateEngine == NULL) {
ma_post_log_message(pContext, NULL, MA_LOG_LEVEL_INFO, "[OpenSL|ES] Cannot find symbol slCreateEngine.");
return MA_NO_BACKEND;
}
/* Initialize global data first if applicable. */
ma_spinlock_lock(&g_maOpenSLSpinlock);
{
result = ma_context_init_engine_nolock__opensl(pContext);
}
ma_spinlock_unlock(&g_maOpenSLSpinlock);
if (result != MA_SUCCESS) {
return result; /* Failed to initialize the OpenSL engine. */
}
pContext->isBackendAsynchronous = MA_TRUE;
pContext->onUninit = ma_context_uninit__opensl;
pContext->onDeviceIDEqual = ma_context_is_device_id_equal__opensl;
pContext->onEnumDevices = ma_context_enumerate_devices__opensl;
pContext->onGetDeviceInfo = ma_context_get_device_info__opensl;
pContext->onDeviceInit = ma_device_init__opensl;
pContext->onDeviceUninit = ma_device_uninit__opensl;
pContext->onDeviceStart = ma_device_start__opensl;
pContext->onDeviceStop = ma_device_stop__opensl;
return MA_SUCCESS;
}
#endif /* OpenSL|ES */
/******************************************************************************
Web Audio Backend
******************************************************************************/
#ifdef MA_HAS_WEBAUDIO
#include <emscripten/emscripten.h>
static ma_bool32 ma_is_capture_supported__webaudio()
{
return EM_ASM_INT({
return (navigator.mediaDevices !== undefined && navigator.mediaDevices.getUserMedia !== undefined);
}, 0) != 0; /* Must pass in a dummy argument for C99 compatibility. */
}
#ifdef __cplusplus
extern "C" {
#endif
void EMSCRIPTEN_KEEPALIVE ma_device_process_pcm_frames_capture__webaudio(ma_device* pDevice, int frameCount, float* pFrames)
{
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_capture(pDevice, (ma_uint32)frameCount, pFrames, &pDevice->webaudio.duplexRB);
} else {
ma_device__send_frames_to_client(pDevice, (ma_uint32)frameCount, pFrames); /* Send directly to the client. */
}
}
void EMSCRIPTEN_KEEPALIVE ma_device_process_pcm_frames_playback__webaudio(ma_device* pDevice, int frameCount, float* pFrames)
{
if (pDevice->type == ma_device_type_duplex) {
ma_device__handle_duplex_callback_playback(pDevice, (ma_uint32)frameCount, pFrames, &pDevice->webaudio.duplexRB);
} else {
ma_device__read_frames_from_client(pDevice, (ma_uint32)frameCount, pFrames); /* Read directly from the device. */
}
}
#ifdef __cplusplus
}
#endif
static ma_bool32 ma_context_is_device_id_equal__webaudio(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1)
{
MA_ASSERT(pContext != NULL);
MA_ASSERT(pID0 != NULL);
MA_ASSERT(pID1 != NULL);
(void)pContext;
return ma_strcmp(pID0->webaudio, pID1->webaudio) == 0;
}
static ma_result ma_context_enumerate_devices__webaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
{
ma_bool32 cbResult = MA_TRUE;
MA_ASSERT(pContext != NULL);
MA_ASSERT(callback != NULL);
/* Only supporting default devices for now. */
/* 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);
cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
}
/* Capture. */
if (cbResult) {
if (ma_is_capture_supported__webaudio()) {
ma_device_info deviceInfo;
MA_ZERO_OBJECT(&deviceInfo);
ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
}
}
return MA_SUCCESS;
}
static ma_result ma_context_get_device_info__webaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo)
{
MA_ASSERT(pContext != NULL);
/* No exclusive mode with Web Audio. */
if (shareMode == ma_share_mode_exclusive) {
return MA_SHARE_MODE_NOT_SUPPORTED;
}
if (deviceType == ma_device_type_capture && !ma_is_capture_supported__webaudio()) {
return MA_NO_DEVICE;
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
/*
Stop the device. I think there is a chance the callback could get fired after calling this, hence why we want
to clear the callback before closing.
*/
device.webaudio.close();
device.webaudio = undefined;
/* Can't forget to free the intermediary buffer. This is the buffer that's shared between JavaScript and C. */
if (device.intermediaryBuffer !== undefined) {
Module._free(device.intermediaryBuffer);
device.intermediaryBuffer = undefined;
device.intermediaryBufferView = undefined;
device.intermediaryBufferSizeInBytes = undefined;
}
/* Make sure the device is untracked so the slot can be reused later. */
miniaudio.untrack_device_by_index($0);
}, deviceIndex, deviceType);
}
static void ma_device_uninit__webaudio(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_capture, pDevice->webaudio.indexCapture);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_playback, pDevice->webaudio.indexPlayback);
}
if (pDevice->type == ma_device_type_duplex) {
ma_pcm_rb_uninit(&pDevice->webaudio.duplexRB);
}
}
static ma_result ma_device_init_by_type__webaudio(ma_context* pContext, const ma_device_config* pConfig, ma_device_type deviceType, ma_device* pDevice)
{
int deviceIndex;
ma_uint32 internalPeriodSizeInFrames;
MA_ASSERT(pContext != NULL);
MA_ASSERT(pConfig != NULL);
MA_ASSERT(deviceType != ma_device_type_duplex);
MA_ASSERT(pDevice != NULL);
if (deviceType == ma_device_type_capture && !ma_is_capture_supported__webaudio()) {
return MA_NO_DEVICE;
}
/*
Try calculating an appropriate buffer size. There have been reports of the default buffer size being too small on some browsers. If we're using default buffer size, we'll make sure
the period size is a big biffer than our standard defaults.
*/
internalPeriodSizeInFrames = pConfig->periodSizeInFrames;
if (internalPeriodSizeInFrames == 0) {
ma_uint32 periodSizeInMilliseconds = pConfig->periodSizeInMilliseconds;
if (pDevice->usingDefaultBufferSize) {
if (pConfig->performanceProfile == ma_performance_profile_low_latency) {
periodSizeInMilliseconds = 33; /* 1 frame @ 30 FPS */
} else {
periodSizeInMilliseconds = 333;
}
}
internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(periodSizeInMilliseconds, pConfig->sampleRate);
}
/* The size of the buffer must be a power of 2 and between 256 and 16384. */
if (internalPeriodSizeInFrames < 256) {
internalPeriodSizeInFrames = 256;
} else if (internalPeriodSizeInFrames > 16384) {
internalPeriodSizeInFrames = 16384;
} else {
internalPeriodSizeInFrames = ma_next_power_of_2(internalPeriodSizeInFrames);
}
/* We create the device on the JavaScript side and reference it using an index. We use this to make it possible to reference the device between JavaScript and C. */
deviceIndex = EM_ASM_INT({
var channels = $0;
var sampleRate = $1;
var bufferSize = $2; /* In PCM frames. */
var isCapture = $3;
var pDevice = $4;
if (typeof(miniaudio) === 'undefined') {
return -1; /* Context not initialized. */
}
var device = {};
/* The AudioContext must be created in a suspended state. */
device.webaudio = new (window.AudioContext || window.webkitAudioContext)({sampleRate:sampleRate});
device.webaudio.suspend();
/*
We need an intermediary buffer which we use for JavaScript and C interop. This buffer stores interleaved f32 PCM data. Because it's passed between
JavaScript and C it needs to be allocated and freed using Module._malloc() and Module._free().
*/
device.intermediaryBufferSizeInBytes = channels * bufferSize * 4;
device.intermediaryBuffer = Module._malloc(device.intermediaryBufferSizeInBytes);
device.intermediaryBufferView = new Float32Array(Module.HEAPF32.buffer, device.intermediaryBuffer, device.intermediaryBufferSizeInBytes);
/*
Both playback and capture devices use a ScriptProcessorNode for performing per-sample operations.
ScriptProcessorNode is actually deprecated so this is likely to be temporary. The way this works for playback is very simple. You just set a callback
that's periodically fired, just like a normal audio callback function. But apparently this design is "flawed" and is now deprecated in favour of
something called AudioWorklets which _forces_ you to load a _separate_ .js file at run time... nice... Hopefully ScriptProcessorNode will continue to
work for years to come, but this may need to change to use AudioSourceBufferNode instead, which I think is what Emscripten uses for it's built-in SDL
implementation. I'll be avoiding that insane AudioWorklet API like the plague...
For capture it is a bit unintuitive. We use the ScriptProccessorNode _only_ to get the raw PCM data. It is connected to an AudioContext just like the
playback case, however we just output silence to the AudioContext instead of passing any real data. It would make more sense to me to use the
MediaRecorder API, but unfortunately you need to specify a MIME time (Opus, Vorbis, etc.) for the binary blob that's returned to the client, but I've
been unable to figure out how to get this as raw PCM. The closest I can think is to use the MIME type for WAV files and just parse it, but I don't know
how well this would work. Although ScriptProccessorNode is deprecated, in practice it seems to have pretty good browser support so I'm leaving it like
this for now. If anyone knows how I could get raw PCM data using the MediaRecorder API please let me know!
*/
device.scriptNode = device.webaudio.createScriptProcessor(bufferSize, channels, channels);
if (isCapture) {
device.scriptNode.onaudioprocess = function(e) {
if (device.intermediaryBuffer === undefined) {
return; /* This means the device has been uninitialized. */
}
/* Make sure silence it output to the AudioContext destination. Not doing this will cause sound to come out of the speakers! */
for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) {
e.outputBuffer.getChannelData(iChannel).fill(0.0);
}
/* There are some situations where we may want to send silence to the client. */
var sendSilence = false;
if (device.streamNode === undefined) {
sendSilence = true;
}
/* Sanity check. This will never happen, right? */
if (e.inputBuffer.numberOfChannels != channels) {
console.log("Capture: Channel count mismatch. " + e.inputBufer.numberOfChannels + " != " + channels + ". Sending silence.");
sendSilence = true;
}
/* This looped design guards against the situation where e.inputBuffer is a different size to the original buffer size. Should never happen in practice. */
var totalFramesProcessed = 0;
while (totalFramesProcessed < e.inputBuffer.length) {
var framesRemaining = e.inputBuffer.length - totalFramesProcessed;
var framesToProcess = framesRemaining;
if (framesToProcess > (device.intermediaryBufferSizeInBytes/channels/4)) {
framesToProcess = (device.intermediaryBufferSizeInBytes/channels/4);
}
/* We need to do the reverse of the playback case. We need to interleave the input data and copy it into the intermediary buffer. Then we send it to the client. */
if (sendSilence) {
device.intermediaryBufferView.fill(0.0);
} else {
for (var iFrame = 0; iFrame < framesToProcess; ++iFrame) {
for (var iChannel = 0; iChannel < e.inputBuffer.numberOfChannels; ++iChannel) {
device.intermediaryBufferView[iFrame*channels + iChannel] = e.inputBuffer.getChannelData(iChannel)[totalFramesProcessed + iFrame];
}
}
}
/* Send data to the client from our intermediary buffer. */
ccall("ma_device_process_pcm_frames_capture__webaudio", "undefined", ["number", "number", "number"], [pDevice, framesToProcess, device.intermediaryBuffer]);
totalFramesProcessed += framesToProcess;
}
};
navigator.mediaDevices.getUserMedia({audio:true, video:false})
.then(function(stream) {
device.streamNode = device.webaudio.createMediaStreamSource(stream);
device.streamNode.connect(device.scriptNode);
device.scriptNode.connect(device.webaudio.destination);
})
.catch(function(error) {
/* I think this should output silence... */
device.scriptNode.connect(device.webaudio.destination);
});
} else {
device.scriptNode.onaudioprocess = function(e) {
if (device.intermediaryBuffer === undefined) {
return; /* This means the device has been uninitialized. */
}
var outputSilence = false;
/* Sanity check. This will never happen, right? */
if (e.outputBuffer.numberOfChannels != channels) {
console.log("Playback: Channel count mismatch. " + e.outputBufer.numberOfChannels + " != " + channels + ". Outputting silence.");
outputSilence = true;
return;
}
/* This looped design guards against the situation where e.outputBuffer is a different size to the original buffer size. Should never happen in practice. */
var totalFramesProcessed = 0;
while (totalFramesProcessed < e.outputBuffer.length) {
var framesRemaining = e.outputBuffer.length - totalFramesProcessed;
var framesToProcess = framesRemaining;
if (framesToProcess > (device.intermediaryBufferSizeInBytes/channels/4)) {
framesToProcess = (device.intermediaryBufferSizeInBytes/channels/4);
}
/* Read data from the client into our intermediary buffer. */
ccall("ma_device_process_pcm_frames_playback__webaudio", "undefined", ["number", "number", "number"], [pDevice, framesToProcess, device.intermediaryBuffer]);
/* At this point we'll have data in our intermediary buffer which we now need to deinterleave and copy over to the output buffers. */
if (outputSilence) {
for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) {
e.outputBuffer.getChannelData(iChannel).fill(0.0);
}
} else {
for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) {
for (var iFrame = 0; iFrame < framesToProcess; ++iFrame) {
e.outputBuffer.getChannelData(iChannel)[totalFramesProcessed + iFrame] = device.intermediaryBufferView[iFrame*channels + iChannel];
}
}
}
totalFramesProcessed += framesToProcess;
}
};
device.scriptNode.connect(device.webaudio.destination);
}
return miniaudio.track_device(device);
}, (deviceType == ma_device_type_capture) ? pConfig->capture.channels : pConfig->playback.channels, pConfig->sampleRate, internalPeriodSizeInFrames, deviceType == ma_device_type_capture, pDevice);
if (deviceIndex < 0) {
return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
}
if (deviceType == ma_device_type_capture) {
pDevice->webaudio.indexCapture = deviceIndex;
pDevice->capture.internalFormat = ma_format_f32;
pDevice->capture.internalChannels = pConfig->capture.channels;
ma_get_standard_channel_map(ma_standard_channel_map_webaudio, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap);
pDevice->capture.internalSampleRate = EM_ASM_INT({ return miniaudio.get_device_by_index($0).webaudio.sampleRate; }, deviceIndex);
pDevice->capture.internalPeriodSizeInFrames = internalPeriodSizeInFrames;
pDevice->capture.internalPeriods = 1;
} else {
pDevice->webaudio.indexPlayback = deviceIndex;
pDevice->playback.internalFormat = ma_format_f32;
pDevice->playback.internalChannels = pConfig->playback.channels;
ma_get_standard_channel_map(ma_standard_channel_map_webaudio, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap);
pDevice->playback.internalSampleRate = EM_ASM_INT({ return miniaudio.get_device_by_index($0).webaudio.sampleRate; }, deviceIndex);
pDevice->playback.internalPeriodSizeInFrames = internalPeriodSizeInFrames;
pDevice->playback.internalPeriods = 1;
}
return MA_SUCCESS;
}
static ma_result ma_device_init__webaudio(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
{
ma_result result;
if (pConfig->deviceType == ma_device_type_loopback) {
return MA_DEVICE_TYPE_NOT_SUPPORTED;
}
/* No exclusive mode with Web Audio. */
if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) ||
((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) {
return MA_SHARE_MODE_NOT_SUPPORTED;
}
if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
result = ma_device_init_by_type__webaudio(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) {
result = ma_device_init_by_type__webaudio(pContext, pConfig, ma_device_type_playback, pDevice);
if (result != MA_SUCCESS) {
if (pConfig->deviceType == ma_device_type_duplex) {
ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_capture, pDevice->webaudio.indexCapture);
}
return result;
}
}
/*
We need a ring buffer for moving data from the capture device to the playback device. The capture callback is the producer
and the playback callback is the consumer. The buffer needs to be large enough to hold internalPeriodSizeInFrames based on
the external sample rate.
*/
if (pConfig->deviceType == ma_device_type_duplex) {
ma_uint32 rbSizeInFrames = (ma_uint32)ma_calculate_frame_count_after_resampling(pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalPeriodSizeInFrames) * 2;
result = ma_pcm_rb_init(pDevice->capture.format, pDevice->capture.channels, rbSizeInFrames, NULL, &pDevice->pContext->allocationCallbacks, &pDevice->webaudio.duplexRB);
if (result != MA_SUCCESS) {
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_capture, pDevice->webaudio.indexCapture);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_playback, pDevice->webaudio.indexPlayback);
}
return result;
}
/* We need a period to act as a buffer for cases where the playback and capture device's end up desyncing. */
{
ma_uint32 marginSizeInFrames = rbSizeInFrames / 3; /* <-- Dividing by 3 because internalPeriods is always set to 1 for WebAudio. */
void* pMarginData;
ma_pcm_rb_acquire_write(&pDevice->webaudio.duplexRB, &marginSizeInFrames, &pMarginData);
{
MA_ZERO_MEMORY(pMarginData, marginSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels));
}
ma_pcm_rb_commit_write(&pDevice->webaudio.duplexRB, marginSizeInFrames, pMarginData);
}
}
return MA_SUCCESS;
}
static ma_result ma_device_start__webaudio(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
EM_ASM({
miniaudio.get_device_by_index($0).webaudio.resume();
}, pDevice->webaudio.indexCapture);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
EM_ASM({
miniaudio.get_device_by_index($0).webaudio.resume();
}, pDevice->webaudio.indexPlayback);
}
return MA_SUCCESS;
}
static ma_result ma_device_stop__webaudio(ma_device* pDevice)
{
MA_ASSERT(pDevice != NULL);
/*
From the WebAudio API documentation for AudioContext.suspend():
Suspends the progression of AudioContext's currentTime, allows any current context processing blocks that are already processed to be played to the
destination, and then allows the system to release its claim on audio hardware.
I read this to mean that "any current context processing blocks" are processed by suspend() - i.e. They they are drained. We therefore shouldn't need to
do any kind of explicit draining.
*/
if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
EM_ASM({
miniaudio.get_device_by_index($0).webaudio.suspend();
}, pDevice->webaudio.indexCapture);
}
if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
EM_ASM({
miniaudio.get_device_by_index($0).webaudio.suspend();
}, pDevice->webaudio.indexPlayback);
}
ma_stop_proc onStop = pDevice->onStop;
if (onStop) {
onStop(pDevice);
}
return MA_SUCCESS;
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
return MA_INVALID_ARGS;
}
pDevice->masterVolumeFactor = volume;
return MA_SUCCESS;
}
MA_API ma_result ma_device_get_master_volume(ma_device* pDevice, float* pVolume)
{
if (pVolume == NULL) {
return MA_INVALID_ARGS;
}
if (pDevice == NULL) {
*pVolume = 0;
return MA_INVALID_ARGS;
}
*pVolume = pDevice->masterVolumeFactor;
return MA_SUCCESS;
}
MA_API ma_result ma_device_set_master_gain_db(ma_device* pDevice, float gainDB)
{
if (gainDB > 0) {
return MA_INVALID_ARGS;
}
return ma_device_set_master_volume(pDevice, ma_gain_db_to_factor(gainDB));
}
MA_API ma_result ma_device_get_master_gain_db(ma_device* pDevice, float* pGainDB)
{
float factor;
ma_result result;
if (pGainDB == NULL) {
return MA_INVALID_ARGS;
}
result = ma_device_get_master_volume(pDevice, &factor);
if (result != MA_SUCCESS) {
*pGainDB = 0;
return result;
}
*pGainDB = ma_factor_to_gain_db(factor);
return MA_SUCCESS;
}
#endif /* MA_NO_DEVICE_IO */
MA_API ma_uint32 ma_scale_buffer_size(ma_uint32 baseBufferSize, float scale)
{
return ma_max(1, (ma_uint32)(baseBufferSize*scale));
}
MA_API ma_uint32 ma_calculate_buffer_size_in_milliseconds_from_frames(ma_uint32 bufferSizeInFrames, ma_uint32 sampleRate)
{
return bufferSizeInFrames / (sampleRate/1000);
}
MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate)
{
return bufferSizeInMilliseconds * (sampleRate/1000);
}
MA_API void ma_copy_pcm_frames(void* dst, const void* src, ma_uint64 frameCount, ma_format format, ma_uint32 channels)
{
if (dst == src) {
return; /* No-op. */
}
ma_copy_memory_64(dst, src, frameCount * ma_get_bytes_per_frame(format, channels));
}
MA_API void ma_silence_pcm_frames(void* p, ma_uint64 frameCount, ma_format format, ma_uint32 channels)
{
if (format == ma_format_u8) {
ma_uint64 sampleCount = frameCount * channels;
ma_uint64 iSample;
for (iSample = 0; iSample < sampleCount; iSample += 1) {
((ma_uint8*)p)[iSample] = 128;
}
} else {
ma_zero_memory_64(p, frameCount * ma_get_bytes_per_frame(format, channels));
}
}
MA_API void* ma_offset_pcm_frames_ptr(void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels)
{
return ma_offset_ptr(p, offsetInFrames * ma_get_bytes_per_frame(format, channels));
}
MA_API const void* ma_offset_pcm_frames_const_ptr(const void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels)
{
return ma_offset_ptr(p, offsetInFrames * ma_get_bytes_per_frame(format, channels));
}
MA_API void ma_clip_samples_f32(float* p, ma_uint64 sampleCount)
{
ma_uint32 iSample;
/* TODO: Research a branchless SSE implementation. */
for (iSample = 0; iSample < sampleCount; iSample += 1) {
p[iSample] = ma_clip_f32(p[iSample]);
}
}
MA_API void ma_copy_and_apply_volume_factor_u8(ma_uint8* pSamplesOut, const ma_uint8* pSamplesIn, ma_uint64 sampleCount, float factor)
{
ma_uint64 iSample;
if (pSamplesOut == NULL || pSamplesIn == NULL) {
return;
}
for (iSample = 0; iSample < sampleCount; iSample += 1) {
pSamplesOut[iSample] = (ma_uint8)(pSamplesIn[iSample] * factor);
}
}
MA_API void ma_copy_and_apply_volume_factor_s16(ma_int16* pSamplesOut, const ma_int16* pSamplesIn, ma_uint64 sampleCount, float factor)
{
ma_uint64 iSample;
if (pSamplesOut == NULL || pSamplesIn == NULL) {
return;
}
for (iSample = 0; iSample < sampleCount; iSample += 1) {
pSamplesOut[iSample] = (ma_int16)(pSamplesIn[iSample] * factor);
}
}
MA_API void ma_copy_and_apply_volume_factor_s24(void* pSamplesOut, const void* pSamplesIn, ma_uint64 sampleCount, float factor)
{
ma_uint64 iSample;
ma_uint8* pSamplesOut8;
ma_uint8* pSamplesIn8;
if (pSamplesOut == NULL || pSamplesIn == NULL) {
return;
}
pSamplesOut8 = (ma_uint8*)pSamplesOut;
pSamplesIn8 = (ma_uint8*)pSamplesIn;
for (iSample = 0; iSample < sampleCount; iSample += 1) {
ma_int32 sampleS32;
sampleS32 = (ma_int32)(((ma_uint32)(pSamplesIn8[iSample*3+0]) << 8) | ((ma_uint32)(pSamplesIn8[iSample*3+1]) << 16) | ((ma_uint32)(pSamplesIn8[iSample*3+2])) << 24);
sampleS32 = (ma_int32)(sampleS32 * factor);
pSamplesOut8[iSample*3+0] = (ma_uint8)(((ma_uint32)sampleS32 & 0x0000FF00) >> 8);
pSamplesOut8[iSample*3+1] = (ma_uint8)(((ma_uint32)sampleS32 & 0x00FF0000) >> 16);
pSamplesOut8[iSample*3+2] = (ma_uint8)(((ma_uint32)sampleS32 & 0xFF000000) >> 24);
}
}
MA_API void ma_copy_and_apply_volume_factor_s32(ma_int32* pSamplesOut, const ma_int32* pSamplesIn, ma_uint64 sampleCount, float factor)
{
ma_uint64 iSample;
if (pSamplesOut == NULL || pSamplesIn == NULL) {
return;
}
for (iSample = 0; iSample < sampleCount; iSample += 1) {
pSamplesOut[iSample] = (ma_int32)(pSamplesIn[iSample] * factor);
}
}
MA_API void ma_copy_and_apply_volume_factor_f32(float* pSamplesOut, const float* pSamplesIn, ma_uint64 sampleCount, float factor)
{
ma_uint64 iSample;
if (pSamplesOut == NULL || pSamplesIn == NULL) {
return;
}
for (iSample = 0; iSample < sampleCount; iSample += 1) {
pSamplesOut[iSample] = pSamplesIn[iSample] * factor;
}
}
MA_API void ma_apply_volume_factor_u8(ma_uint8* pSamples, ma_uint64 sampleCount, float factor)
{
ma_copy_and_apply_volume_factor_u8(pSamples, pSamples, sampleCount, factor);
}
MA_API void ma_apply_volume_factor_s16(ma_int16* pSamples, ma_uint64 sampleCount, float factor)
{
ma_copy_and_apply_volume_factor_s16(pSamples, pSamples, sampleCount, factor);
}
MA_API void ma_apply_volume_factor_s24(void* pSamples, ma_uint64 sampleCount, float factor)
{
ma_copy_and_apply_volume_factor_s24(pSamples, pSamples, sampleCount, factor);
}
MA_API void ma_apply_volume_factor_s32(ma_int32* pSamples, ma_uint64 sampleCount, float factor)
{
ma_copy_and_apply_volume_factor_s32(pSamples, pSamples, sampleCount, factor);
}
MA_API void ma_apply_volume_factor_f32(float* pSamples, ma_uint64 sampleCount, float factor)
{
ma_copy_and_apply_volume_factor_f32(pSamples, pSamples, sampleCount, 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_copy_and_apply_volume_factor_u8(pPCMFramesOut, pPCMFramesIn, frameCount*channels, 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_copy_and_apply_volume_factor_s16(pPCMFramesOut, pPCMFramesIn, frameCount*channels, 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_copy_and_apply_volume_factor_s24(pPCMFramesOut, pPCMFramesIn, frameCount*channels, 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_copy_and_apply_volume_factor_s32(pPCMFramesOut, pPCMFramesIn, frameCount*channels, 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_copy_and_apply_volume_factor_f32(pPCMFramesOut, pPCMFramesIn, frameCount*channels, factor);
}
MA_API void ma_copy_and_apply_volume_factor_pcm_frames(void* pPCMFramesOut, const void* pPCMFramesIn, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor)
{
switch (format)
{
case ma_format_u8: ma_copy_and_apply_volume_factor_pcm_frames_u8 ((ma_uint8*)pPCMFramesOut, (const ma_uint8*)pPCMFramesIn, frameCount, channels, factor); return;
case ma_format_s16: ma_copy_and_apply_volume_factor_pcm_frames_s16((ma_int16*)pPCMFramesOut, (const ma_int16*)pPCMFramesIn, frameCount, channels, factor); return;
case ma_format_s24: ma_copy_and_apply_volume_factor_pcm_frames_s24( pPCMFramesOut, pPCMFramesIn, frameCount, channels, factor); return;
case ma_format_s32: ma_copy_and_apply_volume_factor_pcm_frames_s32((ma_int32*)pPCMFramesOut, (const ma_int32*)pPCMFramesIn, frameCount, channels, factor); return;
case ma_format_f32: ma_copy_and_apply_volume_factor_pcm_frames_f32( (float*)pPCMFramesOut, (const float*)pPCMFramesIn, frameCount, channels, factor); return;
default: return; /* Do nothing. */
}
}
MA_API void ma_apply_volume_factor_pcm_frames_u8(ma_uint8* pPCMFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
{
ma_copy_and_apply_volume_factor_pcm_frames_u8(pPCMFrames, pPCMFrames, frameCount, channels, factor);
}
MA_API void ma_apply_volume_factor_pcm_frames_s16(ma_int16* pPCMFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
{
ma_copy_and_apply_volume_factor_pcm_frames_s16(pPCMFrames, pPCMFrames, frameCount, channels, factor);
}
MA_API void ma_apply_volume_factor_pcm_frames_s24(void* pPCMFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
{
ma_copy_and_apply_volume_factor_pcm_frames_s24(pPCMFrames, pPCMFrames, frameCount, channels, factor);
}
MA_API void ma_apply_volume_factor_pcm_frames_s32(ma_int32* pPCMFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
{
ma_copy_and_apply_volume_factor_pcm_frames_s32(pPCMFrames, pPCMFrames, frameCount, channels, factor);
}
MA_API void ma_apply_volume_factor_pcm_frames_f32(float* pPCMFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
{
ma_copy_and_apply_volume_factor_pcm_frames_f32(pPCMFrames, pPCMFrames, frameCount, channels, factor);
}
MA_API void ma_apply_volume_factor_pcm_frames(void* pPCMFrames, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor)
{
ma_copy_and_apply_volume_factor_pcm_frames(pPCMFrames, pPCMFrames, frameCount, format, channels, factor);
}
MA_API float ma_factor_to_gain_db(float factor)
{
return (float)(20*ma_log10f(factor));
}
MA_API float ma_gain_db_to_factor(float gain)
{
return (float)ma_powf(10, gain/20.0f);
}
/**************************************************************************************************************************************************************
Format Conversion
**************************************************************************************************************************************************************/
static MA_INLINE ma_int16 ma_pcm_sample_f32_to_s16(float x)
{
return (ma_int16)(x * 32767.0f);
}
static MA_INLINE ma_int16 ma_pcm_sample_u8_to_s16_no_scale(ma_uint8 x)
{
return (ma_int16)((ma_int16)x - 128);
}
static MA_INLINE ma_int64 ma_pcm_sample_s24_to_s32_no_scale(const ma_uint8* x)
{
return (ma_int64)(((ma_uint64)x[0] << 40) | ((ma_uint64)x[1] << 48) | ((ma_uint64)x[2] << 56)) >> 40; /* Make sure the sign bits are maintained. */
}
static MA_INLINE void ma_pcm_sample_s32_to_s24_no_scale(ma_int64 x, ma_uint8* s24)
{
s24[0] = (ma_uint8)((x & 0x000000FF) >> 0);
s24[1] = (ma_uint8)((x & 0x0000FF00) >> 8);
s24[2] = (ma_uint8)((x & 0x00FF0000) >> 16);
}
static MA_INLINE ma_uint8 ma_clip_u8(ma_int16 x)
{
return (ma_uint8)(ma_clamp(x, -128, 127) + 128);
}
static MA_INLINE ma_int16 ma_clip_s16(ma_int32 x)
{
return (ma_int16)ma_clamp(x, -32768, 32767);
}
static MA_INLINE ma_int64 ma_clip_s24(ma_int64 x)
{
return (ma_int64)ma_clamp(x, -8388608, 8388607);
}
static MA_INLINE ma_int32 ma_clip_s32(ma_int64 x)
{
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
float x = (float)src_u8[i];
x = x * 0.00784313725490196078f; /* 0..255 to 0..2 */
x = x - 1; /* 0..2 to -1..1 */
dst_f32[i] = x;
}
(void)ditherMode;
}
static MA_INLINE void ma_pcm_u8_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_u8_to_f32__reference(dst, src, count, ditherMode);
}
#if defined(MA_SUPPORT_SSE2)
static MA_INLINE void ma_pcm_u8_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_AVX2)
static MA_INLINE void ma_pcm_u8_to_f32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_NEON)
static MA_INLINE void ma_pcm_u8_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
MA_API void ma_pcm_u8_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_u8_to_f32__reference(dst, src, count, ditherMode);
#else
# if MA_PREFERRED_SIMD == MA_SIMD_AVX2
if (ma_has_avx2()) {
ma_pcm_u8_to_f32__avx2(dst, src, count, ditherMode);
} else
#elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
if (ma_has_sse2()) {
ma_pcm_u8_to_f32__sse2(dst, src, count, ditherMode);
} else
#elif MA_PREFERRED_SIMD == MA_SIMD_NEON
if (ma_has_neon()) {
ma_pcm_u8_to_f32__neon(dst, src, count, ditherMode);
} else
#endif
{
ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
}
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
static MA_INLINE void ma_pcm_interleave_u8__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_uint8* dst_u8 = (ma_uint8*)dst;
const ma_uint8** src_u8 = (const ma_uint8**)src;
ma_uint64 iFrame;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; iChannel += 1) {
dst_u8[iFrame*channels + iChannel] = src_u8[iChannel][iFrame];
}
}
}
#else
static MA_INLINE void ma_pcm_interleave_u8__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_uint8* dst_u8 = (ma_uint8*)dst;
const ma_uint8** src_u8 = (const ma_uint8**)src;
if (channels == 1) {
ma_copy_memory_64(dst, src[0], frameCount * sizeof(ma_uint8));
} else if (channels == 2) {
ma_uint64 iFrame;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
dst_u8[iFrame*2 + 0] = src_u8[0][iFrame];
dst_u8[iFrame*2 + 1] = src_u8[1][iFrame];
}
} else {
ma_uint64 iFrame;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; iChannel += 1) {
dst_u8[iFrame*channels + iChannel] = src_u8[iChannel][iFrame];
}
}
}
}
#endif
MA_API void ma_pcm_interleave_u8(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_interleave_u8__reference(dst, src, frameCount, channels);
#else
ma_pcm_interleave_u8__optimized(dst, src, frameCount, channels);
#endif
}
static MA_INLINE void ma_pcm_deinterleave_u8__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_uint8** dst_u8 = (ma_uint8**)dst;
const ma_uint8* src_u8 = (const ma_uint8*)src;
ma_uint64 iFrame;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; iChannel += 1) {
dst_u8[iChannel][iFrame] = src_u8[iFrame*channels + iChannel];
}
}
}
static MA_INLINE void ma_pcm_deinterleave_u8__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_pcm_deinterleave_u8__reference(dst, src, frameCount, channels);
}
MA_API void ma_pcm_deinterleave_u8(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_deinterleave_u8__reference(dst, src, frameCount, channels);
#else
ma_pcm_deinterleave_u8__optimized(dst, src, frameCount, channels);
#endif
}
/* s16 */
static MA_INLINE void ma_pcm_s16_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_uint8* dst_u8 = (ma_uint8*)dst;
const ma_int16* src_s16 = (const ma_int16*)src;
if (ditherMode == ma_dither_mode_none) {
ma_uint64 i;
for (i = 0; i < count; i += 1) {
ma_int16 x = src_s16[i];
x = (ma_int16)(x >> 8);
x = (ma_int16)(x + 128);
dst_u8[i] = (ma_uint8)x;
}
} else {
ma_uint64 i;
for (i = 0; i < count; i += 1) {
ma_int16 x = src_s16[i];
/* Dither. Don't overflow. */
ma_int32 dither = ma_dither_s32(ditherMode, -0x80, 0x7F);
if ((x + dither) <= 0x7FFF) {
x = (ma_int16)(x + dither);
} else {
x = 0x7FFF;
}
x = (ma_int16)(x >> 8);
x = (ma_int16)(x + 128);
dst_u8[i] = (ma_uint8)x;
}
}
}
static MA_INLINE void ma_pcm_s16_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s16_to_u8__reference(dst, src, count, ditherMode);
}
#if defined(MA_SUPPORT_SSE2)
static MA_INLINE void ma_pcm_s16_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_AVX2)
static MA_INLINE void ma_pcm_s16_to_u8__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_NEON)
static MA_INLINE void ma_pcm_s16_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
#else
/* The fast way. */
x = x * 0.000030517578125f; /* -32768..32767 to -1..0.999969482421875 */
#endif
dst_f32[i] = x;
}
(void)ditherMode;
}
static MA_INLINE void ma_pcm_s16_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s16_to_f32__reference(dst, src, count, ditherMode);
}
#if defined(MA_SUPPORT_SSE2)
static MA_INLINE void ma_pcm_s16_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_AVX2)
static MA_INLINE void ma_pcm_s16_to_f32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_NEON)
static MA_INLINE void ma_pcm_s16_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
MA_API void ma_pcm_s16_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_s16_to_f32__reference(dst, src, count, ditherMode);
#else
# if MA_PREFERRED_SIMD == MA_SIMD_AVX2
if (ma_has_avx2()) {
ma_pcm_s16_to_f32__avx2(dst, src, count, ditherMode);
} else
#elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
if (ma_has_sse2()) {
ma_pcm_s16_to_f32__sse2(dst, src, count, ditherMode);
} else
#elif MA_PREFERRED_SIMD == MA_SIMD_NEON
if (ma_has_neon()) {
ma_pcm_s16_to_f32__neon(dst, src, count, ditherMode);
} else
#endif
{
ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
}
static MA_INLINE void ma_pcm_interleave_s16__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_int16* dst_s16 = (ma_int16*)dst;
const ma_int16** src_s16 = (const ma_int16**)src;
ma_uint64 iFrame;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; iChannel += 1) {
dst_s16[iFrame*channels + iChannel] = src_s16[iChannel][iFrame];
}
}
}
static MA_INLINE void ma_pcm_interleave_s16__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_pcm_interleave_s16__reference(dst, src, frameCount, channels);
}
MA_API void ma_pcm_interleave_s16(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_interleave_s16__reference(dst, src, frameCount, channels);
#else
ma_pcm_interleave_s16__optimized(dst, src, frameCount, channels);
#endif
}
static MA_INLINE void ma_pcm_deinterleave_s16__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_int16** dst_s16 = (ma_int16**)dst;
const ma_int16* src_s16 = (const ma_int16*)src;
ma_uint64 iFrame;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; iChannel += 1) {
dst_s16[iChannel][iFrame] = src_s16[iFrame*channels + iChannel];
}
}
}
static MA_INLINE void ma_pcm_deinterleave_s16__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_pcm_deinterleave_s16__reference(dst, src, frameCount, channels);
}
MA_API void ma_pcm_deinterleave_s16(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_deinterleave_s16__reference(dst, src, frameCount, channels);
#else
ma_pcm_deinterleave_s16__optimized(dst, src, frameCount, channels);
#endif
}
/* s24 */
static MA_INLINE void ma_pcm_s24_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_uint8* dst_u8 = (ma_uint8*)dst;
const ma_uint8* src_s24 = (const ma_uint8*)src;
if (ditherMode == ma_dither_mode_none) {
ma_uint64 i;
for (i = 0; i < count; i += 1) {
dst_u8[i] = (ma_uint8)((ma_int8)src_s24[i*3 + 2] + 128);
}
} else {
ma_uint64 i;
for (i = 0; i < count; i += 1) {
ma_int32 x = (ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24);
/* Dither. Don't overflow. */
ma_int32 dither = ma_dither_s32(ditherMode, -0x800000, 0x7FFFFF);
if ((ma_int64)x + dither <= 0x7FFFFFFF) {
x = x + dither;
} else {
x = 0x7FFFFFFF;
}
x = x >> 24;
x = x + 128;
dst_u8[i] = (ma_uint8)x;
}
}
}
static MA_INLINE void ma_pcm_s24_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s24_to_u8__reference(dst, src, count, ditherMode);
}
#if defined(MA_SUPPORT_SSE2)
static MA_INLINE void ma_pcm_s24_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_AVX2)
static MA_INLINE void ma_pcm_s24_to_u8__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_NEON)
static MA_INLINE void ma_pcm_s24_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
}
#endif
MA_API void ma_pcm_s24_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
#else
/* The fast way. */
x = x * 0.00000011920928955078125f; /* -8388608..8388607 to -1..0.999969482421875 */
#endif
dst_f32[i] = x;
}
(void)ditherMode;
}
static MA_INLINE void ma_pcm_s24_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s24_to_f32__reference(dst, src, count, ditherMode);
}
#if defined(MA_SUPPORT_SSE2)
static MA_INLINE void ma_pcm_s24_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_AVX2)
static MA_INLINE void ma_pcm_s24_to_f32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_NEON)
static MA_INLINE void ma_pcm_s24_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
MA_API void ma_pcm_s24_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_s24_to_f32__reference(dst, src, count, ditherMode);
#else
# if MA_PREFERRED_SIMD == MA_SIMD_AVX2
if (ma_has_avx2()) {
ma_pcm_s24_to_f32__avx2(dst, src, count, ditherMode);
} else
#elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
if (ma_has_sse2()) {
ma_pcm_s24_to_f32__sse2(dst, src, count, ditherMode);
} else
#elif MA_PREFERRED_SIMD == MA_SIMD_NEON
if (ma_has_neon()) {
ma_pcm_s24_to_f32__neon(dst, src, count, ditherMode);
} else
#endif
{
ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
}
static MA_INLINE void ma_pcm_interleave_s24__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_uint8* dst8 = (ma_uint8*)dst;
const ma_uint8** src8 = (const ma_uint8**)src;
ma_uint64 iFrame;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; iChannel += 1) {
dst8[iFrame*3*channels + iChannel*3 + 0] = src8[iChannel][iFrame*3 + 0];
dst8[iFrame*3*channels + iChannel*3 + 1] = src8[iChannel][iFrame*3 + 1];
dst8[iFrame*3*channels + iChannel*3 + 2] = src8[iChannel][iFrame*3 + 2];
}
}
}
static MA_INLINE void ma_pcm_interleave_s24__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_pcm_interleave_s24__reference(dst, src, frameCount, channels);
}
MA_API void ma_pcm_interleave_s24(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_interleave_s24__reference(dst, src, frameCount, channels);
#else
ma_pcm_interleave_s24__optimized(dst, src, frameCount, channels);
#endif
}
static MA_INLINE void ma_pcm_deinterleave_s24__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_uint8** dst8 = (ma_uint8**)dst;
const ma_uint8* src8 = (const ma_uint8*)src;
ma_uint32 iFrame;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; iChannel += 1) {
dst8[iChannel][iFrame*3 + 0] = src8[iFrame*3*channels + iChannel*3 + 0];
dst8[iChannel][iFrame*3 + 1] = src8[iFrame*3*channels + iChannel*3 + 1];
dst8[iChannel][iFrame*3 + 2] = src8[iFrame*3*channels + iChannel*3 + 2];
}
}
}
static MA_INLINE void ma_pcm_deinterleave_s24__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_pcm_deinterleave_s24__reference(dst, src, frameCount, channels);
}
MA_API void ma_pcm_deinterleave_s24(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_deinterleave_s24__reference(dst, src, frameCount, channels);
#else
ma_pcm_deinterleave_s24__optimized(dst, src, frameCount, channels);
#endif
}
/* s32 */
static MA_INLINE void ma_pcm_s32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_uint8* dst_u8 = (ma_uint8*)dst;
const ma_int32* src_s32 = (const ma_int32*)src;
if (ditherMode == ma_dither_mode_none) {
ma_uint64 i;
for (i = 0; i < count; i += 1) {
ma_int32 x = src_s32[i];
x = x >> 24;
x = x + 128;
dst_u8[i] = (ma_uint8)x;
}
} else {
ma_uint64 i;
for (i = 0; i < count; i += 1) {
ma_int32 x = src_s32[i];
/* Dither. Don't overflow. */
ma_int32 dither = ma_dither_s32(ditherMode, -0x800000, 0x7FFFFF);
if ((ma_int64)x + dither <= 0x7FFFFFFF) {
x = x + dither;
} else {
x = 0x7FFFFFFF;
}
x = x >> 24;
x = x + 128;
dst_u8[i] = (ma_uint8)x;
}
}
}
static MA_INLINE void ma_pcm_s32_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s32_to_u8__reference(dst, src, count, ditherMode);
}
#if defined(MA_SUPPORT_SSE2)
static MA_INLINE void ma_pcm_s32_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_AVX2)
static MA_INLINE void ma_pcm_s32_to_u8__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_NEON)
static MA_INLINE void ma_pcm_s32_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
x = x - 1;
#else
x = x / 2147483648.0;
#endif
dst_f32[i] = (float)x;
}
(void)ditherMode; /* No dithering for s32 -> f32. */
}
static MA_INLINE void ma_pcm_s32_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s32_to_f32__reference(dst, src, count, ditherMode);
}
#if defined(MA_SUPPORT_SSE2)
static MA_INLINE void ma_pcm_s32_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_AVX2)
static MA_INLINE void ma_pcm_s32_to_f32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_NEON)
static MA_INLINE void ma_pcm_s32_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
MA_API void ma_pcm_s32_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_s32_to_f32__reference(dst, src, count, ditherMode);
#else
# if MA_PREFERRED_SIMD == MA_SIMD_AVX2
if (ma_has_avx2()) {
ma_pcm_s32_to_f32__avx2(dst, src, count, ditherMode);
} else
#elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
if (ma_has_sse2()) {
ma_pcm_s32_to_f32__sse2(dst, src, count, ditherMode);
} else
#elif MA_PREFERRED_SIMD == MA_SIMD_NEON
if (ma_has_neon()) {
ma_pcm_s32_to_f32__neon(dst, src, count, ditherMode);
} else
#endif
{
ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
}
#endif
}
static MA_INLINE void ma_pcm_interleave_s32__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_int32* dst_s32 = (ma_int32*)dst;
const ma_int32** src_s32 = (const ma_int32**)src;
ma_uint64 iFrame;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; iChannel += 1) {
dst_s32[iFrame*channels + iChannel] = src_s32[iChannel][iFrame];
}
}
}
static MA_INLINE void ma_pcm_interleave_s32__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_pcm_interleave_s32__reference(dst, src, frameCount, channels);
}
MA_API void ma_pcm_interleave_s32(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_interleave_s32__reference(dst, src, frameCount, channels);
#else
ma_pcm_interleave_s32__optimized(dst, src, frameCount, channels);
#endif
}
static MA_INLINE void ma_pcm_deinterleave_s32__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_int32** dst_s32 = (ma_int32**)dst;
const ma_int32* src_s32 = (const ma_int32*)src;
ma_uint64 iFrame;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; iChannel += 1) {
dst_s32[iChannel][iFrame] = src_s32[iFrame*channels + iChannel];
}
}
}
static MA_INLINE void ma_pcm_deinterleave_s32__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_pcm_deinterleave_s32__reference(dst, src, frameCount, channels);
}
MA_API void ma_pcm_deinterleave_s32(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_deinterleave_s32__reference(dst, src, frameCount, channels);
#else
ma_pcm_deinterleave_s32__optimized(dst, src, frameCount, channels);
#endif
}
/* f32 */
static MA_INLINE void ma_pcm_f32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_uint64 i;
ma_uint8* dst_u8 = (ma_uint8*)dst;
const float* src_f32 = (const float*)src;
float ditherMin = 0;
float ditherMax = 0;
if (ditherMode != ma_dither_mode_none) {
ditherMin = 1.0f / -128;
ditherMax = 1.0f / 127;
}
for (i = 0; i < count; i += 1) {
float x = src_f32[i];
x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
x = x + 1; /* -1..1 to 0..2 */
x = x * 127.5f; /* 0..2 to 0..255 */
dst_u8[i] = (ma_uint8)x;
}
}
static MA_INLINE void ma_pcm_f32_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_f32_to_u8__reference(dst, src, count, ditherMode);
}
#if defined(MA_SUPPORT_SSE2)
static MA_INLINE void ma_pcm_f32_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_AVX2)
static MA_INLINE void ma_pcm_f32_to_u8__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_NEON)
static MA_INLINE void ma_pcm_f32_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
}
#endif
MA_API void ma_pcm_f32_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_f32_to_u8__reference(dst, src, count, ditherMode);
#else
# if MA_PREFERRED_SIMD == MA_SIMD_AVX2
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
(void)ditherMode; /* No dithering for f32 -> s32. */
}
static MA_INLINE void ma_pcm_f32_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_f32_to_s32__reference(dst, src, count, ditherMode);
}
#if defined(MA_SUPPORT_SSE2)
static MA_INLINE void ma_pcm_f32_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_AVX2)
static MA_INLINE void ma_pcm_f32_to_s32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
}
#endif
#if defined(MA_SUPPORT_NEON)
static MA_INLINE void ma_pcm_f32_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
}
#endif
MA_API void ma_pcm_f32_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_f32_to_s32__reference(dst, src, count, ditherMode);
#else
# if MA_PREFERRED_SIMD == MA_SIMD_AVX2
if (ma_has_avx2()) {
ma_pcm_f32_to_s32__avx2(dst, src, count, ditherMode);
} else
#elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
if (ma_has_sse2()) {
ma_pcm_f32_to_s32__sse2(dst, src, count, ditherMode);
} else
#elif MA_PREFERRED_SIMD == MA_SIMD_NEON
if (ma_has_neon()) {
ma_pcm_f32_to_s32__neon(dst, src, count, ditherMode);
} else
#endif
{
ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
}
#endif
}
MA_API void ma_pcm_f32_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
{
(void)ditherMode;
ma_copy_memory_64(dst, src, count * sizeof(float));
}
static void ma_pcm_interleave_f32__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
float* dst_f32 = (float*)dst;
const float** src_f32 = (const float**)src;
ma_uint64 iFrame;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; iChannel += 1) {
dst_f32[iFrame*channels + iChannel] = src_f32[iChannel][iFrame];
}
}
}
static void ma_pcm_interleave_f32__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_pcm_interleave_f32__reference(dst, src, frameCount, channels);
}
MA_API void ma_pcm_interleave_f32(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_interleave_f32__reference(dst, src, frameCount, channels);
#else
ma_pcm_interleave_f32__optimized(dst, src, frameCount, channels);
#endif
}
static void ma_pcm_deinterleave_f32__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
float** dst_f32 = (float**)dst;
const float* src_f32 = (const float*)src;
ma_uint64 iFrame;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; iChannel += 1) {
dst_f32[iChannel][iFrame] = src_f32[iFrame*channels + iChannel];
}
}
}
static void ma_pcm_deinterleave_f32__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
ma_pcm_deinterleave_f32__reference(dst, src, frameCount, channels);
}
MA_API void ma_pcm_deinterleave_f32(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
{
#ifdef MA_USE_REFERENCE_CONVERSION_APIS
ma_pcm_deinterleave_f32__reference(dst, src, frameCount, channels);
#else
ma_pcm_deinterleave_f32__optimized(dst, src, frameCount, channels);
#endif
}
MA_API void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode)
{
if (formatOut == formatIn) {
ma_copy_memory_64(pOut, pIn, sampleCount * ma_get_bytes_per_sample(formatOut));
return;
}
switch (formatIn)
{
case ma_format_u8:
{
switch (formatOut)
{
case ma_format_s16: ma_pcm_u8_to_s16(pOut, pIn, sampleCount, ditherMode); return;
case ma_format_s24: ma_pcm_u8_to_s24(pOut, pIn, sampleCount, ditherMode); return;
case ma_format_s32: ma_pcm_u8_to_s32(pOut, pIn, sampleCount, ditherMode); return;
case ma_format_f32: ma_pcm_u8_to_f32(pOut, pIn, sampleCount, ditherMode); return;
default: break;
}
} break;
case ma_format_s16:
{
switch (formatOut)
{
case ma_format_u8: ma_pcm_s16_to_u8( pOut, pIn, sampleCount, ditherMode); return;
case ma_format_s24: ma_pcm_s16_to_s24(pOut, pIn, sampleCount, ditherMode); return;
case ma_format_s32: ma_pcm_s16_to_s32(pOut, pIn, sampleCount, ditherMode); return;
case ma_format_f32: ma_pcm_s16_to_f32(pOut, pIn, sampleCount, ditherMode); return;
default: break;
}
} break;
case ma_format_s24:
{
switch (formatOut)
{
case ma_format_u8: ma_pcm_s24_to_u8( pOut, pIn, sampleCount, ditherMode); return;
case ma_format_s16: ma_pcm_s24_to_s16(pOut, pIn, sampleCount, ditherMode); return;
case ma_format_s32: ma_pcm_s24_to_s32(pOut, pIn, sampleCount, ditherMode); return;
case ma_format_f32: ma_pcm_s24_to_f32(pOut, pIn, sampleCount, ditherMode); return;
default: break;
}
} break;
case ma_format_s32:
{
switch (formatOut)
{
case ma_format_u8: ma_pcm_s32_to_u8( pOut, pIn, sampleCount, ditherMode); return;
case ma_format_s16: ma_pcm_s32_to_s16(pOut, pIn, sampleCount, ditherMode); return;
case ma_format_s24: ma_pcm_s32_to_s24(pOut, pIn, sampleCount, ditherMode); return;
case ma_format_f32: ma_pcm_s32_to_f32(pOut, pIn, sampleCount, ditherMode); return;
default: break;
}
} break;
case ma_format_f32:
{
switch (formatOut)
{
case ma_format_u8: ma_pcm_f32_to_u8( pOut, pIn, sampleCount, ditherMode); return;
case ma_format_s16: ma_pcm_f32_to_s16(pOut, pIn, sampleCount, ditherMode); return;
case ma_format_s24: ma_pcm_f32_to_s24(pOut, pIn, sampleCount, ditherMode); return;
case ma_format_s32: ma_pcm_f32_to_s32(pOut, pIn, sampleCount, ditherMode); return;
default: break;
}
} break;
default: break;
}
}
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)
{
ma_pcm_convert(pOut, formatOut, pIn, formatIn, frameCount * channels, ditherMode);
}
MA_API void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames)
{
if (pInterleavedPCMFrames == NULL || ppDeinterleavedPCMFrames == NULL) {
return; /* Invalid args. */
}
/* For efficiency we do this per format. */
switch (format) {
case ma_format_s16:
{
const ma_int16* pSrcS16 = (const ma_int16*)pInterleavedPCMFrames;
ma_uint64 iPCMFrame;
for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; ++iChannel) {
ma_int16* pDstS16 = (ma_int16*)ppDeinterleavedPCMFrames[iChannel];
pDstS16[iPCMFrame] = pSrcS16[iPCMFrame*channels+iChannel];
}
}
} break;
case ma_format_f32:
{
const float* pSrcF32 = (const float*)pInterleavedPCMFrames;
ma_uint64 iPCMFrame;
for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; ++iChannel) {
float* pDstF32 = (float*)ppDeinterleavedPCMFrames[iChannel];
pDstF32[iPCMFrame] = pSrcF32[iPCMFrame*channels+iChannel];
}
}
} break;
default:
{
ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format);
ma_uint64 iPCMFrame;
for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; ++iChannel) {
void* pDst = ma_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes);
const void* pSrc = ma_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes);
memcpy(pDst, pSrc, sampleSizeInBytes);
}
}
} break;
}
}
MA_API void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames)
{
switch (format)
{
case ma_format_s16:
{
ma_int16* pDstS16 = (ma_int16*)pInterleavedPCMFrames;
ma_uint64 iPCMFrame;
for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; ++iChannel) {
const ma_int16* pSrcS16 = (const ma_int16*)ppDeinterleavedPCMFrames[iChannel];
pDstS16[iPCMFrame*channels+iChannel] = pSrcS16[iPCMFrame];
}
}
} break;
case ma_format_f32:
{
float* pDstF32 = (float*)pInterleavedPCMFrames;
ma_uint64 iPCMFrame;
for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; ++iChannel) {
const float* pSrcF32 = (const float*)ppDeinterleavedPCMFrames[iChannel];
pDstF32[iPCMFrame*channels+iChannel] = pSrcF32[iPCMFrame];
}
}
} break;
default:
{
ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format);
ma_uint64 iPCMFrame;
for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; ++iChannel) {
void* pDst = ma_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes);
const void* pSrc = ma_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes);
memcpy(pDst, pSrc, sampleSizeInBytes);
}
}
} break;
}
}
/**************************************************************************************************************************************************************
Biquad Filter
**************************************************************************************************************************************************************/
#ifndef MA_BIQUAD_FIXED_POINT_SHIFT
#define MA_BIQUAD_FIXED_POINT_SHIFT 14
#endif
static ma_int32 ma_biquad_float_to_fp(double x)
{
return (ma_int32)(x * (1 << MA_BIQUAD_FIXED_POINT_SHIFT));
}
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)
{
ma_biquad_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.b0 = b0;
config.b1 = b1;
config.b2 = b2;
config.a0 = a0;
config.a1 = a1;
config.a2 = a2;
return config;
}
MA_API ma_result ma_biquad_init(const ma_biquad_config* pConfig, ma_biquad* pBQ)
{
if (pBQ == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pBQ);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
if (pConfig->channels < MA_MIN_CHANNELS || pConfig->channels > MA_MAX_CHANNELS) {
return MA_INVALID_ARGS;
}
return ma_biquad_reinit(pConfig, pBQ);
}
MA_API ma_result ma_biquad_reinit(const ma_biquad_config* pConfig, ma_biquad* pBQ)
{
if (pBQ == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
if (pConfig->a0 == 0) {
return MA_INVALID_ARGS; /* Division by zero. */
}
/* Only supporting f32 and s16. */
if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
return MA_INVALID_ARGS;
}
/* The format cannot be changed after initialization. */
if (pBQ->format != ma_format_unknown && pBQ->format != pConfig->format) {
return MA_INVALID_OPERATION;
}
/* The channel count cannot be changed after initialization. */
if (pBQ->channels != 0 && pBQ->channels != pConfig->channels) {
return MA_INVALID_OPERATION;
}
pBQ->format = pConfig->format;
pBQ->channels = pConfig->channels;
/* Normalize. */
if (pConfig->format == ma_format_f32) {
pBQ->b0.f32 = (float)(pConfig->b0 / pConfig->a0);
pBQ->b1.f32 = (float)(pConfig->b1 / pConfig->a0);
pBQ->b2.f32 = (float)(pConfig->b2 / pConfig->a0);
pBQ->a1.f32 = (float)(pConfig->a1 / pConfig->a0);
pBQ->a2.f32 = (float)(pConfig->a2 / pConfig->a0);
} else {
pBQ->b0.s32 = ma_biquad_float_to_fp(pConfig->b0 / pConfig->a0);
pBQ->b1.s32 = ma_biquad_float_to_fp(pConfig->b1 / pConfig->a0);
pBQ->b2.s32 = ma_biquad_float_to_fp(pConfig->b2 / pConfig->a0);
pBQ->a1.s32 = ma_biquad_float_to_fp(pConfig->a1 / pConfig->a0);
pBQ->a2.s32 = ma_biquad_float_to_fp(pConfig->a2 / pConfig->a0);
}
return MA_SUCCESS;
}
static MA_INLINE void ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(ma_biquad* pBQ, float* pY, const float* pX)
{
ma_uint32 c;
const float b0 = pBQ->b0.f32;
const float b1 = pBQ->b1.f32;
const float b2 = pBQ->b2.f32;
const float a1 = pBQ->a1.f32;
const float a2 = pBQ->a2.f32;
for (c = 0; c < pBQ->channels; c += 1) {
float r1 = pBQ->r1[c].f32;
float r2 = pBQ->r2[c].f32;
float x = pX[c];
float y;
y = b0*x + r1;
r1 = b1*x - a1*y + r2;
r2 = b2*x - a2*y;
pY[c] = y;
pBQ->r1[c].f32 = r1;
pBQ->r2[c].f32 = r2;
}
}
static MA_INLINE void ma_biquad_process_pcm_frame_f32(ma_biquad* pBQ, float* pY, const float* pX)
{
ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(pBQ, pY, pX);
}
static MA_INLINE void ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(ma_biquad* pBQ, ma_int16* pY, const ma_int16* pX)
{
ma_uint32 c;
const ma_int32 b0 = pBQ->b0.s32;
const ma_int32 b1 = pBQ->b1.s32;
const ma_int32 b2 = pBQ->b2.s32;
const ma_int32 a1 = pBQ->a1.s32;
const ma_int32 a2 = pBQ->a2.s32;
for (c = 0; c < pBQ->channels; c += 1) {
ma_int32 r1 = pBQ->r1[c].s32;
ma_int32 r2 = pBQ->r2[c].s32;
ma_int32 x = pX[c];
ma_int32 y;
y = (b0*x + r1) >> MA_BIQUAD_FIXED_POINT_SHIFT;
r1 = (b1*x - a1*y + r2);
r2 = (b2*x - a2*y);
pY[c] = (ma_int16)ma_clamp(y, -32768, 32767);
pBQ->r1[c].s32 = r1;
pBQ->r2[c].s32 = r2;
}
}
static MA_INLINE void ma_biquad_process_pcm_frame_s16(ma_biquad* pBQ, ma_int16* pY, const ma_int16* pX)
{
ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(pBQ, pY, pX);
}
MA_API ma_result ma_biquad_process_pcm_frames(ma_biquad* pBQ, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
ma_uint32 n;
if (pBQ == NULL || pFramesOut == NULL || pFramesIn == NULL) {
return MA_INVALID_ARGS;
}
/* Note that the logic below needs to support in-place filtering. That is, it must support the case where pFramesOut and pFramesIn are the same. */
if (pBQ->format == ma_format_f32) {
/* */ float* pY = ( float*)pFramesOut;
const float* pX = (const float*)pFramesIn;
for (n = 0; n < frameCount; n += 1) {
ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(pBQ, pY, pX);
pY += pBQ->channels;
pX += pBQ->channels;
}
} else if (pBQ->format == ma_format_s16) {
/* */ ma_int16* pY = ( ma_int16*)pFramesOut;
const ma_int16* pX = (const ma_int16*)pFramesIn;
for (n = 0; n < frameCount; n += 1) {
ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(pBQ, pY, pX);
pY += pBQ->channels;
pX += pBQ->channels;
}
} else {
MA_ASSERT(MA_FALSE);
return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */
}
return MA_SUCCESS;
}
MA_API ma_uint32 ma_biquad_get_latency(ma_biquad* pBQ)
{
if (pBQ == NULL) {
return 0;
}
return 2;
}
/**************************************************************************************************************************************************************
Low-Pass Filter
**************************************************************************************************************************************************************/
MA_API ma_lpf1_config ma_lpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency)
{
ma_lpf1_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.cutoffFrequency = cutoffFrequency;
config.q = 0.5;
return config;
}
MA_API ma_lpf2_config ma_lpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q)
{
ma_lpf2_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.cutoffFrequency = cutoffFrequency;
config.q = q;
/* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */
if (config.q == 0) {
config.q = 0.707107;
}
return config;
}
MA_API ma_result ma_lpf1_init(const ma_lpf1_config* pConfig, ma_lpf1* pLPF)
{
if (pLPF == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pLPF);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
if (pConfig->channels < MA_MIN_CHANNELS || pConfig->channels > MA_MAX_CHANNELS) {
return MA_INVALID_ARGS;
}
return ma_lpf1_reinit(pConfig, pLPF);
}
MA_API ma_result ma_lpf1_reinit(const ma_lpf1_config* pConfig, ma_lpf1* pLPF)
{
double a;
if (pLPF == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
/* Only supporting f32 and s16. */
if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
return MA_INVALID_ARGS;
}
/* The format cannot be changed after initialization. */
if (pLPF->format != ma_format_unknown && pLPF->format != pConfig->format) {
return MA_INVALID_OPERATION;
}
/* The channel count cannot be changed after initialization. */
if (pLPF->channels != 0 && pLPF->channels != pConfig->channels) {
return MA_INVALID_OPERATION;
}
pLPF->format = pConfig->format;
pLPF->channels = pConfig->channels;
a = ma_exp(-2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate);
if (pConfig->format == ma_format_f32) {
pLPF->a.f32 = (float)a;
} else {
pLPF->a.s32 = ma_biquad_float_to_fp(a);
}
return MA_SUCCESS;
}
static MA_INLINE void ma_lpf1_process_pcm_frame_f32(ma_lpf1* pLPF, float* pY, const float* pX)
{
ma_uint32 c;
const float a = pLPF->a.f32;
const float b = 1 - a;
for (c = 0; c < pLPF->channels; c += 1) {
float r1 = pLPF->r1[c].f32;
float x = pX[c];
float y;
y = b*x + a*r1;
pY[c] = y;
pLPF->r1[c].f32 = y;
}
}
static MA_INLINE void ma_lpf1_process_pcm_frame_s16(ma_lpf1* pLPF, ma_int16* pY, const ma_int16* pX)
{
ma_uint32 c;
const ma_int32 a = pLPF->a.s32;
const ma_int32 b = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - a);
for (c = 0; c < pLPF->channels; c += 1) {
ma_int32 r1 = pLPF->r1[c].s32;
ma_int32 x = pX[c];
ma_int32 y;
y = (b*x + a*r1) >> MA_BIQUAD_FIXED_POINT_SHIFT;
pY[c] = (ma_int16)y;
pLPF->r1[c].s32 = (ma_int32)y;
}
}
MA_API ma_result ma_lpf1_process_pcm_frames(ma_lpf1* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
ma_uint32 n;
if (pLPF == NULL || pFramesOut == NULL || pFramesIn == NULL) {
return MA_INVALID_ARGS;
}
/* Note that the logic below needs to support in-place filtering. That is, it must support the case where pFramesOut and pFramesIn are the same. */
if (pLPF->format == ma_format_f32) {
/* */ float* pY = ( float*)pFramesOut;
const float* pX = (const float*)pFramesIn;
for (n = 0; n < frameCount; n += 1) {
ma_lpf1_process_pcm_frame_f32(pLPF, pY, pX);
pY += pLPF->channels;
pX += pLPF->channels;
}
} else if (pLPF->format == ma_format_s16) {
/* */ ma_int16* pY = ( ma_int16*)pFramesOut;
const ma_int16* pX = (const ma_int16*)pFramesIn;
for (n = 0; n < frameCount; n += 1) {
ma_lpf1_process_pcm_frame_s16(pLPF, pY, pX);
pY += pLPF->channels;
pX += pLPF->channels;
}
} else {
MA_ASSERT(MA_FALSE);
return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */
}
return MA_SUCCESS;
}
MA_API ma_uint32 ma_lpf1_get_latency(ma_lpf1* pLPF)
{
if (pLPF == NULL) {
return 0;
}
return 1;
}
static MA_INLINE ma_biquad_config ma_lpf2__get_biquad_config(const ma_lpf2_config* pConfig)
{
ma_biquad_config bqConfig;
double q;
double w;
double s;
double c;
double a;
MA_ASSERT(pConfig != NULL);
q = pConfig->q;
w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate;
s = ma_sin(w);
c = ma_cos(w);
a = s / (2*q);
bqConfig.b0 = (1 - c) / 2;
bqConfig.b1 = 1 - c;
bqConfig.b2 = (1 - c) / 2;
bqConfig.a0 = 1 + a;
bqConfig.a1 = -2 * c;
bqConfig.a2 = 1 - a;
bqConfig.format = pConfig->format;
bqConfig.channels = pConfig->channels;
return bqConfig;
}
MA_API ma_result ma_lpf2_init(const ma_lpf2_config* pConfig, ma_lpf2* pLPF)
{
ma_result result;
ma_biquad_config bqConfig;
if (pLPF == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pLPF);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_lpf2__get_biquad_config(pConfig);
result = ma_biquad_init(&bqConfig, &pLPF->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
MA_API ma_result ma_lpf2_reinit(const ma_lpf2_config* pConfig, ma_lpf2* pLPF)
{
ma_result result;
ma_biquad_config bqConfig;
if (pLPF == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_lpf2__get_biquad_config(pConfig);
result = ma_biquad_reinit(&bqConfig, &pLPF->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
static MA_INLINE void ma_lpf2_process_pcm_frame_s16(ma_lpf2* pLPF, ma_int16* pFrameOut, const ma_int16* pFrameIn)
{
ma_biquad_process_pcm_frame_s16(&pLPF->bq, pFrameOut, pFrameIn);
}
static MA_INLINE void ma_lpf2_process_pcm_frame_f32(ma_lpf2* pLPF, float* pFrameOut, const float* pFrameIn)
{
ma_biquad_process_pcm_frame_f32(&pLPF->bq, pFrameOut, pFrameIn);
}
MA_API ma_result ma_lpf2_process_pcm_frames(ma_lpf2* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
if (pLPF == NULL) {
return MA_INVALID_ARGS;
}
return ma_biquad_process_pcm_frames(&pLPF->bq, pFramesOut, pFramesIn, frameCount);
}
MA_API ma_uint32 ma_lpf2_get_latency(ma_lpf2* pLPF)
{
if (pLPF == NULL) {
return 0;
}
return ma_biquad_get_latency(&pLPF->bq);
}
MA_API ma_lpf_config ma_lpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
{
ma_lpf_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.cutoffFrequency = cutoffFrequency;
config.order = ma_min(order, MA_MAX_FILTER_ORDER);
return config;
}
static ma_result ma_lpf_reinit__internal(const ma_lpf_config* pConfig, ma_lpf* pLPF, ma_bool32 isNew)
{
ma_result result;
ma_uint32 lpf1Count;
ma_uint32 lpf2Count;
ma_uint32 ilpf1;
ma_uint32 ilpf2;
if (pLPF == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
/* Only supporting f32 and s16. */
if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
return MA_INVALID_ARGS;
}
/* The format cannot be changed after initialization. */
if (pLPF->format != ma_format_unknown && pLPF->format != pConfig->format) {
return MA_INVALID_OPERATION;
}
/* The channel count cannot be changed after initialization. */
if (pLPF->channels != 0 && pLPF->channels != pConfig->channels) {
return MA_INVALID_OPERATION;
}
if (pConfig->order > MA_MAX_FILTER_ORDER) {
return MA_INVALID_ARGS;
}
lpf1Count = pConfig->order % 2;
lpf2Count = pConfig->order / 2;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
if (result != MA_SUCCESS) {
return result;
}
}
for (ilpf2 = 0; ilpf2 < lpf2Count; ilpf2 += 1) {
ma_lpf2_config lpf2Config;
double q;
double a;
/* Tempting to use 0.707107, but won't result in a Butterworth filter if the order is > 2. */
if (lpf1Count == 1) {
a = (1 + ilpf2*1) * (MA_PI_D/(pConfig->order*1)); /* Odd order. */
} else {
a = (1 + ilpf2*2) * (MA_PI_D/(pConfig->order*2)); /* Even order. */
}
q = 1 / (2*ma_cos(a));
lpf2Config = ma_lpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q);
if (isNew) {
result = ma_lpf2_init(&lpf2Config, &pLPF->lpf2[ilpf2]);
} else {
result = ma_lpf2_reinit(&lpf2Config, &pLPF->lpf2[ilpf2]);
}
if (result != MA_SUCCESS) {
return result;
}
}
pLPF->lpf1Count = lpf1Count;
pLPF->lpf2Count = lpf2Count;
pLPF->format = pConfig->format;
pLPF->channels = pConfig->channels;
pLPF->sampleRate = pConfig->sampleRate;
return MA_SUCCESS;
}
MA_API ma_result ma_lpf_init(const ma_lpf_config* pConfig, ma_lpf* pLPF)
{
if (pLPF == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pLPF);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
return ma_lpf_reinit__internal(pConfig, pLPF, /*isNew*/MA_TRUE);
}
MA_API ma_result ma_lpf_reinit(const ma_lpf_config* pConfig, ma_lpf* pLPF)
{
return ma_lpf_reinit__internal(pConfig, pLPF, /*isNew*/MA_FALSE);
}
static MA_INLINE void ma_lpf_process_pcm_frame_f32(ma_lpf* pLPF, float* pY, const void* pX)
{
ma_uint32 ilpf1;
ma_uint32 ilpf2;
MA_ASSERT(pLPF->format == ma_format_f32);
MA_COPY_MEMORY(pY, pX, ma_get_bytes_per_frame(pLPF->format, pLPF->channels));
for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
ma_lpf1_process_pcm_frame_f32(&pLPF->lpf1[ilpf1], pY, pY);
}
for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
ma_lpf2_process_pcm_frame_f32(&pLPF->lpf2[ilpf2], pY, pY);
}
}
static MA_INLINE void ma_lpf_process_pcm_frame_s16(ma_lpf* pLPF, ma_int16* pY, const ma_int16* pX)
{
ma_uint32 ilpf1;
ma_uint32 ilpf2;
MA_ASSERT(pLPF->format == ma_format_s16);
MA_COPY_MEMORY(pY, pX, ma_get_bytes_per_frame(pLPF->format, pLPF->channels));
for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
ma_lpf1_process_pcm_frame_s16(&pLPF->lpf1[ilpf1], pY, pY);
}
for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
ma_lpf2_process_pcm_frame_s16(&pLPF->lpf2[ilpf2], pY, pY);
}
}
MA_API ma_result ma_lpf_process_pcm_frames(ma_lpf* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
ma_result result;
ma_uint32 ilpf1;
ma_uint32 ilpf2;
if (pLPF == NULL) {
return MA_INVALID_ARGS;
}
/* Faster path for in-place. */
if (pFramesOut == pFramesIn) {
for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
result = ma_lpf1_process_pcm_frames(&pLPF->lpf1[ilpf1], pFramesOut, pFramesOut, frameCount);
if (result != MA_SUCCESS) {
return result;
}
}
for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
result = ma_lpf2_process_pcm_frames(&pLPF->lpf2[ilpf2], pFramesOut, pFramesOut, frameCount);
if (result != MA_SUCCESS) {
return result;
}
}
}
/* Slightly slower path for copying. */
if (pFramesOut != pFramesIn) {
ma_uint32 iFrame;
/* */ if (pLPF->format == ma_format_f32) {
/* */ float* pFramesOutF32 = ( float*)pFramesOut;
const float* pFramesInF32 = (const float*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_lpf_process_pcm_frame_f32(pLPF, pFramesOutF32, pFramesInF32);
pFramesOutF32 += pLPF->channels;
pFramesInF32 += pLPF->channels;
}
} else if (pLPF->format == ma_format_s16) {
/* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_lpf_process_pcm_frame_s16(pLPF, pFramesOutS16, pFramesInS16);
pFramesOutS16 += pLPF->channels;
pFramesInS16 += pLPF->channels;
}
} else {
MA_ASSERT(MA_FALSE);
return MA_INVALID_OPERATION; /* Should never hit this. */
}
}
return MA_SUCCESS;
}
MA_API ma_uint32 ma_lpf_get_latency(ma_lpf* pLPF)
{
if (pLPF == NULL) {
return 0;
}
return pLPF->lpf2Count*2 + pLPF->lpf1Count;
}
/**************************************************************************************************************************************************************
High-Pass Filtering
**************************************************************************************************************************************************************/
MA_API ma_hpf1_config ma_hpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency)
{
ma_hpf1_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.cutoffFrequency = cutoffFrequency;
return config;
}
MA_API ma_hpf2_config ma_hpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q)
{
ma_hpf2_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.cutoffFrequency = cutoffFrequency;
config.q = q;
/* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */
if (config.q == 0) {
config.q = 0.707107;
}
return config;
}
MA_API ma_result ma_hpf1_init(const ma_hpf1_config* pConfig, ma_hpf1* pHPF)
{
if (pHPF == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pHPF);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
if (pConfig->channels < MA_MIN_CHANNELS || pConfig->channels > MA_MAX_CHANNELS) {
return MA_INVALID_ARGS;
}
return ma_hpf1_reinit(pConfig, pHPF);
}
MA_API ma_result ma_hpf1_reinit(const ma_hpf1_config* pConfig, ma_hpf1* pHPF)
{
double a;
if (pHPF == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
/* Only supporting f32 and s16. */
if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
return MA_INVALID_ARGS;
}
/* The format cannot be changed after initialization. */
if (pHPF->format != ma_format_unknown && pHPF->format != pConfig->format) {
return MA_INVALID_OPERATION;
}
/* The channel count cannot be changed after initialization. */
if (pHPF->channels != 0 && pHPF->channels != pConfig->channels) {
return MA_INVALID_OPERATION;
}
pHPF->format = pConfig->format;
pHPF->channels = pConfig->channels;
a = ma_exp(-2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate);
if (pConfig->format == ma_format_f32) {
pHPF->a.f32 = (float)a;
} else {
pHPF->a.s32 = ma_biquad_float_to_fp(a);
}
return MA_SUCCESS;
}
static MA_INLINE void ma_hpf1_process_pcm_frame_f32(ma_hpf1* pHPF, float* pY, const float* pX)
{
ma_uint32 c;
const float a = 1 - pHPF->a.f32;
const float b = 1 - a;
for (c = 0; c < pHPF->channels; c += 1) {
float r1 = pHPF->r1[c].f32;
float x = pX[c];
float y;
y = b*x - a*r1;
pY[c] = y;
pHPF->r1[c].f32 = y;
}
}
static MA_INLINE void ma_hpf1_process_pcm_frame_s16(ma_hpf1* pHPF, ma_int16* pY, const ma_int16* pX)
{
ma_uint32 c;
const ma_int32 a = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - pHPF->a.s32);
const ma_int32 b = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - a);
for (c = 0; c < pHPF->channels; c += 1) {
ma_int32 r1 = pHPF->r1[c].s32;
ma_int32 x = pX[c];
ma_int32 y;
y = (b*x - a*r1) >> MA_BIQUAD_FIXED_POINT_SHIFT;
pY[c] = (ma_int16)y;
pHPF->r1[c].s32 = (ma_int32)y;
}
}
MA_API ma_result ma_hpf1_process_pcm_frames(ma_hpf1* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
ma_uint32 n;
if (pHPF == NULL || pFramesOut == NULL || pFramesIn == NULL) {
return MA_INVALID_ARGS;
}
/* Note that the logic below needs to support in-place filtering. That is, it must support the case where pFramesOut and pFramesIn are the same. */
if (pHPF->format == ma_format_f32) {
/* */ float* pY = ( float*)pFramesOut;
const float* pX = (const float*)pFramesIn;
for (n = 0; n < frameCount; n += 1) {
ma_hpf1_process_pcm_frame_f32(pHPF, pY, pX);
pY += pHPF->channels;
pX += pHPF->channels;
}
} else if (pHPF->format == ma_format_s16) {
/* */ ma_int16* pY = ( ma_int16*)pFramesOut;
const ma_int16* pX = (const ma_int16*)pFramesIn;
for (n = 0; n < frameCount; n += 1) {
ma_hpf1_process_pcm_frame_s16(pHPF, pY, pX);
pY += pHPF->channels;
pX += pHPF->channels;
}
} else {
MA_ASSERT(MA_FALSE);
return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */
}
return MA_SUCCESS;
}
MA_API ma_uint32 ma_hpf1_get_latency(ma_hpf1* pHPF)
{
if (pHPF == NULL) {
return 0;
}
return 1;
}
static MA_INLINE ma_biquad_config ma_hpf2__get_biquad_config(const ma_hpf2_config* pConfig)
{
ma_biquad_config bqConfig;
double q;
double w;
double s;
double c;
double a;
MA_ASSERT(pConfig != NULL);
q = pConfig->q;
w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate;
s = ma_sin(w);
c = ma_cos(w);
a = s / (2*q);
bqConfig.b0 = (1 + c) / 2;
bqConfig.b1 = -(1 + c);
bqConfig.b2 = (1 + c) / 2;
bqConfig.a0 = 1 + a;
bqConfig.a1 = -2 * c;
bqConfig.a2 = 1 - a;
bqConfig.format = pConfig->format;
bqConfig.channels = pConfig->channels;
return bqConfig;
}
MA_API ma_result ma_hpf2_init(const ma_hpf2_config* pConfig, ma_hpf2* pHPF)
{
ma_result result;
ma_biquad_config bqConfig;
if (pHPF == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pHPF);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_hpf2__get_biquad_config(pConfig);
result = ma_biquad_init(&bqConfig, &pHPF->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
MA_API ma_result ma_hpf2_reinit(const ma_hpf2_config* pConfig, ma_hpf2* pHPF)
{
ma_result result;
ma_biquad_config bqConfig;
if (pHPF == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_hpf2__get_biquad_config(pConfig);
result = ma_biquad_reinit(&bqConfig, &pHPF->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
static MA_INLINE void ma_hpf2_process_pcm_frame_s16(ma_hpf2* pHPF, ma_int16* pFrameOut, const ma_int16* pFrameIn)
{
ma_biquad_process_pcm_frame_s16(&pHPF->bq, pFrameOut, pFrameIn);
}
static MA_INLINE void ma_hpf2_process_pcm_frame_f32(ma_hpf2* pHPF, float* pFrameOut, const float* pFrameIn)
{
ma_biquad_process_pcm_frame_f32(&pHPF->bq, pFrameOut, pFrameIn);
}
MA_API ma_result ma_hpf2_process_pcm_frames(ma_hpf2* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
if (pHPF == NULL) {
return MA_INVALID_ARGS;
}
return ma_biquad_process_pcm_frames(&pHPF->bq, pFramesOut, pFramesIn, frameCount);
}
MA_API ma_uint32 ma_hpf2_get_latency(ma_hpf2* pHPF)
{
if (pHPF == NULL) {
return 0;
}
return ma_biquad_get_latency(&pHPF->bq);
}
MA_API ma_hpf_config ma_hpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
{
ma_hpf_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.cutoffFrequency = cutoffFrequency;
config.order = ma_min(order, MA_MAX_FILTER_ORDER);
return config;
}
static ma_result ma_hpf_reinit__internal(const ma_hpf_config* pConfig, ma_hpf* pHPF, ma_bool32 isNew)
{
ma_result result;
ma_uint32 hpf1Count;
ma_uint32 hpf2Count;
ma_uint32 ihpf1;
ma_uint32 ihpf2;
if (pHPF == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
/* Only supporting f32 and s16. */
if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
return MA_INVALID_ARGS;
}
/* The format cannot be changed after initialization. */
if (pHPF->format != ma_format_unknown && pHPF->format != pConfig->format) {
return MA_INVALID_OPERATION;
}
/* The channel count cannot be changed after initialization. */
if (pHPF->channels != 0 && pHPF->channels != pConfig->channels) {
return MA_INVALID_OPERATION;
}
if (pConfig->order > MA_MAX_FILTER_ORDER) {
return MA_INVALID_ARGS;
}
hpf1Count = pConfig->order % 2;
hpf2Count = pConfig->order / 2;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
if (result != MA_SUCCESS) {
return result;
}
}
for (ihpf2 = 0; ihpf2 < hpf2Count; ihpf2 += 1) {
ma_hpf2_config hpf2Config;
double q;
double a;
/* Tempting to use 0.707107, but won't result in a Butterworth filter if the order is > 2. */
if (hpf1Count == 1) {
a = (1 + ihpf2*1) * (MA_PI_D/(pConfig->order*1)); /* Odd order. */
} else {
a = (1 + ihpf2*2) * (MA_PI_D/(pConfig->order*2)); /* Even order. */
}
q = 1 / (2*ma_cos(a));
hpf2Config = ma_hpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q);
if (isNew) {
result = ma_hpf2_init(&hpf2Config, &pHPF->hpf2[ihpf2]);
} else {
result = ma_hpf2_reinit(&hpf2Config, &pHPF->hpf2[ihpf2]);
}
if (result != MA_SUCCESS) {
return result;
}
}
pHPF->hpf1Count = hpf1Count;
pHPF->hpf2Count = hpf2Count;
pHPF->format = pConfig->format;
pHPF->channels = pConfig->channels;
pHPF->sampleRate = pConfig->sampleRate;
return MA_SUCCESS;
}
MA_API ma_result ma_hpf_init(const ma_hpf_config* pConfig, ma_hpf* pHPF)
{
if (pHPF == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pHPF);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
return ma_hpf_reinit__internal(pConfig, pHPF, /*isNew*/MA_TRUE);
}
MA_API ma_result ma_hpf_reinit(const ma_hpf_config* pConfig, ma_hpf* pHPF)
{
return ma_hpf_reinit__internal(pConfig, pHPF, /*isNew*/MA_FALSE);
}
MA_API ma_result ma_hpf_process_pcm_frames(ma_hpf* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
ma_result result;
ma_uint32 ihpf1;
ma_uint32 ihpf2;
if (pHPF == NULL) {
return MA_INVALID_ARGS;
}
/* Faster path for in-place. */
if (pFramesOut == pFramesIn) {
for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
result = ma_hpf1_process_pcm_frames(&pHPF->hpf1[ihpf1], pFramesOut, pFramesOut, frameCount);
if (result != MA_SUCCESS) {
return result;
}
}
for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
result = ma_hpf2_process_pcm_frames(&pHPF->hpf2[ihpf2], pFramesOut, pFramesOut, frameCount);
if (result != MA_SUCCESS) {
return result;
}
}
}
/* Slightly slower path for copying. */
if (pFramesOut != pFramesIn) {
ma_uint32 iFrame;
/* */ if (pHPF->format == ma_format_f32) {
/* */ float* pFramesOutF32 = ( float*)pFramesOut;
const float* pFramesInF32 = (const float*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
MA_COPY_MEMORY(pFramesOutF32, pFramesInF32, ma_get_bytes_per_frame(pHPF->format, pHPF->channels));
for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
ma_hpf1_process_pcm_frame_f32(&pHPF->hpf1[ihpf1], pFramesOutF32, pFramesOutF32);
}
for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
ma_hpf2_process_pcm_frame_f32(&pHPF->hpf2[ihpf2], pFramesOutF32, pFramesOutF32);
}
pFramesOutF32 += pHPF->channels;
pFramesInF32 += pHPF->channels;
}
} else if (pHPF->format == ma_format_s16) {
/* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
MA_COPY_MEMORY(pFramesOutS16, pFramesInS16, ma_get_bytes_per_frame(pHPF->format, pHPF->channels));
for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
ma_hpf1_process_pcm_frame_s16(&pHPF->hpf1[ihpf1], pFramesOutS16, pFramesOutS16);
}
for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
ma_hpf2_process_pcm_frame_s16(&pHPF->hpf2[ihpf2], pFramesOutS16, pFramesOutS16);
}
pFramesOutS16 += pHPF->channels;
pFramesInS16 += pHPF->channels;
}
} else {
MA_ASSERT(MA_FALSE);
return MA_INVALID_OPERATION; /* Should never hit this. */
}
}
return MA_SUCCESS;
}
MA_API ma_uint32 ma_hpf_get_latency(ma_hpf* pHPF)
{
if (pHPF == NULL) {
return 0;
}
return pHPF->hpf2Count*2 + pHPF->hpf1Count;
}
/**************************************************************************************************************************************************************
Band-Pass Filtering
**************************************************************************************************************************************************************/
MA_API ma_bpf2_config ma_bpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q)
{
ma_bpf2_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.cutoffFrequency = cutoffFrequency;
config.q = q;
/* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */
if (config.q == 0) {
config.q = 0.707107;
}
return config;
}
static MA_INLINE ma_biquad_config ma_bpf2__get_biquad_config(const ma_bpf2_config* pConfig)
{
ma_biquad_config bqConfig;
double q;
double w;
double s;
double c;
double a;
MA_ASSERT(pConfig != NULL);
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate;
s = ma_sin(w);
c = ma_cos(w);
a = s / (2*q);
bqConfig.b0 = q * a;
bqConfig.b1 = 0;
bqConfig.b2 = -q * a;
bqConfig.a0 = 1 + a;
bqConfig.a1 = -2 * c;
bqConfig.a2 = 1 - a;
bqConfig.format = pConfig->format;
bqConfig.channels = pConfig->channels;
return bqConfig;
}
MA_API ma_result ma_bpf2_init(const ma_bpf2_config* pConfig, ma_bpf2* pBPF)
{
ma_result result;
ma_biquad_config bqConfig;
if (pBPF == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pBPF);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_bpf2__get_biquad_config(pConfig);
result = ma_biquad_init(&bqConfig, &pBPF->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
MA_API ma_result ma_bpf2_reinit(const ma_bpf2_config* pConfig, ma_bpf2* pBPF)
{
ma_result result;
ma_biquad_config bqConfig;
if (pBPF == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_bpf2__get_biquad_config(pConfig);
result = ma_biquad_reinit(&bqConfig, &pBPF->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
static MA_INLINE void ma_bpf2_process_pcm_frame_s16(ma_bpf2* pBPF, ma_int16* pFrameOut, const ma_int16* pFrameIn)
{
ma_biquad_process_pcm_frame_s16(&pBPF->bq, pFrameOut, pFrameIn);
}
static MA_INLINE void ma_bpf2_process_pcm_frame_f32(ma_bpf2* pBPF, float* pFrameOut, const float* pFrameIn)
{
ma_biquad_process_pcm_frame_f32(&pBPF->bq, pFrameOut, pFrameIn);
}
MA_API ma_result ma_bpf2_process_pcm_frames(ma_bpf2* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
if (pBPF == NULL) {
return MA_INVALID_ARGS;
}
return ma_biquad_process_pcm_frames(&pBPF->bq, pFramesOut, pFramesIn, frameCount);
}
MA_API ma_uint32 ma_bpf2_get_latency(ma_bpf2* pBPF)
{
if (pBPF == NULL) {
return 0;
}
return ma_biquad_get_latency(&pBPF->bq);
}
MA_API ma_bpf_config ma_bpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
{
ma_bpf_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.cutoffFrequency = cutoffFrequency;
config.order = ma_min(order, MA_MAX_FILTER_ORDER);
return config;
}
static ma_result ma_bpf_reinit__internal(const ma_bpf_config* pConfig, ma_bpf* pBPF, ma_bool32 isNew)
{
ma_result result;
ma_uint32 bpf2Count;
ma_uint32 ibpf2;
if (pBPF == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
/* Only supporting f32 and s16. */
if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
return MA_INVALID_ARGS;
}
/* The format cannot be changed after initialization. */
if (pBPF->format != ma_format_unknown && pBPF->format != pConfig->format) {
return MA_INVALID_OPERATION;
}
/* The channel count cannot be changed after initialization. */
if (pBPF->channels != 0 && pBPF->channels != pConfig->channels) {
return MA_INVALID_OPERATION;
}
if (pConfig->order > MA_MAX_FILTER_ORDER) {
return MA_INVALID_ARGS;
}
/* We must have an even number of order. */
if ((pConfig->order & 0x1) != 0) {
return MA_INVALID_ARGS;
}
bpf2Count = pConfig->order / 2;
MA_ASSERT(bpf2Count <= ma_countof(pBPF->bpf2));
/* The filter order can't change between reinits. */
if (!isNew) {
if (pBPF->bpf2Count != bpf2Count) {
return MA_INVALID_OPERATION;
}
}
for (ibpf2 = 0; ibpf2 < bpf2Count; ibpf2 += 1) {
ma_bpf2_config bpf2Config;
double q;
/* TODO: Calculate Q to make this a proper Butterworth filter. */
q = 0.707107;
bpf2Config = ma_bpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q);
if (isNew) {
result = ma_bpf2_init(&bpf2Config, &pBPF->bpf2[ibpf2]);
} else {
result = ma_bpf2_reinit(&bpf2Config, &pBPF->bpf2[ibpf2]);
}
if (result != MA_SUCCESS) {
return result;
}
}
pBPF->bpf2Count = bpf2Count;
pBPF->format = pConfig->format;
pBPF->channels = pConfig->channels;
return MA_SUCCESS;
}
MA_API ma_result ma_bpf_init(const ma_bpf_config* pConfig, ma_bpf* pBPF)
{
if (pBPF == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pBPF);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
return ma_bpf_reinit__internal(pConfig, pBPF, /*isNew*/MA_TRUE);
}
MA_API ma_result ma_bpf_reinit(const ma_bpf_config* pConfig, ma_bpf* pBPF)
{
return ma_bpf_reinit__internal(pConfig, pBPF, /*isNew*/MA_FALSE);
}
MA_API ma_result ma_bpf_process_pcm_frames(ma_bpf* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
ma_result result;
ma_uint32 ibpf2;
if (pBPF == NULL) {
return MA_INVALID_ARGS;
}
/* Faster path for in-place. */
if (pFramesOut == pFramesIn) {
for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
result = ma_bpf2_process_pcm_frames(&pBPF->bpf2[ibpf2], pFramesOut, pFramesOut, frameCount);
if (result != MA_SUCCESS) {
return result;
}
}
}
/* Slightly slower path for copying. */
if (pFramesOut != pFramesIn) {
ma_uint32 iFrame;
/* */ if (pBPF->format == ma_format_f32) {
/* */ float* pFramesOutF32 = ( float*)pFramesOut;
const float* pFramesInF32 = (const float*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
MA_COPY_MEMORY(pFramesOutF32, pFramesInF32, ma_get_bytes_per_frame(pBPF->format, pBPF->channels));
for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
ma_bpf2_process_pcm_frame_f32(&pBPF->bpf2[ibpf2], pFramesOutF32, pFramesOutF32);
}
pFramesOutF32 += pBPF->channels;
pFramesInF32 += pBPF->channels;
}
} else if (pBPF->format == ma_format_s16) {
/* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
MA_COPY_MEMORY(pFramesOutS16, pFramesInS16, ma_get_bytes_per_frame(pBPF->format, pBPF->channels));
for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
ma_bpf2_process_pcm_frame_s16(&pBPF->bpf2[ibpf2], pFramesOutS16, pFramesOutS16);
}
pFramesOutS16 += pBPF->channels;
pFramesInS16 += pBPF->channels;
}
} else {
MA_ASSERT(MA_FALSE);
return MA_INVALID_OPERATION; /* Should never hit this. */
}
}
return MA_SUCCESS;
}
MA_API ma_uint32 ma_bpf_get_latency(ma_bpf* pBPF)
{
if (pBPF == NULL) {
return 0;
}
return pBPF->bpf2Count*2;
}
/**************************************************************************************************************************************************************
Notching Filter
**************************************************************************************************************************************************************/
MA_API ma_notch2_config ma_notch2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency)
{
ma_notch2_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.q = q;
config.frequency = frequency;
if (config.q == 0) {
config.q = 0.707107;
}
return config;
}
static MA_INLINE ma_biquad_config ma_notch2__get_biquad_config(const ma_notch2_config* pConfig)
{
ma_biquad_config bqConfig;
double q;
double w;
double s;
double c;
double a;
MA_ASSERT(pConfig != NULL);
q = pConfig->q;
w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
s = ma_sin(w);
c = ma_cos(w);
a = s / (2*q);
bqConfig.b0 = 1;
bqConfig.b1 = -2 * c;
bqConfig.b2 = 1;
bqConfig.a0 = 1 + a;
bqConfig.a1 = -2 * c;
bqConfig.a2 = 1 - a;
bqConfig.format = pConfig->format;
bqConfig.channels = pConfig->channels;
return bqConfig;
}
MA_API ma_result ma_notch2_init(const ma_notch2_config* pConfig, ma_notch2* pFilter)
{
ma_result result;
ma_biquad_config bqConfig;
if (pFilter == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pFilter);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_notch2__get_biquad_config(pConfig);
result = ma_biquad_init(&bqConfig, &pFilter->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
MA_API ma_result ma_notch2_reinit(const ma_notch2_config* pConfig, ma_notch2* pFilter)
{
ma_result result;
ma_biquad_config bqConfig;
if (pFilter == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_notch2__get_biquad_config(pConfig);
result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
static MA_INLINE void ma_notch2_process_pcm_frame_s16(ma_notch2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
{
ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
}
static MA_INLINE void ma_notch2_process_pcm_frame_f32(ma_notch2* pFilter, float* pFrameOut, const float* pFrameIn)
{
ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
}
MA_API ma_result ma_notch2_process_pcm_frames(ma_notch2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
if (pFilter == NULL) {
return MA_INVALID_ARGS;
}
return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
}
MA_API ma_uint32 ma_notch2_get_latency(ma_notch2* pFilter)
{
if (pFilter == NULL) {
return 0;
}
return ma_biquad_get_latency(&pFilter->bq);
}
/**************************************************************************************************************************************************************
Peaking EQ Filter
**************************************************************************************************************************************************************/
MA_API ma_peak2_config ma_peak2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
{
ma_peak2_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.gainDB = gainDB;
config.q = q;
config.frequency = frequency;
if (config.q == 0) {
config.q = 0.707107;
}
return config;
}
static MA_INLINE ma_biquad_config ma_peak2__get_biquad_config(const ma_peak2_config* pConfig)
{
ma_biquad_config bqConfig;
double q;
double w;
double s;
double c;
double a;
double A;
MA_ASSERT(pConfig != NULL);
q = pConfig->q;
w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
s = ma_sin(w);
c = ma_cos(w);
a = s / (2*q);
A = ma_pow(10, (pConfig->gainDB / 40));
bqConfig.b0 = 1 + (a * A);
bqConfig.b1 = -2 * c;
bqConfig.b2 = 1 - (a * A);
bqConfig.a0 = 1 + (a / A);
bqConfig.a1 = -2 * c;
bqConfig.a2 = 1 - (a / A);
bqConfig.format = pConfig->format;
bqConfig.channels = pConfig->channels;
return bqConfig;
}
MA_API ma_result ma_peak2_init(const ma_peak2_config* pConfig, ma_peak2* pFilter)
{
ma_result result;
ma_biquad_config bqConfig;
if (pFilter == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pFilter);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_peak2__get_biquad_config(pConfig);
result = ma_biquad_init(&bqConfig, &pFilter->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
MA_API ma_result ma_peak2_reinit(const ma_peak2_config* pConfig, ma_peak2* pFilter)
{
ma_result result;
ma_biquad_config bqConfig;
if (pFilter == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_peak2__get_biquad_config(pConfig);
result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
static MA_INLINE void ma_peak2_process_pcm_frame_s16(ma_peak2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
{
ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
}
static MA_INLINE void ma_peak2_process_pcm_frame_f32(ma_peak2* pFilter, float* pFrameOut, const float* pFrameIn)
{
ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
}
MA_API ma_result ma_peak2_process_pcm_frames(ma_peak2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
if (pFilter == NULL) {
return MA_INVALID_ARGS;
}
return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
}
MA_API ma_uint32 ma_peak2_get_latency(ma_peak2* pFilter)
{
if (pFilter == NULL) {
return 0;
}
return ma_biquad_get_latency(&pFilter->bq);
}
/**************************************************************************************************************************************************************
Low Shelf Filter
**************************************************************************************************************************************************************/
MA_API ma_loshelf2_config ma_loshelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency)
{
ma_loshelf2_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.gainDB = gainDB;
config.shelfSlope = shelfSlope;
config.frequency = frequency;
return config;
}
static MA_INLINE ma_biquad_config ma_loshelf2__get_biquad_config(const ma_loshelf2_config* pConfig)
{
ma_biquad_config bqConfig;
double w;
double s;
double c;
double A;
double S;
double a;
double sqrtA;
MA_ASSERT(pConfig != NULL);
w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
s = ma_sin(w);
c = ma_cos(w);
A = ma_pow(10, (pConfig->gainDB / 40));
S = pConfig->shelfSlope;
a = s/2 * ma_sqrt((A + 1/A) * (1/S - 1) + 2);
sqrtA = 2*ma_sqrt(A)*a;
bqConfig.b0 = A * ((A + 1) - (A - 1)*c + sqrtA);
bqConfig.b1 = 2 * A * ((A - 1) - (A + 1)*c);
bqConfig.b2 = A * ((A + 1) - (A - 1)*c - sqrtA);
bqConfig.a0 = (A + 1) + (A - 1)*c + sqrtA;
bqConfig.a1 = -2 * ((A - 1) + (A + 1)*c);
bqConfig.a2 = (A + 1) + (A - 1)*c - sqrtA;
bqConfig.format = pConfig->format;
bqConfig.channels = pConfig->channels;
return bqConfig;
}
MA_API ma_result ma_loshelf2_init(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter)
{
ma_result result;
ma_biquad_config bqConfig;
if (pFilter == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pFilter);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_loshelf2__get_biquad_config(pConfig);
result = ma_biquad_init(&bqConfig, &pFilter->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
MA_API ma_result ma_loshelf2_reinit(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter)
{
ma_result result;
ma_biquad_config bqConfig;
if (pFilter == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_loshelf2__get_biquad_config(pConfig);
result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
static MA_INLINE void ma_loshelf2_process_pcm_frame_s16(ma_loshelf2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
{
ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
}
static MA_INLINE void ma_loshelf2_process_pcm_frame_f32(ma_loshelf2* pFilter, float* pFrameOut, const float* pFrameIn)
{
ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
}
MA_API ma_result ma_loshelf2_process_pcm_frames(ma_loshelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
if (pFilter == NULL) {
return MA_INVALID_ARGS;
}
return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
}
MA_API ma_uint32 ma_loshelf2_get_latency(ma_loshelf2* pFilter)
{
if (pFilter == NULL) {
return 0;
}
return ma_biquad_get_latency(&pFilter->bq);
}
/**************************************************************************************************************************************************************
High Shelf Filter
**************************************************************************************************************************************************************/
MA_API ma_hishelf2_config ma_hishelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency)
{
ma_hishelf2_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.gainDB = gainDB;
config.shelfSlope = shelfSlope;
config.frequency = frequency;
return config;
}
static MA_INLINE ma_biquad_config ma_hishelf2__get_biquad_config(const ma_hishelf2_config* pConfig)
{
ma_biquad_config bqConfig;
double w;
double s;
double c;
double A;
double S;
double a;
double sqrtA;
MA_ASSERT(pConfig != NULL);
w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
s = ma_sin(w);
c = ma_cos(w);
A = ma_pow(10, (pConfig->gainDB / 40));
S = pConfig->shelfSlope;
a = s/2 * ma_sqrt((A + 1/A) * (1/S - 1) + 2);
sqrtA = 2*ma_sqrt(A)*a;
bqConfig.b0 = A * ((A + 1) + (A - 1)*c + sqrtA);
bqConfig.b1 = -2 * A * ((A - 1) + (A + 1)*c);
bqConfig.b2 = A * ((A + 1) + (A - 1)*c - sqrtA);
bqConfig.a0 = (A + 1) - (A - 1)*c + sqrtA;
bqConfig.a1 = 2 * ((A - 1) - (A + 1)*c);
bqConfig.a2 = (A + 1) - (A - 1)*c - sqrtA;
bqConfig.format = pConfig->format;
bqConfig.channels = pConfig->channels;
return bqConfig;
}
MA_API ma_result ma_hishelf2_init(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter)
{
ma_result result;
ma_biquad_config bqConfig;
if (pFilter == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pFilter);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_hishelf2__get_biquad_config(pConfig);
result = ma_biquad_init(&bqConfig, &pFilter->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
MA_API ma_result ma_hishelf2_reinit(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter)
{
ma_result result;
ma_biquad_config bqConfig;
if (pFilter == NULL || pConfig == NULL) {
return MA_INVALID_ARGS;
}
bqConfig = ma_hishelf2__get_biquad_config(pConfig);
result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
static MA_INLINE void ma_hishelf2_process_pcm_frame_s16(ma_hishelf2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
{
ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
}
static MA_INLINE void ma_hishelf2_process_pcm_frame_f32(ma_hishelf2* pFilter, float* pFrameOut, const float* pFrameIn)
{
ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
}
MA_API ma_result ma_hishelf2_process_pcm_frames(ma_hishelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
if (pFilter == NULL) {
return MA_INVALID_ARGS;
}
return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
}
MA_API ma_uint32 ma_hishelf2_get_latency(ma_hishelf2* pFilter)
{
if (pFilter == NULL) {
return 0;
}
return ma_biquad_get_latency(&pFilter->bq);
}
/**************************************************************************************************************************************************************
Resampling
**************************************************************************************************************************************************************/
MA_API ma_linear_resampler_config ma_linear_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
{
ma_linear_resampler_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRateIn = sampleRateIn;
config.sampleRateOut = sampleRateOut;
config.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
config.lpfNyquistFactor = 1;
return config;
}
static void ma_linear_resampler_adjust_timer_for_new_rate(ma_linear_resampler* pResampler, ma_uint32 oldSampleRateOut, ma_uint32 newSampleRateOut)
{
/*
So what's happening here? Basically we need to adjust the fractional component of the time advance based on the new rate. The old time advance will
be based on the old sample rate, but we are needing to adjust it to that it's based on the new sample rate.
*/
ma_uint32 oldRateTimeWhole = pResampler->inTimeFrac / oldSampleRateOut; /* <-- This should almost never be anything other than 0, but leaving it here to make this more general and robust just in case. */
ma_uint32 oldRateTimeFract = pResampler->inTimeFrac % oldSampleRateOut;
pResampler->inTimeFrac =
(oldRateTimeWhole * newSampleRateOut) +
((oldRateTimeFract * newSampleRateOut) / oldSampleRateOut);
/* Make sure the fractional part is less than the output sample rate. */
pResampler->inTimeInt += pResampler->inTimeFrac / pResampler->config.sampleRateOut;
pResampler->inTimeFrac = pResampler->inTimeFrac % pResampler->config.sampleRateOut;
}
static ma_result ma_linear_resampler_set_rate_internal(ma_linear_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut, ma_bool32 isResamplerAlreadyInitialized)
{
ma_result result;
ma_uint32 gcf;
ma_uint32 lpfSampleRate;
double lpfCutoffFrequency;
ma_lpf_config lpfConfig;
ma_uint32 oldSampleRateOut; /* Required for adjusting time advance down the bottom. */
if (pResampler == NULL) {
return MA_INVALID_ARGS;
}
if (sampleRateIn == 0 || sampleRateOut == 0) {
return MA_INVALID_ARGS;
}
oldSampleRateOut = pResampler->config.sampleRateOut;
pResampler->config.sampleRateIn = sampleRateIn;
pResampler->config.sampleRateOut = sampleRateOut;
/* Simplify the sample rate. */
gcf = ma_gcf_u32(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut);
pResampler->config.sampleRateIn /= gcf;
pResampler->config.sampleRateOut /= gcf;
/* Always initialize the low-pass filter, even when the order is 0. */
if (pResampler->config.lpfOrder > MA_MAX_FILTER_ORDER) {
return MA_INVALID_ARGS;
}
lpfSampleRate = (ma_uint32)(ma_max(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut));
lpfCutoffFrequency = ( double)(ma_min(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut) * 0.5 * pResampler->config.lpfNyquistFactor);
lpfConfig = ma_lpf_config_init(pResampler->config.format, pResampler->config.channels, lpfSampleRate, lpfCutoffFrequency, pResampler->config.lpfOrder);
/*
If the resampler is alreay initialized we don't want to do a fresh initialization of the low-pass filter because it will result in the cached frames
getting cleared. Instead we re-initialize the filter which will maintain any cached frames.
*/
if (isResamplerAlreadyInitialized) {
result = ma_lpf_reinit(&lpfConfig, &pResampler->lpf);
} else {
result = ma_lpf_init(&lpfConfig, &pResampler->lpf);
}
if (result != MA_SUCCESS) {
return result;
}
pResampler->inAdvanceInt = pResampler->config.sampleRateIn / pResampler->config.sampleRateOut;
pResampler->inAdvanceFrac = pResampler->config.sampleRateIn % pResampler->config.sampleRateOut;
/* Our timer was based on the old rate. We need to adjust it so that it's based on the new rate. */
ma_linear_resampler_adjust_timer_for_new_rate(pResampler, oldSampleRateOut, pResampler->config.sampleRateOut);
return MA_SUCCESS;
}
MA_API ma_result ma_linear_resampler_init(const ma_linear_resampler_config* pConfig, ma_linear_resampler* pResampler)
{
ma_result result;
if (pResampler == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pResampler);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
if (pConfig->channels < MA_MIN_CHANNELS || pConfig->channels > MA_MAX_CHANNELS) {
return MA_INVALID_ARGS;
}
pResampler->config = *pConfig;
/* Setting the rate will set up the filter and time advances for us. */
result = ma_linear_resampler_set_rate_internal(pResampler, pConfig->sampleRateIn, pConfig->sampleRateOut, /* isResamplerAlreadyInitialized = */ MA_FALSE);
if (result != MA_SUCCESS) {
return result;
}
pResampler->inTimeInt = 1; /* Set this to one to force an input sample to always be loaded for the first output frame. */
pResampler->inTimeFrac = 0;
return MA_SUCCESS;
}
MA_API void ma_linear_resampler_uninit(ma_linear_resampler* pResampler)
{
if (pResampler == NULL) {
return;
}
}
static MA_INLINE ma_int16 ma_linear_resampler_mix_s16(ma_int16 x, ma_int16 y, ma_int32 a, const ma_int32 shift)
{
ma_int32 b;
ma_int32 c;
ma_int32 r;
MA_ASSERT(a <= (1<<shift));
b = x * ((1<<shift) - a);
c = y * a;
r = b + c;
return (ma_int16)(r >> shift);
}
static void ma_linear_resampler_interpolate_frame_s16(ma_linear_resampler* pResampler, ma_int16* pFrameOut)
{
ma_uint32 c;
ma_uint32 a;
const ma_uint32 shift = 12;
MA_ASSERT(pResampler != NULL);
MA_ASSERT(pFrameOut != NULL);
a = (pResampler->inTimeFrac << shift) / pResampler->config.sampleRateOut;
for (c = 0; c < pResampler->config.channels; c += 1) {
ma_int16 s = ma_linear_resampler_mix_s16(pResampler->x0.s16[c], pResampler->x1.s16[c], a, shift);
pFrameOut[c] = s;
}
}
static void ma_linear_resampler_interpolate_frame_f32(ma_linear_resampler* pResampler, float* pFrameOut)
{
ma_uint32 c;
float a;
MA_ASSERT(pResampler != NULL);
MA_ASSERT(pFrameOut != NULL);
a = (float)pResampler->inTimeFrac / pResampler->config.sampleRateOut;
for (c = 0; c < pResampler->config.channels; c += 1) {
float s = ma_mix_f32_fast(pResampler->x0.f32[c], pResampler->x1.f32[c], a);
pFrameOut[c] = s;
}
}
static ma_result ma_linear_resampler_process_pcm_frames_s16_downsample(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
const ma_int16* pFramesInS16;
/* */ ma_int16* pFramesOutS16;
ma_uint64 frameCountIn;
ma_uint64 frameCountOut;
ma_uint64 framesProcessedIn;
ma_uint64 framesProcessedOut;
MA_ASSERT(pResampler != NULL);
MA_ASSERT(pFrameCountIn != NULL);
MA_ASSERT(pFrameCountOut != NULL);
pFramesInS16 = (const ma_int16*)pFramesIn;
pFramesOutS16 = ( ma_int16*)pFramesOut;
frameCountIn = *pFrameCountIn;
frameCountOut = *pFrameCountOut;
framesProcessedIn = 0;
framesProcessedOut = 0;
while (framesProcessedOut < frameCountOut) {
/* Before interpolating we need to load the buffers. When doing this we need to ensure we run every input sample through the filter. */
while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
ma_uint32 iChannel;
if (pFramesInS16 != NULL) {
for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
pResampler->x1.s16[iChannel] = pFramesInS16[iChannel];
}
pFramesInS16 += pResampler->config.channels;
} else {
for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
pResampler->x1.s16[iChannel] = 0;
}
}
/* Filter. */
ma_lpf_process_pcm_frame_s16(&pResampler->lpf, pResampler->x1.s16, pResampler->x1.s16);
framesProcessedIn += 1;
pResampler->inTimeInt -= 1;
}
if (pResampler->inTimeInt > 0) {
break; /* Ran out of input data. */
}
/* Getting here means the frames have been loaded and filtered and we can generate the next output frame. */
if (pFramesOutS16 != NULL) {
MA_ASSERT(pResampler->inTimeInt == 0);
ma_linear_resampler_interpolate_frame_s16(pResampler, pFramesOutS16);
pFramesOutS16 += pResampler->config.channels;
}
framesProcessedOut += 1;
/* Advance time forward. */
pResampler->inTimeInt += pResampler->inAdvanceInt;
pResampler->inTimeFrac += pResampler->inAdvanceFrac;
if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
pResampler->inTimeInt += 1;
}
}
*pFrameCountIn = framesProcessedIn;
*pFrameCountOut = framesProcessedOut;
return MA_SUCCESS;
}
static ma_result ma_linear_resampler_process_pcm_frames_s16_upsample(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
const ma_int16* pFramesInS16;
/* */ ma_int16* pFramesOutS16;
ma_uint64 frameCountIn;
ma_uint64 frameCountOut;
ma_uint64 framesProcessedIn;
ma_uint64 framesProcessedOut;
MA_ASSERT(pResampler != NULL);
MA_ASSERT(pFrameCountIn != NULL);
MA_ASSERT(pFrameCountOut != NULL);
pFramesInS16 = (const ma_int16*)pFramesIn;
pFramesOutS16 = ( ma_int16*)pFramesOut;
frameCountIn = *pFrameCountIn;
frameCountOut = *pFrameCountOut;
framesProcessedIn = 0;
framesProcessedOut = 0;
while (framesProcessedOut < frameCountOut) {
/* Before interpolating we need to load the buffers. */
while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
ma_uint32 iChannel;
if (pFramesInS16 != NULL) {
for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
pResampler->x1.s16[iChannel] = pFramesInS16[iChannel];
}
pFramesInS16 += pResampler->config.channels;
} else {
for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
pResampler->x1.s16[iChannel] = 0;
}
}
framesProcessedIn += 1;
pResampler->inTimeInt -= 1;
}
if (pResampler->inTimeInt > 0) {
break; /* Ran out of input data. */
}
/* Getting here means the frames have been loaded and we can generate the next output frame. */
if (pFramesOutS16 != NULL) {
MA_ASSERT(pResampler->inTimeInt == 0);
ma_linear_resampler_interpolate_frame_s16(pResampler, pFramesOutS16);
/* Filter. */
ma_lpf_process_pcm_frame_s16(&pResampler->lpf, pFramesOutS16, pFramesOutS16);
pFramesOutS16 += pResampler->config.channels;
}
framesProcessedOut += 1;
/* Advance time forward. */
pResampler->inTimeInt += pResampler->inAdvanceInt;
pResampler->inTimeFrac += pResampler->inAdvanceFrac;
if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
pResampler->inTimeInt += 1;
}
}
*pFrameCountIn = framesProcessedIn;
*pFrameCountOut = framesProcessedOut;
return MA_SUCCESS;
}
static ma_result ma_linear_resampler_process_pcm_frames_s16(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
MA_ASSERT(pResampler != NULL);
if (pResampler->config.sampleRateIn > pResampler->config.sampleRateOut) {
return ma_linear_resampler_process_pcm_frames_s16_downsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
} else {
return ma_linear_resampler_process_pcm_frames_s16_upsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
}
}
static ma_result ma_linear_resampler_process_pcm_frames_f32_downsample(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
const float* pFramesInF32;
/* */ float* pFramesOutF32;
ma_uint64 frameCountIn;
ma_uint64 frameCountOut;
ma_uint64 framesProcessedIn;
ma_uint64 framesProcessedOut;
MA_ASSERT(pResampler != NULL);
MA_ASSERT(pFrameCountIn != NULL);
MA_ASSERT(pFrameCountOut != NULL);
pFramesInF32 = (const float*)pFramesIn;
pFramesOutF32 = ( float*)pFramesOut;
frameCountIn = *pFrameCountIn;
frameCountOut = *pFrameCountOut;
framesProcessedIn = 0;
framesProcessedOut = 0;
while (framesProcessedOut < frameCountOut) {
/* Before interpolating we need to load the buffers. When doing this we need to ensure we run every input sample through the filter. */
while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
ma_uint32 iChannel;
if (pFramesInF32 != NULL) {
for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
pResampler->x1.f32[iChannel] = pFramesInF32[iChannel];
}
pFramesInF32 += pResampler->config.channels;
} else {
for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
pResampler->x1.f32[iChannel] = 0;
}
}
/* Filter. */
ma_lpf_process_pcm_frame_f32(&pResampler->lpf, pResampler->x1.f32, pResampler->x1.f32);
framesProcessedIn += 1;
pResampler->inTimeInt -= 1;
}
if (pResampler->inTimeInt > 0) {
break; /* Ran out of input data. */
}
/* Getting here means the frames have been loaded and filtered and we can generate the next output frame. */
if (pFramesOutF32 != NULL) {
MA_ASSERT(pResampler->inTimeInt == 0);
ma_linear_resampler_interpolate_frame_f32(pResampler, pFramesOutF32);
pFramesOutF32 += pResampler->config.channels;
}
framesProcessedOut += 1;
/* Advance time forward. */
pResampler->inTimeInt += pResampler->inAdvanceInt;
pResampler->inTimeFrac += pResampler->inAdvanceFrac;
if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
pResampler->inTimeInt += 1;
}
}
*pFrameCountIn = framesProcessedIn;
*pFrameCountOut = framesProcessedOut;
return MA_SUCCESS;
}
static ma_result ma_linear_resampler_process_pcm_frames_f32_upsample(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
const float* pFramesInF32;
/* */ float* pFramesOutF32;
ma_uint64 frameCountIn;
ma_uint64 frameCountOut;
ma_uint64 framesProcessedIn;
ma_uint64 framesProcessedOut;
MA_ASSERT(pResampler != NULL);
MA_ASSERT(pFrameCountIn != NULL);
MA_ASSERT(pFrameCountOut != NULL);
pFramesInF32 = (const float*)pFramesIn;
pFramesOutF32 = ( float*)pFramesOut;
frameCountIn = *pFrameCountIn;
frameCountOut = *pFrameCountOut;
framesProcessedIn = 0;
framesProcessedOut = 0;
while (framesProcessedOut < frameCountOut) {
/* Before interpolating we need to load the buffers. */
while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
ma_uint32 iChannel;
if (pFramesInF32 != NULL) {
for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
pResampler->x1.f32[iChannel] = pFramesInF32[iChannel];
}
pFramesInF32 += pResampler->config.channels;
} else {
for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
pResampler->x1.f32[iChannel] = 0;
}
}
framesProcessedIn += 1;
pResampler->inTimeInt -= 1;
}
if (pResampler->inTimeInt > 0) {
break; /* Ran out of input data. */
}
/* Getting here means the frames have been loaded and we can generate the next output frame. */
if (pFramesOutF32 != NULL) {
MA_ASSERT(pResampler->inTimeInt == 0);
ma_linear_resampler_interpolate_frame_f32(pResampler, pFramesOutF32);
/* Filter. */
ma_lpf_process_pcm_frame_f32(&pResampler->lpf, pFramesOutF32, pFramesOutF32);
pFramesOutF32 += pResampler->config.channels;
}
framesProcessedOut += 1;
/* Advance time forward. */
pResampler->inTimeInt += pResampler->inAdvanceInt;
pResampler->inTimeFrac += pResampler->inAdvanceFrac;
if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
pResampler->inTimeInt += 1;
}
}
*pFrameCountIn = framesProcessedIn;
*pFrameCountOut = framesProcessedOut;
return MA_SUCCESS;
}
static ma_result ma_linear_resampler_process_pcm_frames_f32(ma_linear_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
MA_ASSERT(pResampler != NULL);
if (pResampler->config.sampleRateIn > pResampler->config.sampleRateOut) {
return ma_linear_resampler_process_pcm_frames_f32_downsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
} else {
return ma_linear_resampler_process_pcm_frames_f32_upsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
}
}
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)
{
if (pResampler == NULL) {
return MA_INVALID_ARGS;
}
/* */ if (pResampler->config.format == ma_format_s16) {
return ma_linear_resampler_process_pcm_frames_s16(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
} else if (pResampler->config.format == ma_format_f32) {
return ma_linear_resampler_process_pcm_frames_f32(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
} else {
/* Should never get here. Getting here means the format is not supported and you didn't check the return value of ma_linear_resampler_init(). */
MA_ASSERT(MA_FALSE);
return MA_INVALID_ARGS;
}
}
MA_API ma_result ma_linear_resampler_set_rate(ma_linear_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
{
return ma_linear_resampler_set_rate_internal(pResampler, sampleRateIn, sampleRateOut, /* isResamplerAlreadyInitialized = */ MA_TRUE);
}
MA_API ma_result ma_linear_resampler_set_rate_ratio(ma_linear_resampler* pResampler, float ratioInOut)
{
ma_uint32 n;
ma_uint32 d;
d = 1000;
n = (ma_uint32)(ratioInOut * d);
if (n == 0) {
return MA_INVALID_ARGS; /* Ratio too small. */
}
MA_ASSERT(n != 0);
return ma_linear_resampler_set_rate(pResampler, n, d);
}
MA_API ma_uint64 ma_linear_resampler_get_required_input_frame_count(ma_linear_resampler* pResampler, ma_uint64 outputFrameCount)
{
ma_uint64 inputFrameCount;
if (pResampler == NULL) {
return 0;
}
if (outputFrameCount == 0) {
return 0;
}
/* Any whole input frames are consumed before the first output frame is generated. */
inputFrameCount = pResampler->inTimeInt;
outputFrameCount -= 1;
/* The rest of the output frames can be calculated in constant time. */
inputFrameCount += outputFrameCount * pResampler->inAdvanceInt;
inputFrameCount += (pResampler->inTimeFrac + (outputFrameCount * pResampler->inAdvanceFrac)) / pResampler->config.sampleRateOut;
return inputFrameCount;
}
MA_API ma_uint64 ma_linear_resampler_get_expected_output_frame_count(ma_linear_resampler* pResampler, ma_uint64 inputFrameCount)
{
ma_uint64 outputFrameCount;
ma_uint64 preliminaryInputFrameCountFromFrac;
ma_uint64 preliminaryInputFrameCount;
if (pResampler == NULL) {
return 0;
}
/*
The first step is to get a preliminary output frame count. This will either be exactly equal to what we need, or less by 1. We need to
determine how many input frames will be consumed by this value. If it's greater than our original input frame count it means we won't
be able to generate an extra frame because we will have run out of input data. Otherwise we will have enough input for the generation
of an extra output frame. This add-by-one logic is necessary due to how the data loading logic works when processing frames.
*/
outputFrameCount = (inputFrameCount * pResampler->config.sampleRateOut) / pResampler->config.sampleRateIn;
/*
We need to determine how many *whole* input frames will have been processed to generate our preliminary output frame count. This is
used in the logic below to determine whether or not we need to add an extra output frame.
*/
preliminaryInputFrameCountFromFrac = (pResampler->inTimeFrac + outputFrameCount*pResampler->inAdvanceFrac) / pResampler->config.sampleRateOut;
preliminaryInputFrameCount = (pResampler->inTimeInt + outputFrameCount*pResampler->inAdvanceInt ) + preliminaryInputFrameCountFromFrac;
/*
If the total number of *whole* input frames that would be required to generate our preliminary output frame count is greather than
the amount of whole input frames we have available as input we need to *not* add an extra output frame as there won't be enough data
to actually process. Otherwise we need to add the extra output frame.
*/
if (preliminaryInputFrameCount <= inputFrameCount) {
outputFrameCount += 1;
}
return outputFrameCount;
}
MA_API ma_uint64 ma_linear_resampler_get_input_latency(ma_linear_resampler* pResampler)
{
if (pResampler == NULL) {
return 0;
}
return 1 + ma_lpf_get_latency(&pResampler->lpf);
}
MA_API ma_uint64 ma_linear_resampler_get_output_latency(ma_linear_resampler* pResampler)
{
if (pResampler == NULL) {
return 0;
}
return ma_linear_resampler_get_input_latency(pResampler) * pResampler->config.sampleRateOut / pResampler->config.sampleRateIn;
}
#if defined(ma_speex_resampler_h)
#define MA_HAS_SPEEX_RESAMPLER
static ma_result ma_result_from_speex_err(int err)
{
switch (err)
{
case RESAMPLER_ERR_SUCCESS: return MA_SUCCESS;
case RESAMPLER_ERR_ALLOC_FAILED: return MA_OUT_OF_MEMORY;
case RESAMPLER_ERR_BAD_STATE: return MA_ERROR;
case RESAMPLER_ERR_INVALID_ARG: return MA_INVALID_ARGS;
case RESAMPLER_ERR_PTR_OVERLAP: return MA_INVALID_ARGS;
case RESAMPLER_ERR_OVERFLOW: return MA_ERROR;
default: return MA_ERROR;
}
}
#endif /* ma_speex_resampler_h */
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)
{
ma_resampler_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRateIn = sampleRateIn;
config.sampleRateOut = sampleRateOut;
config.algorithm = algorithm;
/* Linear. */
config.linear.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
config.linear.lpfNyquistFactor = 1;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
return MA_INVALID_ARGS;
}
pResampler->config = *pConfig;
switch (pConfig->algorithm)
{
case ma_resample_algorithm_linear:
{
ma_linear_resampler_config linearConfig;
linearConfig = ma_linear_resampler_config_init(pConfig->format, pConfig->channels, pConfig->sampleRateIn, pConfig->sampleRateOut);
linearConfig.lpfOrder = pConfig->linear.lpfOrder;
linearConfig.lpfNyquistFactor = pConfig->linear.lpfNyquistFactor;
result = ma_linear_resampler_init(&linearConfig, &pResampler->state.linear);
if (result != MA_SUCCESS) {
return result;
}
} break;
case ma_resample_algorithm_speex:
{
#if defined(MA_HAS_SPEEX_RESAMPLER)
int speexErr;
pResampler->state.speex.pSpeexResamplerState = speex_resampler_init(pConfig->channels, pConfig->sampleRateIn, pConfig->sampleRateOut, pConfig->speex.quality, &speexErr);
if (pResampler->state.speex.pSpeexResamplerState == NULL) {
return ma_result_from_speex_err(speexErr);
}
#else
/* Speex resampler not available. */
return MA_NO_BACKEND;
#endif
} break;
default: return MA_INVALID_ARGS;
}
return MA_SUCCESS;
}
MA_API void ma_resampler_uninit(ma_resampler* pResampler)
{
if (pResampler == NULL) {
return;
}
if (pResampler->config.algorithm == ma_resample_algorithm_linear) {
ma_linear_resampler_uninit(&pResampler->state.linear);
}
#if defined(MA_HAS_SPEEX_RESAMPLER)
if (pResampler->config.algorithm == ma_resample_algorithm_speex) {
speex_resampler_destroy((SpeexResamplerState*)pResampler->state.speex.pSpeexResamplerState);
}
#endif
}
static ma_result ma_resampler_process_pcm_frames__read__linear(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
return ma_linear_resampler_process_pcm_frames(&pResampler->state.linear, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
}
#if defined(MA_HAS_SPEEX_RESAMPLER)
static ma_result ma_resampler_process_pcm_frames__read__speex(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
int speexErr;
ma_uint64 frameCountOut;
ma_uint64 frameCountIn;
ma_uint64 framesProcessedOut;
ma_uint64 framesProcessedIn;
unsigned int framesPerIteration = UINT_MAX;
MA_ASSERT(pResampler != NULL);
MA_ASSERT(pFramesOut != NULL);
MA_ASSERT(pFrameCountOut != NULL);
MA_ASSERT(pFrameCountIn != NULL);
/*
Reading from the Speex resampler requires a bit of dancing around for a few reasons. The first thing is that it's frame counts
are in unsigned int's whereas ours is in ma_uint64. We therefore need to run the conversion in a loop. The other, more complicated
problem, is that we need to keep track of the input time, similar to what we do with the linear resampler. The reason we need to
do this is for ma_resampler_get_required_input_frame_count() and ma_resampler_get_expected_output_frame_count().
*/
frameCountOut = *pFrameCountOut;
frameCountIn = *pFrameCountIn;
framesProcessedOut = 0;
framesProcessedIn = 0;
while (framesProcessedOut < frameCountOut && framesProcessedIn < frameCountIn) {
unsigned int frameCountInThisIteration;
unsigned int frameCountOutThisIteration;
const void* pFramesInThisIteration;
void* pFramesOutThisIteration;
frameCountInThisIteration = framesPerIteration;
if ((ma_uint64)frameCountInThisIteration > (frameCountIn - framesProcessedIn)) {
frameCountInThisIteration = (unsigned int)(frameCountIn - framesProcessedIn);
}
frameCountOutThisIteration = framesPerIteration;
if ((ma_uint64)frameCountOutThisIteration > (frameCountOut - framesProcessedOut)) {
frameCountOutThisIteration = (unsigned int)(frameCountOut - framesProcessedOut);
}
pFramesInThisIteration = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pResampler->config.format, pResampler->config.channels));
pFramesOutThisIteration = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pResampler->config.format, pResampler->config.channels));
if (pResampler->config.format == ma_format_f32) {
speexErr = speex_resampler_process_interleaved_float((SpeexResamplerState*)pResampler->state.speex.pSpeexResamplerState, (const float*)pFramesInThisIteration, &frameCountInThisIteration, (float*)pFramesOutThisIteration, &frameCountOutThis...
} else if (pResampler->config.format == ma_format_s16) {
speexErr = speex_resampler_process_interleaved_int((SpeexResamplerState*)pResampler->state.speex.pSpeexResamplerState, (const spx_int16_t*)pFramesInThisIteration, &frameCountInThisIteration, (spx_int16_t*)pFramesOutThisIteration, &frameCo...
} else {
/* Format not supported. Should never get here. */
MA_ASSERT(MA_FALSE);
return MA_INVALID_OPERATION;
}
if (speexErr != RESAMPLER_ERR_SUCCESS) {
return ma_result_from_speex_err(speexErr);
}
framesProcessedIn += frameCountInThisIteration;
framesProcessedOut += frameCountOutThisIteration;
}
*pFrameCountOut = framesProcessedOut;
*pFrameCountIn = framesProcessedIn;
return MA_SUCCESS;
}
#endif
static ma_result ma_resampler_process_pcm_frames__read(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
MA_ASSERT(pResampler != NULL);
MA_ASSERT(pFramesOut != NULL);
/* pFramesOut is not NULL, which means we must have a capacity. */
if (pFrameCountOut == NULL) {
return MA_INVALID_ARGS;
}
/* It doesn't make sense to not have any input frames to process. */
if (pFrameCountIn == NULL || pFramesIn == NULL) {
return MA_INVALID_ARGS;
}
switch (pResampler->config.algorithm)
{
case ma_resample_algorithm_linear:
{
return ma_resampler_process_pcm_frames__read__linear(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
}
case ma_resample_algorithm_speex:
{
#if defined(MA_HAS_SPEEX_RESAMPLER)
return ma_resampler_process_pcm_frames__read__speex(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
#else
break;
#endif
}
default: break;
}
/* Should never get here. */
MA_ASSERT(MA_FALSE);
return MA_INVALID_ARGS;
}
static ma_result ma_resampler_process_pcm_frames__seek__linear(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, ma_uint64* pFrameCountOut)
{
MA_ASSERT(pResampler != NULL);
/* Seeking is supported natively by the linear resampler. */
return ma_linear_resampler_process_pcm_frames(&pResampler->state.linear, pFramesIn, pFrameCountIn, NULL, pFrameCountOut);
}
#if defined(MA_HAS_SPEEX_RESAMPLER)
static ma_result ma_resampler_process_pcm_frames__seek__speex(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, ma_uint64* pFrameCountOut)
{
/* The generic seek method is implemented in on top of ma_resampler_process_pcm_frames__read() by just processing into a dummy buffer. */
float devnull[4096];
ma_uint64 totalOutputFramesToProcess;
ma_uint64 totalOutputFramesProcessed;
ma_uint64 totalInputFramesProcessed;
ma_uint32 bpf;
ma_result result;
MA_ASSERT(pResampler != NULL);
totalOutputFramesProcessed = 0;
totalInputFramesProcessed = 0;
bpf = ma_get_bytes_per_frame(pResampler->config.format, pResampler->config.channels);
if (pFrameCountOut != NULL) {
/* Seek by output frames. */
totalOutputFramesToProcess = *pFrameCountOut;
} else {
/* Seek by input frames. */
MA_ASSERT(pFrameCountIn != NULL);
totalOutputFramesToProcess = ma_resampler_get_expected_output_frame_count(pResampler, *pFrameCountIn);
}
if (pFramesIn != NULL) {
/* Process input data. */
MA_ASSERT(pFrameCountIn != NULL);
while (totalOutputFramesProcessed < totalOutputFramesToProcess && totalInputFramesProcessed < *pFrameCountIn) {
ma_uint64 inputFramesToProcessThisIteration = (*pFrameCountIn - totalInputFramesProcessed);
ma_uint64 outputFramesToProcessThisIteration = (totalOutputFramesToProcess - totalOutputFramesProcessed);
if (outputFramesToProcessThisIteration > sizeof(devnull) / bpf) {
outputFramesToProcessThisIteration = sizeof(devnull) / bpf;
}
result = ma_resampler_process_pcm_frames__read(pResampler, ma_offset_ptr(pFramesIn, totalInputFramesProcessed*bpf), &inputFramesToProcessThisIteration, ma_offset_ptr(devnull, totalOutputFramesProcessed*bpf), &outputFramesToProcessThisIter...
if (result != MA_SUCCESS) {
return result;
}
totalOutputFramesProcessed += outputFramesToProcessThisIteration;
totalInputFramesProcessed += inputFramesToProcessThisIteration;
}
} else {
/* Don't process input data - just update timing and filter state as if zeroes were passed in. */
while (totalOutputFramesProcessed < totalOutputFramesToProcess) {
ma_uint64 inputFramesToProcessThisIteration = 16384;
ma_uint64 outputFramesToProcessThisIteration = (totalOutputFramesToProcess - totalOutputFramesProcessed);
if (outputFramesToProcessThisIteration > sizeof(devnull) / bpf) {
outputFramesToProcessThisIteration = sizeof(devnull) / bpf;
}
result = ma_resampler_process_pcm_frames__read(pResampler, NULL, &inputFramesToProcessThisIteration, ma_offset_ptr(devnull, totalOutputFramesProcessed*bpf), &outputFramesToProcessThisIteration);
if (result != MA_SUCCESS) {
return result;
}
totalOutputFramesProcessed += outputFramesToProcessThisIteration;
totalInputFramesProcessed += inputFramesToProcessThisIteration;
}
}
if (pFrameCountIn != NULL) {
*pFrameCountIn = totalInputFramesProcessed;
}
if (pFrameCountOut != NULL) {
*pFrameCountOut = totalOutputFramesProcessed;
}
return MA_SUCCESS;
}
#endif
static ma_result ma_resampler_process_pcm_frames__seek(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, ma_uint64* pFrameCountOut)
{
MA_ASSERT(pResampler != NULL);
switch (pResampler->config.algorithm)
{
case ma_resample_algorithm_linear:
{
return ma_resampler_process_pcm_frames__seek__linear(pResampler, pFramesIn, pFrameCountIn, pFrameCountOut);
} break;
case ma_resample_algorithm_speex:
{
#if defined(MA_HAS_SPEEX_RESAMPLER)
return ma_resampler_process_pcm_frames__seek__speex(pResampler, pFramesIn, pFrameCountIn, pFrameCountOut);
#else
break;
#endif
};
default: break;
}
/* Should never hit this. */
MA_ASSERT(MA_FALSE);
return MA_INVALID_ARGS;
}
MA_API ma_result ma_resampler_process_pcm_frames(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
if (pResampler == NULL) {
return MA_INVALID_ARGS;
}
if (pFrameCountOut == NULL && pFrameCountIn == NULL) {
return MA_INVALID_ARGS;
}
if (pFramesOut != NULL) {
/* Reading. */
return ma_resampler_process_pcm_frames__read(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
} else {
/* Seeking. */
return ma_resampler_process_pcm_frames__seek(pResampler, pFramesIn, pFrameCountIn, pFrameCountOut);
}
}
MA_API ma_result ma_resampler_set_rate(ma_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
{
if (pResampler == NULL) {
return MA_INVALID_ARGS;
}
if (sampleRateIn == 0 || sampleRateOut == 0) {
return MA_INVALID_ARGS;
}
pResampler->config.sampleRateIn = sampleRateIn;
pResampler->config.sampleRateOut = sampleRateOut;
switch (pResampler->config.algorithm)
{
case ma_resample_algorithm_linear:
{
return ma_linear_resampler_set_rate(&pResampler->state.linear, sampleRateIn, sampleRateOut);
} break;
case ma_resample_algorithm_speex:
{
#if defined(MA_HAS_SPEEX_RESAMPLER)
return ma_result_from_speex_err(speex_resampler_set_rate((SpeexResamplerState*)pResampler->state.speex.pSpeexResamplerState, sampleRateIn, sampleRateOut));
#else
break;
#endif
};
default: break;
}
/* Should never get here. */
MA_ASSERT(MA_FALSE);
return MA_INVALID_OPERATION;
}
MA_API ma_result ma_resampler_set_rate_ratio(ma_resampler* pResampler, float ratio)
{
if (pResampler == NULL) {
return MA_INVALID_ARGS;
}
if (pResampler->config.algorithm == ma_resample_algorithm_linear) {
return ma_linear_resampler_set_rate_ratio(&pResampler->state.linear, ratio);
} else {
/* Getting here means the backend does not have native support for setting the rate as a ratio so we just do it generically. */
ma_uint32 n;
ma_uint32 d;
d = 1000;
n = (ma_uint32)(ratio * d);
if (n == 0) {
return MA_INVALID_ARGS; /* Ratio too small. */
}
MA_ASSERT(n != 0);
return ma_resampler_set_rate(pResampler, n, d);
}
}
MA_API ma_uint64 ma_resampler_get_required_input_frame_count(ma_resampler* pResampler, ma_uint64 outputFrameCount)
{
if (pResampler == NULL) {
return 0;
}
if (outputFrameCount == 0) {
return 0;
}
switch (pResampler->config.algorithm)
{
case ma_resample_algorithm_linear:
{
return ma_linear_resampler_get_required_input_frame_count(&pResampler->state.linear, outputFrameCount);
}
case ma_resample_algorithm_speex:
{
#if defined(MA_HAS_SPEEX_RESAMPLER)
ma_uint64 count;
int speexErr = ma_speex_resampler_get_required_input_frame_count((SpeexResamplerState*)pResampler->state.speex.pSpeexResamplerState, outputFrameCount, &count);
if (speexErr != RESAMPLER_ERR_SUCCESS) {
return 0;
}
return count;
#else
break;
#endif
}
default: break;
}
/* Should never get here. */
MA_ASSERT(MA_FALSE);
return 0;
}
MA_API ma_uint64 ma_resampler_get_expected_output_frame_count(ma_resampler* pResampler, ma_uint64 inputFrameCount)
{
if (pResampler == NULL) {
return 0; /* Invalid args. */
}
if (inputFrameCount == 0) {
return 0;
}
switch (pResampler->config.algorithm)
{
case ma_resample_algorithm_linear:
{
return ma_linear_resampler_get_expected_output_frame_count(&pResampler->state.linear, inputFrameCount);
}
case ma_resample_algorithm_speex:
{
#if defined(MA_HAS_SPEEX_RESAMPLER)
ma_uint64 count;
int speexErr = ma_speex_resampler_get_expected_output_frame_count((SpeexResamplerState*)pResampler->state.speex.pSpeexResamplerState, inputFrameCount, &count);
if (speexErr != RESAMPLER_ERR_SUCCESS) {
return 0;
}
return count;
#else
break;
#endif
}
default: break;
}
/* Should never get here. */
MA_ASSERT(MA_FALSE);
return 0;
}
MA_API ma_uint64 ma_resampler_get_input_latency(ma_resampler* pResampler)
{
if (pResampler == NULL) {
return 0;
}
switch (pResampler->config.algorithm)
{
case ma_resample_algorithm_linear:
{
return ma_linear_resampler_get_input_latency(&pResampler->state.linear);
}
case ma_resample_algorithm_speex:
{
#if defined(MA_HAS_SPEEX_RESAMPLER)
return (ma_uint64)ma_speex_resampler_get_input_latency((SpeexResamplerState*)pResampler->state.speex.pSpeexResamplerState);
#else
break;
#endif
}
default: break;
}
/* Should never get here. */
MA_ASSERT(MA_FALSE);
return 0;
}
MA_API ma_uint64 ma_resampler_get_output_latency(ma_resampler* pResampler)
{
if (pResampler == NULL) {
return 0;
}
switch (pResampler->config.algorithm)
{
case ma_resample_algorithm_linear:
{
return ma_linear_resampler_get_output_latency(&pResampler->state.linear);
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
}
}
}
}
}
}
}
/* Unmapped output channels. */
for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
ma_channel channelPosOut = pConverter->channelMapOut[iChannelOut];
if (ma_is_spatial_channel_position(channelPosOut)) {
if (!ma_channel_map_contains_channel_position(pConverter->channelsIn, pConverter->channelMapIn, channelPosOut)) {
for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
ma_channel channelPosIn = pConverter->channelMapIn[iChannelIn];
if (ma_is_spatial_channel_position(channelPosIn)) {
float weight = 0;
if (pConverter->mixingMode == ma_channel_mix_mode_rectangular) {
weight = ma_calculate_channel_position_rectangular_weight(channelPosIn, channelPosOut);
}
/* Only apply the weight if we haven't already got some contribution from the respective channels. */
if (pConverter->format == ma_format_f32) {
if (pConverter->weights.f32[iChannelIn][iChannelOut] == 0) {
pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
}
} else {
if (pConverter->weights.s16[iChannelIn][iChannelOut] == 0) {
pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
}
}
}
}
}
}
}
} break;
case ma_channel_mix_mode_custom_weights:
case ma_channel_mix_mode_simple:
default:
{
/* Fallthrough. */
} break;
}
return MA_SUCCESS;
}
MA_API void ma_channel_converter_uninit(ma_channel_converter* pConverter)
{
if (pConverter == NULL) {
return;
}
}
static ma_result ma_channel_converter_process_pcm_frames__passthrough(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
MA_ASSERT(pConverter != NULL);
MA_ASSERT(pFramesOut != NULL);
MA_ASSERT(pFramesIn != NULL);
ma_copy_memory_64(pFramesOut, pFramesIn, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut));
return MA_SUCCESS;
}
static ma_result ma_channel_converter_process_pcm_frames__simple_shuffle(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
ma_uint32 iFrame;
ma_uint32 iChannelIn;
MA_ASSERT(pConverter != NULL);
MA_ASSERT(pFramesOut != NULL);
MA_ASSERT(pFramesIn != NULL);
MA_ASSERT(pConverter->channelsIn == pConverter->channelsOut);
switch (pConverter->format)
{
case ma_format_u8:
{
/* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
pFramesOutU8[pConverter->shuffleTable[iChannelIn]] = pFramesInU8[iChannelIn];
}
pFramesOutU8 += pConverter->channelsOut;
pFramesInU8 += pConverter->channelsIn;
}
} break;
case ma_format_s16:
{
/* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
pFramesOutS16[pConverter->shuffleTable[iChannelIn]] = pFramesInS16[iChannelIn];
}
pFramesOutS16 += pConverter->channelsOut;
pFramesInS16 += pConverter->channelsIn;
}
} break;
case ma_format_s24:
{
/* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
ma_uint32 iChannelOut = pConverter->shuffleTable[iChannelIn];
pFramesOutS24[iChannelOut*3 + 0] = pFramesInS24[iChannelIn*3 + 0];
pFramesOutS24[iChannelOut*3 + 1] = pFramesInS24[iChannelIn*3 + 1];
pFramesOutS24[iChannelOut*3 + 2] = pFramesInS24[iChannelIn*3 + 2];
}
pFramesOutS24 += pConverter->channelsOut*3;
pFramesInS24 += pConverter->channelsIn*3;
}
} break;
case ma_format_s32:
{
/* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
pFramesOutS32[pConverter->shuffleTable[iChannelIn]] = pFramesInS32[iChannelIn];
}
pFramesOutS32 += pConverter->channelsOut;
pFramesInS32 += pConverter->channelsIn;
}
} break;
case ma_format_f32:
{
/* */ float* pFramesOutF32 = ( float*)pFramesOut;
const float* pFramesInF32 = (const float*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
pFramesOutF32[pConverter->shuffleTable[iChannelIn]] = pFramesInF32[iChannelIn];
}
pFramesOutF32 += pConverter->channelsOut;
pFramesInF32 += pConverter->channelsIn;
}
} break;
default: return MA_INVALID_OPERATION; /* Unknown format. */
}
return MA_SUCCESS;
}
static ma_result ma_channel_converter_process_pcm_frames__simple_mono_expansion(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
ma_uint64 iFrame;
MA_ASSERT(pConverter != NULL);
MA_ASSERT(pFramesOut != NULL);
MA_ASSERT(pFramesIn != NULL);
MA_ASSERT(pConverter->channelsIn == 1);
switch (pConverter->format)
{
case ma_format_u8:
{
/* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
pFramesOutU8[iFrame*pConverter->channelsOut + iChannel] = pFramesInU8[iFrame];
}
}
} break;
case ma_format_s16:
{
/* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
if (pConverter->channelsOut == 2) {
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
pFramesOutS16[iFrame*2 + 0] = pFramesInS16[iFrame];
pFramesOutS16[iFrame*2 + 1] = pFramesInS16[iFrame];
}
} else {
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
pFramesOutS16[iFrame*pConverter->channelsOut + iChannel] = pFramesInS16[iFrame];
}
}
}
} break;
case ma_format_s24:
{
/* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
ma_uint64 iSampleOut = iFrame*pConverter->channelsOut + iChannel;
ma_uint64 iSampleIn = iFrame;
pFramesOutS24[iSampleOut*3 + 0] = pFramesInS24[iSampleIn*3 + 0];
pFramesOutS24[iSampleOut*3 + 1] = pFramesInS24[iSampleIn*3 + 1];
pFramesOutS24[iSampleOut*3 + 2] = pFramesInS24[iSampleIn*3 + 2];
}
}
} break;
case ma_format_s32:
{
/* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
pFramesOutS32[iFrame*pConverter->channelsOut + iChannel] = pFramesInS32[iFrame];
}
}
} break;
case ma_format_f32:
{
/* */ float* pFramesOutF32 = ( float*)pFramesOut;
const float* pFramesInF32 = (const float*)pFramesIn;
if (pConverter->channelsOut == 2) {
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
pFramesOutF32[iFrame*2 + 0] = pFramesInF32[iFrame];
pFramesOutF32[iFrame*2 + 1] = pFramesInF32[iFrame];
}
} else {
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
pFramesOutF32[iFrame*pConverter->channelsOut + iChannel] = pFramesInF32[iFrame];
}
}
}
} break;
default: return MA_INVALID_OPERATION; /* Unknown format. */
}
return MA_SUCCESS;
}
static ma_result ma_channel_converter_process_pcm_frames__stereo_to_mono(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
ma_uint64 iFrame;
MA_ASSERT(pConverter != NULL);
MA_ASSERT(pFramesOut != NULL);
MA_ASSERT(pFramesIn != NULL);
MA_ASSERT(pConverter->channelsIn == 2);
MA_ASSERT(pConverter->channelsOut == 1);
switch (pConverter->format)
{
case ma_format_u8:
{
/* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
pFramesOutU8[iFrame] = ma_clip_u8((ma_int16)((ma_pcm_sample_u8_to_s16_no_scale(pFramesInU8[iFrame*2+0]) + ma_pcm_sample_u8_to_s16_no_scale(pFramesInU8[iFrame*2+1])) / 2));
}
} break;
case ma_format_s16:
{
/* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
pFramesOutS16[iFrame] = (ma_int16)(((ma_int32)pFramesInS16[iFrame*2+0] + (ma_int32)pFramesInS16[iFrame*2+1]) / 2);
}
} break;
case ma_format_s24:
{
/* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
ma_int64 s24_0 = ma_pcm_sample_s24_to_s32_no_scale(&pFramesInS24[(iFrame*2+0)*3]);
ma_int64 s24_1 = ma_pcm_sample_s24_to_s32_no_scale(&pFramesInS24[(iFrame*2+1)*3]);
ma_pcm_sample_s32_to_s24_no_scale((s24_0 + s24_1) / 2, &pFramesOutS24[iFrame*3]);
}
} break;
case ma_format_s32:
{
/* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
pFramesOutS32[iFrame] = (ma_int16)(((ma_int32)pFramesInS32[iFrame*2+0] + (ma_int32)pFramesInS32[iFrame*2+1]) / 2);
}
} break;
case ma_format_f32:
{
/* */ float* pFramesOutF32 = ( float*)pFramesOut;
const float* pFramesInF32 = (const float*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; ++iFrame) {
pFramesOutF32[iFrame] = (pFramesInF32[iFrame*2+0] + pFramesInF32[iFrame*2+0]) * 0.5f;
}
} break;
default: return MA_INVALID_OPERATION; /* Unknown format. */
}
return MA_SUCCESS;
}
static ma_result ma_channel_converter_process_pcm_frames__weights(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
ma_uint32 iFrame;
ma_uint32 iChannelIn;
ma_uint32 iChannelOut;
MA_ASSERT(pConverter != NULL);
MA_ASSERT(pFramesOut != NULL);
MA_ASSERT(pFramesIn != NULL);
/* This is the more complicated case. Each of the output channels is accumulated with 0 or more input channels. */
/* Clear. */
ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut));
/* Accumulate. */
switch (pConverter->format)
{
case ma_format_u8:
{
/* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
ma_int16 u8_O = ma_pcm_sample_u8_to_s16_no_scale(pFramesOutU8[iFrame*pConverter->channelsOut + iChannelOut]);
ma_int16 u8_I = ma_pcm_sample_u8_to_s16_no_scale(pFramesInU8 [iFrame*pConverter->channelsIn + iChannelIn ]);
ma_int32 s = (ma_int32)ma_clamp(u8_O + ((u8_I * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT), -128, 127);
pFramesOutU8[iFrame*pConverter->channelsOut + iChannelOut] = ma_clip_u8((ma_int16)s);
}
}
}
} break;
case ma_format_s16:
{
/* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
ma_int32 s = pFramesOutS16[iFrame*pConverter->channelsOut + iChannelOut];
s += (pFramesInS16[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT;
pFramesOutS16[iFrame*pConverter->channelsOut + iChannelOut] = (ma_int16)ma_clamp(s, -32768, 32767);
}
}
}
} break;
case ma_format_s24:
{
/* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
ma_int64 s24_O = ma_pcm_sample_s24_to_s32_no_scale(&pFramesOutS24[(iFrame*pConverter->channelsOut + iChannelOut)*3]);
ma_int64 s24_I = ma_pcm_sample_s24_to_s32_no_scale(&pFramesInS24 [(iFrame*pConverter->channelsIn + iChannelIn )*3]);
ma_int64 s24 = (ma_int32)ma_clamp(s24_O + ((s24_I * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT), -8388608, 8388607);
ma_pcm_sample_s32_to_s24_no_scale(s24, &pFramesOutS24[(iFrame*pConverter->channelsOut + iChannelOut)*3]);
}
}
}
} break;
case ma_format_s32:
{
/* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
ma_int64 s = pFramesOutS32[iFrame*pConverter->channelsOut + iChannelOut];
s += ((ma_int64)pFramesInS32[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT;
pFramesOutS32[iFrame*pConverter->channelsOut + iChannelOut] = ma_clip_s32(s);
}
}
}
} break;
case ma_format_f32:
{
/* */ float* pFramesOutF32 = ( float*)pFramesOut;
const float* pFramesInF32 = (const float*)pFramesIn;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
pFramesOutF32[iFrame*pConverter->channelsOut + iChannelOut] += pFramesInF32[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.f32[iChannelIn][iChannelOut];
}
}
}
} break;
default: return MA_INVALID_OPERATION; /* Unknown format. */
}
return MA_SUCCESS;
}
MA_API ma_result ma_channel_converter_process_pcm_frames(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
{
if (pConverter == NULL) {
return MA_INVALID_ARGS;
}
if (pFramesOut == NULL) {
return MA_INVALID_ARGS;
}
if (pFramesIn == NULL) {
ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut));
return MA_SUCCESS;
}
if (pConverter->isPassthrough) {
return ma_channel_converter_process_pcm_frames__passthrough(pConverter, pFramesOut, pFramesIn, frameCount);
} else if (pConverter->isSimpleShuffle) {
return ma_channel_converter_process_pcm_frames__simple_shuffle(pConverter, pFramesOut, pFramesIn, frameCount);
} else if (pConverter->isSimpleMonoExpansion) {
return ma_channel_converter_process_pcm_frames__simple_mono_expansion(pConverter, pFramesOut, pFramesIn, frameCount);
} else if (pConverter->isStereoToMono) {
return ma_channel_converter_process_pcm_frames__stereo_to_mono(pConverter, pFramesOut, pFramesIn, frameCount);
} else {
return ma_channel_converter_process_pcm_frames__weights(pConverter, pFramesOut, pFramesIn, frameCount);
}
}
/**************************************************************************************************************************************************************
Data Conversion
**************************************************************************************************************************************************************/
MA_API ma_data_converter_config ma_data_converter_config_init_default()
{
ma_data_converter_config config;
MA_ZERO_OBJECT(&config);
config.ditherMode = ma_dither_mode_none;
config.resampling.algorithm = ma_resample_algorithm_linear;
config.resampling.allowDynamicSampleRate = MA_FALSE; /* Disable dynamic sample rates by default because dynamic rate adjustments should be quite rare and it allows an optimization for cases when the in and out sample rates are the same. */
/* Linear resampling defaults. */
config.resampling.linear.lpfOrder = 1;
config.resampling.linear.lpfNyquistFactor = 1;
/* Speex resampling defaults. */
config.resampling.speex.quality = 3;
return config;
}
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)
{
ma_data_converter_config config = ma_data_converter_config_init_default();
config.formatIn = formatIn;
config.formatOut = formatOut;
config.channelsIn = ma_min(channelsIn, MA_MAX_CHANNELS);
config.channelsOut = ma_min(channelsOut, MA_MAX_CHANNELS);
config.sampleRateIn = sampleRateIn;
config.sampleRateOut = sampleRateOut;
return config;
}
MA_API ma_result ma_data_converter_init(const ma_data_converter_config* pConfig, ma_data_converter* pConverter)
{
ma_result result;
ma_format midFormat;
if (pConverter == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pConverter);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
pConverter->config = *pConfig;
/* Basic validation. */
if (pConfig->channelsIn < MA_MIN_CHANNELS || pConfig->channelsOut < MA_MIN_CHANNELS ||
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
resamplerConfig = ma_resampler_config_init(midFormat, resamplerChannels, pConverter->config.sampleRateIn, pConverter->config.sampleRateOut, pConverter->config.resampling.algorithm);
resamplerConfig.linear.lpfOrder = pConverter->config.resampling.linear.lpfOrder;
resamplerConfig.linear.lpfNyquistFactor = pConverter->config.resampling.linear.lpfNyquistFactor;
resamplerConfig.speex.quality = pConverter->config.resampling.speex.quality;
result = ma_resampler_init(&resamplerConfig, &pConverter->resampler);
if (result != MA_SUCCESS) {
return result;
}
pConverter->hasResampler = MA_TRUE;
}
/* We can simplify pre- and post-format conversion if we have neither channel conversion nor resampling. */
if (pConverter->hasChannelConverter == MA_FALSE && pConverter->hasResampler == MA_FALSE) {
/* We have neither channel conversion nor resampling so we'll only need one of pre- or post-format conversion, or none if the input and output formats are the same. */
if (pConverter->config.formatIn == pConverter->config.formatOut) {
/* The formats are the same so we can just pass through. */
pConverter->hasPreFormatConversion = MA_FALSE;
pConverter->hasPostFormatConversion = MA_FALSE;
} else {
/* The formats are different so we need to do either pre- or post-format conversion. It doesn't matter which. */
pConverter->hasPreFormatConversion = MA_FALSE;
pConverter->hasPostFormatConversion = MA_TRUE;
}
} else {
/* We have a channel converter and/or resampler so we'll need channel conversion based on the mid format. */
if (pConverter->config.formatIn != midFormat) {
pConverter->hasPreFormatConversion = MA_TRUE;
}
if (pConverter->config.formatOut != midFormat) {
pConverter->hasPostFormatConversion = MA_TRUE;
}
}
/* We can enable passthrough optimizations if applicable. Note that we'll only be able to do this if the sample rate is static. */
if (pConverter->hasPreFormatConversion == MA_FALSE &&
pConverter->hasPostFormatConversion == MA_FALSE &&
pConverter->hasChannelConverter == MA_FALSE &&
pConverter->hasResampler == MA_FALSE) {
pConverter->isPassthrough = MA_TRUE;
}
return MA_SUCCESS;
}
MA_API void ma_data_converter_uninit(ma_data_converter* pConverter)
{
if (pConverter == NULL) {
return;
}
if (pConverter->hasResampler) {
ma_resampler_uninit(&pConverter->resampler);
}
}
static ma_result ma_data_converter_process_pcm_frames__passthrough(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
ma_uint64 frameCountIn;
ma_uint64 frameCountOut;
ma_uint64 frameCount;
MA_ASSERT(pConverter != NULL);
frameCountIn = 0;
if (pFrameCountIn != NULL) {
frameCountIn = *pFrameCountIn;
}
frameCountOut = 0;
if (pFrameCountOut != NULL) {
frameCountOut = *pFrameCountOut;
}
frameCount = ma_min(frameCountIn, frameCountOut);
if (pFramesOut != NULL) {
if (pFramesIn != NULL) {
ma_copy_memory_64(pFramesOut, pFramesIn, frameCount * ma_get_bytes_per_frame(pConverter->config.formatOut, pConverter->config.channelsOut));
} else {
ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->config.formatOut, pConverter->config.channelsOut));
}
}
if (pFrameCountIn != NULL) {
*pFrameCountIn = frameCount;
}
if (pFrameCountOut != NULL) {
*pFrameCountOut = frameCount;
}
return MA_SUCCESS;
}
static ma_result ma_data_converter_process_pcm_frames__format_only(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
ma_uint64 frameCountIn;
ma_uint64 frameCountOut;
ma_uint64 frameCount;
MA_ASSERT(pConverter != NULL);
frameCountIn = 0;
if (pFrameCountIn != NULL) {
frameCountIn = *pFrameCountIn;
}
frameCountOut = 0;
if (pFrameCountOut != NULL) {
frameCountOut = *pFrameCountOut;
}
frameCount = ma_min(frameCountIn, frameCountOut);
if (pFramesOut != NULL) {
if (pFramesIn != NULL) {
ma_convert_pcm_frames_format(pFramesOut, pConverter->config.formatOut, pFramesIn, pConverter->config.formatIn, frameCount, pConverter->config.channelsIn, pConverter->config.ditherMode);
} else {
ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->config.formatOut, pConverter->config.channelsOut));
}
}
if (pFrameCountIn != NULL) {
*pFrameCountIn = frameCount;
}
if (pFrameCountOut != NULL) {
*pFrameCountOut = frameCount;
}
return MA_SUCCESS;
}
static ma_result ma_data_converter_process_pcm_frames__resample_with_format_conversion(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
ma_result result = MA_SUCCESS;
ma_uint64 frameCountIn;
ma_uint64 frameCountOut;
ma_uint64 framesProcessedIn;
ma_uint64 framesProcessedOut;
MA_ASSERT(pConverter != NULL);
frameCountIn = 0;
if (pFrameCountIn != NULL) {
frameCountIn = *pFrameCountIn;
}
frameCountOut = 0;
if (pFrameCountOut != NULL) {
frameCountOut = *pFrameCountOut;
}
framesProcessedIn = 0;
framesProcessedOut = 0;
while (framesProcessedOut < frameCountOut) {
ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
const ma_uint32 tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->resampler.config.format, pConverter->resampler.config.channels);
const void* pFramesInThisIteration;
/* */ void* pFramesOutThisIteration;
ma_uint64 frameCountInThisIteration;
ma_uint64 frameCountOutThisIteration;
if (pFramesIn != NULL) {
pFramesInThisIteration = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->config.formatIn, pConverter->config.channelsIn));
} else {
pFramesInThisIteration = NULL;
}
if (pFramesOut != NULL) {
pFramesOutThisIteration = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->config.formatOut, pConverter->config.channelsOut));
} else {
pFramesOutThisIteration = NULL;
}
/* Do a pre format conversion if necessary. */
if (pConverter->hasPreFormatConversion) {
ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
const ma_uint32 tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.config.format, pConverter->resampler.config.channels);
frameCountInThisIteration = (frameCountIn - framesProcessedIn);
if (frameCountInThisIteration > tempBufferInCap) {
frameCountInThisIteration = tempBufferInCap;
}
if (pConverter->hasPostFormatConversion) {
if (frameCountInThisIteration > tempBufferOutCap) {
frameCountInThisIteration = tempBufferOutCap;
}
}
if (pFramesInThisIteration != NULL) {
ma_convert_pcm_frames_format(pTempBufferIn, pConverter->resampler.config.format, pFramesInThisIteration, pConverter->config.formatIn, frameCountInThisIteration, pConverter->config.channelsIn, pConverter->config.ditherMode);
} else {
MA_ZERO_MEMORY(pTempBufferIn, sizeof(pTempBufferIn));
}
frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
if (pConverter->hasPostFormatConversion) {
/* Both input and output conversion required. Output to the temp buffer. */
if (frameCountOutThisIteration > tempBufferOutCap) {
frameCountOutThisIteration = tempBufferOutCap;
}
result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferIn, &frameCountInThisIteration, pTempBufferOut, &frameCountOutThisIteration);
} else {
/* Only pre-format required. Output straight to the output buffer. */
result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferIn, &frameCountInThisIteration, pFramesOutThisIteration, &frameCountOutThisIteration);
}
if (result != MA_SUCCESS) {
break;
}
} else {
/* No pre-format required. Just read straight from the input buffer. */
MA_ASSERT(pConverter->hasPostFormatConversion == MA_TRUE);
frameCountInThisIteration = (frameCountIn - framesProcessedIn);
frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
if (frameCountOutThisIteration > tempBufferOutCap) {
frameCountOutThisIteration = tempBufferOutCap;
}
result = ma_resampler_process_pcm_frames(&pConverter->resampler, pFramesInThisIteration, &frameCountInThisIteration, pTempBufferOut, &frameCountOutThisIteration);
if (result != MA_SUCCESS) {
break;
}
}
/* If we are doing a post format conversion we need to do that now. */
if (pConverter->hasPostFormatConversion) {
if (pFramesOutThisIteration != NULL) {
ma_convert_pcm_frames_format(pFramesOutThisIteration, pConverter->config.formatOut, pTempBufferOut, pConverter->resampler.config.format, frameCountOutThisIteration, pConverter->resampler.config.channels, pConverter->config.ditherMode)...
}
}
framesProcessedIn += frameCountInThisIteration;
framesProcessedOut += frameCountOutThisIteration;
MA_ASSERT(framesProcessedIn <= frameCountIn);
MA_ASSERT(framesProcessedOut <= frameCountOut);
if (frameCountOutThisIteration == 0) {
break; /* Consumed all of our input data. */
}
}
if (pFrameCountIn != NULL) {
*pFrameCountIn = framesProcessedIn;
}
if (pFrameCountOut != NULL) {
*pFrameCountOut = framesProcessedOut;
}
return result;
}
static ma_result ma_data_converter_process_pcm_frames__resample_only(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
MA_ASSERT(pConverter != NULL);
if (pConverter->hasPreFormatConversion == MA_FALSE && pConverter->hasPostFormatConversion == MA_FALSE) {
/* Neither pre- nor post-format required. This is simple case where only resampling is required. */
return ma_resampler_process_pcm_frames(&pConverter->resampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
} else {
/* Format conversion required. */
return ma_data_converter_process_pcm_frames__resample_with_format_conversion(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
}
}
static ma_result ma_data_converter_process_pcm_frames__channels_only(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
ma_result result;
ma_uint64 frameCountIn;
ma_uint64 frameCountOut;
ma_uint64 frameCount;
MA_ASSERT(pConverter != NULL);
frameCountIn = 0;
if (pFrameCountIn != NULL) {
frameCountIn = *pFrameCountIn;
}
frameCountOut = 0;
if (pFrameCountOut != NULL) {
frameCountOut = *pFrameCountOut;
}
frameCount = ma_min(frameCountIn, frameCountOut);
if (pConverter->hasPreFormatConversion == MA_FALSE && pConverter->hasPostFormatConversion == MA_FALSE) {
/* No format conversion required. */
result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pFramesOut, pFramesIn, frameCount);
if (result != MA_SUCCESS) {
return result;
}
} else {
/* Format conversion required. */
ma_uint64 framesProcessed = 0;
while (framesProcessed < frameCount) {
ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
const ma_uint32 tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut);
const void* pFramesInThisIteration;
/* */ void* pFramesOutThisIteration;
ma_uint64 frameCountThisIteration;
if (pFramesIn != NULL) {
pFramesInThisIteration = ma_offset_ptr(pFramesIn, framesProcessed * ma_get_bytes_per_frame(pConverter->config.formatIn, pConverter->config.channelsIn));
} else {
pFramesInThisIteration = NULL;
}
if (pFramesOut != NULL) {
pFramesOutThisIteration = ma_offset_ptr(pFramesOut, framesProcessed * ma_get_bytes_per_frame(pConverter->config.formatOut, pConverter->config.channelsOut));
} else {
pFramesOutThisIteration = NULL;
}
/* Do a pre format conversion if necessary. */
if (pConverter->hasPreFormatConversion) {
ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
const ma_uint32 tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsIn);
frameCountThisIteration = (frameCount - framesProcessed);
if (frameCountThisIteration > tempBufferInCap) {
frameCountThisIteration = tempBufferInCap;
}
if (pConverter->hasPostFormatConversion) {
if (frameCountThisIteration > tempBufferOutCap) {
frameCountThisIteration = tempBufferOutCap;
}
}
if (pFramesInThisIteration != NULL) {
ma_convert_pcm_frames_format(pTempBufferIn, pConverter->channelConverter.format, pFramesInThisIteration, pConverter->config.formatIn, frameCountThisIteration, pConverter->config.channelsIn, pConverter->config.ditherMode);
} else {
MA_ZERO_MEMORY(pTempBufferIn, sizeof(pTempBufferIn));
}
if (pConverter->hasPostFormatConversion) {
/* Both input and output conversion required. Output to the temp buffer. */
result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferOut, pTempBufferIn, frameCountThisIteration);
} else {
/* Only pre-format required. Output straight to the output buffer. */
result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pFramesOutThisIteration, pTempBufferIn, frameCountThisIteration);
}
if (result != MA_SUCCESS) {
break;
}
} else {
/* No pre-format required. Just read straight from the input buffer. */
MA_ASSERT(pConverter->hasPostFormatConversion == MA_TRUE);
frameCountThisIteration = (frameCount - framesProcessed);
if (frameCountThisIteration > tempBufferOutCap) {
frameCountThisIteration = tempBufferOutCap;
}
result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferOut, pFramesInThisIteration, frameCountThisIteration);
if (result != MA_SUCCESS) {
break;
}
}
/* If we are doing a post format conversion we need to do that now. */
if (pConverter->hasPostFormatConversion) {
if (pFramesOutThisIteration != NULL) {
ma_convert_pcm_frames_format(pFramesOutThisIteration, pConverter->config.formatOut, pTempBufferOut, pConverter->channelConverter.format, frameCountThisIteration, pConverter->channelConverter.channelsOut, pConverter->config.ditherM...
}
}
framesProcessed += frameCountThisIteration;
}
}
if (pFrameCountIn != NULL) {
*pFrameCountIn = frameCount;
}
if (pFrameCountOut != NULL) {
*pFrameCountOut = frameCount;
}
return MA_SUCCESS;
}
static ma_result ma_data_converter_process_pcm_frames__resampling_first(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
ma_result result;
ma_uint64 frameCountIn;
ma_uint64 frameCountOut;
ma_uint64 framesProcessedIn;
ma_uint64 framesProcessedOut;
ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format. */
ma_uint64 tempBufferInCap;
ma_uint8 pTempBufferMid[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format, channel converter input format. */
ma_uint64 tempBufferMidCap;
ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In channel converter output format. */
ma_uint64 tempBufferOutCap;
MA_ASSERT(pConverter != NULL);
MA_ASSERT(pConverter->resampler.config.format == pConverter->channelConverter.format);
MA_ASSERT(pConverter->resampler.config.channels == pConverter->channelConverter.channelsIn);
MA_ASSERT(pConverter->resampler.config.channels < pConverter->channelConverter.channelsOut);
frameCountIn = 0;
if (pFrameCountIn != NULL) {
frameCountIn = *pFrameCountIn;
}
frameCountOut = 0;
if (pFrameCountOut != NULL) {
frameCountOut = *pFrameCountOut;
}
framesProcessedIn = 0;
framesProcessedOut = 0;
tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.config.format, pConverter->resampler.config.channels);
tempBufferMidCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.config.format, pConverter->resampler.config.channels);
tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut);
while (framesProcessedOut < frameCountOut) {
ma_uint64 frameCountInThisIteration;
ma_uint64 frameCountOutThisIteration;
const void* pRunningFramesIn = NULL;
void* pRunningFramesOut = NULL;
const void* pResampleBufferIn;
void* pChannelsBufferOut;
if (pFramesIn != NULL) {
pRunningFramesIn = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->config.formatIn, pConverter->config.channelsIn));
}
if (pFramesOut != NULL) {
pRunningFramesOut = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->config.formatOut, pConverter->config.channelsOut));
}
/* Run input data through the resampler and output it to the temporary buffer. */
frameCountInThisIteration = (frameCountIn - framesProcessedIn);
if (pConverter->hasPreFormatConversion) {
if (frameCountInThisIteration > tempBufferInCap) {
frameCountInThisIteration = tempBufferInCap;
}
}
frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
if (frameCountOutThisIteration > tempBufferMidCap) {
frameCountOutThisIteration = tempBufferMidCap;
}
/* We can't read more frames than can fit in the output buffer. */
if (pConverter->hasPostFormatConversion) {
if (frameCountOutThisIteration > tempBufferOutCap) {
frameCountOutThisIteration = tempBufferOutCap;
}
}
/* We need to ensure we don't try to process too many input frames that we run out of room in the output buffer. If this happens we'll end up glitching. */
{
ma_uint64 requiredInputFrameCount = ma_resampler_get_required_input_frame_count(&pConverter->resampler, frameCountOutThisIteration);
if (frameCountInThisIteration > requiredInputFrameCount) {
frameCountInThisIteration = requiredInputFrameCount;
}
}
if (pConverter->hasPreFormatConversion) {
if (pFramesIn != NULL) {
ma_convert_pcm_frames_format(pTempBufferIn, pConverter->resampler.config.format, pRunningFramesIn, pConverter->config.formatIn, frameCountInThisIteration, pConverter->config.channelsIn, pConverter->config.ditherMode);
pResampleBufferIn = pTempBufferIn;
} else {
pResampleBufferIn = NULL;
}
} else {
pResampleBufferIn = pRunningFramesIn;
}
result = ma_resampler_process_pcm_frames(&pConverter->resampler, pResampleBufferIn, &frameCountInThisIteration, pTempBufferMid, &frameCountOutThisIteration);
if (result != MA_SUCCESS) {
return result;
}
/*
The input data has been resampled so now we need to run it through the channel converter. The input data is always contained in pTempBufferMid. We only need to do
this part if we have an output buffer.
*/
if (pFramesOut != NULL) {
if (pConverter->hasPostFormatConversion) {
pChannelsBufferOut = pTempBufferOut;
} else {
pChannelsBufferOut = pRunningFramesOut;
}
result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pChannelsBufferOut, pTempBufferMid, frameCountOutThisIteration);
if (result != MA_SUCCESS) {
return result;
}
/* Finally we do post format conversion. */
if (pConverter->hasPostFormatConversion) {
ma_convert_pcm_frames_format(pRunningFramesOut, pConverter->config.formatOut, pChannelsBufferOut, pConverter->channelConverter.format, frameCountOutThisIteration, pConverter->channelConverter.channelsOut, pConverter->config.ditherMode...
}
}
framesProcessedIn += frameCountInThisIteration;
framesProcessedOut += frameCountOutThisIteration;
MA_ASSERT(framesProcessedIn <= frameCountIn);
MA_ASSERT(framesProcessedOut <= frameCountOut);
if (frameCountOutThisIteration == 0) {
break; /* Consumed all of our input data. */
}
}
if (pFrameCountIn != NULL) {
*pFrameCountIn = framesProcessedIn;
}
if (pFrameCountOut != NULL) {
*pFrameCountOut = framesProcessedOut;
}
return MA_SUCCESS;
}
static ma_result ma_data_converter_process_pcm_frames__channels_first(ma_data_converter* pConverter, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
{
ma_result result;
ma_uint64 frameCountIn;
ma_uint64 frameCountOut;
ma_uint64 framesProcessedIn;
ma_uint64 framesProcessedOut;
ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format. */
ma_uint64 tempBufferInCap;
ma_uint8 pTempBufferMid[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format, channel converter input format. */
ma_uint64 tempBufferMidCap;
ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In channel converter output format. */
ma_uint64 tempBufferOutCap;
MA_ASSERT(pConverter != NULL);
MA_ASSERT(pConverter->resampler.config.format == pConverter->channelConverter.format);
MA_ASSERT(pConverter->resampler.config.channels == pConverter->channelConverter.channelsOut);
MA_ASSERT(pConverter->resampler.config.channels < pConverter->channelConverter.channelsIn);
frameCountIn = 0;
if (pFrameCountIn != NULL) {
frameCountIn = *pFrameCountIn;
}
frameCountOut = 0;
if (pFrameCountOut != NULL) {
frameCountOut = *pFrameCountOut;
}
framesProcessedIn = 0;
framesProcessedOut = 0;
tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsIn);
tempBufferMidCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut);
tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->resampler.config.format, pConverter->resampler.config.channels);
while (framesProcessedOut < frameCountOut) {
ma_uint64 frameCountInThisIteration;
ma_uint64 frameCountOutThisIteration;
const void* pRunningFramesIn = NULL;
void* pRunningFramesOut = NULL;
const void* pChannelsBufferIn;
void* pResampleBufferOut;
if (pFramesIn != NULL) {
pRunningFramesIn = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->config.formatIn, pConverter->config.channelsIn));
}
if (pFramesOut != NULL) {
pRunningFramesOut = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->config.formatOut, pConverter->config.channelsOut));
}
/* Run input data through the channel converter and output it to the temporary buffer. */
frameCountInThisIteration = (frameCountIn - framesProcessedIn);
if (pConverter->hasPreFormatConversion) {
if (frameCountInThisIteration > tempBufferInCap) {
frameCountInThisIteration = tempBufferInCap;
}
if (pRunningFramesIn != NULL) {
ma_convert_pcm_frames_format(pTempBufferIn, pConverter->channelConverter.format, pRunningFramesIn, pConverter->config.formatIn, frameCountInThisIteration, pConverter->config.channelsIn, pConverter->config.ditherMode);
pChannelsBufferIn = pTempBufferIn;
} else {
pChannelsBufferIn = NULL;
}
} else {
pChannelsBufferIn = pRunningFramesIn;
}
/*
We can't convert more frames than will fit in the output buffer. We shouldn't actually need to do this check because the channel count is always reduced
in this case which means we should always have capacity, but I'm leaving it here just for safety for future maintenance.
*/
if (frameCountInThisIteration > tempBufferMidCap) {
frameCountInThisIteration = tempBufferMidCap;
}
/*
Make sure we don't read any more input frames than we need to fill the output frame count. If we do this we will end up in a situation where we lose some
input samples and will end up glitching.
*/
frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
if (frameCountOutThisIteration > tempBufferMidCap) {
frameCountOutThisIteration = tempBufferMidCap;
}
if (pConverter->hasPostFormatConversion) {
ma_uint64 requiredInputFrameCount;
if (frameCountOutThisIteration > tempBufferOutCap) {
frameCountOutThisIteration = tempBufferOutCap;
}
requiredInputFrameCount = ma_resampler_get_required_input_frame_count(&pConverter->resampler, frameCountOutThisIteration);
if (frameCountInThisIteration > requiredInputFrameCount) {
frameCountInThisIteration = requiredInputFrameCount;
}
}
result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferMid, pChannelsBufferIn, frameCountInThisIteration);
if (result != MA_SUCCESS) {
return result;
}
/* At this point we have converted the channels to the output channel count which we now need to resample. */
if (pConverter->hasPostFormatConversion) {
pResampleBufferOut = pTempBufferOut;
} else {
pResampleBufferOut = pRunningFramesOut;
}
result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferMid, &frameCountInThisIteration, pResampleBufferOut, &frameCountOutThisIteration);
if (result != MA_SUCCESS) {
return result;
}
/* Finally we can do the post format conversion. */
if (pConverter->hasPostFormatConversion) {
if (pRunningFramesOut != NULL) {
ma_convert_pcm_frames_format(pRunningFramesOut, pConverter->config.formatOut, pResampleBufferOut, pConverter->resampler.config.format, frameCountOutThisIteration, pConverter->config.channelsOut, pConverter->config.ditherMode);
}
}
framesProcessedIn += frameCountInThisIteration;
framesProcessedOut += frameCountOutThisIteration;
MA_ASSERT(framesProcessedIn <= frameCountIn);
MA_ASSERT(framesProcessedOut <= frameCountOut);
if (frameCountOutThisIteration == 0) {
break; /* Consumed all of our input data. */
}
}
if (pFrameCountIn != NULL) {
*pFrameCountIn = framesProcessedIn;
}
if (pFrameCountOut != NULL) {
*pFrameCountOut = framesProcessedOut;
}
return MA_SUCCESS;
}
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)
{
if (pConverter == NULL) {
return MA_INVALID_ARGS;
}
if (pConverter->isPassthrough) {
return ma_data_converter_process_pcm_frames__passthrough(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
}
/*
Here is where the real work is done. Getting here means we're not using a passthrough and we need to move the data through each of the relevant stages. The order
of our stages depends on the input and output channel count. If the input channels is less than the output channels we want to do sample rate conversion first so
that it has less work (resampling is the most expensive part of format conversion).
*/
if (pConverter->config.channelsIn < pConverter->config.channelsOut) {
/* Do resampling first, if necessary. */
MA_ASSERT(pConverter->hasChannelConverter == MA_TRUE);
if (pConverter->hasResampler) {
/* Resampling first. */
return ma_data_converter_process_pcm_frames__resampling_first(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
} else {
/* Resampling not required. */
return ma_data_converter_process_pcm_frames__channels_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
}
} else {
/* Do channel conversion first, if necessary. */
if (pConverter->hasChannelConverter) {
if (pConverter->hasResampler) {
/* Channel routing first. */
return ma_data_converter_process_pcm_frames__channels_first(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
} else {
/* Resampling not required. */
return ma_data_converter_process_pcm_frames__channels_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
}
} else {
/* Channel routing not required. */
if (pConverter->hasResampler) {
/* Resampling only. */
return ma_data_converter_process_pcm_frames__resample_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
} else {
/* No channel routing nor resampling required. Just format conversion. */
return ma_data_converter_process_pcm_frames__format_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
}
}
}
}
MA_API ma_result ma_data_converter_set_rate(ma_data_converter* pConverter, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
{
if (pConverter == NULL) {
return MA_INVALID_ARGS;
}
if (pConverter->hasResampler == MA_FALSE) {
return MA_INVALID_OPERATION; /* Dynamic resampling not enabled. */
}
return ma_resampler_set_rate(&pConverter->resampler, sampleRateIn, sampleRateOut);
}
MA_API ma_result ma_data_converter_set_rate_ratio(ma_data_converter* pConverter, float ratioInOut)
{
if (pConverter == NULL) {
return MA_INVALID_ARGS;
}
if (pConverter->hasResampler == MA_FALSE) {
return MA_INVALID_OPERATION; /* Dynamic resampling not enabled. */
}
return ma_resampler_set_rate_ratio(&pConverter->resampler, ratioInOut);
}
MA_API ma_uint64 ma_data_converter_get_required_input_frame_count(ma_data_converter* pConverter, ma_uint64 outputFrameCount)
{
if (pConverter == NULL) {
return 0;
}
if (pConverter->hasResampler) {
return ma_resampler_get_required_input_frame_count(&pConverter->resampler, outputFrameCount);
} else {
return outputFrameCount; /* 1:1 */
}
}
MA_API ma_uint64 ma_data_converter_get_expected_output_frame_count(ma_data_converter* pConverter, ma_uint64 inputFrameCount)
{
if (pConverter == NULL) {
return 0;
}
if (pConverter->hasResampler) {
return ma_resampler_get_expected_output_frame_count(&pConverter->resampler, inputFrameCount);
} else {
return inputFrameCount; /* 1:1 */
}
}
MA_API ma_uint64 ma_data_converter_get_input_latency(ma_data_converter* pConverter)
{
if (pConverter == NULL) {
return 0;
}
if (pConverter->hasResampler) {
return ma_resampler_get_input_latency(&pConverter->resampler);
}
return 0; /* No latency without a resampler. */
}
MA_API ma_uint64 ma_data_converter_get_output_latency(ma_data_converter* pConverter)
{
if (pConverter == NULL) {
return 0;
}
if (pConverter->hasResampler) {
return ma_resampler_get_output_latency(&pConverter->resampler);
}
return 0; /* No latency without a resampler. */
}
/**************************************************************************************************************************************************************
Channel Maps
**************************************************************************************************************************************************************/
static void ma_get_standard_channel_map_microsoft(ma_uint32 channels, ma_channel* pChannelMap)
{
/* Based off the speaker configurations mentioned here: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ksmedia/ns-ksmedia-ksaudio_channel_config */
switch (channels)
{
case 1:
{
pChannelMap[0] = MA_CHANNEL_MONO;
} break;
case 2:
{
pChannelMap[0] = MA_CHANNEL_FRONT_LEFT;
pChannelMap[1] = MA_CHANNEL_FRONT_RIGHT;
} break;
case 3: /* Not defined, but best guess. */
{
pChannelMap[0] = MA_CHANNEL_FRONT_LEFT;
pChannelMap[1] = MA_CHANNEL_FRONT_RIGHT;
pChannelMap[2] = MA_CHANNEL_FRONT_CENTER;
} break;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
for (iChannel = 0; iChannel < channels; ++iChannel) {
if (pChannelMap[iChannel] == MA_CHANNEL_MONO) {
return MA_FALSE;
}
}
}
return MA_TRUE;
}
MA_API ma_bool32 ma_channel_map_equal(ma_uint32 channels, const ma_channel* pChannelMapA, const ma_channel* pChannelMapB)
{
ma_uint32 iChannel;
if (pChannelMapA == pChannelMapB) {
return MA_TRUE;
}
for (iChannel = 0; iChannel < channels; ++iChannel) {
if (pChannelMapA[iChannel] != pChannelMapB[iChannel]) {
return MA_FALSE;
}
}
return MA_TRUE;
}
MA_API ma_bool32 ma_channel_map_blank(ma_uint32 channels, const ma_channel* pChannelMap)
{
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; ++iChannel) {
if (pChannelMap[iChannel] != MA_CHANNEL_NONE) {
return MA_FALSE;
}
}
return MA_TRUE;
}
MA_API ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition)
{
ma_uint32 iChannel;
for (iChannel = 0; iChannel < channels; ++iChannel) {
if (pChannelMap[iChannel] == channelPosition) {
return MA_TRUE;
}
}
return MA_FALSE;
}
/**************************************************************************************************************************************************************
Conversion Helpers
**************************************************************************************************************************************************************/
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_data_converter_config config;
config = ma_data_converter_config_init(formatIn, formatOut, channelsIn, channelsOut, sampleRateIn, sampleRateOut);
ma_get_standard_channel_map(ma_standard_channel_map_default, channelsOut, config.channelMapOut);
ma_get_standard_channel_map(ma_standard_channel_map_default, channelsIn, config.channelMapIn);
config.resampling.linear.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
return ma_convert_frames_ex(pOut, frameCountOut, pIn, frameCountIn, &config);
}
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)
{
ma_result result;
ma_data_converter converter;
if (frameCountIn == 0 || pConfig == NULL) {
return 0;
}
result = ma_data_converter_init(pConfig, &converter);
if (result != MA_SUCCESS) {
return 0; /* Failed to initialize the data converter. */
}
if (pOut == NULL) {
frameCountOut = ma_data_converter_get_expected_output_frame_count(&converter, frameCountIn);
} else {
result = ma_data_converter_process_pcm_frames(&converter, pIn, &frameCountIn, pOut, &frameCountOut);
if (result != MA_SUCCESS) {
frameCountOut = 0;
}
}
ma_data_converter_uninit(&converter);
return frameCountOut;
}
/**************************************************************************************************************************************************************
Ring Buffer
**************************************************************************************************************************************************************/
static MA_INLINE ma_uint32 ma_rb__extract_offset_in_bytes(ma_uint32 encodedOffset)
{
return encodedOffset & 0x7FFFFFFF;
}
static MA_INLINE ma_uint32 ma_rb__extract_offset_loop_flag(ma_uint32 encodedOffset)
{
return encodedOffset & 0x80000000;
}
static MA_INLINE void* ma_rb__get_read_ptr(ma_rb* pRB)
{
MA_ASSERT(pRB != NULL);
return ma_offset_ptr(pRB->pBuffer, ma_rb__extract_offset_in_bytes(pRB->encodedReadOffset));
}
static MA_INLINE void* ma_rb__get_write_ptr(ma_rb* pRB)
{
MA_ASSERT(pRB != NULL);
return ma_offset_ptr(pRB->pBuffer, ma_rb__extract_offset_in_bytes(pRB->encodedWriteOffset));
}
static MA_INLINE ma_uint32 ma_rb__construct_offset(ma_uint32 offsetInBytes, ma_uint32 offsetLoopFlag)
{
return offsetLoopFlag | offsetInBytes;
}
static MA_INLINE void ma_rb__deconstruct_offset(ma_uint32 encodedOffset, ma_uint32* pOffsetInBytes, ma_uint32* pOffsetLoopFlag)
{
MA_ASSERT(pOffsetInBytes != NULL);
MA_ASSERT(pOffsetLoopFlag != NULL);
*pOffsetInBytes = ma_rb__extract_offset_in_bytes(encodedOffset);
*pOffsetLoopFlag = ma_rb__extract_offset_loop_flag(encodedOffset);
}
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_result result;
const ma_uint32 maxSubBufferSize = 0x7FFFFFFF - (MA_SIMD_ALIGNMENT-1);
if (pRB == NULL) {
return MA_INVALID_ARGS;
}
if (subbufferSizeInBytes == 0 || subbufferCount == 0) {
return MA_INVALID_ARGS;
}
if (subbufferSizeInBytes > maxSubBufferSize) {
return MA_INVALID_ARGS; /* Maximum buffer size is ~2GB. The most significant bit is a flag for use internally. */
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
return 0;
}
return dist;
}
MA_API ma_uint32 ma_rb_available_write(ma_rb* pRB)
{
if (pRB == NULL) {
return 0;
}
return (ma_uint32)(ma_rb_get_subbuffer_size(pRB) - ma_rb_pointer_distance(pRB));
}
MA_API size_t ma_rb_get_subbuffer_size(ma_rb* pRB)
{
if (pRB == NULL) {
return 0;
}
return pRB->subbufferSizeInBytes;
}
MA_API size_t ma_rb_get_subbuffer_stride(ma_rb* pRB)
{
if (pRB == NULL) {
return 0;
}
if (pRB->subbufferStrideInBytes == 0) {
return (size_t)pRB->subbufferSizeInBytes;
}
return (size_t)pRB->subbufferStrideInBytes;
}
MA_API size_t ma_rb_get_subbuffer_offset(ma_rb* pRB, size_t subbufferIndex)
{
if (pRB == NULL) {
return 0;
}
return subbufferIndex * ma_rb_get_subbuffer_stride(pRB);
}
MA_API void* ma_rb_get_subbuffer_ptr(ma_rb* pRB, size_t subbufferIndex, void* pBuffer)
{
if (pRB == NULL) {
return NULL;
}
return ma_offset_ptr(pBuffer, ma_rb_get_subbuffer_offset(pRB, subbufferIndex));
}
static MA_INLINE ma_uint32 ma_pcm_rb_get_bpf(ma_pcm_rb* pRB)
{
MA_ASSERT(pRB != NULL);
return ma_get_bytes_per_frame(pRB->format, pRB->channels);
}
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* pAllocationCallba...
{
ma_uint32 bpf;
ma_result result;
if (pRB == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pRB);
bpf = ma_get_bytes_per_frame(format, channels);
if (bpf == 0) {
return MA_INVALID_ARGS;
}
result = ma_rb_init_ex(subbufferSizeInFrames*bpf, subbufferCount, subbufferStrideInFrames*bpf, pOptionalPreallocatedBuffer, pAllocationCallbacks, &pRB->rb);
if (result != MA_SUCCESS) {
return result;
}
pRB->format = format;
pRB->channels = channels;
return MA_SUCCESS;
}
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)
{
return ma_pcm_rb_init_ex(format, channels, bufferSizeInFrames, 1, 0, pOptionalPreallocatedBuffer, pAllocationCallbacks, pRB);
}
MA_API void ma_pcm_rb_uninit(ma_pcm_rb* pRB)
{
if (pRB == NULL) {
return;
}
ma_rb_uninit(&pRB->rb);
}
MA_API void ma_pcm_rb_reset(ma_pcm_rb* pRB)
{
if (pRB == NULL) {
return;
}
ma_rb_reset(&pRB->rb);
}
MA_API ma_result ma_pcm_rb_acquire_read(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut)
{
size_t sizeInBytes;
ma_result result;
if (pRB == NULL || pSizeInFrames == NULL) {
return MA_INVALID_ARGS;
}
sizeInBytes = *pSizeInFrames * ma_pcm_rb_get_bpf(pRB);
result = ma_rb_acquire_read(&pRB->rb, &sizeInBytes, ppBufferOut);
if (result != MA_SUCCESS) {
return result;
}
*pSizeInFrames = (ma_uint32)(sizeInBytes / (size_t)ma_pcm_rb_get_bpf(pRB));
return MA_SUCCESS;
}
MA_API ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames, void* pBufferOut)
{
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
if (alignment == 0) {
return 0;
}
extraBytes = alignment-1 + sizeof(void*);
pUnaligned = ma_malloc(sz + extraBytes, pAllocationCallbacks);
if (pUnaligned == NULL) {
return NULL;
}
pAligned = (void*)(((ma_uintptr)pUnaligned + extraBytes) & ~((ma_uintptr)(alignment-1)));
((void**)pAligned)[-1] = pUnaligned;
return pAligned;
}
MA_API void ma_aligned_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
{
ma_free(((void**)p)[-1], pAllocationCallbacks);
}
MA_API const char* ma_get_format_name(ma_format format)
{
switch (format)
{
case ma_format_unknown: return "Unknown";
case ma_format_u8: return "8-bit Unsigned Integer";
case ma_format_s16: return "16-bit Signed Integer";
case ma_format_s24: return "24-bit Signed Integer (Tightly Packed)";
case ma_format_s32: return "32-bit Signed Integer";
case ma_format_f32: return "32-bit IEEE Floating Point";
default: return "Invalid";
}
}
MA_API void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels)
{
ma_uint32 i;
for (i = 0; i < channels; ++i) {
pOut[i] = ma_mix_f32(pInA[i], pInB[i], factor);
}
}
MA_API ma_uint32 ma_get_bytes_per_sample(ma_format format)
{
ma_uint32 sizes[] = {
0, /* unknown */
1, /* u8 */
2, /* s16 */
3, /* s24 */
4, /* s32 */
4, /* f32 */
};
return sizes[format];
}
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)
{
ma_data_source_callbacks* pCallbacks = (ma_data_source_callbacks*)pDataSource;
if (pCallbacks == NULL) {
return MA_INVALID_ARGS;
}
if (pCallbacks->onRead == NULL) {
return MA_NOT_IMPLEMENTED;
}
/* A very small optimization for the non looping case. */
if (loop == MA_FALSE) {
return pCallbacks->onRead(pDataSource, pFramesOut, frameCount, pFramesRead);
} else {
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
if (ma_data_source_get_data_format(pDataSource, &format, &channels, &sampleRate) != MA_SUCCESS) {
return pCallbacks->onRead(pDataSource, pFramesOut, frameCount, pFramesRead); /* We don't have a way to retrieve the data format which means we don't know how to offset the output buffer. Just read as much as we can. */
} else {
ma_result result = MA_SUCCESS;
ma_uint64 totalFramesProcessed;
void* pRunningFramesOut = pFramesOut;
totalFramesProcessed = 0;
while (totalFramesProcessed < frameCount) {
ma_uint64 framesProcessed;
ma_uint64 framesRemaining = frameCount - totalFramesProcessed;
result = pCallbacks->onRead(pDataSource, pRunningFramesOut, framesRemaining, &framesProcessed);
totalFramesProcessed += framesProcessed;
/*
If we encounted an error from the read callback, make sure it's propagated to the caller. The caller may need to know whether or not MA_BUSY is returned which is
not necessarily considered an error.
*/
if (result != MA_SUCCESS && result != MA_AT_END) {
break;
}
/*
We can determine if we've reached the end by checking the return value of the onRead() callback. If it's less than what we requested it means
we've reached the end. To loop back to the start, all we need to do is seek back to the first frame.
*/
if (framesProcessed < framesRemaining || result == MA_AT_END) {
if (ma_data_source_seek_to_pcm_frame(pDataSource, 0) != MA_SUCCESS) {
break;
}
}
if (pRunningFramesOut != NULL) {
pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesProcessed * ma_get_bytes_per_frame(format, channels));
}
}
if (pFramesRead != NULL) {
*pFramesRead = totalFramesProcessed;
}
return result;
}
}
}
MA_API ma_result ma_data_source_seek_pcm_frames(ma_data_source* pDataSource, ma_uint64 frameCount, ma_uint64* pFramesSeeked, ma_bool32 loop)
{
return ma_data_source_read_pcm_frames(pDataSource, NULL, frameCount, pFramesSeeked, loop);
}
MA_API ma_result ma_data_source_seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex)
{
ma_data_source_callbacks* pCallbacks = (ma_data_source_callbacks*)pDataSource;
if (pCallbacks == NULL || pCallbacks->onSeek == NULL) {
return MA_INVALID_ARGS;
}
return pCallbacks->onSeek(pDataSource, frameIndex);
}
MA_API ma_result ma_data_source_map(ma_data_source* pDataSource, void** ppFramesOut, ma_uint64* pFrameCount)
{
ma_data_source_callbacks* pCallbacks = (ma_data_source_callbacks*)pDataSource;
if (pCallbacks == NULL || pCallbacks->onMap == NULL) {
return MA_INVALID_ARGS;
}
return pCallbacks->onMap(pDataSource, ppFramesOut, pFrameCount);
}
MA_API ma_result ma_data_source_unmap(ma_data_source* pDataSource, ma_uint64 frameCount)
{
ma_data_source_callbacks* pCallbacks = (ma_data_source_callbacks*)pDataSource;
if (pCallbacks == NULL || pCallbacks->onUnmap == NULL) {
return MA_INVALID_ARGS;
}
return pCallbacks->onUnmap(pDataSource, frameCount);
}
MA_API ma_result ma_data_source_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate)
{
ma_result result;
ma_format format;
ma_uint32 channels;
ma_uint32 sampleRate;
ma_data_source_callbacks* pCallbacks = (ma_data_source_callbacks*)pDataSource;
if (pCallbacks == NULL || pCallbacks->onGetDataFormat == NULL) {
return MA_INVALID_ARGS;
}
result = pCallbacks->onGetDataFormat(pDataSource, &format, &channels, &sampleRate);
if (result != MA_SUCCESS) {
return result;
}
if (pFormat != NULL) {
*pFormat = format;
}
if (pChannels != NULL) {
*pChannels = channels;
}
if (pSampleRate != NULL) {
*pSampleRate = sampleRate;
}
return MA_SUCCESS;
}
MA_API ma_result ma_data_source_get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor)
{
ma_data_source_callbacks* pCallbacks = (ma_data_source_callbacks*)pDataSource;
if (pCursor == NULL) {
return MA_INVALID_ARGS;
}
*pCursor = 0;
if (pCallbacks == NULL) {
return MA_INVALID_ARGS;
}
if (pCallbacks->onGetCursor == NULL) {
return MA_NOT_IMPLEMENTED;
}
return pCallbacks->onGetCursor(pDataSource, pCursor);
}
MA_API ma_result ma_data_source_get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength)
{
ma_data_source_callbacks* pCallbacks = (ma_data_source_callbacks*)pDataSource;
if (pLength == NULL) {
return MA_INVALID_ARGS;
}
*pLength = 0;
if (pCallbacks == NULL) {
return MA_INVALID_ARGS;
}
if (pCallbacks->onGetLength == NULL) {
return MA_NOT_IMPLEMENTED;
}
return pCallbacks->onGetLength(pDataSource, pLength);
}
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)
{
ma_audio_buffer_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sizeInFrames = sizeInFrames;
config.pData = pData;
ma_allocation_callbacks_init_copy(&config.allocationCallbacks, pAllocationCallbacks);
return config;
}
static ma_result ma_audio_buffer__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
{
ma_uint64 framesRead = ma_audio_buffer_read_pcm_frames((ma_audio_buffer*)pDataSource, pFramesOut, frameCount, MA_FALSE);
if (pFramesRead != NULL) {
*pFramesRead = framesRead;
}
if (framesRead < frameCount) {
return MA_AT_END;
}
return MA_SUCCESS;
}
static ma_result ma_audio_buffer__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
{
return ma_audio_buffer_seek_to_pcm_frame((ma_audio_buffer*)pDataSource, frameIndex);
}
static ma_result ma_audio_buffer__data_source_on_map(ma_data_source* pDataSource, void** ppFramesOut, ma_uint64* pFrameCount)
{
return ma_audio_buffer_map((ma_audio_buffer*)pDataSource, ppFramesOut, pFrameCount);
}
static ma_result ma_audio_buffer__data_source_on_unmap(ma_data_source* pDataSource, ma_uint64 frameCount)
{
return ma_audio_buffer_unmap((ma_audio_buffer*)pDataSource, frameCount);
}
static ma_result ma_audio_buffer__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate)
{
ma_audio_buffer* pAudioBuffer = (ma_audio_buffer*)pDataSource;
*pFormat = pAudioBuffer->format;
*pChannels = pAudioBuffer->channels;
*pSampleRate = 0; /* There is no notion of a sample rate with audio buffers. */
return MA_SUCCESS;
}
static ma_result ma_audio_buffer__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
{
ma_audio_buffer* pAudioBuffer = (ma_audio_buffer*)pDataSource;
*pCursor = pAudioBuffer->cursor;
return MA_SUCCESS;
}
static ma_result ma_audio_buffer__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
{
ma_audio_buffer* pAudioBuffer = (ma_audio_buffer*)pDataSource;
*pLength = pAudioBuffer->sizeInFrames;
return MA_SUCCESS;
}
static ma_result ma_audio_buffer_init_ex(const ma_audio_buffer_config* pConfig, ma_bool32 doCopy, ma_audio_buffer* pAudioBuffer)
{
if (pAudioBuffer == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_MEMORY(pAudioBuffer, sizeof(*pAudioBuffer) - sizeof(pAudioBuffer->_pExtraData)); /* Safety. Don't overwrite the extra data. */
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
if (pConfig->sizeInFrames == 0) {
return MA_INVALID_ARGS; /* Not allowing buffer sizes of 0 frames. */
}
pAudioBuffer->ds.onRead = ma_audio_buffer__data_source_on_read;
pAudioBuffer->ds.onSeek = ma_audio_buffer__data_source_on_seek;
pAudioBuffer->ds.onMap = ma_audio_buffer__data_source_on_map;
pAudioBuffer->ds.onUnmap = ma_audio_buffer__data_source_on_unmap;
pAudioBuffer->ds.onGetDataFormat = ma_audio_buffer__data_source_on_get_data_format;
pAudioBuffer->ds.onGetCursor = ma_audio_buffer__data_source_on_get_cursor;
pAudioBuffer->ds.onGetLength = ma_audio_buffer__data_source_on_get_length;
pAudioBuffer->format = pConfig->format;
pAudioBuffer->channels = pConfig->channels;
pAudioBuffer->cursor = 0;
pAudioBuffer->sizeInFrames = pConfig->sizeInFrames;
pAudioBuffer->pData = NULL; /* Set properly later. */
ma_allocation_callbacks_init_copy(&pAudioBuffer->allocationCallbacks, &pConfig->allocationCallbacks);
if (doCopy) {
ma_uint64 allocationSizeInBytes;
void* pData;
allocationSizeInBytes = pAudioBuffer->sizeInFrames * ma_get_bytes_per_frame(pAudioBuffer->format, pAudioBuffer->channels);
if (allocationSizeInBytes > MA_SIZE_MAX) {
return MA_OUT_OF_MEMORY; /* Too big. */
}
pData = ma__malloc_from_callbacks((size_t)allocationSizeInBytes, &pAudioBuffer->allocationCallbacks); /* Safe cast to size_t. */
if (pData == NULL) {
return MA_OUT_OF_MEMORY;
}
if (pConfig->pData != NULL) {
ma_copy_pcm_frames(pData, pConfig->pData, pAudioBuffer->sizeInFrames, pAudioBuffer->format, pAudioBuffer->channels);
} else {
ma_silence_pcm_frames(pData, pAudioBuffer->sizeInFrames, pAudioBuffer->format, pAudioBuffer->channels);
}
pAudioBuffer->pData = pData;
pAudioBuffer->ownsData = MA_TRUE;
} else {
pAudioBuffer->pData = pConfig->pData;
pAudioBuffer->ownsData = MA_FALSE;
}
return MA_SUCCESS;
}
static void ma_audio_buffer_uninit_ex(ma_audio_buffer* pAudioBuffer, ma_bool32 doFree)
{
if (pAudioBuffer == NULL) {
return;
}
if (pAudioBuffer->ownsData && pAudioBuffer->pData != &pAudioBuffer->_pExtraData[0]) {
ma__free_from_callbacks((void*)pAudioBuffer->pData, &pAudioBuffer->allocationCallbacks); /* Naugty const cast, but OK in this case since we've guarded it with the ownsData check. */
}
if (doFree) {
ma_allocation_callbacks allocationCallbacks = pAudioBuffer->allocationCallbacks;
ma__free_from_callbacks(pAudioBuffer, &allocationCallbacks);
}
}
MA_API ma_result ma_audio_buffer_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer)
{
return ma_audio_buffer_init_ex(pConfig, MA_FALSE, pAudioBuffer);
}
MA_API ma_result ma_audio_buffer_init_copy(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer)
{
return ma_audio_buffer_init_ex(pConfig, MA_TRUE, pAudioBuffer);
}
MA_API ma_result ma_audio_buffer_alloc_and_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer** ppAudioBuffer)
{
ma_result result;
ma_audio_buffer* pAudioBuffer;
ma_audio_buffer_config innerConfig; /* We'll be making some changes to the config, so need to make a copy. */
ma_uint64 allocationSizeInBytes;
if (ppAudioBuffer == NULL) {
return MA_INVALID_ARGS;
}
*ppAudioBuffer = NULL; /* Safety. */
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
innerConfig = *pConfig;
ma_allocation_callbacks_init_copy(&innerConfig.allocationCallbacks, &pConfig->allocationCallbacks);
allocationSizeInBytes = sizeof(*pAudioBuffer) - sizeof(pAudioBuffer->_pExtraData) + (pConfig->sizeInFrames * ma_get_bytes_per_frame(pConfig->format, pConfig->channels));
if (allocationSizeInBytes > MA_SIZE_MAX) {
return MA_OUT_OF_MEMORY; /* Too big. */
}
pAudioBuffer = (ma_audio_buffer*)ma__malloc_from_callbacks((size_t)allocationSizeInBytes, &innerConfig.allocationCallbacks); /* Safe cast to size_t. */
if (pAudioBuffer == NULL) {
return MA_OUT_OF_MEMORY;
}
if (pConfig->pData != NULL) {
ma_copy_pcm_frames(&pAudioBuffer->_pExtraData[0], pConfig->pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels);
} else {
ma_silence_pcm_frames(&pAudioBuffer->_pExtraData[0], pConfig->sizeInFrames, pConfig->format, pConfig->channels);
}
innerConfig.pData = &pAudioBuffer->_pExtraData[0];
result = ma_audio_buffer_init_ex(&innerConfig, MA_FALSE, pAudioBuffer);
if (result != MA_SUCCESS) {
ma__free_from_callbacks(pAudioBuffer, &innerConfig.allocationCallbacks);
return result;
}
*ppAudioBuffer = pAudioBuffer;
return MA_SUCCESS;
}
MA_API void ma_audio_buffer_uninit(ma_audio_buffer* pAudioBuffer)
{
ma_audio_buffer_uninit_ex(pAudioBuffer, MA_FALSE);
}
MA_API void ma_audio_buffer_uninit_and_free(ma_audio_buffer* pAudioBuffer)
{
ma_audio_buffer_uninit_ex(pAudioBuffer, MA_TRUE);
}
MA_API ma_uint64 ma_audio_buffer_read_pcm_frames(ma_audio_buffer* pAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop)
{
ma_uint64 totalFramesRead = 0;
if (pAudioBuffer == NULL) {
return 0;
}
if (frameCount == 0) {
return 0;
}
while (totalFramesRead < frameCount) {
ma_uint64 framesAvailable = pAudioBuffer->sizeInFrames - pAudioBuffer->cursor;
ma_uint64 framesRemaining = frameCount - totalFramesRead;
ma_uint64 framesToRead;
framesToRead = framesRemaining;
if (framesToRead > framesAvailable) {
framesToRead = framesAvailable;
}
if (pFramesOut != NULL) {
ma_copy_pcm_frames(pFramesOut, ma_offset_ptr(pAudioBuffer->pData, pAudioBuffer->cursor * ma_get_bytes_per_frame(pAudioBuffer->format, pAudioBuffer->channels)), frameCount, pAudioBuffer->format, pAudioBuffer->channels);
}
totalFramesRead += framesToRead;
pAudioBuffer->cursor += framesToRead;
if (pAudioBuffer->cursor == pAudioBuffer->sizeInFrames) {
if (loop) {
pAudioBuffer->cursor = 0;
} else {
break; /* We've reached the end and we're not looping. Done. */
}
}
MA_ASSERT(pAudioBuffer->cursor < pAudioBuffer->sizeInFrames);
}
return totalFramesRead;
}
MA_API ma_result ma_audio_buffer_seek_to_pcm_frame(ma_audio_buffer* pAudioBuffer, ma_uint64 frameIndex)
{
if (pAudioBuffer == NULL) {
return MA_INVALID_ARGS;
}
if (frameIndex > pAudioBuffer->sizeInFrames) {
return MA_INVALID_ARGS;
}
pAudioBuffer->cursor = (size_t)frameIndex;
return MA_SUCCESS;
}
MA_API ma_result ma_audio_buffer_map(ma_audio_buffer* pAudioBuffer, void** ppFramesOut, ma_uint64* pFrameCount)
{
ma_uint64 framesAvailable;
ma_uint64 frameCount = 0;
if (ppFramesOut != NULL) {
*ppFramesOut = NULL; /* Safety. */
}
if (pFrameCount != NULL) {
frameCount = *pFrameCount;
*pFrameCount = 0; /* Safety. */
}
if (pAudioBuffer == NULL || ppFramesOut == NULL || pFrameCount == NULL) {
return MA_INVALID_ARGS;
}
framesAvailable = pAudioBuffer->sizeInFrames - pAudioBuffer->cursor;
if (frameCount > framesAvailable) {
frameCount = framesAvailable;
}
*ppFramesOut = ma_offset_ptr(pAudioBuffer->pData, pAudioBuffer->cursor * ma_get_bytes_per_frame(pAudioBuffer->format, pAudioBuffer->channels));
*pFrameCount = frameCount;
return MA_SUCCESS;
}
MA_API ma_result ma_audio_buffer_unmap(ma_audio_buffer* pAudioBuffer, ma_uint64 frameCount)
{
ma_uint64 framesAvailable;
if (pAudioBuffer == NULL) {
return MA_INVALID_ARGS;
}
framesAvailable = pAudioBuffer->sizeInFrames - pAudioBuffer->cursor;
if (frameCount > framesAvailable) {
return MA_INVALID_ARGS; /* The frame count was too big. This should never happen in an unmapping. Need to make sure the caller is aware of this. */
}
pAudioBuffer->cursor += frameCount;
if (pAudioBuffer->cursor == pAudioBuffer->sizeInFrames) {
return MA_AT_END; /* Successful. Need to tell the caller that the end has been reached so that it can loop if desired. */
} else {
return MA_SUCCESS;
}
}
MA_API ma_result ma_audio_buffer_at_end(ma_audio_buffer* pAudioBuffer)
{
if (pAudioBuffer == NULL) {
return MA_FALSE;
}
return pAudioBuffer->cursor == pAudioBuffer->sizeInFrames;
}
MA_API ma_result ma_audio_buffer_get_available_frames(ma_audio_buffer* pAudioBuffer, ma_uint64* pAvailableFrames)
{
if (pAvailableFrames == NULL) {
return MA_INVALID_ARGS;
}
*pAvailableFrames = 0;
if (pAudioBuffer == NULL) {
return MA_INVALID_ARGS;
}
if (pAudioBuffer->sizeInFrames <= pAudioBuffer->cursor) {
*pAvailableFrames = 0;
} else {
*pAvailableFrames = pAudioBuffer->sizeInFrames - pAudioBuffer->cursor;
}
return MA_SUCCESS;
}
/**************************************************************************************************************************************************************
VFS
**************************************************************************************************************************************************************/
MA_API ma_result ma_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
{
ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
if (pFile == NULL) {
return MA_INVALID_ARGS;
}
*pFile = NULL;
if (pVFS == NULL || pFilePath == NULL || openMode == 0) {
return MA_INVALID_ARGS;
}
if (pCallbacks->onOpen == NULL) {
return MA_NOT_IMPLEMENTED;
}
return pCallbacks->onOpen(pVFS, pFilePath, openMode, pFile);
}
MA_API ma_result ma_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
{
ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
if (pFile == NULL) {
return MA_INVALID_ARGS;
}
*pFile = NULL;
if (pVFS == NULL || pFilePath == NULL || openMode == 0) {
return MA_INVALID_ARGS;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
{
drwav_uint32 manufacturer;
drwav_uint32 product;
drwav_uint32 samplePeriod;
drwav_uint32 midiUnityNotes;
drwav_uint32 midiPitchFraction;
drwav_uint32 smpteFormat;
drwav_uint32 smpteOffset;
drwav_uint32 numSampleLoops;
drwav_uint32 samplerData;
drwav_smpl_loop loops[DRWAV_MAX_SMPL_LOOPS];
} drwav_smpl;
typedef struct
{
drwav_read_proc onRead;
drwav_write_proc onWrite;
drwav_seek_proc onSeek;
void* pUserData;
drwav_allocation_callbacks allocationCallbacks;
drwav_container container;
drwav_fmt fmt;
drwav_uint32 sampleRate;
drwav_uint16 channels;
drwav_uint16 bitsPerSample;
drwav_uint16 translatedFormatTag;
drwav_uint64 totalPCMFrameCount;
drwav_uint64 dataChunkDataSize;
drwav_uint64 dataChunkDataPos;
drwav_uint64 bytesRemaining;
drwav_uint64 dataChunkDataSizeTargetWrite;
drwav_bool32 isSequentialWrite;
drwav_smpl smpl;
drwav__memory_stream memoryStream;
drwav__memory_stream_write memoryStreamWrite;
struct
{
drwav_uint64 iCurrentPCMFrame;
} compressed;
struct
{
drwav_uint32 bytesRemainingInBlock;
drwav_uint16 predictor[2];
drwav_int32 delta[2];
drwav_int32 cachedFrames[4];
drwav_uint32 cachedFrameCount;
drwav_int32 prevFrames[2][2];
} msadpcm;
struct
{
drwav_uint32 bytesRemainingInBlock;
drwav_int32 predictor[2];
drwav_int32 stepIndex[2];
drwav_int32 cachedFrames[16];
drwav_uint32 cachedFrameCount;
} ima;
} drwav;
DRWAV_API drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_write(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_write_sequential(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_write_sequential_pcm_frames(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_uint64 drwav_target_write_size_bytes(const drwav_data_format* pFormat, drwav_uint64 totalSampleCount);
DRWAV_API drwav_result drwav_uninit(drwav* pWav);
DRWAV_API size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut);
DRWAV_API drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut);
DRWAV_API drwav_uint64 drwav_read_pcm_frames_le(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut);
DRWAV_API drwav_uint64 drwav_read_pcm_frames_be(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut);
DRWAV_API drwav_bool32 drwav_seek_to_pcm_frame(drwav* pWav, drwav_uint64 targetFrameIndex);
DRWAV_API size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData);
DRWAV_API drwav_uint64 drwav_write_pcm_frames(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
DRWAV_API drwav_uint64 drwav_write_pcm_frames_le(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
DRWAV_API drwav_uint64 drwav_write_pcm_frames_be(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
#ifndef DR_WAV_NO_CONVERSION_API
DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut);
DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16le(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut);
DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16be(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut);
DRWAV_API void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
DRWAV_API void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
DRWAV_API void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCount);
DRWAV_API void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount);
DRWAV_API void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount);
DRWAV_API void drwav_alaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
DRWAV_API void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut);
DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32le(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut);
DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32be(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut);
DRWAV_API void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
DRWAV_API void drwav_s16_to_f32(float* pOut, const drwav_int16* pIn, size_t sampleCount);
DRWAV_API void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
DRWAV_API void drwav_s32_to_f32(float* pOut, const drwav_int32* pIn, size_t sampleCount);
DRWAV_API void drwav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount);
DRWAV_API void drwav_alaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
DRWAV_API void drwav_mulaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut);
DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32le(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut);
DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32be(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut);
DRWAV_API void drwav_u8_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
DRWAV_API void drwav_s16_to_s32(drwav_int32* pOut, const drwav_int16* pIn, size_t sampleCount);
DRWAV_API void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
DRWAV_API void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t sampleCount);
DRWAV_API void drwav_f64_to_s32(drwav_int32* pOut, const double* pIn, size_t sampleCount);
DRWAV_API void drwav_alaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
DRWAV_API void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
#endif
#ifndef DR_WAV_NO_STDIO
DRWAV_API drwav_bool32 drwav_init_file(drwav* pWav, const char* filename, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_file_w(drwav* pWav, const wchar_t* filename, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_file_ex_w(drwav* pWav, const wchar_t* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_file_write(drwav* pWav, const char* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_file_write_sequential(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_file_write_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_file_write_sequential_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks);
#endif
DRWAV_API drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_memory_ex(drwav* pWav, const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_memory_write(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_memory_write_sequential(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_bool32 drwav_init_memory_write_sequential_pcm_frames(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks);
#ifndef DR_WAV_NO_CONVERSION_API
DRWAV_API drwav_int16* drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAl...
DRWAV_API float* drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocati...
DRWAV_API drwav_int32* drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAl...
#ifndef DR_WAV_NO_STDIO
DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
#endif
DRWAV_API drwav_int16* drwav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API float* drwav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_int32* drwav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
#endif
DRWAV_API void drwav_free(void* p, const drwav_allocation_callbacks* pAllocationCallbacks);
DRWAV_API drwav_uint16 drwav_bytes_to_u16(const drwav_uint8* data);
DRWAV_API drwav_int16 drwav_bytes_to_s16(const drwav_uint8* data);
DRWAV_API drwav_uint32 drwav_bytes_to_u32(const drwav_uint8* data);
DRWAV_API drwav_int32 drwav_bytes_to_s32(const drwav_uint8* data);
DRWAV_API drwav_uint64 drwav_bytes_to_u64(const drwav_uint8* data);
DRWAV_API drwav_int64 drwav_bytes_to_s64(const drwav_uint8* data);
DRWAV_API drwav_bool32 drwav_guid_equal(const drwav_uint8 a[16], const drwav_uint8 b[16]);
DRWAV_API drwav_bool32 drwav_fourcc_equal(const drwav_uint8* a, const char* b);
#ifdef __cplusplus
}
#endif
#endif
/* dr_wav_h end */
#endif /* MA_NO_WAV */
#if !defined(MA_NO_FLAC) && !defined(MA_NO_DECODING)
/* dr_flac_h begin */
#ifndef dr_flac_h
#define dr_flac_h
#ifdef __cplusplus
extern "C" {
#endif
#define DRFLAC_STRINGIFY(x) #x
#define DRFLAC_XSTRINGIFY(x) DRFLAC_STRINGIFY(x)
#define DRFLAC_VERSION_MAJOR 0
#define DRFLAC_VERSION_MINOR 12
#define DRFLAC_VERSION_REVISION 20
#define DRFLAC_VERSION_STRING DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MAJOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MINOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_REVISION)
#include <stddef.h>
typedef signed char drflac_int8;
typedef unsigned char drflac_uint8;
typedef signed short drflac_int16;
typedef unsigned short drflac_uint16;
typedef signed int drflac_int32;
typedef unsigned int drflac_uint32;
#if defined(_MSC_VER)
typedef signed __int64 drflac_int64;
typedef unsigned __int64 drflac_uint64;
#else
#if defined(__GNUC__)
#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 drflac_int64;
typedef unsigned long long drflac_uint64;
#if defined(__GNUC__)
#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 drflac_uint64 drflac_uintptr;
#else
typedef drflac_uint32 drflac_uintptr;
#endif
typedef drflac_uint8 drflac_bool8;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
drflac_uint32 commentCount;
const void* pComments;
} vorbis_comment;
struct
{
char catalog[128];
drflac_uint64 leadInSampleCount;
drflac_bool32 isCD;
drflac_uint8 trackCount;
const void* pTrackData;
} cuesheet;
struct
{
drflac_uint32 type;
drflac_uint32 mimeLength;
const char* mime;
drflac_uint32 descriptionLength;
const char* description;
drflac_uint32 width;
drflac_uint32 height;
drflac_uint32 colorDepth;
drflac_uint32 indexColorCount;
drflac_uint32 pictureDataSize;
const drflac_uint8* pPictureData;
} picture;
} data;
} drflac_metadata;
typedef size_t (* drflac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
typedef drflac_bool32 (* drflac_seek_proc)(void* pUserData, int offset, drflac_seek_origin origin);
typedef void (* drflac_meta_proc)(void* pUserData, drflac_metadata* pMetadata);
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);
} drflac_allocation_callbacks;
typedef struct
{
const drflac_uint8* data;
size_t dataSize;
size_t currentReadPos;
} drflac__memory_stream;
typedef struct
{
drflac_read_proc onRead;
drflac_seek_proc onSeek;
void* pUserData;
size_t unalignedByteCount;
drflac_cache_t unalignedCache;
drflac_uint32 nextL2Line;
drflac_uint32 consumedBits;
drflac_cache_t cacheL2[DR_FLAC_BUFFER_SIZE/sizeof(drflac_cache_t)];
drflac_cache_t cache;
drflac_uint16 crc16;
drflac_cache_t crc16Cache;
drflac_uint32 crc16CacheIgnoredBytes;
} drflac_bs;
typedef struct
{
drflac_uint8 subframeType;
drflac_uint8 wastedBitsPerSample;
drflac_uint8 lpcOrder;
drflac_int32* pSamplesS32;
} drflac_subframe;
typedef struct
{
drflac_uint64 pcmFrameNumber;
drflac_uint32 flacFrameNumber;
drflac_uint32 sampleRate;
drflac_uint16 blockSizeInPCMFrames;
drflac_uint8 channelAssignment;
drflac_uint8 bitsPerSample;
drflac_uint8 crc8;
} drflac_frame_header;
typedef struct
{
drflac_frame_header header;
drflac_uint32 pcmFramesRemaining;
drflac_subframe subframes[8];
} drflac_frame;
typedef struct
{
drflac_meta_proc onMeta;
void* pUserDataMD;
drflac_allocation_callbacks allocationCallbacks;
drflac_uint32 sampleRate;
drflac_uint8 channels;
drflac_uint8 bitsPerSample;
drflac_uint16 maxBlockSizeInPCMFrames;
drflac_uint64 totalPCMFrameCount;
drflac_container container;
drflac_uint32 seekpointCount;
drflac_frame currentFLACFrame;
drflac_uint64 currentPCMFrame;
drflac_uint64 firstFLACFramePosInBytes;
drflac__memory_stream memoryStream;
drflac_int32* pDecodedSamples;
drflac_seekpoint* pSeekpoints;
void* _oggbs;
drflac_bool32 _noSeekTableSeek : 1;
drflac_bool32 _noBinarySearchSeek : 1;
drflac_bool32 _noBruteForceSeek : 1;
drflac_bs bs;
drflac_uint8 pExtraData[1];
} drflac;
DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API void drflac_close(drflac* pFlac);
DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut);
DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut);
DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut);
DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex);
#ifndef DR_FLAC_NO_STDIO
DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
#endif
DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API drflac* drflac_open_memory_with_metadata(const void* pData, size_t dataSize, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pA...
DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pA...
DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocati...
#ifndef DR_FLAC_NO_STDIO
DRFLAC_API drflac_int32* drflac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API drflac_int16* drflac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API float* drflac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
#endif
DRFLAC_API drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks);
typedef struct
{
drflac_uint32 countRemaining;
const char* pRunningData;
} drflac_vorbis_comment_iterator;
DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments);
DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut);
typedef struct
{
drflac_uint32 countRemaining;
const char* pRunningData;
} drflac_cuesheet_track_iterator;
#pragma pack(4)
typedef struct
{
drflac_uint64 offset;
drflac_uint8 index;
drflac_uint8 reserved[3];
} drflac_cuesheet_track_index;
#pragma pack()
typedef struct
{
drflac_uint64 offset;
drflac_uint8 trackNumber;
char ISRC[12];
drflac_bool8 isAudio;
drflac_bool8 preEmphasis;
drflac_uint8 indexCount;
const drflac_cuesheet_track_index* pIndexPoints;
} drflac_cuesheet_track;
DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData);
DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack);
#ifdef __cplusplus
}
#endif
#endif
/* dr_flac_h end */
#endif /* MA_NO_FLAC */
#if !defined(MA_NO_MP3) && !defined(MA_NO_DECODING)
/* dr_mp3_h begin */
#ifndef dr_mp3_h
#define dr_mp3_h
#ifdef __cplusplus
extern "C" {
#endif
#define DRMP3_STRINGIFY(x) #x
#define DRMP3_XSTRINGIFY(x) DRMP3_STRINGIFY(x)
#define DRMP3_VERSION_MAJOR 0
#define DRMP3_VERSION_MINOR 6
#define DRMP3_VERSION_REVISION 17
#define DRMP3_VERSION_STRING DRMP3_XSTRINGIFY(DRMP3_VERSION_MAJOR) "." DRMP3_XSTRINGIFY(DRMP3_VERSION_MINOR) "." DRMP3_XSTRINGIFY(DRMP3_VERSION_REVISION)
#include <stddef.h>
typedef signed char drmp3_int8;
typedef unsigned char drmp3_uint8;
typedef signed short drmp3_int16;
typedef unsigned short drmp3_uint16;
typedef signed int drmp3_int32;
typedef unsigned int drmp3_uint32;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
#define DRMP3_TOO_BIG -11
#define DRMP3_PATH_TOO_LONG -12
#define DRMP3_NAME_TOO_LONG -13
#define DRMP3_NOT_DIRECTORY -14
#define DRMP3_IS_DIRECTORY -15
#define DRMP3_DIRECTORY_NOT_EMPTY -16
#define DRMP3_END_OF_FILE -17
#define DRMP3_NO_SPACE -18
#define DRMP3_BUSY -19
#define DRMP3_IO_ERROR -20
#define DRMP3_INTERRUPT -21
#define DRMP3_UNAVAILABLE -22
#define DRMP3_ALREADY_IN_USE -23
#define DRMP3_BAD_ADDRESS -24
#define DRMP3_BAD_SEEK -25
#define DRMP3_BAD_PIPE -26
#define DRMP3_DEADLOCK -27
#define DRMP3_TOO_MANY_LINKS -28
#define DRMP3_NOT_IMPLEMENTED -29
#define DRMP3_NO_MESSAGE -30
#define DRMP3_BAD_MESSAGE -31
#define DRMP3_NO_DATA_AVAILABLE -32
#define DRMP3_INVALID_DATA -33
#define DRMP3_TIMEOUT -34
#define DRMP3_NO_NETWORK -35
#define DRMP3_NOT_UNIQUE -36
#define DRMP3_NOT_SOCKET -37
#define DRMP3_NO_ADDRESS -38
#define DRMP3_BAD_PROTOCOL -39
#define DRMP3_PROTOCOL_UNAVAILABLE -40
#define DRMP3_PROTOCOL_NOT_SUPPORTED -41
#define DRMP3_PROTOCOL_FAMILY_NOT_SUPPORTED -42
#define DRMP3_ADDRESS_FAMILY_NOT_SUPPORTED -43
#define DRMP3_SOCKET_NOT_SUPPORTED -44
#define DRMP3_CONNECTION_RESET -45
#define DRMP3_ALREADY_CONNECTED -46
#define DRMP3_NOT_CONNECTED -47
#define DRMP3_CONNECTION_REFUSED -48
#define DRMP3_NO_HOST -49
#define DRMP3_IN_PROGRESS -50
#define DRMP3_CANCELLED -51
#define DRMP3_MEMORY_ALREADY_MAPPED -52
#define DRMP3_AT_END -53
#define DRMP3_MAX_PCM_FRAMES_PER_MP3_FRAME 1152
#define DRMP3_MAX_SAMPLES_PER_FRAME (DRMP3_MAX_PCM_FRAMES_PER_MP3_FRAME*2)
#ifdef _MSC_VER
#define DRMP3_INLINE __forceinline
#elif defined(__GNUC__)
#if defined(__STRICT_ANSI__)
#define DRMP3_INLINE __inline__ __attribute__((always_inline))
#else
#define DRMP3_INLINE inline __attribute__((always_inline))
#endif
#else
#define DRMP3_INLINE
#endif
DRMP3_API void drmp3_version(drmp3_uint32* pMajor, drmp3_uint32* pMinor, drmp3_uint32* pRevision);
DRMP3_API const char* drmp3_version_string(void);
typedef struct
{
int frame_bytes, channels, hz, layer, bitrate_kbps;
} drmp3dec_frame_info;
typedef struct
{
float mdct_overlap[2][9*32], qmf_state[15*2*32];
int reserv, free_format_bytes;
drmp3_uint8 header[4], reserv_buf[511];
} drmp3dec;
DRMP3_API void drmp3dec_init(drmp3dec *dec);
DRMP3_API int drmp3dec_decode_frame(drmp3dec *dec, const drmp3_uint8 *mp3, int mp3_bytes, void *pcm, drmp3dec_frame_info *info);
DRMP3_API void drmp3dec_f32_to_s16(const float *in, drmp3_int16 *out, size_t num_samples);
#ifndef DRMP3_DEFAULT_CHANNELS
#define DRMP3_DEFAULT_CHANNELS 2
#endif
#ifndef DRMP3_DEFAULT_SAMPLE_RATE
#define DRMP3_DEFAULT_SAMPLE_RATE 44100
#endif
typedef enum
{
drmp3_seek_origin_start,
drmp3_seek_origin_current
} drmp3_seek_origin;
typedef struct
{
drmp3_uint64 seekPosInBytes;
drmp3_uint64 pcmFrameIndex;
drmp3_uint16 mp3FramesToDiscard;
drmp3_uint16 pcmFramesToDiscard;
} drmp3_seek_point;
typedef size_t (* drmp3_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
typedef drmp3_bool32 (* drmp3_seek_proc)(void* pUserData, int offset, drmp3_seek_origin origin);
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);
} drmp3_allocation_callbacks;
typedef struct
{
drmp3_uint32 channels;
drmp3_uint32 sampleRate;
} drmp3_config;
typedef struct
{
drmp3dec decoder;
drmp3dec_frame_info frameInfo;
drmp3_uint32 channels;
drmp3_uint32 sampleRate;
drmp3_read_proc onRead;
drmp3_seek_proc onSeek;
void* pUserData;
drmp3_allocation_callbacks allocationCallbacks;
drmp3_uint32 mp3FrameChannels;
drmp3_uint32 mp3FrameSampleRate;
drmp3_uint32 pcmFramesConsumedInMP3Frame;
drmp3_uint32 pcmFramesRemainingInMP3Frame;
drmp3_uint8 pcmFrames[sizeof(float)*DRMP3_MAX_SAMPLES_PER_FRAME];
drmp3_uint64 currentPCMFrame;
drmp3_uint64 streamCursor;
drmp3_seek_point* pSeekPoints;
drmp3_uint32 seekPointCount;
size_t dataSize;
size_t dataCapacity;
size_t dataConsumed;
drmp3_uint8* pData;
drmp3_bool32 atEnd : 1;
struct
{
const drmp3_uint8* pData;
size_t dataSize;
size_t currentReadPos;
} memory;
} drmp3;
DRMP3_API drmp3_bool32 drmp3_init(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_allocation_callbacks* pAllocationCallbacks);
DRMP3_API drmp3_bool32 drmp3_init_memory(drmp3* pMP3, const void* pData, size_t dataSize, const drmp3_allocation_callbacks* pAllocationCallbacks);
#ifndef DR_MP3_NO_STDIO
DRMP3_API drmp3_bool32 drmp3_init_file(drmp3* pMP3, const char* pFilePath, const drmp3_allocation_callbacks* pAllocationCallbacks);
DRMP3_API drmp3_bool32 drmp3_init_file_w(drmp3* pMP3, const wchar_t* pFilePath, const drmp3_allocation_callbacks* pAllocationCallbacks);
#endif
DRMP3_API void drmp3_uninit(drmp3* pMP3);
DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_f32(drmp3* pMP3, drmp3_uint64 framesToRead, float* pBufferOut);
DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_s16(drmp3* pMP3, drmp3_uint64 framesToRead, drmp3_int16* pBufferOut);
DRMP3_API drmp3_bool32 drmp3_seek_to_pcm_frame(drmp3* pMP3, drmp3_uint64 frameIndex);
DRMP3_API drmp3_uint64 drmp3_get_pcm_frame_count(drmp3* pMP3);
DRMP3_API drmp3_uint64 drmp3_get_mp3_frame_count(drmp3* pMP3);
DRMP3_API drmp3_bool32 drmp3_get_mp3_and_pcm_frame_count(drmp3* pMP3, drmp3_uint64* pMP3FrameCount, drmp3_uint64* pPCMFrameCount);
DRMP3_API drmp3_bool32 drmp3_calculate_seek_points(drmp3* pMP3, drmp3_uint32* pSeekPointCount, drmp3_seek_point* pSeekPoints);
DRMP3_API drmp3_bool32 drmp3_bind_seek_table(drmp3* pMP3, drmp3_uint32 seekPointCount, drmp3_seek_point* pSeekPoints);
DRMP3_API float* drmp3_open_and_read_pcm_frames_f32(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
DRMP3_API drmp3_int16* drmp3_open_and_read_pcm_frames_s16(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
DRMP3_API float* drmp3_open_memory_and_read_pcm_frames_f32(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
DRMP3_API drmp3_int16* drmp3_open_memory_and_read_pcm_frames_s16(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
#ifndef DR_MP3_NO_STDIO
DRMP3_API float* drmp3_open_file_and_read_pcm_frames_f32(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
DRMP3_API drmp3_int16* drmp3_open_file_and_read_pcm_frames_s16(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
#endif
DRMP3_API void* drmp3_malloc(size_t sz, const drmp3_allocation_callbacks* pAllocationCallbacks);
DRMP3_API void drmp3_free(void* p, const drmp3_allocation_callbacks* pAllocationCallbacks);
#ifdef __cplusplus
}
#endif
#endif
/* dr_mp3_h end */
#endif /* MA_NO_MP3 */
/**************************************************************************************************************************************************************
Decoding
**************************************************************************************************************************************************************/
#ifndef MA_NO_DECODING
static size_t ma_decoder_read_bytes(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead)
{
size_t bytesRead;
MA_ASSERT(pDecoder != NULL);
MA_ASSERT(pBufferOut != NULL);
bytesRead = pDecoder->onRead(pDecoder, pBufferOut, bytesToRead);
pDecoder->readPointerInBytes += bytesRead;
return bytesRead;
}
static ma_bool32 ma_decoder_seek_bytes(ma_decoder* pDecoder, int byteOffset, ma_seek_origin origin)
{
ma_bool32 wasSuccessful;
MA_ASSERT(pDecoder != NULL);
wasSuccessful = pDecoder->onSeek(pDecoder, byteOffset, origin);
if (wasSuccessful) {
if (origin == ma_seek_origin_start) {
pDecoder->readPointerInBytes = (ma_uint64)byteOffset;
} else {
pDecoder->readPointerInBytes += byteOffset;
}
}
return wasSuccessful;
}
MA_API ma_decoder_config ma_decoder_config_init(ma_format outputFormat, ma_uint32 outputChannels, ma_uint32 outputSampleRate)
{
ma_decoder_config config;
MA_ZERO_OBJECT(&config);
config.format = outputFormat;
config.channels = ma_min(outputChannels, ma_countof(config.channelMap));
config.sampleRate = outputSampleRate;
config.resampling.algorithm = ma_resample_algorithm_linear;
config.resampling.linear.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
config.resampling.speex.quality = 3;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
} else {
pDecoder->outputFormat = pConfig->format;
}
if (pConfig->channels == 0) {
pDecoder->outputChannels = pDecoder->internalChannels;
} else {
pDecoder->outputChannels = pConfig->channels;
}
if (pConfig->sampleRate == 0) {
pDecoder->outputSampleRate = pDecoder->internalSampleRate;
} else {
pDecoder->outputSampleRate = pConfig->sampleRate;
}
if (ma_channel_map_blank(pDecoder->outputChannels, pConfig->channelMap)) {
ma_get_standard_channel_map(ma_standard_channel_map_default, pDecoder->outputChannels, pDecoder->outputChannelMap);
} else {
MA_COPY_MEMORY(pDecoder->outputChannelMap, pConfig->channelMap, sizeof(pConfig->channelMap));
}
converterConfig = ma_data_converter_config_init(
pDecoder->internalFormat, pDecoder->outputFormat,
pDecoder->internalChannels, pDecoder->outputChannels,
pDecoder->internalSampleRate, pDecoder->outputSampleRate
);
ma_channel_map_copy(converterConfig.channelMapIn, pDecoder->internalChannelMap, pDecoder->internalChannels);
ma_channel_map_copy(converterConfig.channelMapOut, pDecoder->outputChannelMap, pDecoder->outputChannels);
converterConfig.channelMixMode = pConfig->channelMixMode;
converterConfig.ditherMode = pConfig->ditherMode;
converterConfig.resampling.allowDynamicSampleRate = MA_FALSE; /* Never allow dynamic sample rate conversion. Setting this to true will disable passthrough optimizations. */
converterConfig.resampling.algorithm = pConfig->resampling.algorithm;
converterConfig.resampling.linear.lpfOrder = pConfig->resampling.linear.lpfOrder;
converterConfig.resampling.speex.quality = pConfig->resampling.speex.quality;
return ma_data_converter_init(&converterConfig, &pDecoder->converter);
}
/* WAV */
#ifdef dr_wav_h
#define MA_HAS_WAV
static size_t ma_decoder_internal_on_read__wav(void* pUserData, void* pBufferOut, size_t bytesToRead)
{
ma_decoder* pDecoder = (ma_decoder*)pUserData;
MA_ASSERT(pDecoder != NULL);
return ma_decoder_read_bytes(pDecoder, pBufferOut, bytesToRead);
}
static drwav_bool32 ma_decoder_internal_on_seek__wav(void* pUserData, int offset, drwav_seek_origin origin)
{
ma_decoder* pDecoder = (ma_decoder*)pUserData;
MA_ASSERT(pDecoder != NULL);
return ma_decoder_seek_bytes(pDecoder, offset, (origin == drwav_seek_origin_start) ? ma_seek_origin_start : ma_seek_origin_current);
}
static ma_uint64 ma_decoder_internal_on_read_pcm_frames__wav(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount)
{
drwav* pWav;
MA_ASSERT(pDecoder != NULL);
MA_ASSERT(pFramesOut != NULL);
pWav = (drwav*)pDecoder->pInternalDecoder;
MA_ASSERT(pWav != NULL);
switch (pDecoder->internalFormat) {
case ma_format_s16: return drwav_read_pcm_frames_s16(pWav, frameCount, (drwav_int16*)pFramesOut);
case ma_format_s32: return drwav_read_pcm_frames_s32(pWav, frameCount, (drwav_int32*)pFramesOut);
case ma_format_f32: return drwav_read_pcm_frames_f32(pWav, frameCount, (float*)pFramesOut);
default: break;
}
/* Should never get here. If we do, it means the internal format was not set correctly at initialization time. */
MA_ASSERT(MA_FALSE);
return 0;
}
static ma_result ma_decoder_internal_on_seek_to_pcm_frame__wav(ma_decoder* pDecoder, ma_uint64 frameIndex)
{
drwav* pWav;
drwav_bool32 result;
pWav = (drwav*)pDecoder->pInternalDecoder;
MA_ASSERT(pWav != NULL);
result = drwav_seek_to_pcm_frame(pWav, frameIndex);
if (result) {
return MA_SUCCESS;
} else {
return MA_ERROR;
}
}
static ma_result ma_decoder_internal_on_uninit__wav(ma_decoder* pDecoder)
{
drwav_uninit((drwav*)pDecoder->pInternalDecoder);
ma__free_from_callbacks(pDecoder->pInternalDecoder, &pDecoder->allocationCallbacks);
return MA_SUCCESS;
}
static ma_uint64 ma_decoder_internal_on_get_length_in_pcm_frames__wav(ma_decoder* pDecoder)
{
return ((drwav*)pDecoder->pInternalDecoder)->totalPCMFrameCount;
}
static ma_result ma_decoder_init_wav__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
drwav* pWav;
drwav_allocation_callbacks allocationCallbacks;
MA_ASSERT(pConfig != NULL);
MA_ASSERT(pDecoder != NULL);
pWav = (drwav*)ma__malloc_from_callbacks(sizeof(*pWav), &pDecoder->allocationCallbacks);
if (pWav == NULL) {
return MA_OUT_OF_MEMORY;
}
allocationCallbacks.pUserData = pDecoder->allocationCallbacks.pUserData;
allocationCallbacks.onMalloc = pDecoder->allocationCallbacks.onMalloc;
allocationCallbacks.onRealloc = pDecoder->allocationCallbacks.onRealloc;
allocationCallbacks.onFree = pDecoder->allocationCallbacks.onFree;
/* Try opening the decoder first. */
if (!drwav_init(pWav, ma_decoder_internal_on_read__wav, ma_decoder_internal_on_seek__wav, pDecoder, &allocationCallbacks)) {
ma__free_from_callbacks(pWav, &pDecoder->allocationCallbacks);
return MA_ERROR;
}
/* If we get here it means we successfully initialized the WAV decoder. We can now initialize the rest of the ma_decoder. */
pDecoder->onReadPCMFrames = ma_decoder_internal_on_read_pcm_frames__wav;
pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__wav;
pDecoder->onUninit = ma_decoder_internal_on_uninit__wav;
pDecoder->onGetLengthInPCMFrames = ma_decoder_internal_on_get_length_in_pcm_frames__wav;
pDecoder->pInternalDecoder = pWav;
/* Try to be as optimal as possible for the internal format. If miniaudio does not support a format we will fall back to f32. */
pDecoder->internalFormat = ma_format_unknown;
switch (pWav->translatedFormatTag) {
case DR_WAVE_FORMAT_PCM:
{
if (pWav->bitsPerSample == 8) {
pDecoder->internalFormat = ma_format_s16;
} else if (pWav->bitsPerSample == 16) {
pDecoder->internalFormat = ma_format_s16;
} else if (pWav->bitsPerSample == 32) {
pDecoder->internalFormat = ma_format_s32;
}
} break;
case DR_WAVE_FORMAT_IEEE_FLOAT:
{
if (pWav->bitsPerSample == 32) {
pDecoder->internalFormat = ma_format_f32;
}
} break;
case DR_WAVE_FORMAT_ALAW:
case DR_WAVE_FORMAT_MULAW:
case DR_WAVE_FORMAT_ADPCM:
case DR_WAVE_FORMAT_DVI_ADPCM:
{
pDecoder->internalFormat = ma_format_s16;
} break;
}
if (pDecoder->internalFormat == ma_format_unknown) {
pDecoder->internalFormat = ma_format_f32;
}
pDecoder->internalChannels = pWav->channels;
pDecoder->internalSampleRate = pWav->sampleRate;
ma_get_standard_channel_map(ma_standard_channel_map_microsoft, pDecoder->internalChannels, pDecoder->internalChannelMap);
return MA_SUCCESS;
}
#endif /* dr_wav_h */
/* FLAC */
#ifdef dr_flac_h
#define MA_HAS_FLAC
static size_t ma_decoder_internal_on_read__flac(void* pUserData, void* pBufferOut, size_t bytesToRead)
{
ma_decoder* pDecoder = (ma_decoder*)pUserData;
MA_ASSERT(pDecoder != NULL);
return ma_decoder_read_bytes(pDecoder, pBufferOut, bytesToRead);
}
static drflac_bool32 ma_decoder_internal_on_seek__flac(void* pUserData, int offset, drflac_seek_origin origin)
{
ma_decoder* pDecoder = (ma_decoder*)pUserData;
MA_ASSERT(pDecoder != NULL);
return ma_decoder_seek_bytes(pDecoder, offset, (origin == drflac_seek_origin_start) ? ma_seek_origin_start : ma_seek_origin_current);
}
static ma_uint64 ma_decoder_internal_on_read_pcm_frames__flac(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount)
{
drflac* pFlac;
MA_ASSERT(pDecoder != NULL);
MA_ASSERT(pFramesOut != NULL);
pFlac = (drflac*)pDecoder->pInternalDecoder;
MA_ASSERT(pFlac != NULL);
switch (pDecoder->internalFormat) {
case ma_format_s16: return drflac_read_pcm_frames_s16(pFlac, frameCount, (drflac_int16*)pFramesOut);
case ma_format_s32: return drflac_read_pcm_frames_s32(pFlac, frameCount, (drflac_int32*)pFramesOut);
case ma_format_f32: return drflac_read_pcm_frames_f32(pFlac, frameCount, (float*)pFramesOut);
default: break;
}
/* Should never get here. If we do, it means the internal format was not set correctly at initialization time. */
MA_ASSERT(MA_FALSE);
return 0;
}
static ma_result ma_decoder_internal_on_seek_to_pcm_frame__flac(ma_decoder* pDecoder, ma_uint64 frameIndex)
{
drflac* pFlac;
drflac_bool32 result;
pFlac = (drflac*)pDecoder->pInternalDecoder;
MA_ASSERT(pFlac != NULL);
result = drflac_seek_to_pcm_frame(pFlac, frameIndex);
if (result) {
return MA_SUCCESS;
} else {
return MA_ERROR;
}
}
static ma_result ma_decoder_internal_on_uninit__flac(ma_decoder* pDecoder)
{
drflac_close((drflac*)pDecoder->pInternalDecoder);
return MA_SUCCESS;
}
static ma_uint64 ma_decoder_internal_on_get_length_in_pcm_frames__flac(ma_decoder* pDecoder)
{
return ((drflac*)pDecoder->pInternalDecoder)->totalPCMFrameCount;
}
static ma_result ma_decoder_init_flac__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
drflac* pFlac;
drflac_allocation_callbacks allocationCallbacks;
MA_ASSERT(pConfig != NULL);
MA_ASSERT(pDecoder != NULL);
allocationCallbacks.pUserData = pDecoder->allocationCallbacks.pUserData;
allocationCallbacks.onMalloc = pDecoder->allocationCallbacks.onMalloc;
allocationCallbacks.onRealloc = pDecoder->allocationCallbacks.onRealloc;
allocationCallbacks.onFree = pDecoder->allocationCallbacks.onFree;
/* Try opening the decoder first. */
pFlac = drflac_open(ma_decoder_internal_on_read__flac, ma_decoder_internal_on_seek__flac, pDecoder, &allocationCallbacks);
if (pFlac == NULL) {
return MA_ERROR;
}
/* If we get here it means we successfully initialized the FLAC decoder. We can now initialize the rest of the ma_decoder. */
pDecoder->onReadPCMFrames = ma_decoder_internal_on_read_pcm_frames__flac;
pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__flac;
pDecoder->onUninit = ma_decoder_internal_on_uninit__flac;
pDecoder->onGetLengthInPCMFrames = ma_decoder_internal_on_get_length_in_pcm_frames__flac;
pDecoder->pInternalDecoder = pFlac;
/*
dr_flac supports reading as s32, s16 and f32. Try to do a one-to-one mapping if possible, but fall back to s32 if not. s32 is the "native" FLAC format
since it's the only one that's truly lossless. If the internal bits per sample is <= 16 we will decode to ma_format_s16 to keep it more efficient.
*/
if (pConfig->format == ma_format_unknown) {
if (pFlac->bitsPerSample <= 16) {
pDecoder->internalFormat = ma_format_s16;
} else {
pDecoder->internalFormat = ma_format_s32;
}
} else {
if (pConfig->format == ma_format_s16 || pConfig->format == ma_format_f32) {
pDecoder->internalFormat = pConfig->format;
} else {
pDecoder->internalFormat = ma_format_s32; /* s32 as the baseline to ensure no loss of precision for 24-bit encoded files. */
}
}
pDecoder->internalChannels = pFlac->channels;
pDecoder->internalSampleRate = pFlac->sampleRate;
ma_get_standard_channel_map(ma_standard_channel_map_flac, pDecoder->internalChannels, pDecoder->internalChannelMap);
return MA_SUCCESS;
}
#endif /* dr_flac_h */
/* MP3 */
#ifdef dr_mp3_h
#define MA_HAS_MP3
static size_t ma_decoder_internal_on_read__mp3(void* pUserData, void* pBufferOut, size_t bytesToRead)
{
ma_decoder* pDecoder = (ma_decoder*)pUserData;
MA_ASSERT(pDecoder != NULL);
return ma_decoder_read_bytes(pDecoder, pBufferOut, bytesToRead);
}
static drmp3_bool32 ma_decoder_internal_on_seek__mp3(void* pUserData, int offset, drmp3_seek_origin origin)
{
ma_decoder* pDecoder = (ma_decoder*)pUserData;
MA_ASSERT(pDecoder != NULL);
return ma_decoder_seek_bytes(pDecoder, offset, (origin == drmp3_seek_origin_start) ? ma_seek_origin_start : ma_seek_origin_current);
}
static ma_uint64 ma_decoder_internal_on_read_pcm_frames__mp3(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount)
{
drmp3* pMP3;
MA_ASSERT(pDecoder != NULL);
MA_ASSERT(pFramesOut != NULL);
pMP3 = (drmp3*)pDecoder->pInternalDecoder;
MA_ASSERT(pMP3 != NULL);
#if defined(DR_MP3_FLOAT_OUTPUT)
MA_ASSERT(pDecoder->internalFormat == ma_format_f32);
return drmp3_read_pcm_frames_f32(pMP3, frameCount, (float*)pFramesOut);
#else
MA_ASSERT(pDecoder->internalFormat == ma_format_s16);
return drmp3_read_pcm_frames_s16(pMP3, frameCount, (drmp3_int16*)pFramesOut);
#endif
}
static ma_result ma_decoder_internal_on_seek_to_pcm_frame__mp3(ma_decoder* pDecoder, ma_uint64 frameIndex)
{
drmp3* pMP3;
drmp3_bool32 result;
pMP3 = (drmp3*)pDecoder->pInternalDecoder;
MA_ASSERT(pMP3 != NULL);
result = drmp3_seek_to_pcm_frame(pMP3, frameIndex);
if (result) {
return MA_SUCCESS;
} else {
return MA_ERROR;
}
}
static ma_result ma_decoder_internal_on_uninit__mp3(ma_decoder* pDecoder)
{
drmp3_uninit((drmp3*)pDecoder->pInternalDecoder);
ma__free_from_callbacks(pDecoder->pInternalDecoder, &pDecoder->allocationCallbacks);
return MA_SUCCESS;
}
static ma_uint64 ma_decoder_internal_on_get_length_in_pcm_frames__mp3(ma_decoder* pDecoder)
{
return drmp3_get_pcm_frame_count((drmp3*)pDecoder->pInternalDecoder);
}
static ma_result ma_decoder_init_mp3__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
drmp3* pMP3;
drmp3_allocation_callbacks allocationCallbacks;
MA_ASSERT(pConfig != NULL);
MA_ASSERT(pDecoder != NULL);
pMP3 = (drmp3*)ma__malloc_from_callbacks(sizeof(*pMP3), &pDecoder->allocationCallbacks);
if (pMP3 == NULL) {
return MA_OUT_OF_MEMORY;
}
allocationCallbacks.pUserData = pDecoder->allocationCallbacks.pUserData;
allocationCallbacks.onMalloc = pDecoder->allocationCallbacks.onMalloc;
allocationCallbacks.onRealloc = pDecoder->allocationCallbacks.onRealloc;
allocationCallbacks.onFree = pDecoder->allocationCallbacks.onFree;
/*
Try opening the decoder first. We always use whatever dr_mp3 reports for channel count and sample rate. The format is determined by
the presence of DR_MP3_FLOAT_OUTPUT.
*/
if (!drmp3_init(pMP3, ma_decoder_internal_on_read__mp3, ma_decoder_internal_on_seek__mp3, pDecoder, &allocationCallbacks)) {
ma__free_from_callbacks(pMP3, &pDecoder->allocationCallbacks);
return MA_ERROR;
}
/* If we get here it means we successfully initialized the MP3 decoder. We can now initialize the rest of the ma_decoder. */
pDecoder->onReadPCMFrames = ma_decoder_internal_on_read_pcm_frames__mp3;
pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__mp3;
pDecoder->onUninit = ma_decoder_internal_on_uninit__mp3;
pDecoder->onGetLengthInPCMFrames = ma_decoder_internal_on_get_length_in_pcm_frames__mp3;
pDecoder->pInternalDecoder = pMP3;
/* Internal format. */
#if defined(DR_MP3_FLOAT_OUTPUT)
pDecoder->internalFormat = ma_format_f32;
#else
pDecoder->internalFormat = ma_format_s16;
#endif
pDecoder->internalChannels = pMP3->channels;
pDecoder->internalSampleRate = pMP3->sampleRate;
ma_get_standard_channel_map(ma_standard_channel_map_default, pDecoder->internalChannels, pDecoder->internalChannelMap);
return MA_SUCCESS;
}
#endif /* dr_mp3_h */
/* Vorbis */
#ifdef STB_VORBIS_INCLUDE_STB_VORBIS_H
#define MA_HAS_VORBIS
/* The size in bytes of each chunk of data to read from the Vorbis stream. */
#define MA_VORBIS_DATA_CHUNK_SIZE 4096
typedef struct
{
stb_vorbis* pInternalVorbis;
ma_uint8* pData;
size_t dataSize;
size_t dataCapacity;
ma_uint32 framesConsumed; /* The number of frames consumed in ppPacketData. */
ma_uint32 framesRemaining; /* The number of frames remaining in ppPacketData. */
float** ppPacketData;
} ma_vorbis_decoder;
static ma_uint64 ma_vorbis_decoder_read_pcm_frames(ma_vorbis_decoder* pVorbis, ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount)
{
float* pFramesOutF;
ma_uint64 totalFramesRead;
MA_ASSERT(pVorbis != NULL);
MA_ASSERT(pDecoder != NULL);
pFramesOutF = (float*)pFramesOut;
totalFramesRead = 0;
while (frameCount > 0) {
/* Read from the in-memory buffer first. */
ma_uint32 framesToReadFromCache = (ma_uint32)ma_min(pVorbis->framesRemaining, frameCount); /* Safe cast because pVorbis->framesRemaining is 32-bit. */
if (pFramesOut != NULL) {
ma_uint64 iFrame;
for (iFrame = 0; iFrame < framesToReadFromCache; iFrame += 1) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < pDecoder->internalChannels; ++iChannel) {
pFramesOutF[iChannel] = pVorbis->ppPacketData[iChannel][pVorbis->framesConsumed+iFrame];
}
pFramesOutF += pDecoder->internalChannels;
}
}
pVorbis->framesConsumed += framesToReadFromCache;
pVorbis->framesRemaining -= framesToReadFromCache;
frameCount -= framesToReadFromCache;
totalFramesRead += framesToReadFromCache;
if (frameCount == 0) {
break;
}
MA_ASSERT(pVorbis->framesRemaining == 0);
/* We've run out of cached frames, so decode the next packet and continue iteration. */
do
{
int samplesRead;
int consumedDataSize;
if (pVorbis->dataSize > INT_MAX) {
break; /* Too big. */
}
samplesRead = 0;
consumedDataSize = stb_vorbis_decode_frame_pushdata(pVorbis->pInternalVorbis, pVorbis->pData, (int)pVorbis->dataSize, NULL, (float***)&pVorbis->ppPacketData, &samplesRead);
if (consumedDataSize != 0) {
size_t leftoverDataSize = (pVorbis->dataSize - (size_t)consumedDataSize);
size_t i;
for (i = 0; i < leftoverDataSize; ++i) {
pVorbis->pData[i] = pVorbis->pData[i + consumedDataSize];
}
pVorbis->dataSize = leftoverDataSize;
pVorbis->framesConsumed = 0;
pVorbis->framesRemaining = samplesRead;
break;
} else {
/* Need more data. If there's any room in the existing buffer allocation fill that first. Otherwise expand. */
size_t bytesRead;
if (pVorbis->dataCapacity == pVorbis->dataSize) {
/* No room. Expand. */
size_t oldCap = pVorbis->dataCapacity;
size_t newCap = pVorbis->dataCapacity + MA_VORBIS_DATA_CHUNK_SIZE;
ma_uint8* pNewData;
pNewData = (ma_uint8*)ma__realloc_from_callbacks(pVorbis->pData, newCap, oldCap, &pDecoder->allocationCallbacks);
if (pNewData == NULL) {
return totalFramesRead; /* Out of memory. */
}
pVorbis->pData = pNewData;
pVorbis->dataCapacity = newCap;
}
/* Fill in a chunk. */
bytesRead = ma_decoder_read_bytes(pDecoder, pVorbis->pData + pVorbis->dataSize, (pVorbis->dataCapacity - pVorbis->dataSize));
if (bytesRead == 0) {
return totalFramesRead; /* Error reading more data. */
}
pVorbis->dataSize += bytesRead;
}
} while (MA_TRUE);
}
return totalFramesRead;
}
static ma_result ma_vorbis_decoder_seek_to_pcm_frame(ma_vorbis_decoder* pVorbis, ma_decoder* pDecoder, ma_uint64 frameIndex)
{
float buffer[4096];
MA_ASSERT(pVorbis != NULL);
MA_ASSERT(pDecoder != NULL);
/*
This is terribly inefficient because stb_vorbis does not have a good seeking solution with it's push API. Currently this just performs
a full decode right from the start of the stream. Later on I'll need to write a layer that goes through all of the Ogg pages until we
find the one containing the sample we need. Then we know exactly where to seek for stb_vorbis.
TODO: Use seeking logic documented for stb_vorbis_flush_pushdata().
*/
if (!ma_decoder_seek_bytes(pDecoder, 0, ma_seek_origin_start)) {
return MA_ERROR;
}
stb_vorbis_flush_pushdata(pVorbis->pInternalVorbis);
pVorbis->framesConsumed = 0;
pVorbis->framesRemaining = 0;
pVorbis->dataSize = 0;
while (frameIndex > 0) {
ma_uint32 framesRead;
ma_uint32 framesToRead = ma_countof(buffer)/pDecoder->internalChannels;
if (framesToRead > frameIndex) {
framesToRead = (ma_uint32)frameIndex;
}
framesRead = (ma_uint32)ma_vorbis_decoder_read_pcm_frames(pVorbis, pDecoder, buffer, framesToRead);
if (framesRead == 0) {
return MA_ERROR;
}
frameIndex -= framesRead;
}
return MA_SUCCESS;
}
static ma_result ma_decoder_internal_on_seek_to_pcm_frame__vorbis(ma_decoder* pDecoder, ma_uint64 frameIndex)
{
ma_vorbis_decoder* pVorbis = (ma_vorbis_decoder*)pDecoder->pInternalDecoder;
MA_ASSERT(pVorbis != NULL);
return ma_vorbis_decoder_seek_to_pcm_frame(pVorbis, pDecoder, frameIndex);
}
static ma_result ma_decoder_internal_on_uninit__vorbis(ma_decoder* pDecoder)
{
ma_vorbis_decoder* pVorbis = (ma_vorbis_decoder*)pDecoder->pInternalDecoder;
MA_ASSERT(pVorbis != NULL);
stb_vorbis_close(pVorbis->pInternalVorbis);
ma__free_from_callbacks(pVorbis->pData, &pDecoder->allocationCallbacks);
ma__free_from_callbacks(pVorbis, &pDecoder->allocationCallbacks);
return MA_SUCCESS;
}
static ma_uint64 ma_decoder_internal_on_read_pcm_frames__vorbis(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount)
{
ma_vorbis_decoder* pVorbis;
MA_ASSERT(pDecoder != NULL);
MA_ASSERT(pFramesOut != NULL);
MA_ASSERT(pDecoder->internalFormat == ma_format_f32);
pVorbis = (ma_vorbis_decoder*)pDecoder->pInternalDecoder;
MA_ASSERT(pVorbis != NULL);
return ma_vorbis_decoder_read_pcm_frames(pVorbis, pDecoder, pFramesOut, frameCount);
}
static ma_uint64 ma_decoder_internal_on_get_length_in_pcm_frames__vorbis(ma_decoder* pDecoder)
{
/* No good way to do this with Vorbis. */
(void)pDecoder;
return 0;
}
static ma_result ma_decoder_init_vorbis__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
stb_vorbis* pInternalVorbis = NULL;
size_t dataSize = 0;
size_t dataCapacity = 0;
ma_uint8* pData = NULL;
stb_vorbis_info vorbisInfo;
size_t vorbisDataSize;
ma_vorbis_decoder* pVorbis;
MA_ASSERT(pConfig != NULL);
MA_ASSERT(pDecoder != NULL);
/* We grow the buffer in chunks. */
do
{
/* Allocate memory for a new chunk. */
ma_uint8* pNewData;
size_t bytesRead;
int vorbisError = 0;
int consumedDataSize = 0;
size_t oldCapacity = dataCapacity;
dataCapacity += MA_VORBIS_DATA_CHUNK_SIZE;
pNewData = (ma_uint8*)ma__realloc_from_callbacks(pData, dataCapacity, oldCapacity, &pDecoder->allocationCallbacks);
if (pNewData == NULL) {
ma__free_from_callbacks(pData, &pDecoder->allocationCallbacks);
return MA_OUT_OF_MEMORY;
}
pData = pNewData;
/* Fill in a chunk. */
bytesRead = ma_decoder_read_bytes(pDecoder, pData + dataSize, (dataCapacity - dataSize));
if (bytesRead == 0) {
return MA_ERROR;
}
dataSize += bytesRead;
if (dataSize > INT_MAX) {
return MA_ERROR; /* Too big. */
}
pInternalVorbis = stb_vorbis_open_pushdata(pData, (int)dataSize, &consumedDataSize, &vorbisError, NULL);
if (pInternalVorbis != NULL) {
/*
If we get here it means we were able to open the stb_vorbis decoder. There may be some leftover bytes in our buffer, so
we need to move those bytes down to the front of the buffer since they'll be needed for future decoding.
*/
size_t leftoverDataSize = (dataSize - (size_t)consumedDataSize);
size_t i;
for (i = 0; i < leftoverDataSize; ++i) {
pData[i] = pData[i + consumedDataSize];
}
dataSize = leftoverDataSize;
break; /* Success. */
} else {
if (vorbisError == VORBIS_need_more_data) {
continue;
} else {
return MA_ERROR; /* Failed to open the stb_vorbis decoder. */
}
}
} while (MA_TRUE);
/* If we get here it means we successfully opened the Vorbis decoder. */
vorbisInfo = stb_vorbis_get_info(pInternalVorbis);
/* Don't allow more than MA_MAX_CHANNELS channels. */
if (vorbisInfo.channels > MA_MAX_CHANNELS) {
stb_vorbis_close(pInternalVorbis);
ma__free_from_callbacks(pData, &pDecoder->allocationCallbacks);
return MA_ERROR; /* Too many channels. */
}
vorbisDataSize = sizeof(ma_vorbis_decoder) + sizeof(float)*vorbisInfo.max_frame_size;
pVorbis = (ma_vorbis_decoder*)ma__malloc_from_callbacks(vorbisDataSize, &pDecoder->allocationCallbacks);
if (pVorbis == NULL) {
stb_vorbis_close(pInternalVorbis);
ma__free_from_callbacks(pData, &pDecoder->allocationCallbacks);
return MA_OUT_OF_MEMORY;
}
MA_ZERO_MEMORY(pVorbis, vorbisDataSize);
pVorbis->pInternalVorbis = pInternalVorbis;
pVorbis->pData = pData;
pVorbis->dataSize = dataSize;
pVorbis->dataCapacity = dataCapacity;
pDecoder->onReadPCMFrames = ma_decoder_internal_on_read_pcm_frames__vorbis;
pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__vorbis;
pDecoder->onUninit = ma_decoder_internal_on_uninit__vorbis;
pDecoder->onGetLengthInPCMFrames = ma_decoder_internal_on_get_length_in_pcm_frames__vorbis;
pDecoder->pInternalDecoder = pVorbis;
/* The internal format is always f32. */
pDecoder->internalFormat = ma_format_f32;
pDecoder->internalChannels = vorbisInfo.channels;
pDecoder->internalSampleRate = vorbisInfo.sample_rate;
ma_get_standard_channel_map(ma_standard_channel_map_vorbis, pDecoder->internalChannels, pDecoder->internalChannelMap);
return MA_SUCCESS;
}
#endif /* STB_VORBIS_INCLUDE_STB_VORBIS_H */
/* Raw */
static ma_uint64 ma_decoder_internal_on_read_pcm_frames__raw(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount)
{
ma_uint32 bpf;
ma_uint64 totalFramesRead;
void* pRunningFramesOut;
MA_ASSERT(pDecoder != NULL);
/* For raw decoding we just read directly from the decoder's callbacks. */
bpf = ma_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels);
totalFramesRead = 0;
pRunningFramesOut = pFramesOut;
while (totalFramesRead < frameCount) {
ma_uint64 framesReadThisIteration;
ma_uint64 framesToReadThisIteration = (frameCount - totalFramesRead);
if (framesToReadThisIteration > 0x7FFFFFFF/bpf) {
framesToReadThisIteration = 0x7FFFFFFF/bpf;
}
if (pFramesOut != NULL) {
framesReadThisIteration = ma_decoder_read_bytes(pDecoder, pRunningFramesOut, (size_t)framesToReadThisIteration * bpf) / bpf; /* Safe cast to size_t. */
pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesReadThisIteration * bpf);
} else {
/* We'll first try seeking. If this fails it means the end was reached and we'll to do a read-and-discard slow path to get the exact amount. */
if (ma_decoder_seek_bytes(pDecoder, (int)framesToReadThisIteration, ma_seek_origin_current)) {
framesReadThisIteration = framesToReadThisIteration;
} else {
/* Slow path. Need to fall back to a read-and-discard. This is required so we can get the exact number of remaining. */
ma_uint8 buffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
ma_uint32 bufferCap = sizeof(buffer) / bpf;
framesReadThisIteration = 0;
while (framesReadThisIteration < framesToReadThisIteration) {
ma_uint64 framesReadNow;
ma_uint64 framesToReadNow = framesToReadThisIteration - framesReadThisIteration;
if (framesToReadNow > bufferCap) {
framesToReadNow = bufferCap;
}
framesReadNow = ma_decoder_read_bytes(pDecoder, buffer, (size_t)(framesToReadNow * bpf)) / bpf; /* Safe cast. */
framesReadThisIteration += framesReadNow;
if (framesReadNow < framesToReadNow) {
break; /* The end has been reached. */
}
}
}
}
totalFramesRead += framesReadThisIteration;
if (framesReadThisIteration < framesToReadThisIteration) {
break; /* Done. */
}
}
return totalFramesRead;
}
static ma_result ma_decoder_internal_on_seek_to_pcm_frame__raw(ma_decoder* pDecoder, ma_uint64 frameIndex)
{
ma_bool32 result = MA_FALSE;
ma_uint64 totalBytesToSeek;
MA_ASSERT(pDecoder != NULL);
if (pDecoder->onSeek == NULL) {
return MA_ERROR;
}
/* The callback uses a 32 bit integer whereas we use a 64 bit unsigned integer. We just need to continuously seek until we're at the correct position. */
totalBytesToSeek = frameIndex * ma_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels);
if (totalBytesToSeek < 0x7FFFFFFF) {
/* Simple case. */
result = ma_decoder_seek_bytes(pDecoder, (int)(frameIndex * ma_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels)), ma_seek_origin_start);
} else {
/* Complex case. Start by doing a seek relative to the start. Then keep looping using offset seeking. */
result = ma_decoder_seek_bytes(pDecoder, 0x7FFFFFFF, ma_seek_origin_start);
if (result == MA_TRUE) {
totalBytesToSeek -= 0x7FFFFFFF;
while (totalBytesToSeek > 0) {
ma_uint64 bytesToSeekThisIteration = totalBytesToSeek;
if (bytesToSeekThisIteration > 0x7FFFFFFF) {
bytesToSeekThisIteration = 0x7FFFFFFF;
}
result = ma_decoder_seek_bytes(pDecoder, (int)bytesToSeekThisIteration, ma_seek_origin_current);
if (result != MA_TRUE) {
break;
}
totalBytesToSeek -= bytesToSeekThisIteration;
}
}
}
if (result) {
return MA_SUCCESS;
} else {
return MA_ERROR;
}
}
static ma_result ma_decoder_internal_on_uninit__raw(ma_decoder* pDecoder)
{
(void)pDecoder;
return MA_SUCCESS;
}
static ma_uint64 ma_decoder_internal_on_get_length_in_pcm_frames__raw(ma_decoder* pDecoder)
{
(void)pDecoder;
return 0;
}
static ma_result ma_decoder_init_raw__internal(const ma_decoder_config* pConfigIn, const ma_decoder_config* pConfigOut, ma_decoder* pDecoder)
{
MA_ASSERT(pConfigIn != NULL);
MA_ASSERT(pConfigOut != NULL);
MA_ASSERT(pDecoder != NULL);
pDecoder->onReadPCMFrames = ma_decoder_internal_on_read_pcm_frames__raw;
pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__raw;
pDecoder->onUninit = ma_decoder_internal_on_uninit__raw;
pDecoder->onGetLengthInPCMFrames = ma_decoder_internal_on_get_length_in_pcm_frames__raw;
/* Internal format. */
pDecoder->internalFormat = pConfigIn->format;
pDecoder->internalChannels = pConfigIn->channels;
pDecoder->internalSampleRate = pConfigIn->sampleRate;
ma_channel_map_copy(pDecoder->internalChannelMap, pConfigIn->channelMap, pConfigIn->channels);
return MA_SUCCESS;
}
static ma_result ma_decoder__init_allocation_callbacks(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
MA_ASSERT(pDecoder != NULL);
if (pConfig != NULL) {
return ma_allocation_callbacks_init_copy(&pDecoder->allocationCallbacks, &pConfig->allocationCallbacks);
} else {
pDecoder->allocationCallbacks = ma_allocation_callbacks_init_default();
return MA_SUCCESS;
}
}
static ma_result ma_decoder__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
{
ma_uint64 framesRead = ma_decoder_read_pcm_frames((ma_decoder*)pDataSource, pFramesOut, frameCount);
if (pFramesRead != NULL) {
*pFramesRead = framesRead;
}
if (framesRead < frameCount) {
return MA_AT_END;
}
return MA_SUCCESS;
}
static ma_result ma_decoder__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
{
return ma_decoder_seek_to_pcm_frame((ma_decoder*)pDataSource, frameIndex);
}
static ma_result ma_decoder__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate)
{
ma_decoder* pDecoder = (ma_decoder*)pDataSource;
*pFormat = pDecoder->outputFormat;
*pChannels = pDecoder->outputChannels;
*pSampleRate = pDecoder->outputSampleRate;
return MA_SUCCESS;
}
static ma_result ma_decoder__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pLength)
{
ma_decoder* pDecoder = (ma_decoder*)pDataSource;
return ma_decoder_get_cursor_in_pcm_frames(pDecoder, pLength);
}
static ma_result ma_decoder__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
{
ma_decoder* pDecoder = (ma_decoder*)pDataSource;
*pLength = ma_decoder_get_length_in_pcm_frames(pDecoder);
if (*pLength == 0) {
return MA_NOT_IMPLEMENTED;
}
return MA_SUCCESS;
}
static ma_result ma_decoder__preinit(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
ma_result result;
MA_ASSERT(pConfig != NULL);
if (pDecoder == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pDecoder);
if (onRead == NULL || onSeek == NULL) {
return MA_INVALID_ARGS;
}
pDecoder->ds.onRead = ma_decoder__data_source_on_read;
pDecoder->ds.onSeek = ma_decoder__data_source_on_seek;
pDecoder->ds.onGetDataFormat = ma_decoder__data_source_on_get_data_format;
pDecoder->ds.onGetCursor = ma_decoder__data_source_on_get_cursor;
pDecoder->ds.onGetLength = ma_decoder__data_source_on_get_length;
pDecoder->onRead = onRead;
pDecoder->onSeek = onSeek;
pDecoder->pUserData = pUserData;
result = ma_decoder__init_allocation_callbacks(pConfig, pDecoder);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
static ma_result ma_decoder__postinit(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
ma_result result = MA_SUCCESS;
/* Basic validation in case the internal decoder supports different limits to miniaudio. */
if (pDecoder->internalChannels < MA_MIN_CHANNELS || pDecoder->internalChannels > MA_MAX_CHANNELS) {
result = MA_INVALID_DATA;
}
if (result == MA_SUCCESS) {
result = ma_decoder__init_data_converter(pDecoder, pConfig);
}
/* If we failed post initialization we need to uninitialize the decoder before returning to prevent a memory leak. */
if (result != MA_SUCCESS) {
ma_decoder_uninit(pDecoder);
return result;
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
MA_API ma_result ma_decoder_init_file_mp3(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
return ma_decoder_init_vfs_mp3(NULL, pFilePath, pConfig, pDecoder);
}
MA_API ma_result ma_decoder_init_file_vorbis(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
return ma_decoder_init_vfs_vorbis(NULL, pFilePath, pConfig, pDecoder);
}
MA_API ma_result ma_decoder_init_file_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
return ma_decoder_init_vfs_w(NULL, pFilePath, pConfig, pDecoder);
}
MA_API ma_result ma_decoder_init_file_wav_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
return ma_decoder_init_vfs_wav_w(NULL, pFilePath, pConfig, pDecoder);
}
MA_API ma_result ma_decoder_init_file_flac_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
return ma_decoder_init_vfs_flac_w(NULL, pFilePath, pConfig, pDecoder);
}
MA_API ma_result ma_decoder_init_file_mp3_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
return ma_decoder_init_vfs_mp3_w(NULL, pFilePath, pConfig, pDecoder);
}
MA_API ma_result ma_decoder_init_file_vorbis_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
{
return ma_decoder_init_vfs_vorbis_w(NULL, pFilePath, pConfig, pDecoder);
}
MA_API ma_result ma_decoder_uninit(ma_decoder* pDecoder)
{
if (pDecoder == NULL) {
return MA_INVALID_ARGS;
}
if (pDecoder->onUninit) {
pDecoder->onUninit(pDecoder);
}
if (pDecoder->onRead == ma_decoder__on_read_vfs) {
if (pDecoder->backend.vfs.pVFS == NULL) {
ma_default_vfs_close(NULL, pDecoder->backend.vfs.file);
} else {
ma_vfs_close(pDecoder->backend.vfs.pVFS, pDecoder->backend.vfs.file);
}
}
ma_data_converter_uninit(&pDecoder->converter);
return MA_SUCCESS;
}
MA_API ma_result ma_decoder_get_cursor_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pCursor)
{
if (pCursor == NULL) {
return MA_INVALID_ARGS;
}
*pCursor = 0;
if (pDecoder == NULL) {
return MA_INVALID_ARGS;
}
*pCursor = pDecoder->readPointerInPCMFrames;
return MA_SUCCESS;
}
MA_API ma_uint64 ma_decoder_get_length_in_pcm_frames(ma_decoder* pDecoder)
{
if (pDecoder == NULL) {
return 0;
}
if (pDecoder->onGetLengthInPCMFrames) {
ma_uint64 nativeLengthInPCMFrames = pDecoder->onGetLengthInPCMFrames(pDecoder);
if (pDecoder->internalSampleRate == pDecoder->outputSampleRate) {
return nativeLengthInPCMFrames;
} else {
return ma_calculate_frame_count_after_resampling(pDecoder->outputSampleRate, pDecoder->internalSampleRate, nativeLengthInPCMFrames);
}
}
return 0;
}
MA_API ma_uint64 ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount)
{
ma_result result;
ma_uint64 totalFramesReadOut;
ma_uint64 totalFramesReadIn;
void* pRunningFramesOut;
if (pDecoder == NULL) {
return 0;
}
if (pDecoder->onReadPCMFrames == NULL) {
return 0;
}
/* Fast path. */
if (pDecoder->converter.isPassthrough) {
totalFramesReadOut = pDecoder->onReadPCMFrames(pDecoder, pFramesOut, frameCount);
} else {
/*
Getting here means we need to do data conversion. If we're seeking forward and are _not_ doing resampling we can run this in a fast path. If we're doing resampling we
need to run through each sample because we need to ensure it's internal cache is updated.
*/
if (pFramesOut == NULL && pDecoder->converter.hasResampler == MA_FALSE) {
totalFramesReadOut = pDecoder->onReadPCMFrames(pDecoder, NULL, frameCount); /* All decoder backends must support passing in NULL for the output buffer. */
} else {
/* Slow path. Need to run everything through the data converter. */
totalFramesReadOut = 0;
totalFramesReadIn = 0;
pRunningFramesOut = pFramesOut;
while (totalFramesReadOut < frameCount) {
ma_uint8 pIntermediaryBuffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In internal format. */
ma_uint64 intermediaryBufferCap = sizeof(pIntermediaryBuffer) / ma_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels);
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(&pDecoder->converter, framesToReadThisIterationOut);
if (framesToReadThisIterationIn > requiredInputFrameCount) {
framesToReadThisIterationIn = requiredInputFrameCount;
}
if (requiredInputFrameCount > 0) {
framesReadThisIterationIn = pDecoder->onReadPCMFrames(pDecoder, pIntermediaryBuffer, framesToReadThisIterationIn);
totalFramesReadIn += framesReadThisIterationIn;
}
/*
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.
*/
framesReadThisIterationOut = framesToReadThisIterationOut;
result = ma_data_converter_process_pcm_frames(&pDecoder->converter, pIntermediaryBuffer, &framesReadThisIterationIn, pRunningFramesOut, &framesReadThisIterationOut);
if (result != MA_SUCCESS) {
break;
}
totalFramesReadOut += framesReadThisIterationOut;
if (pRunningFramesOut != NULL) {
pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesReadThisIterationOut * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels));
}
if (framesReadThisIterationIn == 0 && framesReadThisIterationOut == 0) {
break; /* We're done. */
}
}
}
}
pDecoder->readPointerInPCMFrames += totalFramesReadOut;
return totalFramesReadOut;
}
MA_API ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex)
{
if (pDecoder == NULL) {
return MA_INVALID_ARGS;
}
if (pDecoder->onSeekToPCMFrame) {
ma_result result;
ma_uint64 internalFrameIndex;
if (pDecoder->internalSampleRate == pDecoder->outputSampleRate) {
internalFrameIndex = frameIndex;
} else {
internalFrameIndex = ma_calculate_frame_count_after_resampling(pDecoder->internalSampleRate, pDecoder->outputSampleRate, frameIndex);
}
result = pDecoder->onSeekToPCMFrame(pDecoder, internalFrameIndex);
if (result == MA_SUCCESS) {
pDecoder->readPointerInPCMFrames = frameIndex;
}
return result;
}
/* Should never get here, but if we do it means onSeekToPCMFrame was not set by the backend. */
return MA_INVALID_ARGS;
}
MA_API ma_result ma_decoder_get_available_frames(ma_decoder* pDecoder, ma_uint64* pAvailableFrames)
{
ma_uint64 totalFrameCount;
if (pAvailableFrames == NULL) {
return MA_INVALID_ARGS;
}
*pAvailableFrames = 0;
if (pDecoder == NULL) {
return MA_INVALID_ARGS;
}
totalFrameCount = ma_decoder_get_length_in_pcm_frames(pDecoder);
if (totalFrameCount == 0) {
return MA_NOT_IMPLEMENTED;
}
if (totalFrameCount <= pDecoder->readPointerInPCMFrames) {
*pAvailableFrames = 0;
} else {
*pAvailableFrames = totalFrameCount - pDecoder->readPointerInPCMFrames;
}
return MA_SUCCESS; /* No frames available. */
}
static ma_result ma_decoder__full_decode_and_uninit(ma_decoder* pDecoder, ma_decoder_config* pConfigOut, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
{
ma_uint64 totalFrameCount;
ma_uint64 bpf;
ma_uint64 dataCapInFrames;
void* pPCMFramesOut;
MA_ASSERT(pDecoder != NULL);
totalFrameCount = 0;
bpf = ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels);
/* The frame count is unknown until we try reading. Thus, we just run in a loop. */
dataCapInFrames = 0;
pPCMFramesOut = NULL;
for (;;) {
ma_uint64 frameCountToTryReading;
ma_uint64 framesJustRead;
/* Make room if there's not enough. */
if (totalFrameCount == dataCapInFrames) {
void* pNewPCMFramesOut;
ma_uint64 oldDataCapInFrames = dataCapInFrames;
ma_uint64 newDataCapInFrames = dataCapInFrames*2;
if (newDataCapInFrames == 0) {
newDataCapInFrames = 4096;
}
if ((newDataCapInFrames * bpf) > MA_SIZE_MAX) {
ma__free_from_callbacks(pPCMFramesOut, &pDecoder->allocationCallbacks);
return MA_TOO_BIG;
}
pNewPCMFramesOut = (void*)ma__realloc_from_callbacks(pPCMFramesOut, (size_t)(newDataCapInFrames * bpf), (size_t)(oldDataCapInFrames * bpf), &pDecoder->allocationCallbacks);
if (pNewPCMFramesOut == NULL) {
ma__free_from_callbacks(pPCMFramesOut, &pDecoder->allocationCallbacks);
return MA_OUT_OF_MEMORY;
}
dataCapInFrames = newDataCapInFrames;
pPCMFramesOut = pNewPCMFramesOut;
}
frameCountToTryReading = dataCapInFrames - totalFrameCount;
MA_ASSERT(frameCountToTryReading > 0);
framesJustRead = ma_decoder_read_pcm_frames(pDecoder, (ma_uint8*)pPCMFramesOut + (totalFrameCount * bpf), frameCountToTryReading);
totalFrameCount += framesJustRead;
if (framesJustRead < frameCountToTryReading) {
break;
}
}
if (pConfigOut != NULL) {
pConfigOut->format = pDecoder->outputFormat;
pConfigOut->channels = pDecoder->outputChannels;
pConfigOut->sampleRate = pDecoder->outputSampleRate;
ma_channel_map_copy(pConfigOut->channelMap, pDecoder->outputChannelMap, pDecoder->outputChannels);
}
if (ppPCMFramesOut != NULL) {
*ppPCMFramesOut = pPCMFramesOut;
} else {
ma__free_from_callbacks(pPCMFramesOut, &pDecoder->allocationCallbacks);
}
if (pFrameCountOut != NULL) {
*pFrameCountOut = totalFrameCount;
}
ma_decoder_uninit(pDecoder);
return MA_SUCCESS;
}
MA_API ma_result ma_decode_from_vfs(ma_vfs* pVFS, const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
{
ma_result result;
ma_decoder_config config;
ma_decoder decoder;
if (pFrameCountOut != NULL) {
*pFrameCountOut = 0;
}
if (ppPCMFramesOut != NULL) {
*ppPCMFramesOut = NULL;
}
config = ma_decoder_config_init_copy(pConfig);
result = ma_decoder_init_vfs(pVFS, pFilePath, &config, &decoder);
if (result != MA_SUCCESS) {
return result;
}
result = ma_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppPCMFramesOut);
return result;
}
MA_API ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
{
return ma_decode_from_vfs(NULL, pFilePath, pConfig, pFrameCountOut, ppPCMFramesOut);
}
MA_API ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
{
ma_decoder_config config;
ma_decoder decoder;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
static drwav_bool32 ma_encoder__internal_on_seek_wav(void* pUserData, int offset, drwav_seek_origin origin)
{
ma_encoder* pEncoder = (ma_encoder*)pUserData;
MA_ASSERT(pEncoder != NULL);
return pEncoder->onSeek(pEncoder, offset, (origin == drwav_seek_origin_start) ? ma_seek_origin_start : ma_seek_origin_current);
}
static ma_result ma_encoder__on_init_wav(ma_encoder* pEncoder)
{
drwav_data_format wavFormat;
drwav_allocation_callbacks allocationCallbacks;
drwav* pWav;
MA_ASSERT(pEncoder != NULL);
pWav = (drwav*)ma__malloc_from_callbacks(sizeof(*pWav), &pEncoder->config.allocationCallbacks);
if (pWav == NULL) {
return MA_OUT_OF_MEMORY;
}
wavFormat.container = drwav_container_riff;
wavFormat.channels = pEncoder->config.channels;
wavFormat.sampleRate = pEncoder->config.sampleRate;
wavFormat.bitsPerSample = ma_get_bytes_per_sample(pEncoder->config.format) * 8;
if (pEncoder->config.format == ma_format_f32) {
wavFormat.format = DR_WAVE_FORMAT_IEEE_FLOAT;
} else {
wavFormat.format = DR_WAVE_FORMAT_PCM;
}
allocationCallbacks.pUserData = pEncoder->config.allocationCallbacks.pUserData;
allocationCallbacks.onMalloc = pEncoder->config.allocationCallbacks.onMalloc;
allocationCallbacks.onRealloc = pEncoder->config.allocationCallbacks.onRealloc;
allocationCallbacks.onFree = pEncoder->config.allocationCallbacks.onFree;
if (!drwav_init_write(pWav, &wavFormat, ma_encoder__internal_on_write_wav, ma_encoder__internal_on_seek_wav, pEncoder, &allocationCallbacks)) {
return MA_ERROR;
}
pEncoder->pInternalEncoder = pWav;
return MA_SUCCESS;
}
static void ma_encoder__on_uninit_wav(ma_encoder* pEncoder)
{
drwav* pWav;
MA_ASSERT(pEncoder != NULL);
pWav = (drwav*)pEncoder->pInternalEncoder;
MA_ASSERT(pWav != NULL);
drwav_uninit(pWav);
ma__free_from_callbacks(pWav, &pEncoder->config.allocationCallbacks);
}
static ma_uint64 ma_encoder__on_write_pcm_frames_wav(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount)
{
drwav* pWav;
MA_ASSERT(pEncoder != NULL);
pWav = (drwav*)pEncoder->pInternalEncoder;
MA_ASSERT(pWav != NULL);
return drwav_write_pcm_frames(pWav, frameCount, pFramesIn);
}
#endif
MA_API ma_encoder_config ma_encoder_config_init(ma_resource_format resourceFormat, ma_format format, ma_uint32 channels, ma_uint32 sampleRate)
{
ma_encoder_config config;
MA_ZERO_OBJECT(&config);
config.resourceFormat = resourceFormat;
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
return config;
}
MA_API ma_result ma_encoder_preinit(const ma_encoder_config* pConfig, ma_encoder* pEncoder)
{
ma_result result;
if (pEncoder == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pEncoder);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
if (pConfig->format == ma_format_unknown || pConfig->channels == 0 || pConfig->sampleRate == 0) {
return MA_INVALID_ARGS;
}
pEncoder->config = *pConfig;
result = ma_allocation_callbacks_init_copy(&pEncoder->config.allocationCallbacks, &pConfig->allocationCallbacks);
if (result != MA_SUCCESS) {
return result;
}
return MA_SUCCESS;
}
MA_API ma_result ma_encoder_init__internal(ma_encoder_write_proc onWrite, ma_encoder_seek_proc onSeek, void* pUserData, ma_encoder* pEncoder)
{
ma_result result = MA_SUCCESS;
/* This assumes ma_encoder_preinit() has been called prior. */
MA_ASSERT(pEncoder != NULL);
if (onWrite == NULL || onSeek == NULL) {
return MA_INVALID_ARGS;
}
pEncoder->onWrite = onWrite;
pEncoder->onSeek = onSeek;
pEncoder->pUserData = pUserData;
switch (pEncoder->config.resourceFormat)
{
case ma_resource_format_wav:
{
#if defined(MA_HAS_WAV)
pEncoder->onInit = ma_encoder__on_init_wav;
pEncoder->onUninit = ma_encoder__on_uninit_wav;
pEncoder->onWritePCMFrames = ma_encoder__on_write_pcm_frames_wav;
#else
result = MA_NO_BACKEND;
#endif
} break;
default:
{
result = MA_INVALID_ARGS;
} break;
}
/* Getting here means we should have our backend callbacks set up. */
if (result == MA_SUCCESS) {
result = pEncoder->onInit(pEncoder);
if (result != MA_SUCCESS) {
return result;
}
}
return MA_SUCCESS;
}
MA_API size_t ma_encoder__on_write_stdio(ma_encoder* pEncoder, const void* pBufferIn, size_t bytesToWrite)
{
return fwrite(pBufferIn, 1, bytesToWrite, (FILE*)pEncoder->pFile);
}
MA_API ma_bool32 ma_encoder__on_seek_stdio(ma_encoder* pEncoder, int byteOffset, ma_seek_origin origin)
{
return fseek((FILE*)pEncoder->pFile, byteOffset, (origin == ma_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
}
MA_API ma_result ma_encoder_init_file(const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
{
ma_result result;
FILE* pFile;
result = ma_encoder_preinit(pConfig, pEncoder);
if (result != MA_SUCCESS) {
return result;
}
/* Now open the file. If this fails we don't need to uninitialize the encoder. */
result = ma_fopen(&pFile, pFilePath, "wb");
if (pFile == NULL) {
return result;
}
pEncoder->pFile = pFile;
return ma_encoder_init__internal(ma_encoder__on_write_stdio, ma_encoder__on_seek_stdio, NULL, pEncoder);
}
MA_API ma_result ma_encoder_init_file_w(const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
{
ma_result result;
FILE* pFile;
result = ma_encoder_preinit(pConfig, pEncoder);
if (result != MA_SUCCESS) {
return result;
}
/* Now open the file. If this fails we don't need to uninitialize the encoder. */
result = ma_wfopen(&pFile, pFilePath, L"wb", &pEncoder->config.allocationCallbacks);
if (pFile != NULL) {
return result;
}
pEncoder->pFile = pFile;
return ma_encoder_init__internal(ma_encoder__on_write_stdio, ma_encoder__on_seek_stdio, NULL, pEncoder);
}
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_result result;
result = ma_encoder_preinit(pConfig, pEncoder);
if (result != MA_SUCCESS) {
return result;
}
return ma_encoder_init__internal(onWrite, onSeek, pUserData, pEncoder);
}
MA_API void ma_encoder_uninit(ma_encoder* pEncoder)
{
if (pEncoder == NULL) {
return;
}
if (pEncoder->onUninit) {
pEncoder->onUninit(pEncoder);
}
/* If we have a file handle, close it. */
if (pEncoder->onWrite == ma_encoder__on_write_stdio) {
fclose((FILE*)pEncoder->pFile);
}
}
MA_API ma_uint64 ma_encoder_write_pcm_frames(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount)
{
if (pEncoder == NULL || pFramesIn == NULL) {
return 0;
}
return pEncoder->onWritePCMFrames(pEncoder, pFramesIn, frameCount);
}
#endif /* MA_NO_ENCODING */
/**************************************************************************************************************************************************************
Generation
**************************************************************************************************************************************************************/
#ifndef MA_NO_GENERATION
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)
{
ma_waveform_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.sampleRate = sampleRate;
config.type = type;
config.amplitude = amplitude;
config.frequency = frequency;
return config;
}
static ma_result ma_waveform__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
{
ma_uint64 framesRead = ma_waveform_read_pcm_frames((ma_waveform*)pDataSource, pFramesOut, frameCount);
if (pFramesRead != NULL) {
*pFramesRead = framesRead;
}
if (framesRead < frameCount) {
return MA_AT_END;
}
return MA_SUCCESS;
}
static ma_result ma_waveform__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
{
return ma_waveform_seek_to_pcm_frame((ma_waveform*)pDataSource, frameIndex);
}
static ma_result ma_waveform__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate)
{
ma_waveform* pWaveform = (ma_waveform*)pDataSource;
*pFormat = pWaveform->config.format;
*pChannels = pWaveform->config.channels;
*pSampleRate = pWaveform->config.sampleRate;
return MA_SUCCESS;
}
static ma_result ma_waveform__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
{
ma_waveform* pWaveform = (ma_waveform*)pDataSource;
*pCursor = (ma_uint64)(pWaveform->time / pWaveform->advance);
return MA_SUCCESS;
}
MA_API ma_result ma_waveform_init(const ma_waveform_config* pConfig, ma_waveform* pWaveform)
{
if (pWaveform == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pWaveform);
pWaveform->ds.onRead = ma_waveform__data_source_on_read;
pWaveform->ds.onSeek = ma_waveform__data_source_on_seek;
pWaveform->ds.onGetDataFormat = ma_waveform__data_source_on_get_data_format;
pWaveform->ds.onGetCursor = ma_waveform__data_source_on_get_cursor;
pWaveform->ds.onGetLength = NULL; /* Intentionally set to NULL since there's no notion of a length in waveforms. */
pWaveform->config = *pConfig;
pWaveform->advance = 1.0 / pWaveform->config.sampleRate;
pWaveform->time = 0;
return MA_SUCCESS;
}
MA_API ma_result ma_waveform_set_amplitude(ma_waveform* pWaveform, double amplitude)
{
if (pWaveform == NULL) {
return MA_INVALID_ARGS;
}
pWaveform->config.amplitude = amplitude;
return MA_SUCCESS;
}
MA_API ma_result ma_waveform_set_frequency(ma_waveform* pWaveform, double frequency)
{
if (pWaveform == NULL) {
return MA_INVALID_ARGS;
}
pWaveform->config.frequency = frequency;
return MA_SUCCESS;
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
return (float)(ma_sin(MA_TAU_D * time * frequency) * amplitude);
}
static ma_int16 ma_waveform_sine_s16(double time, double frequency, double amplitude)
{
return ma_pcm_sample_f32_to_s16(ma_waveform_sine_f32(time, frequency, amplitude));
}
static float ma_waveform_square_f32(double time, double frequency, double amplitude)
{
double t = time * frequency;
double f = t - (ma_int64)t;
double r;
if (f < 0.5) {
r = amplitude;
} else {
r = -amplitude;
}
return (float)r;
}
static ma_int16 ma_waveform_square_s16(double time, double frequency, double amplitude)
{
return ma_pcm_sample_f32_to_s16(ma_waveform_square_f32(time, frequency, amplitude));
}
static float ma_waveform_triangle_f32(double time, double frequency, double amplitude)
{
double t = time * frequency;
double f = t - (ma_int64)t;
double r;
r = 2 * ma_abs(2 * (f - 0.5)) - 1;
return (float)(r * amplitude);
}
static ma_int16 ma_waveform_triangle_s16(double time, double frequency, double amplitude)
{
return ma_pcm_sample_f32_to_s16(ma_waveform_triangle_f32(time, frequency, amplitude));
}
static float ma_waveform_sawtooth_f32(double time, double frequency, double amplitude)
{
double t = time * frequency;
double f = t - (ma_int64)t;
double r;
r = 2 * (f - 0.5);
return (float)(r * amplitude);
}
static ma_int16 ma_waveform_sawtooth_s16(double time, double frequency, double amplitude)
{
return ma_pcm_sample_f32_to_s16(ma_waveform_sawtooth_f32(time, frequency, amplitude));
}
static void ma_waveform_read_pcm_frames__sine(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
{
ma_uint64 iFrame;
ma_uint64 iChannel;
ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
ma_uint32 bpf = bps * pWaveform->config.channels;
MA_ASSERT(pWaveform != NULL);
MA_ASSERT(pFramesOut != NULL);
if (pWaveform->config.format == ma_format_f32) {
float* pFramesOutF32 = (float*)pFramesOut;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_waveform_sine_f32(pWaveform->time, pWaveform->config.frequency, pWaveform->config.amplitude);
pWaveform->time += pWaveform->advance;
for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
}
}
} else if (pWaveform->config.format == ma_format_s16) {
ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_int16 s = ma_waveform_sine_s16(pWaveform->time, pWaveform->config.frequency, pWaveform->config.amplitude);
pWaveform->time += pWaveform->advance;
for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_waveform_sine_f32(pWaveform->time, pWaveform->config.frequency, pWaveform->config.amplitude);
pWaveform->time += pWaveform->advance;
for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
}
}
}
}
static void ma_waveform_read_pcm_frames__square(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
{
ma_uint64 iFrame;
ma_uint64 iChannel;
ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
ma_uint32 bpf = bps * pWaveform->config.channels;
MA_ASSERT(pWaveform != NULL);
MA_ASSERT(pFramesOut != NULL);
if (pWaveform->config.format == ma_format_f32) {
float* pFramesOutF32 = (float*)pFramesOut;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_waveform_square_f32(pWaveform->time, pWaveform->config.frequency, pWaveform->config.amplitude);
pWaveform->time += pWaveform->advance;
for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
}
}
} else if (pWaveform->config.format == ma_format_s16) {
ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_int16 s = ma_waveform_square_s16(pWaveform->time, pWaveform->config.frequency, pWaveform->config.amplitude);
pWaveform->time += pWaveform->advance;
for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_waveform_square_f32(pWaveform->time, pWaveform->config.frequency, pWaveform->config.amplitude);
pWaveform->time += pWaveform->advance;
for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
}
}
}
}
static void ma_waveform_read_pcm_frames__triangle(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
{
ma_uint64 iFrame;
ma_uint64 iChannel;
ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
ma_uint32 bpf = bps * pWaveform->config.channels;
MA_ASSERT(pWaveform != NULL);
MA_ASSERT(pFramesOut != NULL);
if (pWaveform->config.format == ma_format_f32) {
float* pFramesOutF32 = (float*)pFramesOut;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_waveform_triangle_f32(pWaveform->time, pWaveform->config.frequency, pWaveform->config.amplitude);
pWaveform->time += pWaveform->advance;
for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
}
}
} else if (pWaveform->config.format == ma_format_s16) {
ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_int16 s = ma_waveform_triangle_s16(pWaveform->time, pWaveform->config.frequency, pWaveform->config.amplitude);
pWaveform->time += pWaveform->advance;
for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_waveform_triangle_f32(pWaveform->time, pWaveform->config.frequency, pWaveform->config.amplitude);
pWaveform->time += pWaveform->advance;
for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
}
}
}
}
static void ma_waveform_read_pcm_frames__sawtooth(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
{
ma_uint64 iFrame;
ma_uint64 iChannel;
ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
ma_uint32 bpf = bps * pWaveform->config.channels;
MA_ASSERT(pWaveform != NULL);
MA_ASSERT(pFramesOut != NULL);
if (pWaveform->config.format == ma_format_f32) {
float* pFramesOutF32 = (float*)pFramesOut;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_waveform_sawtooth_f32(pWaveform->time, pWaveform->config.frequency, pWaveform->config.amplitude);
pWaveform->time += pWaveform->advance;
for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
}
}
} else if (pWaveform->config.format == ma_format_s16) {
ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_int16 s = ma_waveform_sawtooth_s16(pWaveform->time, pWaveform->config.frequency, pWaveform->config.amplitude);
pWaveform->time += pWaveform->advance;
for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_waveform_sawtooth_f32(pWaveform->time, pWaveform->config.frequency, pWaveform->config.amplitude);
pWaveform->time += pWaveform->advance;
for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
}
}
}
}
MA_API ma_uint64 ma_waveform_read_pcm_frames(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
{
if (pWaveform == NULL) {
return 0;
}
if (pFramesOut != NULL) {
switch (pWaveform->config.type)
{
case ma_waveform_type_sine:
{
ma_waveform_read_pcm_frames__sine(pWaveform, pFramesOut, frameCount);
} break;
case ma_waveform_type_square:
{
ma_waveform_read_pcm_frames__square(pWaveform, pFramesOut, frameCount);
} break;
case ma_waveform_type_triangle:
{
ma_waveform_read_pcm_frames__triangle(pWaveform, pFramesOut, frameCount);
} break;
case ma_waveform_type_sawtooth:
{
ma_waveform_read_pcm_frames__sawtooth(pWaveform, pFramesOut, frameCount);
} break;
default: return 0;
}
} else {
pWaveform->time += pWaveform->advance * (ma_int64)frameCount; /* Cast to int64 required for VC6. Won't affect anything in practice. */
}
return frameCount;
}
MA_API ma_result ma_waveform_seek_to_pcm_frame(ma_waveform* pWaveform, ma_uint64 frameIndex)
{
if (pWaveform == NULL) {
return MA_INVALID_ARGS;
}
pWaveform->time = pWaveform->advance * (ma_int64)frameIndex; /* Casting for VC6. Won't be an issue in practice. */
return MA_SUCCESS;
}
MA_API ma_noise_config ma_noise_config_init(ma_format format, ma_uint32 channels, ma_noise_type type, ma_int32 seed, double amplitude)
{
ma_noise_config config;
MA_ZERO_OBJECT(&config);
config.format = format;
config.channels = channels;
config.type = type;
config.seed = seed;
config.amplitude = amplitude;
if (config.seed == 0) {
config.seed = MA_DEFAULT_LCG_SEED;
}
return config;
}
static ma_result ma_noise__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
{
ma_uint64 framesRead = ma_noise_read_pcm_frames((ma_noise*)pDataSource, pFramesOut, frameCount);
if (pFramesRead != NULL) {
*pFramesRead = framesRead;
}
if (framesRead < frameCount) {
return MA_AT_END;
}
return MA_SUCCESS;
}
static ma_result ma_noise__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
{
/* No-op. Just pretend to be successful. */
(void)pDataSource;
(void)frameIndex;
return MA_SUCCESS;
}
static ma_result ma_noise__data_source_on_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate)
{
ma_noise* pNoise = (ma_noise*)pDataSource;
*pFormat = pNoise->config.format;
*pChannels = pNoise->config.channels;
*pSampleRate = 0; /* There is no notion of sample rate with noise generation. */
return MA_SUCCESS;
}
MA_API ma_result ma_noise_init(const ma_noise_config* pConfig, ma_noise* pNoise)
{
if (pNoise == NULL) {
return MA_INVALID_ARGS;
}
MA_ZERO_OBJECT(pNoise);
if (pConfig == NULL) {
return MA_INVALID_ARGS;
}
if (pConfig->channels < MA_MIN_CHANNELS || pConfig->channels > MA_MAX_CHANNELS) {
return MA_INVALID_ARGS;
}
pNoise->ds.onRead = ma_noise__data_source_on_read;
pNoise->ds.onSeek = ma_noise__data_source_on_seek; /* <-- No-op for noise. */
pNoise->ds.onGetDataFormat = ma_noise__data_source_on_get_data_format;
pNoise->ds.onGetCursor = NULL; /* No notion of a cursor for noise. */
pNoise->ds.onGetLength = NULL; /* No notion of a length for noise. */
pNoise->config = *pConfig;
ma_lcg_seed(&pNoise->lcg, pConfig->seed);
if (pNoise->config.type == ma_noise_type_pink) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) {
pNoise->state.pink.accumulation[iChannel] = 0;
pNoise->state.pink.counter[iChannel] = 1;
}
}
if (pNoise->config.type == ma_noise_type_brownian) {
ma_uint32 iChannel;
for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) {
pNoise->state.brownian.accumulation[iChannel] = 0;
}
}
return MA_SUCCESS;
}
static MA_INLINE float ma_noise_f32_white(ma_noise* pNoise)
{
return (float)(ma_lcg_rand_f64(&pNoise->lcg) * pNoise->config.amplitude);
}
static MA_INLINE ma_int16 ma_noise_s16_white(ma_noise* pNoise)
{
return ma_pcm_sample_f32_to_s16(ma_noise_f32_white(pNoise));
}
static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__white(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
{
ma_uint64 iFrame;
ma_uint32 iChannel;
if (pNoise->config.format == ma_format_f32) {
float* pFramesOutF32 = (float*)pFramesOut;
if (pNoise->config.duplicateChannels) {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_noise_f32_white(pNoise);
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
pFramesOutF32[iFrame*pNoise->config.channels + iChannel] = s;
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
pFramesOutF32[iFrame*pNoise->config.channels + iChannel] = ma_noise_f32_white(pNoise);
}
}
}
} else if (pNoise->config.format == ma_format_s16) {
ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
if (pNoise->config.duplicateChannels) {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_int16 s = ma_noise_s16_white(pNoise);
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
pFramesOutS16[iFrame*pNoise->config.channels + iChannel] = s;
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
pFramesOutS16[iFrame*pNoise->config.channels + iChannel] = ma_noise_s16_white(pNoise);
}
}
}
} else {
ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format);
ma_uint32 bpf = bps * pNoise->config.channels;
if (pNoise->config.duplicateChannels) {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_noise_f32_white(pNoise);
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
float s = ma_noise_f32_white(pNoise);
ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
}
}
}
}
return frameCount;
}
static MA_INLINE unsigned int ma_tzcnt32(unsigned int x)
{
unsigned int n;
/* Special case for odd numbers since they should happen about half the time. */
if (x & 0x1) {
return 0;
}
if (x == 0) {
return sizeof(x) << 3;
}
n = 1;
if ((x & 0x0000FFFF) == 0) { x >>= 16; n += 16; }
if ((x & 0x000000FF) == 0) { x >>= 8; n += 8; }
if ((x & 0x0000000F) == 0) { x >>= 4; n += 4; }
if ((x & 0x00000003) == 0) { x >>= 2; n += 2; }
n -= x & 0x00000001;
return n;
}
/*
Pink noise generation based on Tonic (public domain) with modifications. https://github.com/TonicAudio/Tonic/blob/master/src/Tonic/Noise.h
This is basically _the_ reference for pink noise from what I've found: http://www.firstpr.com.au/dsp/pink-noise/
*/
static MA_INLINE float ma_noise_f32_pink(ma_noise* pNoise, ma_uint32 iChannel)
{
double result;
double binPrev;
double binNext;
unsigned int ibin;
ibin = ma_tzcnt32(pNoise->state.pink.counter[iChannel]) & (ma_countof(pNoise->state.pink.bin[0]) - 1);
binPrev = pNoise->state.pink.bin[iChannel][ibin];
binNext = ma_lcg_rand_f64(&pNoise->lcg);
pNoise->state.pink.bin[iChannel][ibin] = binNext;
pNoise->state.pink.accumulation[iChannel] += (binNext - binPrev);
pNoise->state.pink.counter[iChannel] += 1;
result = (ma_lcg_rand_f64(&pNoise->lcg) + pNoise->state.pink.accumulation[iChannel]);
result /= 10;
return (float)(result * pNoise->config.amplitude);
}
static MA_INLINE ma_int16 ma_noise_s16_pink(ma_noise* pNoise, ma_uint32 iChannel)
{
return ma_pcm_sample_f32_to_s16(ma_noise_f32_pink(pNoise, iChannel));
}
static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__pink(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
{
ma_uint64 iFrame;
ma_uint32 iChannel;
if (pNoise->config.format == ma_format_f32) {
float* pFramesOutF32 = (float*)pFramesOut;
if (pNoise->config.duplicateChannels) {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_noise_f32_pink(pNoise, 0);
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
pFramesOutF32[iFrame*pNoise->config.channels + iChannel] = s;
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
pFramesOutF32[iFrame*pNoise->config.channels + iChannel] = ma_noise_f32_pink(pNoise, iChannel);
}
}
}
} else if (pNoise->config.format == ma_format_s16) {
ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
if (pNoise->config.duplicateChannels) {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_int16 s = ma_noise_s16_pink(pNoise, 0);
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
pFramesOutS16[iFrame*pNoise->config.channels + iChannel] = s;
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
pFramesOutS16[iFrame*pNoise->config.channels + iChannel] = ma_noise_s16_pink(pNoise, iChannel);
}
}
}
} else {
ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format);
ma_uint32 bpf = bps * pNoise->config.channels;
if (pNoise->config.duplicateChannels) {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_noise_f32_pink(pNoise, 0);
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
float s = ma_noise_f32_pink(pNoise, iChannel);
ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
}
}
}
}
return frameCount;
}
static MA_INLINE float ma_noise_f32_brownian(ma_noise* pNoise, ma_uint32 iChannel)
{
double result;
result = (ma_lcg_rand_f64(&pNoise->lcg) + pNoise->state.brownian.accumulation[iChannel]);
result /= 1.005; /* Don't escape the -1..1 range on average. */
pNoise->state.brownian.accumulation[iChannel] = result;
result /= 20;
return (float)(result * pNoise->config.amplitude);
}
static MA_INLINE ma_int16 ma_noise_s16_brownian(ma_noise* pNoise, ma_uint32 iChannel)
{
return ma_pcm_sample_f32_to_s16(ma_noise_f32_brownian(pNoise, iChannel));
}
static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__brownian(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
{
ma_uint64 iFrame;
ma_uint32 iChannel;
if (pNoise->config.format == ma_format_f32) {
float* pFramesOutF32 = (float*)pFramesOut;
if (pNoise->config.duplicateChannels) {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_noise_f32_brownian(pNoise, 0);
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
pFramesOutF32[iFrame*pNoise->config.channels + iChannel] = s;
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
pFramesOutF32[iFrame*pNoise->config.channels + iChannel] = ma_noise_f32_brownian(pNoise, iChannel);
}
}
}
} else if (pNoise->config.format == ma_format_s16) {
ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
if (pNoise->config.duplicateChannels) {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
ma_int16 s = ma_noise_s16_brownian(pNoise, 0);
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
pFramesOutS16[iFrame*pNoise->config.channels + iChannel] = s;
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
pFramesOutS16[iFrame*pNoise->config.channels + iChannel] = ma_noise_s16_brownian(pNoise, iChannel);
}
}
}
} else {
ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format);
ma_uint32 bpf = bps * pNoise->config.channels;
if (pNoise->config.duplicateChannels) {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
float s = ma_noise_f32_brownian(pNoise, 0);
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
}
}
} else {
for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
for (iChannel = 0; iChannel < pNoise->config.channels; iChannel += 1) {
float s = ma_noise_f32_brownian(pNoise, iChannel);
ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
}
}
}
}
return frameCount;
}
MA_API ma_uint64 ma_noise_read_pcm_frames(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
{
if (pNoise == NULL) {
return 0;
}
/* The output buffer is allowed to be NULL. Since we aren't tracking cursors or anything we can just do nothing and pretend to be successful. */
if (pFramesOut == NULL) {
return frameCount;
}
if (pNoise->config.type == ma_noise_type_white) {
return ma_noise_read_pcm_frames__white(pNoise, pFramesOut, frameCount);
}
if (pNoise->config.type == ma_noise_type_pink) {
return ma_noise_read_pcm_frames__pink(pNoise, pFramesOut, frameCount);
}
if (pNoise->config.type == ma_noise_type_brownian) {
return ma_noise_read_pcm_frames__brownian(pNoise, pFramesOut, frameCount);
}
/* Should never get here. */
MA_ASSERT(MA_FALSE);
return 0;
}
#endif /* MA_NO_GENERATION */
/**************************************************************************************************************************************************************
***************************************************************************************************************************************************************
Auto Generated
==============
All code below is auto-generated from a tool. This mostly consists of decoding backend implementations such as dr_wav, dr_flac, etc. If you find a bug in the
code below please report the bug to the respective repository for the relevant project (probably dr_libs).
***************************************************************************************************************************************************************
**************************************************************************************************************************************************************/
#if !defined(MA_NO_WAV) && (!defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING))
#if !defined(DR_WAV_IMPLEMENTATION) && !defined(DRWAV_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */
/* dr_wav_c begin */
#ifndef dr_wav_c
#define dr_wav_c
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#ifndef DR_WAV_NO_STDIO
#include <stdio.h>
#include <wchar.h>
#endif
#ifndef DRWAV_ASSERT
#include <assert.h>
#define DRWAV_ASSERT(expression) assert(expression)
#endif
#ifndef DRWAV_MALLOC
#define DRWAV_MALLOC(sz) malloc((sz))
#endif
#ifndef DRWAV_REALLOC
#define DRWAV_REALLOC(p, sz) realloc((p), (sz))
#endif
#ifndef DRWAV_FREE
#define DRWAV_FREE(p) free((p))
#endif
#ifndef DRWAV_COPY_MEMORY
#define DRWAV_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
#endif
#ifndef DRWAV_ZERO_MEMORY
#define DRWAV_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
#endif
#ifndef DRWAV_ZERO_OBJECT
#define DRWAV_ZERO_OBJECT(p) DRWAV_ZERO_MEMORY((p), sizeof(*p))
#endif
#define drwav_countof(x) (sizeof(x) / sizeof(x[0]))
#define drwav_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
#define drwav_min(a, b) (((a) < (b)) ? (a) : (b))
#define drwav_max(a, b) (((a) > (b)) ? (a) : (b))
#define drwav_clamp(x, lo, hi) (drwav_max((lo), drwav_min((hi), (x))))
#define DRWAV_MAX_SIMD_VECTOR_SIZE 64
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
return NULL;
}
static void* drwav__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (pAllocationCallbacks == NULL) {
return NULL;
}
if (pAllocationCallbacks->onRealloc != NULL) {
return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
}
if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
void* p2;
p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
if (p2 == NULL) {
return NULL;
}
if (p != NULL) {
DRWAV_COPY_MEMORY(p2, p, szOld);
pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
}
return p2;
}
return NULL;
}
static void drwav__free_from_callbacks(void* p, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (p == NULL || pAllocationCallbacks == NULL) {
return;
}
if (pAllocationCallbacks->onFree != NULL) {
pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
}
}
static drwav_allocation_callbacks drwav_copy_allocation_callbacks_or_defaults(const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (pAllocationCallbacks != NULL) {
return *pAllocationCallbacks;
} else {
drwav_allocation_callbacks allocationCallbacks;
allocationCallbacks.pUserData = NULL;
allocationCallbacks.onMalloc = drwav__malloc_default;
allocationCallbacks.onRealloc = drwav__realloc_default;
allocationCallbacks.onFree = drwav__free_default;
return allocationCallbacks;
}
}
static DRWAV_INLINE drwav_bool32 drwav__is_compressed_format_tag(drwav_uint16 formatTag)
{
return
formatTag == DR_WAVE_FORMAT_ADPCM ||
formatTag == DR_WAVE_FORMAT_DVI_ADPCM;
}
static unsigned int drwav__chunk_padding_size_riff(drwav_uint64 chunkSize)
{
return (unsigned int)(chunkSize % 2);
}
static unsigned int drwav__chunk_padding_size_w64(drwav_uint64 chunkSize)
{
return (unsigned int)(chunkSize % 8);
}
static drwav_uint64 drwav_read_pcm_frames_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut);
static drwav_uint64 drwav_read_pcm_frames_s16__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut);
static drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount);
static drwav_result drwav__read_chunk_header(drwav_read_proc onRead, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav_chunk_header* pHeaderOut)
{
if (container == drwav_container_riff || container == drwav_container_rf64) {
drwav_uint8 sizeInBytes[4];
if (onRead(pUserData, pHeaderOut->id.fourcc, 4) != 4) {
return DRWAV_AT_END;
}
if (onRead(pUserData, sizeInBytes, 4) != 4) {
return DRWAV_INVALID_FILE;
}
pHeaderOut->sizeInBytes = drwav__bytes_to_u32(sizeInBytes);
pHeaderOut->paddingSize = drwav__chunk_padding_size_riff(pHeaderOut->sizeInBytes);
*pRunningBytesReadOut += 8;
} else {
drwav_uint8 sizeInBytes[8];
if (onRead(pUserData, pHeaderOut->id.guid, 16) != 16) {
return DRWAV_AT_END;
}
if (onRead(pUserData, sizeInBytes, 8) != 8) {
return DRWAV_INVALID_FILE;
}
pHeaderOut->sizeInBytes = drwav__bytes_to_u64(sizeInBytes) - 24;
pHeaderOut->paddingSize = drwav__chunk_padding_size_w64(pHeaderOut->sizeInBytes);
*pRunningBytesReadOut += 24;
}
return DRWAV_SUCCESS;
}
static drwav_bool32 drwav__seek_forward(drwav_seek_proc onSeek, drwav_uint64 offset, void* pUserData)
{
drwav_uint64 bytesRemainingToSeek = offset;
while (bytesRemainingToSeek > 0) {
if (bytesRemainingToSeek > 0x7FFFFFFF) {
if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_current)) {
return DRWAV_FALSE;
}
bytesRemainingToSeek -= 0x7FFFFFFF;
} else {
if (!onSeek(pUserData, (int)bytesRemainingToSeek, drwav_seek_origin_current)) {
return DRWAV_FALSE;
}
bytesRemainingToSeek = 0;
}
}
return DRWAV_TRUE;
}
static drwav_bool32 drwav__seek_from_start(drwav_seek_proc onSeek, drwav_uint64 offset, void* pUserData)
{
if (offset <= 0x7FFFFFFF) {
return onSeek(pUserData, (int)offset, drwav_seek_origin_start);
}
if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_start)) {
return DRWAV_FALSE;
}
offset -= 0x7FFFFFFF;
for (;;) {
if (offset <= 0x7FFFFFFF) {
return onSeek(pUserData, (int)offset, drwav_seek_origin_current);
}
if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_current)) {
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
if (fmtOut->extendedSize > 0) {
if (fmtOut->formatTag == DR_WAVE_FORMAT_EXTENSIBLE) {
if (fmtOut->extendedSize != 22) {
return DRWAV_FALSE;
}
}
if (fmtOut->formatTag == DR_WAVE_FORMAT_EXTENSIBLE) {
drwav_uint8 fmtext[22];
if (onRead(pUserData, fmtext, fmtOut->extendedSize) != fmtOut->extendedSize) {
return DRWAV_FALSE;
}
fmtOut->validBitsPerSample = drwav__bytes_to_u16(fmtext + 0);
fmtOut->channelMask = drwav__bytes_to_u32(fmtext + 2);
drwav__bytes_to_guid(fmtext + 6, fmtOut->subFormat);
} else {
if (!onSeek(pUserData, fmtOut->extendedSize, drwav_seek_origin_current)) {
return DRWAV_FALSE;
}
}
*pRunningBytesReadOut += fmtOut->extendedSize;
bytesReadSoFar += fmtOut->extendedSize;
}
if (!onSeek(pUserData, (int)(header.sizeInBytes - bytesReadSoFar), drwav_seek_origin_current)) {
return DRWAV_FALSE;
}
*pRunningBytesReadOut += (header.sizeInBytes - bytesReadSoFar);
}
if (header.paddingSize > 0) {
if (!onSeek(pUserData, header.paddingSize, drwav_seek_origin_current)) {
return DRWAV_FALSE;
}
*pRunningBytesReadOut += header.paddingSize;
}
return DRWAV_TRUE;
}
static size_t drwav__on_read(drwav_read_proc onRead, void* pUserData, void* pBufferOut, size_t bytesToRead, drwav_uint64* pCursor)
{
size_t bytesRead;
DRWAV_ASSERT(onRead != NULL);
DRWAV_ASSERT(pCursor != NULL);
bytesRead = onRead(pUserData, pBufferOut, bytesToRead);
*pCursor += bytesRead;
return bytesRead;
}
#if 0
static drwav_bool32 drwav__on_seek(drwav_seek_proc onSeek, void* pUserData, int offset, drwav_seek_origin origin, drwav_uint64* pCursor)
{
DRWAV_ASSERT(onSeek != NULL);
DRWAV_ASSERT(pCursor != NULL);
if (!onSeek(pUserData, offset, origin)) {
return DRWAV_FALSE;
}
if (origin == drwav_seek_origin_start) {
*pCursor = offset;
} else {
*pCursor += offset;
}
return DRWAV_TRUE;
}
#endif
static drwav_uint32 drwav_get_bytes_per_pcm_frame(drwav* pWav)
{
if ((pWav->bitsPerSample & 0x7) == 0) {
return (pWav->bitsPerSample * pWav->fmt.channels) >> 3;
} else {
return pWav->fmt.blockAlign;
}
}
DRWAV_API drwav_uint16 drwav_fmt_get_format(const drwav_fmt* pFMT)
{
if (pFMT == NULL) {
return 0;
}
if (pFMT->formatTag != DR_WAVE_FORMAT_EXTENSIBLE) {
return pFMT->formatTag;
} else {
return drwav__bytes_to_u16(pFMT->subFormat);
}
}
static drwav_bool32 drwav_preinit(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pReadSeekUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (pWav == NULL || onRead == NULL || onSeek == NULL) {
return DRWAV_FALSE;
}
DRWAV_ZERO_MEMORY(pWav, sizeof(*pWav));
pWav->onRead = onRead;
pWav->onSeek = onSeek;
pWav->pUserData = pReadSeekUserData;
pWav->allocationCallbacks = drwav_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
if (pWav->allocationCallbacks.onFree == NULL || (pWav->allocationCallbacks.onMalloc == NULL && pWav->allocationCallbacks.onRealloc == NULL)) {
return DRWAV_FALSE;
}
return DRWAV_TRUE;
}
static drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags)
{
drwav_uint64 cursor;
drwav_bool32 sequential;
drwav_uint8 riff[4];
drwav_fmt fmt;
unsigned short translatedFormatTag;
drwav_bool32 foundDataChunk;
drwav_uint64 dataChunkSize = 0;
drwav_uint64 sampleCountFromFactChunk = 0;
drwav_uint64 chunkSize;
cursor = 0;
sequential = (flags & DRWAV_SEQUENTIAL) != 0;
if (drwav__on_read(pWav->onRead, pWav->pUserData, riff, sizeof(riff), &cursor) != sizeof(riff)) {
return DRWAV_FALSE;
}
if (drwav__fourcc_equal(riff, "RIFF")) {
pWav->container = drwav_container_riff;
} else if (drwav__fourcc_equal(riff, "riff")) {
int i;
drwav_uint8 riff2[12];
pWav->container = drwav_container_w64;
if (drwav__on_read(pWav->onRead, pWav->pUserData, riff2, sizeof(riff2), &cursor) != sizeof(riff2)) {
return DRWAV_FALSE;
}
for (i = 0; i < 12; ++i) {
if (riff2[i] != drwavGUID_W64_RIFF[i+4]) {
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
pWav->smpl.manufacturer = drwav__bytes_to_u32(smplHeaderData+0);
pWav->smpl.product = drwav__bytes_to_u32(smplHeaderData+4);
pWav->smpl.samplePeriod = drwav__bytes_to_u32(smplHeaderData+8);
pWav->smpl.midiUnityNotes = drwav__bytes_to_u32(smplHeaderData+12);
pWav->smpl.midiPitchFraction = drwav__bytes_to_u32(smplHeaderData+16);
pWav->smpl.smpteFormat = drwav__bytes_to_u32(smplHeaderData+20);
pWav->smpl.smpteOffset = drwav__bytes_to_u32(smplHeaderData+24);
pWav->smpl.numSampleLoops = drwav__bytes_to_u32(smplHeaderData+28);
pWav->smpl.samplerData = drwav__bytes_to_u32(smplHeaderData+32);
for (iLoop = 0; iLoop < pWav->smpl.numSampleLoops && iLoop < drwav_countof(pWav->smpl.loops); ++iLoop) {
drwav_uint8 smplLoopData[24];
bytesJustRead = drwav__on_read(pWav->onRead, pWav->pUserData, smplLoopData, sizeof(smplLoopData), &cursor);
chunkSize -= bytesJustRead;
if (bytesJustRead == sizeof(smplLoopData)) {
pWav->smpl.loops[iLoop].cuePointId = drwav__bytes_to_u32(smplLoopData+0);
pWav->smpl.loops[iLoop].type = drwav__bytes_to_u32(smplLoopData+4);
pWav->smpl.loops[iLoop].start = drwav__bytes_to_u32(smplLoopData+8);
pWav->smpl.loops[iLoop].end = drwav__bytes_to_u32(smplLoopData+12);
pWav->smpl.loops[iLoop].fraction = drwav__bytes_to_u32(smplLoopData+16);
pWav->smpl.loops[iLoop].playCount = drwav__bytes_to_u32(smplLoopData+20);
} else {
break;
}
}
}
} else {
}
}
} else {
if (drwav__guid_equal(header.id.guid, drwavGUID_W64_SMPL)) {
}
}
chunkSize += header.paddingSize;
if (!drwav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData)) {
break;
}
cursor += chunkSize;
if (!foundDataChunk) {
pWav->dataChunkDataPos = cursor;
}
}
if (!foundDataChunk) {
return DRWAV_FALSE;
}
if (!sequential) {
if (!drwav__seek_from_start(pWav->onSeek, pWav->dataChunkDataPos, pWav->pUserData)) {
return DRWAV_FALSE;
}
cursor = pWav->dataChunkDataPos;
}
pWav->fmt = fmt;
pWav->sampleRate = fmt.sampleRate;
pWav->channels = fmt.channels;
pWav->bitsPerSample = fmt.bitsPerSample;
pWav->bytesRemaining = dataChunkSize;
pWav->translatedFormatTag = translatedFormatTag;
pWav->dataChunkDataSize = dataChunkSize;
if (sampleCountFromFactChunk != 0) {
pWav->totalPCMFrameCount = sampleCountFromFactChunk;
} else {
pWav->totalPCMFrameCount = dataChunkSize / drwav_get_bytes_per_pcm_frame(pWav);
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
drwav_uint64 totalBlockHeaderSizeInBytes;
drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
if ((blockCount * fmt.blockAlign) < dataChunkSize) {
blockCount += 1;
}
totalBlockHeaderSizeInBytes = blockCount * (6*fmt.channels);
pWav->totalPCMFrameCount = ((dataChunkSize - totalBlockHeaderSizeInBytes) * 2) / fmt.channels;
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
drwav_uint64 totalBlockHeaderSizeInBytes;
drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
if ((blockCount * fmt.blockAlign) < dataChunkSize) {
blockCount += 1;
}
totalBlockHeaderSizeInBytes = blockCount * (4*fmt.channels);
pWav->totalPCMFrameCount = ((dataChunkSize - totalBlockHeaderSizeInBytes) * 2) / fmt.channels;
pWav->totalPCMFrameCount += blockCount;
}
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
if (pWav->channels > 2) {
return DRWAV_FALSE;
}
}
#ifdef DR_WAV_LIBSNDFILE_COMPAT
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (6*pWav->channels))) * 2)) / fmt.channels;
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (4*pWav->channels))) * 2) + (blockCount * pWav->channels)) / fmt.channels;
}
#endif
return DRWAV_TRUE;
}
DRWAV_API drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
{
return drwav_init_ex(pWav, onRead, onSeek, NULL, pUserData, NULL, 0, pAllocationCallbacks);
}
DRWAV_API drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (!drwav_preinit(pWav, onRead, onSeek, pReadSeekUserData, pAllocationCallbacks)) {
return DRWAV_FALSE;
}
return drwav_init__internal(pWav, onChunk, pChunkUserData, flags);
}
static drwav_uint32 drwav__riff_chunk_size_riff(drwav_uint64 dataChunkSize)
{
drwav_uint64 chunkSize = 4 + 24 + dataChunkSize + drwav__chunk_padding_size_riff(dataChunkSize);
if (chunkSize > 0xFFFFFFFFUL) {
chunkSize = 0xFFFFFFFFUL;
}
return (drwav_uint32)chunkSize;
}
static drwav_uint32 drwav__data_chunk_size_riff(drwav_uint64 dataChunkSize)
{
if (dataChunkSize <= 0xFFFFFFFFUL) {
return (drwav_uint32)dataChunkSize;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
if (pFormat->container == drwav_container_rf64) {
drwav_uint32 initialds64ChunkSize = 28;
drwav_uint64 initialRiffChunkSize = 8 + initialds64ChunkSize + initialDataChunkSize;
runningPos += drwav__write(pWav, "ds64", 4);
runningPos += drwav__write_u32ne_to_le(pWav, initialds64ChunkSize);
runningPos += drwav__write_u64ne_to_le(pWav, initialRiffChunkSize);
runningPos += drwav__write_u64ne_to_le(pWav, initialDataChunkSize);
runningPos += drwav__write_u64ne_to_le(pWav, totalSampleCount);
runningPos += drwav__write_u32ne_to_le(pWav, 0);
}
if (pFormat->container == drwav_container_riff || pFormat->container == drwav_container_rf64) {
chunkSizeFMT = 16;
runningPos += drwav__write(pWav, "fmt ", 4);
runningPos += drwav__write_u32ne_to_le(pWav, (drwav_uint32)chunkSizeFMT);
} else if (pFormat->container == drwav_container_w64) {
chunkSizeFMT = 40;
runningPos += drwav__write(pWav, drwavGUID_W64_FMT, 16);
runningPos += drwav__write_u64ne_to_le(pWav, chunkSizeFMT);
}
runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.formatTag);
runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.channels);
runningPos += drwav__write_u32ne_to_le(pWav, pWav->fmt.sampleRate);
runningPos += drwav__write_u32ne_to_le(pWav, pWav->fmt.avgBytesPerSec);
runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.blockAlign);
runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.bitsPerSample);
pWav->dataChunkDataPos = runningPos;
if (pFormat->container == drwav_container_riff) {
drwav_uint32 chunkSizeDATA = (drwav_uint32)initialDataChunkSize;
runningPos += drwav__write(pWav, "data", 4);
runningPos += drwav__write_u32ne_to_le(pWav, chunkSizeDATA);
} else if (pFormat->container == drwav_container_w64) {
drwav_uint64 chunkSizeDATA = 24 + initialDataChunkSize;
runningPos += drwav__write(pWav, drwavGUID_W64_DATA, 16);
runningPos += drwav__write_u64ne_to_le(pWav, chunkSizeDATA);
} else if (pFormat->container == drwav_container_rf64) {
runningPos += drwav__write(pWav, "data", 4);
runningPos += drwav__write_u32ne_to_le(pWav, 0xFFFFFFFF);
}
pWav->container = pFormat->container;
pWav->channels = (drwav_uint16)pFormat->channels;
pWav->sampleRate = pFormat->sampleRate;
pWav->bitsPerSample = (drwav_uint16)pFormat->bitsPerSample;
pWav->translatedFormatTag = (drwav_uint16)pFormat->format;
return DRWAV_TRUE;
}
DRWAV_API drwav_bool32 drwav_init_write(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (!drwav_preinit_write(pWav, pFormat, DRWAV_FALSE, onWrite, onSeek, pUserData, pAllocationCallbacks)) {
return DRWAV_FALSE;
}
return drwav_init_write__internal(pWav, pFormat, 0);
}
DRWAV_API drwav_bool32 drwav_init_write_sequential(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (!drwav_preinit_write(pWav, pFormat, DRWAV_TRUE, onWrite, NULL, pUserData, pAllocationCallbacks)) {
return DRWAV_FALSE;
}
return drwav_init_write__internal(pWav, pFormat, totalSampleCount);
}
DRWAV_API drwav_bool32 drwav_init_write_sequential_pcm_frames(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (pFormat == NULL) {
return DRWAV_FALSE;
}
return drwav_init_write_sequential(pWav, pFormat, totalPCMFrameCount*pFormat->channels, onWrite, pUserData, pAllocationCallbacks);
}
DRWAV_API drwav_uint64 drwav_target_write_size_bytes(const drwav_data_format* pFormat, drwav_uint64 totalSampleCount)
{
drwav_uint64 targetDataSizeBytes = (drwav_uint64)((drwav_int64)totalSampleCount * pFormat->channels * pFormat->bitsPerSample/8.0);
drwav_uint64 riffChunkSizeBytes;
drwav_uint64 fileSizeBytes = 0;
if (pFormat->container == drwav_container_riff) {
riffChunkSizeBytes = drwav__riff_chunk_size_riff(targetDataSizeBytes);
fileSizeBytes = (8 + riffChunkSizeBytes);
} else if (pFormat->container == drwav_container_w64) {
riffChunkSizeBytes = drwav__riff_chunk_size_w64(targetDataSizeBytes);
fileSizeBytes = riffChunkSizeBytes;
} else if (pFormat->container == drwav_container_rf64) {
riffChunkSizeBytes = drwav__riff_chunk_size_rf64(targetDataSizeBytes);
fileSizeBytes = (8 + riffChunkSizeBytes);
}
return fileSizeBytes;
}
#ifndef DR_WAV_NO_STDIO
#include <errno.h>
static drwav_result drwav_result_from_errno(int e)
{
switch (e)
{
case 0: return DRWAV_SUCCESS;
#ifdef EPERM
case EPERM: return DRWAV_INVALID_OPERATION;
#endif
#ifdef ENOENT
case ENOENT: return DRWAV_DOES_NOT_EXIST;
#endif
#ifdef ESRCH
case ESRCH: return DRWAV_DOES_NOT_EXIST;
#endif
#ifdef EINTR
case EINTR: return DRWAV_INTERRUPT;
#endif
#ifdef EIO
case EIO: return DRWAV_IO_ERROR;
#endif
#ifdef ENXIO
case ENXIO: return DRWAV_DOES_NOT_EXIST;
#endif
#ifdef E2BIG
case E2BIG: return DRWAV_INVALID_ARGS;
#endif
#ifdef ENOEXEC
case ENOEXEC: return DRWAV_INVALID_FILE;
#endif
#ifdef EBADF
case EBADF: return DRWAV_INVALID_FILE;
#endif
#ifdef ECHILD
case ECHILD: return DRWAV_ERROR;
#endif
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
DRWAV_API drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
{
FILE* pFile;
if (drwav_fopen(&pFile, filename, "rb") != DRWAV_SUCCESS) {
return DRWAV_FALSE;
}
return drwav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, pAllocationCallbacks);
}
DRWAV_API drwav_bool32 drwav_init_file_w(drwav* pWav, const wchar_t* filename, const drwav_allocation_callbacks* pAllocationCallbacks)
{
return drwav_init_file_ex_w(pWav, filename, NULL, NULL, 0, pAllocationCallbacks);
}
DRWAV_API drwav_bool32 drwav_init_file_ex_w(drwav* pWav, const wchar_t* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
{
FILE* pFile;
if (drwav_wfopen(&pFile, filename, L"rb", pAllocationCallbacks) != DRWAV_SUCCESS) {
return DRWAV_FALSE;
}
return drwav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, pAllocationCallbacks);
}
static drwav_bool32 drwav_init_file_write__internal_FILE(drwav* pWav, FILE* pFile, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
{
drwav_bool32 result;
result = drwav_preinit_write(pWav, pFormat, isSequential, drwav__on_write_stdio, drwav__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
if (result != DRWAV_TRUE) {
fclose(pFile);
return result;
}
result = drwav_init_write__internal(pWav, pFormat, totalSampleCount);
if (result != DRWAV_TRUE) {
fclose(pFile);
return result;
}
return DRWAV_TRUE;
}
static drwav_bool32 drwav_init_file_write__internal(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
{
FILE* pFile;
if (drwav_fopen(&pFile, filename, "wb") != DRWAV_SUCCESS) {
return DRWAV_FALSE;
}
return drwav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks);
}
static drwav_bool32 drwav_init_file_write_w__internal(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
{
FILE* pFile;
if (drwav_wfopen(&pFile, filename, L"wb", pAllocationCallbacks) != DRWAV_SUCCESS) {
return DRWAV_FALSE;
}
return drwav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks);
}
DRWAV_API drwav_bool32 drwav_init_file_write(drwav* pWav, const char* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks)
{
return drwav_init_file_write__internal(pWav, filename, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks);
}
DRWAV_API drwav_bool32 drwav_init_file_write_sequential(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks)
{
return drwav_init_file_write__internal(pWav, filename, pFormat, totalSampleCount, DRWAV_TRUE, pAllocationCallbacks);
}
DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (pFormat == NULL) {
return DRWAV_FALSE;
}
return drwav_init_file_write_sequential(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
}
DRWAV_API drwav_bool32 drwav_init_file_write_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks)
{
return drwav_init_file_write_w__internal(pWav, filename, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks);
}
DRWAV_API drwav_bool32 drwav_init_file_write_sequential_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks)
{
return drwav_init_file_write_w__internal(pWav, filename, pFormat, totalSampleCount, DRWAV_TRUE, pAllocationCallbacks);
}
DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (pFormat == NULL) {
return DRWAV_FALSE;
}
return drwav_init_file_write_sequential_w(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
}
#endif
static size_t drwav__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead)
{
drwav* pWav = (drwav*)pUserData;
size_t bytesRemaining;
DRWAV_ASSERT(pWav != NULL);
DRWAV_ASSERT(pWav->memoryStream.dataSize >= pWav->memoryStream.currentReadPos);
bytesRemaining = pWav->memoryStream.dataSize - pWav->memoryStream.currentReadPos;
if (bytesToRead > bytesRemaining) {
bytesToRead = bytesRemaining;
}
if (bytesToRead > 0) {
DRWAV_COPY_MEMORY(pBufferOut, pWav->memoryStream.data + pWav->memoryStream.currentReadPos, bytesToRead);
pWav->memoryStream.currentReadPos += bytesToRead;
}
return bytesToRead;
}
static drwav_bool32 drwav__on_seek_memory(void* pUserData, int offset, drwav_seek_origin origin)
{
drwav* pWav = (drwav*)pUserData;
DRWAV_ASSERT(pWav != NULL);
if (origin == drwav_seek_origin_current) {
if (offset > 0) {
if (pWav->memoryStream.currentReadPos + offset > pWav->memoryStream.dataSize) {
return DRWAV_FALSE;
}
} else {
if (pWav->memoryStream.currentReadPos < (size_t)-offset) {
return DRWAV_FALSE;
}
}
pWav->memoryStream.currentReadPos += offset;
} else {
if ((drwav_uint32)offset <= pWav->memoryStream.dataSize) {
pWav->memoryStream.currentReadPos = offset;
} else {
return DRWAV_FALSE;
}
}
return DRWAV_TRUE;
}
static size_t drwav__on_write_memory(void* pUserData, const void* pDataIn, size_t bytesToWrite)
{
drwav* pWav = (drwav*)pUserData;
size_t bytesRemaining;
DRWAV_ASSERT(pWav != NULL);
DRWAV_ASSERT(pWav->memoryStreamWrite.dataCapacity >= pWav->memoryStreamWrite.currentWritePos);
bytesRemaining = pWav->memoryStreamWrite.dataCapacity - pWav->memoryStreamWrite.currentWritePos;
if (bytesRemaining < bytesToWrite) {
void* pNewData;
size_t newDataCapacity = (pWav->memoryStreamWrite.dataCapacity == 0) ? 256 : pWav->memoryStreamWrite.dataCapacity * 2;
if ((newDataCapacity - pWav->memoryStreamWrite.currentWritePos) < bytesToWrite) {
newDataCapacity = pWav->memoryStreamWrite.currentWritePos + bytesToWrite;
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
if (pWav->memoryStreamWrite.currentWritePos + offset > pWav->memoryStreamWrite.dataSize) {
offset = (int)(pWav->memoryStreamWrite.dataSize - pWav->memoryStreamWrite.currentWritePos);
}
} else {
if (pWav->memoryStreamWrite.currentWritePos < (size_t)-offset) {
offset = -(int)pWav->memoryStreamWrite.currentWritePos;
}
}
pWav->memoryStreamWrite.currentWritePos += offset;
} else {
if ((drwav_uint32)offset <= pWav->memoryStreamWrite.dataSize) {
pWav->memoryStreamWrite.currentWritePos = offset;
} else {
pWav->memoryStreamWrite.currentWritePos = pWav->memoryStreamWrite.dataSize;
}
}
return DRWAV_TRUE;
}
DRWAV_API drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize, const drwav_allocation_callbacks* pAllocationCallbacks)
{
return drwav_init_memory_ex(pWav, data, dataSize, NULL, NULL, 0, pAllocationCallbacks);
}
DRWAV_API drwav_bool32 drwav_init_memory_ex(drwav* pWav, const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (data == NULL || dataSize == 0) {
return DRWAV_FALSE;
}
if (!drwav_preinit(pWav, drwav__on_read_memory, drwav__on_seek_memory, pWav, pAllocationCallbacks)) {
return DRWAV_FALSE;
}
pWav->memoryStream.data = (const drwav_uint8*)data;
pWav->memoryStream.dataSize = dataSize;
pWav->memoryStream.currentReadPos = 0;
return drwav_init__internal(pWav, onChunk, pChunkUserData, flags);
}
static drwav_bool32 drwav_init_memory_write__internal(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (ppData == NULL || pDataSize == NULL) {
return DRWAV_FALSE;
}
*ppData = NULL;
*pDataSize = 0;
if (!drwav_preinit_write(pWav, pFormat, isSequential, drwav__on_write_memory, drwav__on_seek_memory_write, pWav, pAllocationCallbacks)) {
return DRWAV_FALSE;
}
pWav->memoryStreamWrite.ppData = ppData;
pWav->memoryStreamWrite.pDataSize = pDataSize;
pWav->memoryStreamWrite.dataSize = 0;
pWav->memoryStreamWrite.dataCapacity = 0;
pWav->memoryStreamWrite.currentWritePos = 0;
return drwav_init_write__internal(pWav, pFormat, totalSampleCount);
}
DRWAV_API drwav_bool32 drwav_init_memory_write(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks)
{
return drwav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks);
}
DRWAV_API drwav_bool32 drwav_init_memory_write_sequential(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks)
{
return drwav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, totalSampleCount, DRWAV_TRUE, pAllocationCallbacks);
}
DRWAV_API drwav_bool32 drwav_init_memory_write_sequential_pcm_frames(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (pFormat == NULL) {
return DRWAV_FALSE;
}
return drwav_init_memory_write_sequential(pWav, ppData, pDataSize, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
}
DRWAV_API drwav_result drwav_uninit(drwav* pWav)
{
drwav_result result = DRWAV_SUCCESS;
if (pWav == NULL) {
return DRWAV_INVALID_ARGS;
}
if (pWav->onWrite != NULL) {
drwav_uint32 paddingSize = 0;
if (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64) {
paddingSize = drwav__chunk_padding_size_riff(pWav->dataChunkDataSize);
} else {
paddingSize = drwav__chunk_padding_size_w64(pWav->dataChunkDataSize);
}
if (paddingSize > 0) {
drwav_uint64 paddingData = 0;
drwav__write(pWav, &paddingData, paddingSize);
}
if (pWav->onSeek && !pWav->isSequentialWrite) {
if (pWav->container == drwav_container_riff) {
if (pWav->onSeek(pWav->pUserData, 4, drwav_seek_origin_start)) {
drwav_uint32 riffChunkSize = drwav__riff_chunk_size_riff(pWav->dataChunkDataSize);
drwav__write_u32ne_to_le(pWav, riffChunkSize);
}
if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos + 4, drwav_seek_origin_start)) {
drwav_uint32 dataChunkSize = drwav__data_chunk_size_riff(pWav->dataChunkDataSize);
drwav__write_u32ne_to_le(pWav, dataChunkSize);
}
} else if (pWav->container == drwav_container_w64) {
if (pWav->onSeek(pWav->pUserData, 16, drwav_seek_origin_start)) {
drwav_uint64 riffChunkSize = drwav__riff_chunk_size_w64(pWav->dataChunkDataSize);
drwav__write_u64ne_to_le(pWav, riffChunkSize);
}
if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos + 16, drwav_seek_origin_start)) {
drwav_uint64 dataChunkSize = drwav__data_chunk_size_w64(pWav->dataChunkDataSize);
drwav__write_u64ne_to_le(pWav, dataChunkSize);
}
} else if (pWav->container == drwav_container_rf64) {
int ds64BodyPos = 12 + 8;
if (pWav->onSeek(pWav->pUserData, ds64BodyPos + 0, drwav_seek_origin_start)) {
drwav_uint64 riffChunkSize = drwav__riff_chunk_size_rf64(pWav->dataChunkDataSize);
drwav__write_u64ne_to_le(pWav, riffChunkSize);
}
if (pWav->onSeek(pWav->pUserData, ds64BodyPos + 8, drwav_seek_origin_start)) {
drwav_uint64 dataChunkSize = drwav__data_chunk_size_rf64(pWav->dataChunkDataSize);
drwav__write_u64ne_to_le(pWav, dataChunkSize);
}
}
}
if (pWav->isSequentialWrite) {
if (pWav->dataChunkDataSize != pWav->dataChunkDataSizeTargetWrite) {
result = DRWAV_INVALID_FILE;
}
}
}
#ifndef DR_WAV_NO_STDIO
if (pWav->onRead == drwav__on_read_stdio || pWav->onWrite == drwav__on_write_stdio) {
fclose((FILE*)pWav->pUserData);
}
#endif
return result;
}
DRWAV_API size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut)
{
size_t bytesRead;
if (pWav == NULL || bytesToRead == 0) {
return 0;
}
if (bytesToRead > pWav->bytesRemaining) {
bytesToRead = (size_t)pWav->bytesRemaining;
}
if (pBufferOut != NULL) {
bytesRead = pWav->onRead(pWav->pUserData, pBufferOut, bytesToRead);
} else {
bytesRead = 0;
while (bytesRead < bytesToRead) {
size_t bytesToSeek = (bytesToRead - bytesRead);
if (bytesToSeek > 0x7FFFFFFF) {
bytesToSeek = 0x7FFFFFFF;
}
if (pWav->onSeek(pWav->pUserData, (int)bytesToSeek, drwav_seek_origin_current) == DRWAV_FALSE) {
break;
}
bytesRead += bytesToSeek;
}
while (bytesRead < bytesToRead) {
drwav_uint8 buffer[4096];
size_t bytesSeeked;
size_t bytesToSeek = (bytesToRead - bytesRead);
if (bytesToSeek > sizeof(buffer)) {
bytesToSeek = sizeof(buffer);
}
bytesSeeked = pWav->onRead(pWav->pUserData, buffer, bytesToSeek);
bytesRead += bytesSeeked;
if (bytesSeeked < bytesToSeek) {
break;
}
}
}
pWav->bytesRemaining -= bytesRead;
return bytesRead;
}
DRWAV_API drwav_uint64 drwav_read_pcm_frames_le(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
{
drwav_uint32 bytesPerFrame;
if (pWav == NULL || framesToRead == 0) {
return 0;
}
if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
return 0;
}
bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
if (framesToRead * bytesPerFrame > DRWAV_SIZE_MAX) {
framesToRead = DRWAV_SIZE_MAX / bytesPerFrame;
}
return drwav_read_raw(pWav, (size_t)(framesToRead * bytesPerFrame), pBufferOut) / bytesPerFrame;
}
DRWAV_API drwav_uint64 drwav_read_pcm_frames_be(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
{
drwav_uint64 framesRead = drwav_read_pcm_frames_le(pWav, framesToRead, pBufferOut);
if (pBufferOut != NULL) {
drwav__bswap_samples(pBufferOut, framesRead*pWav->channels, drwav_get_bytes_per_pcm_frame(pWav)/pWav->channels, pWav->translatedFormatTag);
}
return framesRead;
}
DRWAV_API drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
{
if (drwav__is_little_endian()) {
return drwav_read_pcm_frames_le(pWav, framesToRead, pBufferOut);
} else {
return drwav_read_pcm_frames_be(pWav, framesToRead, pBufferOut);
}
}
DRWAV_API drwav_bool32 drwav_seek_to_first_pcm_frame(drwav* pWav)
{
if (pWav->onWrite != NULL) {
return DRWAV_FALSE;
}
if (!pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos, drwav_seek_origin_start)) {
return DRWAV_FALSE;
}
if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
pWav->compressed.iCurrentPCMFrame = 0;
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
DRWAV_ZERO_OBJECT(&pWav->msadpcm);
} else if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
DRWAV_ZERO_OBJECT(&pWav->ima);
} else {
DRWAV_ASSERT(DRWAV_FALSE);
}
}
pWav->bytesRemaining = pWav->dataChunkDataSize;
return DRWAV_TRUE;
}
DRWAV_API drwav_bool32 drwav_seek_to_pcm_frame(drwav* pWav, drwav_uint64 targetFrameIndex)
{
if (pWav == NULL || pWav->onSeek == NULL) {
return DRWAV_FALSE;
}
if (pWav->onWrite != NULL) {
return DRWAV_FALSE;
}
if (pWav->totalPCMFrameCount == 0) {
return DRWAV_TRUE;
}
if (targetFrameIndex >= pWav->totalPCMFrameCount) {
targetFrameIndex = pWav->totalPCMFrameCount - 1;
}
if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
if (targetFrameIndex < pWav->compressed.iCurrentPCMFrame) {
if (!drwav_seek_to_first_pcm_frame(pWav)) {
return DRWAV_FALSE;
}
}
if (targetFrameIndex > pWav->compressed.iCurrentPCMFrame) {
drwav_uint64 offsetInFrames = targetFrameIndex - pWav->compressed.iCurrentPCMFrame;
drwav_int16 devnull[2048];
while (offsetInFrames > 0) {
drwav_uint64 framesRead = 0;
drwav_uint64 framesToRead = offsetInFrames;
if (framesToRead > drwav_countof(devnull)/pWav->channels) {
framesToRead = drwav_countof(devnull)/pWav->channels;
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
framesRead = drwav_read_pcm_frames_s16__msadpcm(pWav, framesToRead, devnull);
} else if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
framesRead = drwav_read_pcm_frames_s16__ima(pWav, framesToRead, devnull);
} else {
DRWAV_ASSERT(DRWAV_FALSE);
}
if (framesRead != framesToRead) {
return DRWAV_FALSE;
}
offsetInFrames -= framesRead;
}
}
} else {
drwav_uint64 totalSizeInBytes;
drwav_uint64 currentBytePos;
drwav_uint64 targetBytePos;
drwav_uint64 offset;
totalSizeInBytes = pWav->totalPCMFrameCount * drwav_get_bytes_per_pcm_frame(pWav);
DRWAV_ASSERT(totalSizeInBytes >= pWav->bytesRemaining);
currentBytePos = totalSizeInBytes - pWav->bytesRemaining;
targetBytePos = targetFrameIndex * drwav_get_bytes_per_pcm_frame(pWav);
if (currentBytePos < targetBytePos) {
offset = (targetBytePos - currentBytePos);
} else {
if (!drwav_seek_to_first_pcm_frame(pWav)) {
return DRWAV_FALSE;
}
offset = targetBytePos;
}
while (offset > 0) {
int offset32 = ((offset > INT_MAX) ? INT_MAX : (int)offset);
if (!pWav->onSeek(pWav->pUserData, offset32, drwav_seek_origin_current)) {
return DRWAV_FALSE;
}
pWav->bytesRemaining -= offset32;
offset -= offset32;
}
}
return DRWAV_TRUE;
}
DRWAV_API size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData)
{
size_t bytesWritten;
if (pWav == NULL || bytesToWrite == 0 || pData == NULL) {
return 0;
}
bytesWritten = pWav->onWrite(pWav->pUserData, pData, bytesToWrite);
pWav->dataChunkDataSize += bytesWritten;
return bytesWritten;
}
DRWAV_API drwav_uint64 drwav_write_pcm_frames_le(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
{
drwav_uint64 bytesToWrite;
drwav_uint64 bytesWritten;
const drwav_uint8* pRunningData;
if (pWav == NULL || framesToWrite == 0 || pData == NULL) {
return 0;
}
bytesToWrite = ((framesToWrite * pWav->channels * pWav->bitsPerSample) / 8);
if (bytesToWrite > DRWAV_SIZE_MAX) {
return 0;
}
bytesWritten = 0;
pRunningData = (const drwav_uint8*)pData;
while (bytesToWrite > 0) {
size_t bytesJustWritten;
drwav_uint64 bytesToWriteThisIteration;
bytesToWriteThisIteration = bytesToWrite;
DRWAV_ASSERT(bytesToWriteThisIteration <= DRWAV_SIZE_MAX);
bytesJustWritten = drwav_write_raw(pWav, (size_t)bytesToWriteThisIteration, pRunningData);
if (bytesJustWritten == 0) {
break;
}
bytesToWrite -= bytesJustWritten;
bytesWritten += bytesJustWritten;
pRunningData += bytesJustWritten;
}
return (bytesWritten * 8) / pWav->bitsPerSample / pWav->channels;
}
DRWAV_API drwav_uint64 drwav_write_pcm_frames_be(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
{
drwav_uint64 bytesToWrite;
drwav_uint64 bytesWritten;
drwav_uint32 bytesPerSample;
const drwav_uint8* pRunningData;
if (pWav == NULL || framesToWrite == 0 || pData == NULL) {
return 0;
}
bytesToWrite = ((framesToWrite * pWav->channels * pWav->bitsPerSample) / 8);
if (bytesToWrite > DRWAV_SIZE_MAX) {
return 0;
}
bytesWritten = 0;
pRunningData = (const drwav_uint8*)pData;
bytesPerSample = drwav_get_bytes_per_pcm_frame(pWav) / pWav->channels;
while (bytesToWrite > 0) {
drwav_uint8 temp[4096];
drwav_uint32 sampleCount;
size_t bytesJustWritten;
drwav_uint64 bytesToWriteThisIteration;
bytesToWriteThisIteration = bytesToWrite;
DRWAV_ASSERT(bytesToWriteThisIteration <= DRWAV_SIZE_MAX);
sampleCount = sizeof(temp)/bytesPerSample;
if (bytesToWriteThisIteration > ((drwav_uint64)sampleCount)*bytesPerSample) {
bytesToWriteThisIteration = ((drwav_uint64)sampleCount)*bytesPerSample;
}
DRWAV_COPY_MEMORY(temp, pRunningData, (size_t)bytesToWriteThisIteration);
drwav__bswap_samples(temp, sampleCount, bytesPerSample, pWav->translatedFormatTag);
bytesJustWritten = drwav_write_raw(pWav, (size_t)bytesToWriteThisIteration, temp);
if (bytesJustWritten == 0) {
break;
}
bytesToWrite -= bytesJustWritten;
bytesWritten += bytesJustWritten;
pRunningData += bytesJustWritten;
}
return (bytesWritten * 8) / pWav->bitsPerSample / pWav->channels;
}
DRWAV_API drwav_uint64 drwav_write_pcm_frames(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
{
if (drwav__is_little_endian()) {
return drwav_write_pcm_frames_le(pWav, framesToWrite, pData);
} else {
return drwav_write_pcm_frames_be(pWav, framesToWrite, pData);
}
}
static drwav_uint64 drwav_read_pcm_frames_s16__msadpcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
{
drwav_uint64 totalFramesRead = 0;
DRWAV_ASSERT(pWav != NULL);
DRWAV_ASSERT(framesToRead > 0);
while (framesToRead > 0 && pWav->compressed.iCurrentPCMFrame < pWav->totalPCMFrameCount) {
if (pWav->msadpcm.cachedFrameCount == 0 && pWav->msadpcm.bytesRemainingInBlock == 0) {
if (pWav->channels == 1) {
drwav_uint8 header[7];
if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
return totalFramesRead;
}
pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
pWav->msadpcm.predictor[0] = header[0];
pWav->msadpcm.delta[0] = drwav__bytes_to_s16(header + 1);
pWav->msadpcm.prevFrames[0][1] = (drwav_int32)drwav__bytes_to_s16(header + 3);
pWav->msadpcm.prevFrames[0][0] = (drwav_int32)drwav__bytes_to_s16(header + 5);
pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][0];
pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[0][1];
pWav->msadpcm.cachedFrameCount = 2;
} else {
drwav_uint8 header[14];
if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
return totalFramesRead;
}
pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
pWav->msadpcm.predictor[0] = header[0];
pWav->msadpcm.predictor[1] = header[1];
pWav->msadpcm.delta[0] = drwav__bytes_to_s16(header + 2);
pWav->msadpcm.delta[1] = drwav__bytes_to_s16(header + 4);
pWav->msadpcm.prevFrames[0][1] = (drwav_int32)drwav__bytes_to_s16(header + 6);
pWav->msadpcm.prevFrames[1][1] = (drwav_int32)drwav__bytes_to_s16(header + 8);
pWav->msadpcm.prevFrames[0][0] = (drwav_int32)drwav__bytes_to_s16(header + 10);
pWav->msadpcm.prevFrames[1][0] = (drwav_int32)drwav__bytes_to_s16(header + 12);
pWav->msadpcm.cachedFrames[0] = pWav->msadpcm.prevFrames[0][0];
pWav->msadpcm.cachedFrames[1] = pWav->msadpcm.prevFrames[1][0];
pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][1];
pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[1][1];
pWav->msadpcm.cachedFrameCount = 2;
}
}
while (framesToRead > 0 && pWav->msadpcm.cachedFrameCount > 0 && pWav->compressed.iCurrentPCMFrame < pWav->totalPCMFrameCount) {
if (pBufferOut != NULL) {
drwav_uint32 iSample = 0;
for (iSample = 0; iSample < pWav->channels; iSample += 1) {
pBufferOut[iSample] = (drwav_int16)pWav->msadpcm.cachedFrames[(drwav_countof(pWav->msadpcm.cachedFrames) - (pWav->msadpcm.cachedFrameCount*pWav->channels)) + iSample];
}
pBufferOut += pWav->channels;
}
framesToRead -= 1;
totalFramesRead += 1;
pWav->compressed.iCurrentPCMFrame += 1;
pWav->msadpcm.cachedFrameCount -= 1;
}
if (framesToRead == 0) {
return totalFramesRead;
}
if (pWav->msadpcm.cachedFrameCount == 0) {
if (pWav->msadpcm.bytesRemainingInBlock == 0) {
continue;
} else {
static drwav_int32 adaptationTable[] = {
230, 230, 230, 230, 307, 409, 512, 614,
768, 614, 512, 409, 307, 230, 230, 230
};
static drwav_int32 coeff1Table[] = { 256, 512, 0, 192, 240, 460, 392 };
static drwav_int32 coeff2Table[] = { 0, -256, 0, 64, 0, -208, -232 };
drwav_uint8 nibbles;
drwav_int32 nibble0;
drwav_int32 nibble1;
if (pWav->onRead(pWav->pUserData, &nibbles, 1) != 1) {
return totalFramesRead;
}
pWav->msadpcm.bytesRemainingInBlock -= 1;
nibble0 = ((nibbles & 0xF0) >> 4); if ((nibbles & 0x80)) { nibble0 |= 0xFFFFFFF0UL; }
nibble1 = ((nibbles & 0x0F) >> 0); if ((nibbles & 0x08)) { nibble1 |= 0xFFFFFFF0UL; }
if (pWav->channels == 1) {
drwav_int32 newSample0;
drwav_int32 newSample1;
newSample0 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
newSample0 += nibble0 * pWav->msadpcm.delta[0];
newSample0 = drwav_clamp(newSample0, -32768, 32767);
pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8;
if (pWav->msadpcm.delta[0] < 16) {
pWav->msadpcm.delta[0] = 16;
}
pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
pWav->msadpcm.prevFrames[0][1] = newSample0;
newSample1 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
newSample1 += nibble1 * pWav->msadpcm.delta[0];
newSample1 = drwav_clamp(newSample1, -32768, 32767);
pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[0]) >> 8;
if (pWav->msadpcm.delta[0] < 16) {
pWav->msadpcm.delta[0] = 16;
}
pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
pWav->msadpcm.prevFrames[0][1] = newSample1;
pWav->msadpcm.cachedFrames[2] = newSample0;
pWav->msadpcm.cachedFrames[3] = newSample1;
pWav->msadpcm.cachedFrameCount = 2;
} else {
drwav_int32 newSample0;
drwav_int32 newSample1;
newSample0 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
newSample0 += nibble0 * pWav->msadpcm.delta[0];
newSample0 = drwav_clamp(newSample0, -32768, 32767);
pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8;
if (pWav->msadpcm.delta[0] < 16) {
pWav->msadpcm.delta[0] = 16;
}
pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
pWav->msadpcm.prevFrames[0][1] = newSample0;
newSample1 = ((pWav->msadpcm.prevFrames[1][1] * coeff1Table[pWav->msadpcm.predictor[1]]) + (pWav->msadpcm.prevFrames[1][0] * coeff2Table[pWav->msadpcm.predictor[1]])) >> 8;
newSample1 += nibble1 * pWav->msadpcm.delta[1];
newSample1 = drwav_clamp(newSample1, -32768, 32767);
pWav->msadpcm.delta[1] = (adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[1]) >> 8;
if (pWav->msadpcm.delta[1] < 16) {
pWav->msadpcm.delta[1] = 16;
}
pWav->msadpcm.prevFrames[1][0] = pWav->msadpcm.prevFrames[1][1];
pWav->msadpcm.prevFrames[1][1] = newSample1;
pWav->msadpcm.cachedFrames[2] = newSample0;
pWav->msadpcm.cachedFrames[3] = newSample1;
pWav->msadpcm.cachedFrameCount = 1;
}
}
}
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_s16__ima(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
{
drwav_uint64 totalFramesRead = 0;
drwav_uint32 iChannel;
static drwav_int32 indexTable[16] = {
-1, -1, -1, -1, 2, 4, 6, 8,
-1, -1, -1, -1, 2, 4, 6, 8
};
static drwav_int32 stepTable[89] = {
7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
};
DRWAV_ASSERT(pWav != NULL);
DRWAV_ASSERT(framesToRead > 0);
while (framesToRead > 0 && pWav->compressed.iCurrentPCMFrame < pWav->totalPCMFrameCount) {
if (pWav->ima.cachedFrameCount == 0 && pWav->ima.bytesRemainingInBlock == 0) {
if (pWav->channels == 1) {
drwav_uint8 header[4];
if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
return totalFramesRead;
}
pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
if (header[2] >= drwav_countof(stepTable)) {
pWav->onSeek(pWav->pUserData, pWav->ima.bytesRemainingInBlock, drwav_seek_origin_current);
pWav->ima.bytesRemainingInBlock = 0;
return totalFramesRead;
}
pWav->ima.predictor[0] = drwav__bytes_to_s16(header + 0);
pWav->ima.stepIndex[0] = header[2];
pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[0];
pWav->ima.cachedFrameCount = 1;
} else {
drwav_uint8 header[8];
if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
return totalFramesRead;
}
pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
if (header[2] >= drwav_countof(stepTable) || header[6] >= drwav_countof(stepTable)) {
pWav->onSeek(pWav->pUserData, pWav->ima.bytesRemainingInBlock, drwav_seek_origin_current);
pWav->ima.bytesRemainingInBlock = 0;
return totalFramesRead;
}
pWav->ima.predictor[0] = drwav__bytes_to_s16(header + 0);
pWav->ima.stepIndex[0] = header[2];
pWav->ima.predictor[1] = drwav__bytes_to_s16(header + 4);
pWav->ima.stepIndex[1] = header[6];
pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 2] = pWav->ima.predictor[0];
pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[1];
pWav->ima.cachedFrameCount = 1;
}
}
while (framesToRead > 0 && pWav->ima.cachedFrameCount > 0 && pWav->compressed.iCurrentPCMFrame < pWav->totalPCMFrameCount) {
if (pBufferOut != NULL) {
drwav_uint32 iSample;
for (iSample = 0; iSample < pWav->channels; iSample += 1) {
pBufferOut[iSample] = (drwav_int16)pWav->ima.cachedFrames[(drwav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + iSample];
}
pBufferOut += pWav->channels;
}
framesToRead -= 1;
totalFramesRead += 1;
pWav->compressed.iCurrentPCMFrame += 1;
pWav->ima.cachedFrameCount -= 1;
}
if (framesToRead == 0) {
return totalFramesRead;
}
if (pWav->ima.cachedFrameCount == 0) {
if (pWav->ima.bytesRemainingInBlock == 0) {
continue;
} else {
pWav->ima.cachedFrameCount = 8;
for (iChannel = 0; iChannel < pWav->channels; ++iChannel) {
drwav_uint32 iByte;
drwav_uint8 nibbles[4];
if (pWav->onRead(pWav->pUserData, &nibbles, 4) != 4) {
pWav->ima.cachedFrameCount = 0;
return totalFramesRead;
}
pWav->ima.bytesRemainingInBlock -= 4;
for (iByte = 0; iByte < 4; ++iByte) {
drwav_uint8 nibble0 = ((nibbles[iByte] & 0x0F) >> 0);
drwav_uint8 nibble1 = ((nibbles[iByte] & 0xF0) >> 4);
drwav_int32 step = stepTable[pWav->ima.stepIndex[iChannel]];
drwav_int32 predictor = pWav->ima.predictor[iChannel];
drwav_int32 diff = step >> 3;
if (nibble0 & 1) diff += step >> 2;
if (nibble0 & 2) diff += step >> 1;
if (nibble0 & 4) diff += step;
if (nibble0 & 8) diff = -diff;
predictor = drwav_clamp(predictor + diff, -32768, 32767);
pWav->ima.predictor[iChannel] = predictor;
pWav->ima.stepIndex[iChannel] = drwav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble0], 0, (drwav_int32)drwav_countof(stepTable)-1);
pWav->ima.cachedFrames[(drwav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + (iByte*2+0)*pWav->channels + iChannel] = predictor;
step = stepTable[pWav->ima.stepIndex[iChannel]];
predictor = pWav->ima.predictor[iChannel];
diff = step >> 3;
if (nibble1 & 1) diff += step >> 2;
if (nibble1 & 2) diff += step >> 1;
if (nibble1 & 4) diff += step;
if (nibble1 & 8) diff = -diff;
predictor = drwav_clamp(predictor + diff, -32768, 32767);
pWav->ima.predictor[iChannel] = predictor;
pWav->ima.stepIndex[iChannel] = drwav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble1], 0, (drwav_int32)drwav_countof(stepTable)-1);
pWav->ima.cachedFrames[(drwav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + (iByte*2+1)*pWav->channels + iChannel] = predictor;
}
}
}
}
}
return totalFramesRead;
}
#ifndef DR_WAV_NO_CONVERSION_API
static unsigned short g_drwavAlawTable[256] = {
0xEA80, 0xEB80, 0xE880, 0xE980, 0xEE80, 0xEF80, 0xEC80, 0xED80, 0xE280, 0xE380, 0xE080, 0xE180, 0xE680, 0xE780, 0xE480, 0xE580,
0xF540, 0xF5C0, 0xF440, 0xF4C0, 0xF740, 0xF7C0, 0xF640, 0xF6C0, 0xF140, 0xF1C0, 0xF040, 0xF0C0, 0xF340, 0xF3C0, 0xF240, 0xF2C0,
0xAA00, 0xAE00, 0xA200, 0xA600, 0xBA00, 0xBE00, 0xB200, 0xB600, 0x8A00, 0x8E00, 0x8200, 0x8600, 0x9A00, 0x9E00, 0x9200, 0x9600,
0xD500, 0xD700, 0xD100, 0xD300, 0xDD00, 0xDF00, 0xD900, 0xDB00, 0xC500, 0xC700, 0xC100, 0xC300, 0xCD00, 0xCF00, 0xC900, 0xCB00,
0xFEA8, 0xFEB8, 0xFE88, 0xFE98, 0xFEE8, 0xFEF8, 0xFEC8, 0xFED8, 0xFE28, 0xFE38, 0xFE08, 0xFE18, 0xFE68, 0xFE78, 0xFE48, 0xFE58,
0xFFA8, 0xFFB8, 0xFF88, 0xFF98, 0xFFE8, 0xFFF8, 0xFFC8, 0xFFD8, 0xFF28, 0xFF38, 0xFF08, 0xFF18, 0xFF68, 0xFF78, 0xFF48, 0xFF58,
0xFAA0, 0xFAE0, 0xFA20, 0xFA60, 0xFBA0, 0xFBE0, 0xFB20, 0xFB60, 0xF8A0, 0xF8E0, 0xF820, 0xF860, 0xF9A0, 0xF9E0, 0xF920, 0xF960,
0xFD50, 0xFD70, 0xFD10, 0xFD30, 0xFDD0, 0xFDF0, 0xFD90, 0xFDB0, 0xFC50, 0xFC70, 0xFC10, 0xFC30, 0xFCD0, 0xFCF0, 0xFC90, 0xFCB0,
0x1580, 0x1480, 0x1780, 0x1680, 0x1180, 0x1080, 0x1380, 0x1280, 0x1D80, 0x1C80, 0x1F80, 0x1E80, 0x1980, 0x1880, 0x1B80, 0x1A80,
0x0AC0, 0x0A40, 0x0BC0, 0x0B40, 0x08C0, 0x0840, 0x09C0, 0x0940, 0x0EC0, 0x0E40, 0x0FC0, 0x0F40, 0x0CC0, 0x0C40, 0x0DC0, 0x0D40,
0x5600, 0x5200, 0x5E00, 0x5A00, 0x4600, 0x4200, 0x4E00, 0x4A00, 0x7600, 0x7200, 0x7E00, 0x7A00, 0x6600, 0x6200, 0x6E00, 0x6A00,
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
};
static DRWAV_INLINE drwav_int16 drwav__alaw_to_s16(drwav_uint8 sampleIn)
{
return (short)g_drwavAlawTable[sampleIn];
}
static DRWAV_INLINE drwav_int16 drwav__mulaw_to_s16(drwav_uint8 sampleIn)
{
return (short)g_drwavMulawTable[sampleIn];
}
static void drwav__pcm_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
{
unsigned int i;
if (bytesPerSample == 1) {
drwav_u8_to_s16(pOut, pIn, totalSampleCount);
return;
}
if (bytesPerSample == 2) {
for (i = 0; i < totalSampleCount; ++i) {
*pOut++ = ((const drwav_int16*)pIn)[i];
}
return;
}
if (bytesPerSample == 3) {
drwav_s24_to_s16(pOut, pIn, totalSampleCount);
return;
}
if (bytesPerSample == 4) {
drwav_s32_to_s16(pOut, (const drwav_int32*)pIn, totalSampleCount);
return;
}
if (bytesPerSample > 8) {
DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
return;
}
for (i = 0; i < totalSampleCount; ++i) {
drwav_uint64 sample = 0;
unsigned int shift = (8 - bytesPerSample) * 8;
unsigned int j;
for (j = 0; j < bytesPerSample; j += 1) {
DRWAV_ASSERT(j < 8);
sample |= (drwav_uint64)(pIn[j]) << shift;
shift += 8;
}
pIn += j;
*pOut++ = (drwav_int16)((drwav_int64)sample >> 48);
}
}
static void drwav__ieee_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
{
if (bytesPerSample == 4) {
drwav_f32_to_s16(pOut, (const float*)pIn, totalSampleCount);
return;
} else if (bytesPerSample == 8) {
drwav_f64_to_s16(pOut, (const double*)pIn, totalSampleCount);
return;
} else {
DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
return;
}
}
static drwav_uint64 drwav_read_pcm_frames_s16__pcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
{
drwav_uint32 bytesPerFrame;
drwav_uint64 totalFramesRead;
drwav_uint8 sampleData[4096];
if ((pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 16) || pBufferOut == NULL) {
return drwav_read_pcm_frames(pWav, framesToRead, pBufferOut);
}
bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
totalFramesRead = 0;
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame), sampleData);
if (framesRead == 0) {
break;
}
drwav__pcm_to_s16(pBufferOut, sampleData, (size_t)(framesRead*pWav->channels), bytesPerFrame/pWav->channels);
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_s16__ieee(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
{
drwav_uint64 totalFramesRead;
drwav_uint8 sampleData[4096];
drwav_uint32 bytesPerFrame;
if (pBufferOut == NULL) {
return drwav_read_pcm_frames(pWav, framesToRead, NULL);
}
bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
totalFramesRead = 0;
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame), sampleData);
if (framesRead == 0) {
break;
}
drwav__ieee_to_s16(pBufferOut, sampleData, (size_t)(framesRead*pWav->channels), bytesPerFrame/pWav->channels);
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_s16__alaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
{
drwav_uint64 totalFramesRead;
drwav_uint8 sampleData[4096];
drwav_uint32 bytesPerFrame;
if (pBufferOut == NULL) {
return drwav_read_pcm_frames(pWav, framesToRead, NULL);
}
bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
totalFramesRead = 0;
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame), sampleData);
if (framesRead == 0) {
break;
}
drwav_alaw_to_s16(pBufferOut, sampleData, (size_t)(framesRead*pWav->channels));
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_s16__mulaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
{
drwav_uint64 totalFramesRead;
drwav_uint8 sampleData[4096];
drwav_uint32 bytesPerFrame;
if (pBufferOut == NULL) {
return drwav_read_pcm_frames(pWav, framesToRead, NULL);
}
bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
totalFramesRead = 0;
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame), sampleData);
if (framesRead == 0) {
break;
}
drwav_mulaw_to_s16(pBufferOut, sampleData, (size_t)(framesRead*pWav->channels));
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
{
if (pWav == NULL || framesToRead == 0) {
return 0;
}
if (pBufferOut == NULL) {
return drwav_read_pcm_frames(pWav, framesToRead, NULL);
}
if (framesToRead * pWav->channels * sizeof(drwav_int16) > DRWAV_SIZE_MAX) {
framesToRead = DRWAV_SIZE_MAX / sizeof(drwav_int16) / pWav->channels;
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) {
return drwav_read_pcm_frames_s16__pcm(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
return drwav_read_pcm_frames_s16__ieee(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW) {
return drwav_read_pcm_frames_s16__alaw(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
return drwav_read_pcm_frames_s16__mulaw(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
return drwav_read_pcm_frames_s16__msadpcm(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
return drwav_read_pcm_frames_s16__ima(pWav, framesToRead, pBufferOut);
}
return 0;
}
DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16le(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
{
drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToRead, pBufferOut);
if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_FALSE) {
drwav__bswap_samples_s16(pBufferOut, framesRead*pWav->channels);
}
return framesRead;
}
DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16be(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
{
drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToRead, pBufferOut);
if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_TRUE) {
drwav__bswap_samples_s16(pBufferOut, framesRead*pWav->channels);
}
return framesRead;
}
DRWAV_API void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
{
int r;
size_t i;
for (i = 0; i < sampleCount; ++i) {
int x = pIn[i];
r = x << 8;
r = r - 32768;
pOut[i] = (short)r;
}
}
DRWAV_API void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
{
int r;
size_t i;
for (i = 0; i < sampleCount; ++i) {
int x = ((int)(((unsigned int)(((const drwav_uint8*)pIn)[i*3+0]) << 8) | ((unsigned int)(((const drwav_uint8*)pIn)[i*3+1]) << 16) | ((unsigned int)(((const drwav_uint8*)pIn)[i*3+2])) << 24)) >> 8;
r = x >> 8;
pOut[i] = (short)r;
}
}
DRWAV_API void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCount)
{
int r;
size_t i;
for (i = 0; i < sampleCount; ++i) {
int x = pIn[i];
r = x >> 16;
pOut[i] = (short)r;
}
}
DRWAV_API void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount)
{
int r;
size_t i;
for (i = 0; i < sampleCount; ++i) {
float x = pIn[i];
float c;
c = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
c = c + 1;
r = (int)(c * 32767.5f);
r = r - 32768;
pOut[i] = (short)r;
}
}
DRWAV_API void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount)
{
int r;
size_t i;
for (i = 0; i < sampleCount; ++i) {
double x = pIn[i];
double c;
c = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
c = c + 1;
r = (int)(c * 32767.5);
r = r - 32768;
pOut[i] = (short)r;
}
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
DRWAV_API void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
{
size_t i;
for (i = 0; i < sampleCount; ++i) {
pOut[i] = drwav__mulaw_to_s16(pIn[i]);
}
}
static void drwav__pcm_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample)
{
unsigned int i;
if (bytesPerSample == 1) {
drwav_u8_to_f32(pOut, pIn, sampleCount);
return;
}
if (bytesPerSample == 2) {
drwav_s16_to_f32(pOut, (const drwav_int16*)pIn, sampleCount);
return;
}
if (bytesPerSample == 3) {
drwav_s24_to_f32(pOut, pIn, sampleCount);
return;
}
if (bytesPerSample == 4) {
drwav_s32_to_f32(pOut, (const drwav_int32*)pIn, sampleCount);
return;
}
if (bytesPerSample > 8) {
DRWAV_ZERO_MEMORY(pOut, sampleCount * sizeof(*pOut));
return;
}
for (i = 0; i < sampleCount; ++i) {
drwav_uint64 sample = 0;
unsigned int shift = (8 - bytesPerSample) * 8;
unsigned int j;
for (j = 0; j < bytesPerSample; j += 1) {
DRWAV_ASSERT(j < 8);
sample |= (drwav_uint64)(pIn[j]) << shift;
shift += 8;
}
pIn += j;
*pOut++ = (float)((drwav_int64)sample / 9223372036854775807.0);
}
}
static void drwav__ieee_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample)
{
if (bytesPerSample == 4) {
unsigned int i;
for (i = 0; i < sampleCount; ++i) {
*pOut++ = ((const float*)pIn)[i];
}
return;
} else if (bytesPerSample == 8) {
drwav_f64_to_f32(pOut, (const double*)pIn, sampleCount);
return;
} else {
DRWAV_ZERO_MEMORY(pOut, sampleCount * sizeof(*pOut));
return;
}
}
static drwav_uint64 drwav_read_pcm_frames_f32__pcm(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
{
drwav_uint64 totalFramesRead;
drwav_uint8 sampleData[4096];
drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
totalFramesRead = 0;
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame), sampleData);
if (framesRead == 0) {
break;
}
drwav__pcm_to_f32(pBufferOut, sampleData, (size_t)framesRead*pWav->channels, bytesPerFrame/pWav->channels);
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_f32__msadpcm(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
{
drwav_uint64 totalFramesRead = 0;
drwav_int16 samples16[2048];
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, drwav_min(framesToRead, drwav_countof(samples16)/pWav->channels), samples16);
if (framesRead == 0) {
break;
}
drwav_s16_to_f32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels));
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_f32__ima(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
{
drwav_uint64 totalFramesRead = 0;
drwav_int16 samples16[2048];
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, drwav_min(framesToRead, drwav_countof(samples16)/pWav->channels), samples16);
if (framesRead == 0) {
break;
}
drwav_s16_to_f32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels));
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_f32__ieee(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
{
drwav_uint64 totalFramesRead;
drwav_uint8 sampleData[4096];
drwav_uint32 bytesPerFrame;
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT && pWav->bitsPerSample == 32) {
return drwav_read_pcm_frames(pWav, framesToRead, pBufferOut);
}
bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
totalFramesRead = 0;
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame), sampleData);
if (framesRead == 0) {
break;
}
drwav__ieee_to_f32(pBufferOut, sampleData, (size_t)(framesRead*pWav->channels), bytesPerFrame/pWav->channels);
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_f32__alaw(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
{
drwav_uint64 totalFramesRead;
drwav_uint8 sampleData[4096];
drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
totalFramesRead = 0;
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame), sampleData);
if (framesRead == 0) {
break;
}
drwav_alaw_to_f32(pBufferOut, sampleData, (size_t)(framesRead*pWav->channels));
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_f32__mulaw(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
{
drwav_uint64 totalFramesRead;
drwav_uint8 sampleData[4096];
drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
totalFramesRead = 0;
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame), sampleData);
if (framesRead == 0) {
break;
}
drwav_mulaw_to_f32(pBufferOut, sampleData, (size_t)(framesRead*pWav->channels));
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
{
if (pWav == NULL || framesToRead == 0) {
return 0;
}
if (pBufferOut == NULL) {
return drwav_read_pcm_frames(pWav, framesToRead, NULL);
}
if (framesToRead * pWav->channels * sizeof(float) > DRWAV_SIZE_MAX) {
framesToRead = DRWAV_SIZE_MAX / sizeof(float) / pWav->channels;
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) {
return drwav_read_pcm_frames_f32__pcm(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
return drwav_read_pcm_frames_f32__msadpcm(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
return drwav_read_pcm_frames_f32__ieee(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW) {
return drwav_read_pcm_frames_f32__alaw(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
return drwav_read_pcm_frames_f32__mulaw(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
return drwav_read_pcm_frames_f32__ima(pWav, framesToRead, pBufferOut);
}
return 0;
}
DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32le(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
{
drwav_uint64 framesRead = drwav_read_pcm_frames_f32(pWav, framesToRead, pBufferOut);
if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_FALSE) {
drwav__bswap_samples_f32(pBufferOut, framesRead*pWav->channels);
}
return framesRead;
}
DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32be(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
{
drwav_uint64 framesRead = drwav_read_pcm_frames_f32(pWav, framesToRead, pBufferOut);
if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_TRUE) {
drwav__bswap_samples_f32(pBufferOut, framesRead*pWav->channels);
}
return framesRead;
}
DRWAV_API void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
}
#ifdef DR_WAV_LIBSNDFILE_COMPAT
for (i = 0; i < sampleCount; ++i) {
*pOut++ = (pIn[i] / 256.0f) * 2 - 1;
}
#else
for (i = 0; i < sampleCount; ++i) {
float x = pIn[i];
x = x * 0.00784313725490196078f;
x = x - 1;
*pOut++ = x;
}
#endif
}
DRWAV_API void drwav_s16_to_f32(float* pOut, const drwav_int16* pIn, size_t sampleCount)
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
}
for (i = 0; i < sampleCount; ++i) {
*pOut++ = pIn[i] * 0.000030517578125f;
}
}
DRWAV_API void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
}
for (i = 0; i < sampleCount; ++i) {
double x;
drwav_uint32 a = ((drwav_uint32)(pIn[i*3+0]) << 8);
drwav_uint32 b = ((drwav_uint32)(pIn[i*3+1]) << 16);
drwav_uint32 c = ((drwav_uint32)(pIn[i*3+2]) << 24);
x = (double)((drwav_int32)(a | b | c) >> 8);
*pOut++ = (float)(x * 0.00000011920928955078125);
}
}
DRWAV_API void drwav_s32_to_f32(float* pOut, const drwav_int32* pIn, size_t sampleCount)
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
}
for (i = 0; i < sampleCount; ++i) {
*pOut++ = (float)(pIn[i] / 2147483648.0);
}
}
DRWAV_API void drwav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount)
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
}
for (i = 0; i < sampleCount; ++i) {
*pOut++ = drwav__mulaw_to_s16(pIn[i]) / 32768.0f;
}
}
static void drwav__pcm_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
{
unsigned int i;
if (bytesPerSample == 1) {
drwav_u8_to_s32(pOut, pIn, totalSampleCount);
return;
}
if (bytesPerSample == 2) {
drwav_s16_to_s32(pOut, (const drwav_int16*)pIn, totalSampleCount);
return;
}
if (bytesPerSample == 3) {
drwav_s24_to_s32(pOut, pIn, totalSampleCount);
return;
}
if (bytesPerSample == 4) {
for (i = 0; i < totalSampleCount; ++i) {
*pOut++ = ((const drwav_int32*)pIn)[i];
}
return;
}
if (bytesPerSample > 8) {
DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
return;
}
for (i = 0; i < totalSampleCount; ++i) {
drwav_uint64 sample = 0;
unsigned int shift = (8 - bytesPerSample) * 8;
unsigned int j;
for (j = 0; j < bytesPerSample; j += 1) {
DRWAV_ASSERT(j < 8);
sample |= (drwav_uint64)(pIn[j]) << shift;
shift += 8;
}
pIn += j;
*pOut++ = (drwav_int32)((drwav_int64)sample >> 32);
}
}
static void drwav__ieee_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
{
if (bytesPerSample == 4) {
drwav_f32_to_s32(pOut, (const float*)pIn, totalSampleCount);
return;
} else if (bytesPerSample == 8) {
drwav_f64_to_s32(pOut, (const double*)pIn, totalSampleCount);
return;
} else {
DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
return;
}
}
static drwav_uint64 drwav_read_pcm_frames_s32__pcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
{
drwav_uint64 totalFramesRead;
drwav_uint8 sampleData[4096];
drwav_uint32 bytesPerFrame;
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 32) {
return drwav_read_pcm_frames(pWav, framesToRead, pBufferOut);
}
bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
totalFramesRead = 0;
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame), sampleData);
if (framesRead == 0) {
break;
}
drwav__pcm_to_s32(pBufferOut, sampleData, (size_t)(framesRead*pWav->channels), bytesPerFrame/pWav->channels);
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_s32__msadpcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
{
drwav_uint64 totalFramesRead = 0;
drwav_int16 samples16[2048];
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, drwav_min(framesToRead, drwav_countof(samples16)/pWav->channels), samples16);
if (framesRead == 0) {
break;
}
drwav_s16_to_s32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels));
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_s32__ima(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
{
drwav_uint64 totalFramesRead = 0;
drwav_int16 samples16[2048];
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, drwav_min(framesToRead, drwav_countof(samples16)/pWav->channels), samples16);
if (framesRead == 0) {
break;
}
drwav_s16_to_s32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels));
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_s32__ieee(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
{
drwav_uint64 totalFramesRead;
drwav_uint8 sampleData[4096];
drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
totalFramesRead = 0;
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame), sampleData);
if (framesRead == 0) {
break;
}
drwav__ieee_to_s32(pBufferOut, sampleData, (size_t)(framesRead*pWav->channels), bytesPerFrame/pWav->channels);
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_s32__alaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
{
drwav_uint64 totalFramesRead;
drwav_uint8 sampleData[4096];
drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
totalFramesRead = 0;
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame), sampleData);
if (framesRead == 0) {
break;
}
drwav_alaw_to_s32(pBufferOut, sampleData, (size_t)(framesRead*pWav->channels));
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
static drwav_uint64 drwav_read_pcm_frames_s32__mulaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
{
drwav_uint64 totalFramesRead;
drwav_uint8 sampleData[4096];
drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
if (bytesPerFrame == 0) {
return 0;
}
totalFramesRead = 0;
while (framesToRead > 0) {
drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame), sampleData);
if (framesRead == 0) {
break;
}
drwav_mulaw_to_s32(pBufferOut, sampleData, (size_t)(framesRead*pWav->channels));
pBufferOut += framesRead*pWav->channels;
framesToRead -= framesRead;
totalFramesRead += framesRead;
}
return totalFramesRead;
}
DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
{
if (pWav == NULL || framesToRead == 0) {
return 0;
}
if (pBufferOut == NULL) {
return drwav_read_pcm_frames(pWav, framesToRead, NULL);
}
if (framesToRead * pWav->channels * sizeof(drwav_int32) > DRWAV_SIZE_MAX) {
framesToRead = DRWAV_SIZE_MAX / sizeof(drwav_int32) / pWav->channels;
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) {
return drwav_read_pcm_frames_s32__pcm(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
return drwav_read_pcm_frames_s32__msadpcm(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
return drwav_read_pcm_frames_s32__ieee(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW) {
return drwav_read_pcm_frames_s32__alaw(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
return drwav_read_pcm_frames_s32__mulaw(pWav, framesToRead, pBufferOut);
}
if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
return drwav_read_pcm_frames_s32__ima(pWav, framesToRead, pBufferOut);
}
return 0;
}
DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32le(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
{
drwav_uint64 framesRead = drwav_read_pcm_frames_s32(pWav, framesToRead, pBufferOut);
if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_FALSE) {
drwav__bswap_samples_s32(pBufferOut, framesRead*pWav->channels);
}
return framesRead;
}
DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32be(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
{
drwav_uint64 framesRead = drwav_read_pcm_frames_s32(pWav, framesToRead, pBufferOut);
if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_TRUE) {
drwav__bswap_samples_s32(pBufferOut, framesRead*pWav->channels);
}
return framesRead;
}
DRWAV_API void drwav_u8_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
}
for (i = 0; i < sampleCount; ++i) {
*pOut++ = ((int)pIn[i] - 128) << 24;
}
}
DRWAV_API void drwav_s16_to_s32(drwav_int32* pOut, const drwav_int16* pIn, size_t sampleCount)
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
}
for (i = 0; i < sampleCount; ++i) {
*pOut++ = pIn[i] << 16;
}
}
DRWAV_API void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
}
for (i = 0; i < sampleCount; ++i) {
unsigned int s0 = pIn[i*3 + 0];
unsigned int s1 = pIn[i*3 + 1];
unsigned int s2 = pIn[i*3 + 2];
drwav_int32 sample32 = (drwav_int32)((s0 << 8) | (s1 << 16) | (s2 << 24));
*pOut++ = sample32;
}
}
DRWAV_API void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t sampleCount)
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
}
for (i = 0; i < sampleCount; ++i) {
*pOut++ = (drwav_int32)(2147483648.0 * pIn[i]);
}
}
DRWAV_API void drwav_f64_to_s32(drwav_int32* pOut, const double* pIn, size_t sampleCount)
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
}
for (i = 0; i < sampleCount; ++i) {
*pOut++ = (drwav_int32)(2147483648.0 * pIn[i]);
}
}
DRWAV_API void drwav_alaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
}
for (i = 0; i < sampleCount; ++i) {
*pOut++ = ((drwav_int32)drwav__alaw_to_s16(pIn[i])) << 16;
}
}
DRWAV_API void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
{
size_t i;
if (pOut == NULL || pIn == NULL) {
return;
}
for (i= 0; i < sampleCount; ++i) {
*pOut++ = ((drwav_int32)drwav__mulaw_to_s16(pIn[i])) << 16;
}
}
static drwav_int16* drwav__read_pcm_frames_and_close_s16(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount)
{
drwav_uint64 sampleDataSize;
drwav_int16* pSampleData;
drwav_uint64 framesRead;
DRWAV_ASSERT(pWav != NULL);
sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(drwav_int16);
if (sampleDataSize > DRWAV_SIZE_MAX) {
drwav_uninit(pWav);
return NULL;
}
pSampleData = (drwav_int16*)drwav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks);
if (pSampleData == NULL) {
drwav_uninit(pWav);
return NULL;
}
framesRead = drwav_read_pcm_frames_s16(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
if (framesRead != pWav->totalPCMFrameCount) {
drwav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
drwav_uninit(pWav);
return NULL;
}
drwav_uninit(pWav);
if (sampleRate) {
*sampleRate = pWav->sampleRate;
}
if (channels) {
*channels = pWav->channels;
}
if (totalFrameCount) {
*totalFrameCount = pWav->totalPCMFrameCount;
}
return pSampleData;
}
static float* drwav__read_pcm_frames_and_close_f32(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount)
{
drwav_uint64 sampleDataSize;
float* pSampleData;
drwav_uint64 framesRead;
DRWAV_ASSERT(pWav != NULL);
sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(float);
if (sampleDataSize > DRWAV_SIZE_MAX) {
drwav_uninit(pWav);
return NULL;
}
pSampleData = (float*)drwav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks);
if (pSampleData == NULL) {
drwav_uninit(pWav);
return NULL;
}
framesRead = drwav_read_pcm_frames_f32(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
if (framesRead != pWav->totalPCMFrameCount) {
drwav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
drwav_uninit(pWav);
return NULL;
}
drwav_uninit(pWav);
if (sampleRate) {
*sampleRate = pWav->sampleRate;
}
if (channels) {
*channels = pWav->channels;
}
if (totalFrameCount) {
*totalFrameCount = pWav->totalPCMFrameCount;
}
return pSampleData;
}
static drwav_int32* drwav__read_pcm_frames_and_close_s32(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount)
{
drwav_uint64 sampleDataSize;
drwav_int32* pSampleData;
drwav_uint64 framesRead;
DRWAV_ASSERT(pWav != NULL);
sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(drwav_int32);
if (sampleDataSize > DRWAV_SIZE_MAX) {
drwav_uninit(pWav);
return NULL;
}
pSampleData = (drwav_int32*)drwav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks);
if (pSampleData == NULL) {
drwav_uninit(pWav);
return NULL;
}
framesRead = drwav_read_pcm_frames_s32(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
if (framesRead != pWav->totalPCMFrameCount) {
drwav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
drwav_uninit(pWav);
return NULL;
}
drwav_uninit(pWav);
if (sampleRate) {
*sampleRate = pWav->sampleRate;
}
if (channels) {
*channels = pWav->channels;
}
if (totalFrameCount) {
*totalFrameCount = pWav->totalPCMFrameCount;
}
return pSampleData;
}
DRWAV_API drwav_int16* drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAl...
{
drwav wav;
if (channelsOut) {
*channelsOut = 0;
}
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (totalFrameCountOut) {
*totalFrameCountOut = 0;
}
if (!drwav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
return NULL;
}
return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
}
DRWAV_API float* drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocati...
{
drwav wav;
if (channelsOut) {
*channelsOut = 0;
}
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (totalFrameCountOut) {
*totalFrameCountOut = 0;
}
if (!drwav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
return NULL;
}
return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
}
DRWAV_API drwav_int32* drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAl...
{
drwav wav;
if (channelsOut) {
*channelsOut = 0;
}
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (totalFrameCountOut) {
*totalFrameCountOut = 0;
}
if (!drwav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
return NULL;
}
return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
}
#ifndef DR_WAV_NO_STDIO
DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
{
drwav wav;
if (channelsOut) {
*channelsOut = 0;
}
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (totalFrameCountOut) {
*totalFrameCountOut = 0;
}
if (!drwav_init_file(&wav, filename, pAllocationCallbacks)) {
return NULL;
}
return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
}
DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
{
drwav wav;
if (channelsOut) {
*channelsOut = 0;
}
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (totalFrameCountOut) {
*totalFrameCountOut = 0;
}
if (!drwav_init_file(&wav, filename, pAllocationCallbacks)) {
return NULL;
}
return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
}
DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
{
drwav wav;
if (channelsOut) {
*channelsOut = 0;
}
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (totalFrameCountOut) {
*totalFrameCountOut = 0;
}
if (!drwav_init_file(&wav, filename, pAllocationCallbacks)) {
return NULL;
}
return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
}
DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
{
drwav wav;
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (channelsOut) {
*channelsOut = 0;
}
if (totalFrameCountOut) {
*totalFrameCountOut = 0;
}
if (!drwav_init_file_w(&wav, filename, pAllocationCallbacks)) {
return NULL;
}
return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
}
DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
{
drwav wav;
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (channelsOut) {
*channelsOut = 0;
}
if (totalFrameCountOut) {
*totalFrameCountOut = 0;
}
if (!drwav_init_file_w(&wav, filename, pAllocationCallbacks)) {
return NULL;
}
return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
}
DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
{
drwav wav;
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (channelsOut) {
*channelsOut = 0;
}
if (totalFrameCountOut) {
*totalFrameCountOut = 0;
}
if (!drwav_init_file_w(&wav, filename, pAllocationCallbacks)) {
return NULL;
}
return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
}
#endif
DRWAV_API drwav_int16* drwav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
{
drwav wav;
if (channelsOut) {
*channelsOut = 0;
}
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (totalFrameCountOut) {
*totalFrameCountOut = 0;
}
if (!drwav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
return NULL;
}
return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
}
DRWAV_API float* drwav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
{
drwav wav;
if (channelsOut) {
*channelsOut = 0;
}
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (totalFrameCountOut) {
*totalFrameCountOut = 0;
}
if (!drwav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
return NULL;
}
return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
}
DRWAV_API drwav_int32* drwav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
{
drwav wav;
if (channelsOut) {
*channelsOut = 0;
}
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (totalFrameCountOut) {
*totalFrameCountOut = 0;
}
if (!drwav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
return NULL;
}
return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
}
#endif
DRWAV_API void drwav_free(void* p, const drwav_allocation_callbacks* pAllocationCallbacks)
{
if (pAllocationCallbacks != NULL) {
drwav__free_from_callbacks(p, pAllocationCallbacks);
} else {
drwav__free_default(p, NULL);
}
}
DRWAV_API drwav_uint16 drwav_bytes_to_u16(const drwav_uint8* data)
{
return drwav__bytes_to_u16(data);
}
DRWAV_API drwav_int16 drwav_bytes_to_s16(const drwav_uint8* data)
{
return drwav__bytes_to_s16(data);
}
DRWAV_API drwav_uint32 drwav_bytes_to_u32(const drwav_uint8* data)
{
return drwav__bytes_to_u32(data);
}
DRWAV_API drwav_int32 drwav_bytes_to_s32(const drwav_uint8* data)
{
return drwav__bytes_to_s32(data);
}
DRWAV_API drwav_uint64 drwav_bytes_to_u64(const drwav_uint8* data)
{
return drwav__bytes_to_u64(data);
}
DRWAV_API drwav_int64 drwav_bytes_to_s64(const drwav_uint8* data)
{
return drwav__bytes_to_s64(data);
}
DRWAV_API drwav_bool32 drwav_guid_equal(const drwav_uint8 a[16], const drwav_uint8 b[16])
{
return drwav__guid_equal(a, b);
}
DRWAV_API drwav_bool32 drwav_fourcc_equal(const drwav_uint8* a, const char* b)
{
return drwav__fourcc_equal(a, b);
}
#endif
/* dr_wav_c end */
#endif /* DRWAV_IMPLEMENTATION */
#endif /* MA_NO_WAV */
#if !defined(MA_NO_FLAC) && !defined(MA_NO_DECODING)
#if !defined(DR_FLAC_IMPLEMENTATION) && !defined(DRFLAC_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */
/* dr_flac_c begin */
#ifndef dr_flac_c
#define dr_flac_c
#if defined(__GNUC__)
#pragma GCC diagnostic push
#if __GNUC__ >= 7
#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#endif
#endif
#ifdef __linux__
#ifndef _BSD_SOURCE
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
drflac_uint32 samplesInPartition;
drflac_uint32 partitionsRemaining;
DRFLAC_ASSERT(bs != NULL);
DRFLAC_ASSERT(blockSize != 0);
if (!drflac__read_uint8(bs, 2, &residualMethod)) {
return DRFLAC_FALSE;
}
if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
return DRFLAC_FALSE;
}
if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
return DRFLAC_FALSE;
}
if (partitionOrder > 8) {
return DRFLAC_FALSE;
}
if ((blockSize / (1 << partitionOrder)) <= order) {
return DRFLAC_FALSE;
}
samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
partitionsRemaining = (1 << partitionOrder);
for (;;)
{
drflac_uint8 riceParam = 0;
if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
if (!drflac__read_uint8(bs, 4, &riceParam)) {
return DRFLAC_FALSE;
}
if (riceParam == 15) {
riceParam = 0xFF;
}
} else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
if (!drflac__read_uint8(bs, 5, &riceParam)) {
return DRFLAC_FALSE;
}
if (riceParam == 31) {
riceParam = 0xFF;
}
}
if (riceParam != 0xFF) {
if (!drflac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) {
return DRFLAC_FALSE;
}
} else {
drflac_uint8 unencodedBitsPerSample = 0;
if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
return DRFLAC_FALSE;
}
if (!drflac__seek_bits(bs, unencodedBitsPerSample * samplesInPartition)) {
return DRFLAC_FALSE;
}
}
if (partitionsRemaining == 1) {
break;
}
partitionsRemaining -= 1;
samplesInPartition = blockSize / (1 << partitionOrder);
}
return DRFLAC_TRUE;
}
static drflac_bool32 drflac__decode_samples__constant(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
{
drflac_uint32 i;
drflac_int32 sample;
if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
return DRFLAC_FALSE;
}
for (i = 0; i < blockSize; ++i) {
pDecodedSamples[i] = sample;
}
return DRFLAC_TRUE;
}
static drflac_bool32 drflac__decode_samples__verbatim(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
{
drflac_uint32 i;
for (i = 0; i < blockSize; ++i) {
drflac_int32 sample;
if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
return DRFLAC_FALSE;
}
pDecodedSamples[i] = sample;
}
return DRFLAC_TRUE;
}
static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
{
drflac_uint32 i;
static drflac_int32 lpcCoefficientsTable[5][4] = {
{0, 0, 0, 0},
{1, 0, 0, 0},
{2, -1, 0, 0},
{3, -3, 1, 0},
{4, -6, 4, -1}
};
for (i = 0; i < lpcOrder; ++i) {
drflac_int32 sample;
if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
return DRFLAC_FALSE;
}
pDecodedSamples[i] = sample;
}
if (!drflac__decode_samples_with_residual(bs, subframeBitsPerSample, blockSize, lpcOrder, 0, lpcCoefficientsTable[lpcOrder], pDecodedSamples)) {
return DRFLAC_FALSE;
}
return DRFLAC_TRUE;
}
static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
{
drflac_uint8 i;
drflac_uint8 lpcPrecision;
drflac_int8 lpcShift;
drflac_int32 coefficients[32];
for (i = 0; i < lpcOrder; ++i) {
drflac_int32 sample;
if (!drflac__read_int32(bs, bitsPerSample, &sample)) {
return DRFLAC_FALSE;
}
pDecodedSamples[i] = sample;
}
if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
return DRFLAC_FALSE;
}
if (lpcPrecision == 15) {
return DRFLAC_FALSE;
}
lpcPrecision += 1;
if (!drflac__read_int8(bs, 5, &lpcShift)) {
return DRFLAC_FALSE;
}
if (lpcShift < 0) {
return DRFLAC_FALSE;
}
DRFLAC_ZERO_MEMORY(coefficients, sizeof(coefficients));
for (i = 0; i < lpcOrder; ++i) {
if (!drflac__read_int32(bs, lpcPrecision, coefficients + i)) {
return DRFLAC_FALSE;
}
}
if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, coefficients, pDecodedSamples)) {
return DRFLAC_FALSE;
}
return DRFLAC_TRUE;
}
static drflac_bool32 drflac__read_next_flac_frame_header(drflac_bs* bs, drflac_uint8 streaminfoBitsPerSample, drflac_frame_header* header)
{
const drflac_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000};
const drflac_uint8 bitsPerSampleTable[8] = {0, 8, 12, (drflac_uint8)-1, 16, 20, 24, (drflac_uint8)-1};
DRFLAC_ASSERT(bs != NULL);
DRFLAC_ASSERT(header != NULL);
for (;;) {
drflac_uint8 crc8 = 0xCE;
drflac_uint8 reserved = 0;
drflac_uint8 blockingStrategy = 0;
drflac_uint8 blockSize = 0;
drflac_uint8 sampleRate = 0;
drflac_uint8 channelAssignment = 0;
drflac_uint8 bitsPerSample = 0;
drflac_bool32 isVariableBlockSize;
if (!drflac__find_and_seek_to_next_sync_code(bs)) {
return DRFLAC_FALSE;
}
if (!drflac__read_uint8(bs, 1, &reserved)) {
return DRFLAC_FALSE;
}
if (reserved == 1) {
continue;
}
crc8 = drflac_crc8(crc8, reserved, 1);
if (!drflac__read_uint8(bs, 1, &blockingStrategy)) {
return DRFLAC_FALSE;
}
crc8 = drflac_crc8(crc8, blockingStrategy, 1);
if (!drflac__read_uint8(bs, 4, &blockSize)) {
return DRFLAC_FALSE;
}
if (blockSize == 0) {
continue;
}
crc8 = drflac_crc8(crc8, blockSize, 4);
if (!drflac__read_uint8(bs, 4, &sampleRate)) {
return DRFLAC_FALSE;
}
crc8 = drflac_crc8(crc8, sampleRate, 4);
if (!drflac__read_uint8(bs, 4, &channelAssignment)) {
return DRFLAC_FALSE;
}
if (channelAssignment > 10) {
continue;
}
crc8 = drflac_crc8(crc8, channelAssignment, 4);
if (!drflac__read_uint8(bs, 3, &bitsPerSample)) {
return DRFLAC_FALSE;
}
if (bitsPerSample == 3 || bitsPerSample == 7) {
continue;
}
crc8 = drflac_crc8(crc8, bitsPerSample, 3);
if (!drflac__read_uint8(bs, 1, &reserved)) {
return DRFLAC_FALSE;
}
if (reserved == 1) {
continue;
}
crc8 = drflac_crc8(crc8, reserved, 1);
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
DRFLAC_ASSERT(blockSize > 0);
if (blockSize == 1) {
header->blockSizeInPCMFrames = 192;
} else if (blockSize >= 2 && blockSize <= 5) {
header->blockSizeInPCMFrames = 576 * (1 << (blockSize - 2));
} else if (blockSize == 6) {
if (!drflac__read_uint16(bs, 8, &header->blockSizeInPCMFrames)) {
return DRFLAC_FALSE;
}
crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 8);
header->blockSizeInPCMFrames += 1;
} else if (blockSize == 7) {
if (!drflac__read_uint16(bs, 16, &header->blockSizeInPCMFrames)) {
return DRFLAC_FALSE;
}
crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 16);
header->blockSizeInPCMFrames += 1;
} else {
DRFLAC_ASSERT(blockSize >= 8);
header->blockSizeInPCMFrames = 256 * (1 << (blockSize - 8));
}
if (sampleRate <= 11) {
header->sampleRate = sampleRateTable[sampleRate];
} else if (sampleRate == 12) {
if (!drflac__read_uint32(bs, 8, &header->sampleRate)) {
return DRFLAC_FALSE;
}
crc8 = drflac_crc8(crc8, header->sampleRate, 8);
header->sampleRate *= 1000;
} else if (sampleRate == 13) {
if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
return DRFLAC_FALSE;
}
crc8 = drflac_crc8(crc8, header->sampleRate, 16);
} else if (sampleRate == 14) {
if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
return DRFLAC_FALSE;
}
crc8 = drflac_crc8(crc8, header->sampleRate, 16);
header->sampleRate *= 10;
} else {
continue;
}
header->channelAssignment = channelAssignment;
header->bitsPerSample = bitsPerSampleTable[bitsPerSample];
if (header->bitsPerSample == 0) {
header->bitsPerSample = streaminfoBitsPerSample;
}
if (!drflac__read_uint8(bs, 8, &header->crc8)) {
return DRFLAC_FALSE;
}
#ifndef DR_FLAC_NO_CRC
if (header->crc8 != crc8) {
continue;
}
#endif
return DRFLAC_TRUE;
}
}
static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe* pSubframe)
{
drflac_uint8 header;
int type;
if (!drflac__read_uint8(bs, 8, &header)) {
return DRFLAC_FALSE;
}
if ((header & 0x80) != 0) {
return DRFLAC_FALSE;
}
type = (header & 0x7E) >> 1;
if (type == 0) {
pSubframe->subframeType = DRFLAC_SUBFRAME_CONSTANT;
} else if (type == 1) {
pSubframe->subframeType = DRFLAC_SUBFRAME_VERBATIM;
} else {
if ((type & 0x20) != 0) {
pSubframe->subframeType = DRFLAC_SUBFRAME_LPC;
pSubframe->lpcOrder = (drflac_uint8)(type & 0x1F) + 1;
} else if ((type & 0x08) != 0) {
pSubframe->subframeType = DRFLAC_SUBFRAME_FIXED;
pSubframe->lpcOrder = (drflac_uint8)(type & 0x07);
if (pSubframe->lpcOrder > 4) {
pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
pSubframe->lpcOrder = 0;
}
} else {
pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
}
}
if (pSubframe->subframeType == DRFLAC_SUBFRAME_RESERVED) {
return DRFLAC_FALSE;
}
pSubframe->wastedBitsPerSample = 0;
if ((header & 0x01) == 1) {
unsigned int wastedBitsPerSample;
if (!drflac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) {
return DRFLAC_FALSE;
}
pSubframe->wastedBitsPerSample = (drflac_uint8)wastedBitsPerSample + 1;
}
return DRFLAC_TRUE;
}
static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex, drflac_int32* pDecodedSamplesOut)
{
drflac_subframe* pSubframe;
drflac_uint32 subframeBitsPerSample;
DRFLAC_ASSERT(bs != NULL);
DRFLAC_ASSERT(frame != NULL);
pSubframe = frame->subframes + subframeIndex;
if (!drflac__read_subframe_header(bs, pSubframe)) {
return DRFLAC_FALSE;
}
subframeBitsPerSample = frame->header.bitsPerSample;
if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
subframeBitsPerSample += 1;
} else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
subframeBitsPerSample += 1;
}
if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
return DRFLAC_FALSE;
}
subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
pSubframe->pSamplesS32 = pDecodedSamplesOut;
switch (pSubframe->subframeType)
{
case DRFLAC_SUBFRAME_CONSTANT:
{
drflac__decode_samples__constant(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
} break;
case DRFLAC_SUBFRAME_VERBATIM:
{
drflac__decode_samples__verbatim(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
} break;
case DRFLAC_SUBFRAME_FIXED:
{
drflac__decode_samples__fixed(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
} break;
case DRFLAC_SUBFRAME_LPC:
{
drflac__decode_samples__lpc(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
} break;
default: return DRFLAC_FALSE;
}
return DRFLAC_TRUE;
}
static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex)
{
drflac_subframe* pSubframe;
drflac_uint32 subframeBitsPerSample;
DRFLAC_ASSERT(bs != NULL);
DRFLAC_ASSERT(frame != NULL);
pSubframe = frame->subframes + subframeIndex;
if (!drflac__read_subframe_header(bs, pSubframe)) {
return DRFLAC_FALSE;
}
subframeBitsPerSample = frame->header.bitsPerSample;
if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
subframeBitsPerSample += 1;
} else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
subframeBitsPerSample += 1;
}
if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
return DRFLAC_FALSE;
}
subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
pSubframe->pSamplesS32 = NULL;
switch (pSubframe->subframeType)
{
case DRFLAC_SUBFRAME_CONSTANT:
{
if (!drflac__seek_bits(bs, subframeBitsPerSample)) {
return DRFLAC_FALSE;
}
} break;
case DRFLAC_SUBFRAME_VERBATIM:
{
unsigned int bitsToSeek = frame->header.blockSizeInPCMFrames * subframeBitsPerSample;
if (!drflac__seek_bits(bs, bitsToSeek)) {
return DRFLAC_FALSE;
}
} break;
case DRFLAC_SUBFRAME_FIXED:
{
unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
if (!drflac__seek_bits(bs, bitsToSeek)) {
return DRFLAC_FALSE;
}
if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
return DRFLAC_FALSE;
}
} break;
case DRFLAC_SUBFRAME_LPC:
{
drflac_uint8 lpcPrecision;
unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
if (!drflac__seek_bits(bs, bitsToSeek)) {
return DRFLAC_FALSE;
}
if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
return DRFLAC_FALSE;
}
if (lpcPrecision == 15) {
return DRFLAC_FALSE;
}
lpcPrecision += 1;
bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5;
if (!drflac__seek_bits(bs, bitsToSeek)) {
return DRFLAC_FALSE;
}
if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
return DRFLAC_FALSE;
}
} break;
default: return DRFLAC_FALSE;
}
return DRFLAC_TRUE;
}
static DRFLAC_INLINE drflac_uint8 drflac__get_channel_count_from_channel_assignment(drflac_int8 channelAssignment)
{
drflac_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2};
DRFLAC_ASSERT(channelAssignment <= 10);
return lookup[channelAssignment];
}
static drflac_result drflac__decode_flac_frame(drflac* pFlac)
{
int channelCount;
int i;
drflac_uint8 paddingSizeInBits;
drflac_uint16 desiredCRC16;
#ifndef DR_FLAC_NO_CRC
drflac_uint16 actualCRC16;
#endif
DRFLAC_ZERO_MEMORY(pFlac->currentFLACFrame.subframes, sizeof(pFlac->currentFLACFrame.subframes));
if (pFlac->currentFLACFrame.header.blockSizeInPCMFrames > pFlac->maxBlockSizeInPCMFrames) {
return DRFLAC_ERROR;
}
channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
if (channelCount != (int)pFlac->channels) {
return DRFLAC_ERROR;
}
for (i = 0; i < channelCount; ++i) {
if (!drflac__decode_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i, pFlac->pDecodedSamples + (pFlac->currentFLACFrame.header.blockSizeInPCMFrames * i))) {
return DRFLAC_ERROR;
}
}
paddingSizeInBits = (drflac_uint8)(DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7);
if (paddingSizeInBits > 0) {
drflac_uint8 padding = 0;
if (!drflac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding)) {
return DRFLAC_AT_END;
}
}
#ifndef DR_FLAC_NO_CRC
actualCRC16 = drflac__flush_crc16(&pFlac->bs);
#endif
if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
return DRFLAC_AT_END;
}
#ifndef DR_FLAC_NO_CRC
if (actualCRC16 != desiredCRC16) {
return DRFLAC_CRC_MISMATCH;
}
#endif
pFlac->currentFLACFrame.pcmFramesRemaining = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
return DRFLAC_SUCCESS;
}
static drflac_result drflac__seek_flac_frame(drflac* pFlac)
{
int channelCount;
int i;
drflac_uint16 desiredCRC16;
#ifndef DR_FLAC_NO_CRC
drflac_uint16 actualCRC16;
#endif
channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
for (i = 0; i < channelCount; ++i) {
if (!drflac__seek_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i)) {
return DRFLAC_ERROR;
}
}
if (!drflac__seek_bits(&pFlac->bs, DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7)) {
return DRFLAC_ERROR;
}
#ifndef DR_FLAC_NO_CRC
actualCRC16 = drflac__flush_crc16(&pFlac->bs);
#endif
if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
return DRFLAC_AT_END;
}
#ifndef DR_FLAC_NO_CRC
if (actualCRC16 != desiredCRC16) {
return DRFLAC_CRC_MISMATCH;
}
#endif
return DRFLAC_SUCCESS;
}
static drflac_bool32 drflac__read_and_decode_next_flac_frame(drflac* pFlac)
{
DRFLAC_ASSERT(pFlac != NULL);
for (;;) {
drflac_result result;
if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
return DRFLAC_FALSE;
}
result = drflac__decode_flac_frame(pFlac);
if (result != DRFLAC_SUCCESS) {
if (result == DRFLAC_CRC_MISMATCH) {
continue;
} else {
return DRFLAC_FALSE;
}
}
return DRFLAC_TRUE;
}
}
static void drflac__get_pcm_frame_range_of_current_flac_frame(drflac* pFlac, drflac_uint64* pFirstPCMFrame, drflac_uint64* pLastPCMFrame)
{
drflac_uint64 firstPCMFrame;
drflac_uint64 lastPCMFrame;
DRFLAC_ASSERT(pFlac != NULL);
firstPCMFrame = pFlac->currentFLACFrame.header.pcmFrameNumber;
if (firstPCMFrame == 0) {
firstPCMFrame = ((drflac_uint64)pFlac->currentFLACFrame.header.flacFrameNumber) * pFlac->maxBlockSizeInPCMFrames;
}
lastPCMFrame = firstPCMFrame + pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
if (lastPCMFrame > 0) {
lastPCMFrame -= 1;
}
if (pFirstPCMFrame) {
*pFirstPCMFrame = firstPCMFrame;
}
if (pLastPCMFrame) {
*pLastPCMFrame = lastPCMFrame;
}
}
static drflac_bool32 drflac__seek_to_first_frame(drflac* pFlac)
{
drflac_bool32 result;
DRFLAC_ASSERT(pFlac != NULL);
result = drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes);
DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
pFlac->currentPCMFrame = 0;
return result;
}
static DRFLAC_INLINE drflac_result drflac__seek_to_next_flac_frame(drflac* pFlac)
{
DRFLAC_ASSERT(pFlac != NULL);
return drflac__seek_flac_frame(pFlac);
}
static drflac_uint64 drflac__seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 pcmFramesToSeek)
{
drflac_uint64 pcmFramesRead = 0;
while (pcmFramesToSeek > 0) {
if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
break;
}
} else {
if (pFlac->currentFLACFrame.pcmFramesRemaining > pcmFramesToSeek) {
pcmFramesRead += pcmFramesToSeek;
pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)pcmFramesToSeek;
pcmFramesToSeek = 0;
} else {
pcmFramesRead += pFlac->currentFLACFrame.pcmFramesRemaining;
pcmFramesToSeek -= pFlac->currentFLACFrame.pcmFramesRemaining;
pFlac->currentFLACFrame.pcmFramesRemaining = 0;
}
}
}
pFlac->currentPCMFrame += pcmFramesRead;
return pcmFramesRead;
}
static drflac_bool32 drflac__seek_to_pcm_frame__brute_force(drflac* pFlac, drflac_uint64 pcmFrameIndex)
{
drflac_bool32 isMidFrame = DRFLAC_FALSE;
drflac_uint64 runningPCMFrameCount;
DRFLAC_ASSERT(pFlac != NULL);
if (pcmFrameIndex >= pFlac->currentPCMFrame) {
runningPCMFrameCount = pFlac->currentPCMFrame;
if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
return DRFLAC_FALSE;
}
} else {
isMidFrame = DRFLAC_TRUE;
}
} else {
runningPCMFrameCount = 0;
if (!drflac__seek_to_first_frame(pFlac)) {
return DRFLAC_FALSE;
}
if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
return DRFLAC_FALSE;
}
}
for (;;) {
drflac_uint64 pcmFrameCountInThisFLACFrame;
drflac_uint64 firstPCMFrameInFLACFrame = 0;
drflac_uint64 lastPCMFrameInFLACFrame = 0;
drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
if (!isMidFrame) {
drflac_result result = drflac__decode_flac_frame(pFlac);
if (result == DRFLAC_SUCCESS) {
return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
} else {
if (result == DRFLAC_CRC_MISMATCH) {
goto next_iteration;
} else {
return DRFLAC_FALSE;
}
}
} else {
return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
}
} else {
if (!isMidFrame) {
drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
if (result == DRFLAC_SUCCESS) {
runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
} else {
if (result == DRFLAC_CRC_MISMATCH) {
goto next_iteration;
} else {
return DRFLAC_FALSE;
}
}
} else {
runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
pFlac->currentFLACFrame.pcmFramesRemaining = 0;
isMidFrame = DRFLAC_FALSE;
}
if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
return DRFLAC_TRUE;
}
}
next_iteration:
if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
return DRFLAC_FALSE;
}
}
}
#if !defined(DR_FLAC_NO_CRC)
#define DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO 0.6f
static drflac_bool32 drflac__seek_to_approximate_flac_frame_to_byte(drflac* pFlac, drflac_uint64 targetByte, drflac_uint64 rangeLo, drflac_uint64 rangeHi, drflac_uint64* pLastSuccessfulSeekOffset)
{
DRFLAC_ASSERT(pFlac != NULL);
DRFLAC_ASSERT(pLastSuccessfulSeekOffset != NULL);
DRFLAC_ASSERT(targetByte >= rangeLo);
DRFLAC_ASSERT(targetByte <= rangeHi);
*pLastSuccessfulSeekOffset = pFlac->firstFLACFramePosInBytes;
for (;;) {
if (!drflac__seek_to_byte(&pFlac->bs, targetByte)) {
if (targetByte == 0) {
drflac__seek_to_first_frame(pFlac);
return DRFLAC_FALSE;
}
targetByte = rangeLo + ((rangeHi - rangeLo)/2);
rangeHi = targetByte;
} else {
DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
#if 1
if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
targetByte = rangeLo + ((rangeHi - rangeLo)/2);
rangeHi = targetByte;
} else {
break;
}
#else
if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
targetByte = rangeLo + ((rangeHi - rangeLo)/2);
rangeHi = targetByte;
} else {
break;
}
#endif
}
}
drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
DRFLAC_ASSERT(targetByte <= rangeHi);
*pLastSuccessfulSeekOffset = targetByte;
return DRFLAC_TRUE;
}
static drflac_bool32 drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 offset)
{
#if 0
if (drflac__decode_flac_frame(pFlac) != DRFLAC_SUCCESS) {
if (drflac__read_and_decode_next_flac_frame(pFlac) == DRFLAC_FALSE) {
return DRFLAC_FALSE;
}
}
#endif
return drflac__seek_forward_by_pcm_frames(pFlac, offset) == offset;
}
static drflac_bool32 drflac__seek_to_pcm_frame__binary_search_internal(drflac* pFlac, drflac_uint64 pcmFrameIndex, drflac_uint64 byteRangeLo, drflac_uint64 byteRangeHi)
{
drflac_uint64 targetByte;
drflac_uint64 pcmRangeLo = pFlac->totalPCMFrameCount;
drflac_uint64 pcmRangeHi = 0;
drflac_uint64 lastSuccessfulSeekOffset = (drflac_uint64)-1;
drflac_uint64 closestSeekOffsetBeforeTargetPCMFrame = byteRangeLo;
drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
targetByte = byteRangeLo + (drflac_uint64)(((drflac_int64)((pcmFrameIndex - pFlac->currentPCMFrame) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO);
if (targetByte > byteRangeHi) {
targetByte = byteRangeHi;
}
for (;;) {
if (drflac__seek_to_approximate_flac_frame_to_byte(pFlac, targetByte, byteRangeLo, byteRangeHi, &lastSuccessfulSeekOffset)) {
drflac_uint64 newPCMRangeLo;
drflac_uint64 newPCMRangeHi;
drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &newPCMRangeLo, &newPCMRangeHi);
if (pcmRangeLo == newPCMRangeLo) {
if (!drflac__seek_to_approximate_flac_frame_to_byte(pFlac, closestSeekOffsetBeforeTargetPCMFrame, closestSeekOffsetBeforeTargetPCMFrame, byteRangeHi, &lastSuccessfulSeekOffset)) {
break;
}
if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
return DRFLAC_TRUE;
} else {
break;
}
}
pcmRangeLo = newPCMRangeLo;
pcmRangeHi = newPCMRangeHi;
if (pcmRangeLo <= pcmFrameIndex && pcmRangeHi >= pcmFrameIndex) {
if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame) ) {
return DRFLAC_TRUE;
} else {
break;
}
} else {
const float approxCompressionRatio = (drflac_int64)(lastSuccessfulSeekOffset - pFlac->firstFLACFramePosInBytes) / ((drflac_int64)(pcmRangeLo * pFlac->channels * pFlac->bitsPerSample)/8.0f);
if (pcmRangeLo > pcmFrameIndex) {
byteRangeHi = lastSuccessfulSeekOffset;
if (byteRangeLo > byteRangeHi) {
byteRangeLo = byteRangeHi;
}
targetByte = byteRangeLo + ((byteRangeHi - byteRangeLo) / 2);
if (targetByte < byteRangeLo) {
targetByte = byteRangeLo;
}
} else {
if ((pcmFrameIndex - pcmRangeLo) < seekForwardThreshold) {
if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
return DRFLAC_TRUE;
} else {
break;
}
} else {
byteRangeLo = lastSuccessfulSeekOffset;
if (byteRangeHi < byteRangeLo) {
byteRangeHi = byteRangeLo;
}
targetByte = lastSuccessfulSeekOffset + (drflac_uint64)(((drflac_int64)((pcmFrameIndex-pcmRangeLo) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * approxCompressionRatio);
if (targetByte > byteRangeHi) {
targetByte = byteRangeHi;
}
if (closestSeekOffsetBeforeTargetPCMFrame < lastSuccessfulSeekOffset) {
closestSeekOffsetBeforeTargetPCMFrame = lastSuccessfulSeekOffset;
}
}
}
}
} else {
break;
}
}
drflac__seek_to_first_frame(pFlac);
return DRFLAC_FALSE;
}
static drflac_bool32 drflac__seek_to_pcm_frame__binary_search(drflac* pFlac, drflac_uint64 pcmFrameIndex)
{
drflac_uint64 byteRangeLo;
drflac_uint64 byteRangeHi;
drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
if (drflac__seek_to_first_frame(pFlac) == DRFLAC_FALSE) {
return DRFLAC_FALSE;
}
if (pcmFrameIndex < seekForwardThreshold) {
return drflac__seek_forward_by_pcm_frames(pFlac, pcmFrameIndex) == pcmFrameIndex;
}
byteRangeLo = pFlac->firstFLACFramePosInBytes;
byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
return drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi);
}
#endif
static drflac_bool32 drflac__seek_to_pcm_frame__seek_table(drflac* pFlac, drflac_uint64 pcmFrameIndex)
{
drflac_uint32 iClosestSeekpoint = 0;
drflac_bool32 isMidFrame = DRFLAC_FALSE;
drflac_uint64 runningPCMFrameCount;
drflac_uint32 iSeekpoint;
DRFLAC_ASSERT(pFlac != NULL);
if (pFlac->pSeekpoints == NULL || pFlac->seekpointCount == 0) {
return DRFLAC_FALSE;
}
for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
if (pFlac->pSeekpoints[iSeekpoint].firstPCMFrame >= pcmFrameIndex) {
break;
}
iClosestSeekpoint = iSeekpoint;
}
if (pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount == 0 || pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount > pFlac->maxBlockSizeInPCMFrames) {
return DRFLAC_FALSE;
}
if (pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame > pFlac->totalPCMFrameCount && pFlac->totalPCMFrameCount > 0) {
return DRFLAC_FALSE;
}
#if !defined(DR_FLAC_NO_CRC)
if (pFlac->totalPCMFrameCount > 0) {
drflac_uint64 byteRangeLo;
drflac_uint64 byteRangeHi;
byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
byteRangeLo = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset;
if (iClosestSeekpoint < pFlac->seekpointCount-1) {
drflac_uint32 iNextSeekpoint = iClosestSeekpoint + 1;
if (pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset >= pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset || pFlac->pSeekpoints[iNextSeekpoint].pcmFrameCount == 0) {
return DRFLAC_FALSE;
}
if (pFlac->pSeekpoints[iNextSeekpoint].firstPCMFrame != (((drflac_uint64)0xFFFFFFFF << 32) | 0xFFFFFFFF)) {
byteRangeHi = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset - 1;
}
}
if (drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
if (drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
if (drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi)) {
return DRFLAC_TRUE;
}
}
}
}
#endif
if (pcmFrameIndex >= pFlac->currentPCMFrame && pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame <= pFlac->currentPCMFrame) {
runningPCMFrameCount = pFlac->currentPCMFrame;
if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
return DRFLAC_FALSE;
}
} else {
isMidFrame = DRFLAC_TRUE;
}
} else {
runningPCMFrameCount = pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame;
if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
return DRFLAC_FALSE;
}
if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
return DRFLAC_FALSE;
}
}
for (;;) {
drflac_uint64 pcmFrameCountInThisFLACFrame;
drflac_uint64 firstPCMFrameInFLACFrame = 0;
drflac_uint64 lastPCMFrameInFLACFrame = 0;
drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
if (!isMidFrame) {
drflac_result result = drflac__decode_flac_frame(pFlac);
if (result == DRFLAC_SUCCESS) {
return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
} else {
if (result == DRFLAC_CRC_MISMATCH) {
goto next_iteration;
} else {
return DRFLAC_FALSE;
}
}
} else {
return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
}
} else {
if (!isMidFrame) {
drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
if (result == DRFLAC_SUCCESS) {
runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
} else {
if (result == DRFLAC_CRC_MISMATCH) {
goto next_iteration;
} else {
return DRFLAC_FALSE;
}
}
} else {
runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
pFlac->currentFLACFrame.pcmFramesRemaining = 0;
isMidFrame = DRFLAC_FALSE;
}
if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
return DRFLAC_TRUE;
}
}
next_iteration:
if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
return DRFLAC_FALSE;
}
}
}
#ifndef DR_FLAC_NO_OGG
typedef struct
{
drflac_uint8 capturePattern[4];
drflac_uint8 structureVersion;
drflac_uint8 headerType;
drflac_uint64 granulePosition;
drflac_uint32 serialNumber;
drflac_uint32 sequenceNumber;
drflac_uint32 checksum;
drflac_uint8 segmentCount;
drflac_uint8 segmentTable[255];
} drflac_ogg_page_header;
#endif
typedef struct
{
drflac_read_proc onRead;
drflac_seek_proc onSeek;
drflac_meta_proc onMeta;
drflac_container container;
void* pUserData;
void* pUserDataMD;
drflac_uint32 sampleRate;
drflac_uint8 channels;
drflac_uint8 bitsPerSample;
drflac_uint64 totalPCMFrameCount;
drflac_uint16 maxBlockSizeInPCMFrames;
drflac_uint64 runningFilePos;
drflac_bool32 hasStreamInfoBlock;
drflac_bool32 hasMetadataBlocks;
drflac_bs bs;
drflac_frame_header firstFrameHeader;
#ifndef DR_FLAC_NO_OGG
drflac_uint32 oggSerial;
drflac_uint64 oggFirstBytePos;
drflac_ogg_page_header oggBosHeader;
#endif
} drflac_init_info;
static DRFLAC_INLINE void drflac__decode_block_header(drflac_uint32 blockHeader, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
{
blockHeader = drflac__be2host_32(blockHeader);
*isLastBlock = (drflac_uint8)((blockHeader & 0x80000000UL) >> 31);
*blockType = (drflac_uint8)((blockHeader & 0x7F000000UL) >> 24);
*blockSize = (blockHeader & 0x00FFFFFFUL);
}
static DRFLAC_INLINE drflac_bool32 drflac__read_and_decode_block_header(drflac_read_proc onRead, void* pUserData, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
{
drflac_uint32 blockHeader;
*blockSize = 0;
if (onRead(pUserData, &blockHeader, 4) != 4) {
return DRFLAC_FALSE;
}
drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize);
return DRFLAC_TRUE;
}
static drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, drflac_streaminfo* pStreamInfo)
{
drflac_uint32 blockSizes;
drflac_uint64 frameSizes = 0;
drflac_uint64 importantProps;
drflac_uint8 md5[16];
if (onRead(pUserData, &blockSizes, 4) != 4) {
return DRFLAC_FALSE;
}
if (onRead(pUserData, &frameSizes, 6) != 6) {
return DRFLAC_FALSE;
}
if (onRead(pUserData, &importantProps, 8) != 8) {
return DRFLAC_FALSE;
}
if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5)) {
return DRFLAC_FALSE;
}
blockSizes = drflac__be2host_32(blockSizes);
frameSizes = drflac__be2host_64(frameSizes);
importantProps = drflac__be2host_64(importantProps);
pStreamInfo->minBlockSizeInPCMFrames = (drflac_uint16)((blockSizes & 0xFFFF0000) >> 16);
pStreamInfo->maxBlockSizeInPCMFrames = (drflac_uint16) (blockSizes & 0x0000FFFF);
pStreamInfo->minFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 24)) >> 40);
pStreamInfo->maxFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 0)) >> 16);
pStreamInfo->sampleRate = (drflac_uint32)((importantProps & (((drflac_uint64)0x000FFFFF << 16) << 28)) >> 44);
pStreamInfo->channels = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000000E << 16) << 24)) >> 41) + 1;
pStreamInfo->bitsPerSample = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000001F << 16) << 20)) >> 36) + 1;
pStreamInfo->totalPCMFrameCount = ((importantProps & ((((drflac_uint64)0x0000000F << 16) << 16) | 0xFFFFFFFF)));
DRFLAC_COPY_MEMORY(pStreamInfo->md5, md5, sizeof(md5));
return DRFLAC_TRUE;
}
static void* drflac__malloc_default(size_t sz, void* pUserData)
{
(void)pUserData;
return DRFLAC_MALLOC(sz);
}
static void* drflac__realloc_default(void* p, size_t sz, void* pUserData)
{
(void)pUserData;
return DRFLAC_REALLOC(p, sz);
}
static void drflac__free_default(void* p, void* pUserData)
{
(void)pUserData;
DRFLAC_FREE(p);
}
static void* drflac__malloc_from_callbacks(size_t sz, const drflac_allocation_callbacks* pAllocationCallbacks)
{
if (pAllocationCallbacks == NULL) {
return NULL;
}
if (pAllocationCallbacks->onMalloc != NULL) {
return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
}
if (pAllocationCallbacks->onRealloc != NULL) {
return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
}
return NULL;
}
static void* drflac__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drflac_allocation_callbacks* pAllocationCallbacks)
{
if (pAllocationCallbacks == NULL) {
return NULL;
}
if (pAllocationCallbacks->onRealloc != NULL) {
return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
}
if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
void* p2;
p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
if (p2 == NULL) {
return NULL;
}
if (p != NULL) {
DRFLAC_COPY_MEMORY(p2, p, szOld);
pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
}
return p2;
}
return NULL;
}
static void drflac__free_from_callbacks(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
{
if (p == NULL || pAllocationCallbacks == NULL) {
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
}
} break;
case DRFLAC_METADATA_BLOCK_TYPE_INVALID:
{
if (onMeta) {
if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
isLastBlock = DRFLAC_TRUE;
}
}
} break;
default:
{
if (onMeta) {
void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
if (pRawData == NULL) {
return DRFLAC_FALSE;
}
if (onRead(pUserData, pRawData, blockSize) != blockSize) {
drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
return DRFLAC_FALSE;
}
metadata.pRawData = pRawData;
metadata.rawDataSize = blockSize;
onMeta(pUserDataMD, &metadata);
drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
}
} break;
}
if (onMeta == NULL && blockSize > 0) {
if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
isLastBlock = DRFLAC_TRUE;
}
}
runningFilePos += blockSize;
if (isLastBlock) {
break;
}
}
*pSeektablePos = seektablePos;
*pSeektableSize = seektableSize;
*pFirstFramePos = runningFilePos;
return DRFLAC_TRUE;
}
static drflac_bool32 drflac__init_private__native(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed)
{
drflac_uint8 isLastBlock;
drflac_uint8 blockType;
drflac_uint32 blockSize;
(void)onSeek;
pInit->container = drflac_container_native;
if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
return DRFLAC_FALSE;
}
if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
if (!relaxed) {
return DRFLAC_FALSE;
} else {
pInit->hasStreamInfoBlock = DRFLAC_FALSE;
pInit->hasMetadataBlocks = DRFLAC_FALSE;
if (!drflac__read_next_flac_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) {
return DRFLAC_FALSE;
}
if (pInit->firstFrameHeader.bitsPerSample == 0) {
return DRFLAC_FALSE;
}
pInit->sampleRate = pInit->firstFrameHeader.sampleRate;
pInit->channels = drflac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment);
pInit->bitsPerSample = pInit->firstFrameHeader.bitsPerSample;
pInit->maxBlockSizeInPCMFrames = 65535;
return DRFLAC_TRUE;
}
} else {
drflac_streaminfo streaminfo;
if (!drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
return DRFLAC_FALSE;
}
pInit->hasStreamInfoBlock = DRFLAC_TRUE;
pInit->sampleRate = streaminfo.sampleRate;
pInit->channels = streaminfo.channels;
pInit->bitsPerSample = streaminfo.bitsPerSample;
pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames;
pInit->hasMetadataBlocks = !isLastBlock;
if (onMeta) {
drflac_metadata metadata;
metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
metadata.pRawData = NULL;
metadata.rawDataSize = 0;
metadata.data.streaminfo = streaminfo;
onMeta(pUserDataMD, &metadata);
}
return DRFLAC_TRUE;
}
}
#ifndef DR_FLAC_NO_OGG
#define DRFLAC_OGG_MAX_PAGE_SIZE 65307
#define DRFLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199
typedef enum
{
drflac_ogg_recover_on_crc_mismatch,
drflac_ogg_fail_on_crc_mismatch
} drflac_ogg_crc_mismatch_recovery;
#ifndef DR_FLAC_NO_CRC
static drflac_uint32 drflac__crc32_table[] = {
0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L,
0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L,
0x2608EDB8L, 0x22C9F00FL, 0x2F8AD6D6L, 0x2B4BCB61L,
0x350C9B64L, 0x31CD86D3L, 0x3C8EA00AL, 0x384FBDBDL,
0x4C11DB70L, 0x48D0C6C7L, 0x4593E01EL, 0x4152FDA9L,
0x5F15ADACL, 0x5BD4B01BL, 0x569796C2L, 0x52568B75L,
0x6A1936C8L, 0x6ED82B7FL, 0x639B0DA6L, 0x675A1011L,
0x791D4014L, 0x7DDC5DA3L, 0x709F7B7AL, 0x745E66CDL,
0x9823B6E0L, 0x9CE2AB57L, 0x91A18D8EL, 0x95609039L,
0x8B27C03CL, 0x8FE6DD8BL, 0x82A5FB52L, 0x8664E6E5L,
0xBE2B5B58L, 0xBAEA46EFL, 0xB7A96036L, 0xB3687D81L,
0xAD2F2D84L, 0xA9EE3033L, 0xA4AD16EAL, 0xA06C0B5DL,
0xD4326D90L, 0xD0F37027L, 0xDDB056FEL, 0xD9714B49L,
0xC7361B4CL, 0xC3F706FBL, 0xCEB42022L, 0xCA753D95L,
0xF23A8028L, 0xF6FB9D9FL, 0xFBB8BB46L, 0xFF79A6F1L,
0xE13EF6F4L, 0xE5FFEB43L, 0xE8BCCD9AL, 0xEC7DD02DL,
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
return DRFLAC_FALSE;
}
}
#else
(void)recoveryMethod;
#endif
oggbs->currentPageHeader = header;
oggbs->bytesRemainingInPage = pageBodySize;
return DRFLAC_TRUE;
}
}
#if 0
static drflac_uint8 drflac_oggbs__get_current_segment_index(drflac_oggbs* oggbs, drflac_uint8* pBytesRemainingInSeg)
{
drflac_uint32 bytesConsumedInPage = drflac_ogg__get_page_body_size(&oggbs->currentPageHeader) - oggbs->bytesRemainingInPage;
drflac_uint8 iSeg = 0;
drflac_uint32 iByte = 0;
while (iByte < bytesConsumedInPage) {
drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
if (iByte + segmentSize > bytesConsumedInPage) {
break;
} else {
iSeg += 1;
iByte += segmentSize;
}
}
*pBytesRemainingInSeg = oggbs->currentPageHeader.segmentTable[iSeg] - (drflac_uint8)(bytesConsumedInPage - iByte);
return iSeg;
}
static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs)
{
for (;;) {
drflac_bool32 atEndOfPage = DRFLAC_FALSE;
drflac_uint8 bytesRemainingInSeg;
drflac_uint8 iFirstSeg = drflac_oggbs__get_current_segment_index(oggbs, &bytesRemainingInSeg);
drflac_uint32 bytesToEndOfPacketOrPage = bytesRemainingInSeg;
for (drflac_uint8 iSeg = iFirstSeg; iSeg < oggbs->currentPageHeader.segmentCount; ++iSeg) {
drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
if (segmentSize < 255) {
if (iSeg == oggbs->currentPageHeader.segmentCount-1) {
atEndOfPage = DRFLAC_TRUE;
}
break;
}
bytesToEndOfPacketOrPage += segmentSize;
}
drflac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, drflac_seek_origin_current);
oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage;
if (atEndOfPage) {
if (!drflac_oggbs__goto_next_page(oggbs)) {
return DRFLAC_FALSE;
}
if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
return DRFLAC_TRUE;
}
} else {
return DRFLAC_TRUE;
}
}
}
static drflac_bool32 drflac_oggbs__seek_to_next_frame(drflac_oggbs* oggbs)
{
return drflac_oggbs__seek_to_next_packet(oggbs);
}
#endif
static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead)
{
drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
drflac_uint8* pRunningBufferOut = (drflac_uint8*)bufferOut;
size_t bytesRead = 0;
DRFLAC_ASSERT(oggbs != NULL);
DRFLAC_ASSERT(pRunningBufferOut != NULL);
while (bytesRead < bytesToRead) {
size_t bytesRemainingToRead = bytesToRead - bytesRead;
if (oggbs->bytesRemainingInPage >= bytesRemainingToRead) {
DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), bytesRemainingToRead);
bytesRead += bytesRemainingToRead;
oggbs->bytesRemainingInPage -= (drflac_uint32)bytesRemainingToRead;
break;
}
if (oggbs->bytesRemainingInPage > 0) {
DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage);
bytesRead += oggbs->bytesRemainingInPage;
pRunningBufferOut += oggbs->bytesRemainingInPage;
oggbs->bytesRemainingInPage = 0;
}
DRFLAC_ASSERT(bytesRemainingToRead > 0);
if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
break;
}
}
return bytesRead;
}
static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_seek_origin origin)
{
drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
int bytesSeeked = 0;
DRFLAC_ASSERT(oggbs != NULL);
DRFLAC_ASSERT(offset >= 0);
if (origin == drflac_seek_origin_start) {
if (!drflac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, drflac_seek_origin_start)) {
return DRFLAC_FALSE;
}
if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
return DRFLAC_FALSE;
}
return drflac__on_seek_ogg(pUserData, offset, drflac_seek_origin_current);
}
DRFLAC_ASSERT(origin == drflac_seek_origin_current);
while (bytesSeeked < offset) {
int bytesRemainingToSeek = offset - bytesSeeked;
DRFLAC_ASSERT(bytesRemainingToSeek >= 0);
if (oggbs->bytesRemainingInPage >= (size_t)bytesRemainingToSeek) {
bytesSeeked += bytesRemainingToSeek;
(void)bytesSeeked;
oggbs->bytesRemainingInPage -= bytesRemainingToSeek;
break;
}
if (oggbs->bytesRemainingInPage > 0) {
bytesSeeked += (int)oggbs->bytesRemainingInPage;
oggbs->bytesRemainingInPage = 0;
}
DRFLAC_ASSERT(bytesRemainingToSeek > 0);
if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
return DRFLAC_FALSE;
}
}
return DRFLAC_TRUE;
}
static drflac_bool32 drflac_ogg__seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
{
drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
drflac_uint64 originalBytePos;
drflac_uint64 runningGranulePosition;
drflac_uint64 runningFrameBytePos;
drflac_uint64 runningPCMFrameCount;
DRFLAC_ASSERT(oggbs != NULL);
originalBytePos = oggbs->currentBytePos;
if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes)) {
return DRFLAC_FALSE;
}
oggbs->bytesRemainingInPage = 0;
runningGranulePosition = 0;
for (;;) {
if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
return DRFLAC_FALSE;
}
runningFrameBytePos = oggbs->currentBytePos - drflac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize;
if (oggbs->currentPageHeader.granulePosition >= pcmFrameIndex) {
break;
}
if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
if (oggbs->currentPageHeader.segmentTable[0] >= 2) {
drflac_uint8 firstBytesInPage[2];
firstBytesInPage[0] = oggbs->pageData[0];
firstBytesInPage[1] = oggbs->pageData[1];
if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) {
runningGranulePosition = oggbs->currentPageHeader.granulePosition;
}
continue;
}
}
}
if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, drflac_seek_origin_start)) {
return DRFLAC_FALSE;
}
if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
return DRFLAC_FALSE;
}
runningPCMFrameCount = runningGranulePosition;
for (;;) {
drflac_uint64 firstPCMFrameInFLACFrame = 0;
drflac_uint64 lastPCMFrameInFLACFrame = 0;
drflac_uint64 pcmFrameCountInThisFrame;
if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
return DRFLAC_FALSE;
}
drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
pcmFrameCountInThisFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
if (pcmFrameIndex == pFlac->totalPCMFrameCount && (runningPCMFrameCount + pcmFrameCountInThisFrame) == pFlac->totalPCMFrameCount) {
drflac_result result = drflac__decode_flac_frame(pFlac);
if (result == DRFLAC_SUCCESS) {
pFlac->currentPCMFrame = pcmFrameIndex;
pFlac->currentFLACFrame.pcmFramesRemaining = 0;
return DRFLAC_TRUE;
} else {
return DRFLAC_FALSE;
}
}
if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFrame)) {
drflac_result result = drflac__decode_flac_frame(pFlac);
if (result == DRFLAC_SUCCESS) {
drflac_uint64 pcmFramesToDecode = (size_t)(pcmFrameIndex - runningPCMFrameCount);
if (pcmFramesToDecode == 0) {
return DRFLAC_TRUE;
}
pFlac->currentPCMFrame = runningPCMFrameCount;
return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
} else {
if (result == DRFLAC_CRC_MISMATCH) {
continue;
} else {
return DRFLAC_FALSE;
}
}
} else {
drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
if (result == DRFLAC_SUCCESS) {
runningPCMFrameCount += pcmFrameCountInThisFrame;
} else {
if (result == DRFLAC_CRC_MISMATCH) {
continue;
} else {
return DRFLAC_FALSE;
}
}
}
}
}
static drflac_bool32 drflac__init_private__ogg(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed)
{
drflac_ogg_page_header header;
drflac_uint32 crc32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
drflac_uint32 bytesRead = 0;
(void)relaxed;
pInit->container = drflac_container_ogg;
pInit->oggFirstBytePos = 0;
if (drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
return DRFLAC_FALSE;
}
pInit->runningFilePos += bytesRead;
for (;;) {
int pageBodySize;
if ((header.headerType & 0x02) == 0) {
return DRFLAC_FALSE;
}
pageBodySize = drflac_ogg__get_page_body_size(&header);
if (pageBodySize == 51) {
drflac_uint32 bytesRemainingInPage = pageBodySize;
drflac_uint8 packetType;
if (onRead(pUserData, &packetType, 1) != 1) {
return DRFLAC_FALSE;
}
bytesRemainingInPage -= 1;
if (packetType == 0x7F) {
drflac_uint8 sig[4];
if (onRead(pUserData, sig, 4) != 4) {
return DRFLAC_FALSE;
}
bytesRemainingInPage -= 4;
if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') {
drflac_uint8 mappingVersion[2];
if (onRead(pUserData, mappingVersion, 2) != 2) {
return DRFLAC_FALSE;
}
if (mappingVersion[0] != 1) {
return DRFLAC_FALSE;
}
if (!onSeek(pUserData, 2, drflac_seek_origin_current)) {
return DRFLAC_FALSE;
}
if (onRead(pUserData, sig, 4) != 4) {
return DRFLAC_FALSE;
}
if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C') {
drflac_streaminfo streaminfo;
drflac_uint8 isLastBlock;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
allocationSize += seektableSize;
}
pFlac = (drflac*)drflac__malloc_from_callbacks(allocationSize, &allocationCallbacks);
if (pFlac == NULL) {
return NULL;
}
drflac__init_from_info(pFlac, &init);
pFlac->allocationCallbacks = allocationCallbacks;
pFlac->pDecodedSamples = (drflac_int32*)drflac_align((size_t)pFlac->pExtraData, DRFLAC_MAX_SIMD_VECTOR_SIZE);
#ifndef DR_FLAC_NO_OGG
if (init.container == drflac_container_ogg) {
drflac_oggbs* pInternalOggbs = (drflac_oggbs*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize + seektableSize);
*pInternalOggbs = oggbs;
pFlac->bs.onRead = drflac__on_read_ogg;
pFlac->bs.onSeek = drflac__on_seek_ogg;
pFlac->bs.pUserData = (void*)pInternalOggbs;
pFlac->_oggbs = (void*)pInternalOggbs;
}
#endif
pFlac->firstFLACFramePosInBytes = firstFramePos;
#ifndef DR_FLAC_NO_OGG
if (init.container == drflac_container_ogg)
{
pFlac->pSeekpoints = NULL;
pFlac->seekpointCount = 0;
}
else
#endif
{
if (seektablePos != 0) {
pFlac->seekpointCount = seektableSize / sizeof(*pFlac->pSeekpoints);
pFlac->pSeekpoints = (drflac_seekpoint*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize);
DRFLAC_ASSERT(pFlac->bs.onSeek != NULL);
DRFLAC_ASSERT(pFlac->bs.onRead != NULL);
if (pFlac->bs.onSeek(pFlac->bs.pUserData, (int)seektablePos, drflac_seek_origin_start)) {
if (pFlac->bs.onRead(pFlac->bs.pUserData, pFlac->pSeekpoints, seektableSize) == seektableSize) {
drflac_uint32 iSeekpoint;
for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
pFlac->pSeekpoints[iSeekpoint].firstPCMFrame = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].firstPCMFrame);
pFlac->pSeekpoints[iSeekpoint].flacFrameOffset = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].flacFrameOffset);
pFlac->pSeekpoints[iSeekpoint].pcmFrameCount = drflac__be2host_16(pFlac->pSeekpoints[iSeekpoint].pcmFrameCount);
}
} else {
pFlac->pSeekpoints = NULL;
pFlac->seekpointCount = 0;
}
if (!pFlac->bs.onSeek(pFlac->bs.pUserData, (int)pFlac->firstFLACFramePosInBytes, drflac_seek_origin_start)) {
drflac__free_from_callbacks(pFlac, &allocationCallbacks);
return NULL;
}
} else {
pFlac->pSeekpoints = NULL;
pFlac->seekpointCount = 0;
}
}
}
if (!init.hasStreamInfoBlock) {
pFlac->currentFLACFrame.header = init.firstFrameHeader;
for (;;) {
drflac_result result = drflac__decode_flac_frame(pFlac);
if (result == DRFLAC_SUCCESS) {
break;
} else {
if (result == DRFLAC_CRC_MISMATCH) {
if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
drflac__free_from_callbacks(pFlac, &allocationCallbacks);
return NULL;
}
continue;
} else {
drflac__free_from_callbacks(pFlac, &allocationCallbacks);
return NULL;
}
}
}
}
return pFlac;
}
#ifndef DR_FLAC_NO_STDIO
#include <stdio.h>
#include <wchar.h>
#include <errno.h>
static drflac_result drflac_result_from_errno(int e)
{
switch (e)
{
case 0: return DRFLAC_SUCCESS;
#ifdef EPERM
case EPERM: return DRFLAC_INVALID_OPERATION;
#endif
#ifdef ENOENT
case ENOENT: return DRFLAC_DOES_NOT_EXIST;
#endif
#ifdef ESRCH
case ESRCH: return DRFLAC_DOES_NOT_EXIST;
#endif
#ifdef EINTR
case EINTR: return DRFLAC_INTERRUPT;
#endif
#ifdef EIO
case EIO: return DRFLAC_IO_ERROR;
#endif
#ifdef ENXIO
case ENXIO: return DRFLAC_DOES_NOT_EXIST;
#endif
#ifdef E2BIG
case E2BIG: return DRFLAC_INVALID_ARGS;
#endif
#ifdef ENOEXEC
case ENOEXEC: return DRFLAC_INVALID_FILE;
#endif
#ifdef EBADF
case EBADF: return DRFLAC_INVALID_FILE;
#endif
#ifdef ECHILD
case ECHILD: return DRFLAC_ERROR;
#endif
#ifdef EAGAIN
case EAGAIN: return DRFLAC_UNAVAILABLE;
#endif
#ifdef ENOMEM
case ENOMEM: return DRFLAC_OUT_OF_MEMORY;
#endif
#ifdef EACCES
case EACCES: return DRFLAC_ACCESS_DENIED;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
drflac* pFlac;
memoryStream.data = (const drflac_uint8*)pData;
memoryStream.dataSize = dataSize;
memoryStream.currentReadPos = 0;
pFlac = drflac_open_with_metadata_private(drflac__on_read_memory, drflac__on_seek_memory, onMeta, drflac_container_unknown, &memoryStream, pUserData, pAllocationCallbacks);
if (pFlac == NULL) {
return NULL;
}
pFlac->memoryStream = memoryStream;
#ifndef DR_FLAC_NO_OGG
if (pFlac->container == drflac_container_ogg)
{
drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
oggbs->pUserData = &pFlac->memoryStream;
}
else
#endif
{
pFlac->bs.pUserData = &pFlac->memoryStream;
}
return pFlac;
}
DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
{
return drflac_open_with_metadata_private(onRead, onSeek, NULL, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
}
DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
{
return drflac_open_with_metadata_private(onRead, onSeek, NULL, container, pUserData, pUserData, pAllocationCallbacks);
}
DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
{
return drflac_open_with_metadata_private(onRead, onSeek, onMeta, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
}
DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
{
return drflac_open_with_metadata_private(onRead, onSeek, onMeta, container, pUserData, pUserData, pAllocationCallbacks);
}
DRFLAC_API void drflac_close(drflac* pFlac)
{
if (pFlac == NULL) {
return;
}
#ifndef DR_FLAC_NO_STDIO
if (pFlac->bs.onRead == drflac__on_read_stdio) {
fclose((FILE*)pFlac->bs.pUserData);
}
#ifndef DR_FLAC_NO_OGG
if (pFlac->container == drflac_container_ogg) {
drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
DRFLAC_ASSERT(pFlac->bs.onRead == drflac__on_read_ogg);
if (oggbs->onRead == drflac__on_read_stdio) {
fclose((FILE*)oggbs->pUserData);
}
}
#endif
#endif
drflac__free_from_callbacks(pFlac, &pFlac->allocationCallbacks);
}
#if 0
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutpu...
{
drflac_uint64 i;
for (i = 0; i < frameCount; ++i) {
drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
drflac_uint32 right = left - side;
pOutputSamples[i*2+0] = (drflac_int32)left;
pOutputSamples[i*2+1] = (drflac_int32)right;
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSa...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
drflac_uint32 right0 = left0 - side0;
drflac_uint32 right1 = left1 - side1;
drflac_uint32 right2 = left2 - side2;
drflac_uint32 right3 = left3 - side3;
pOutputSamples[i*8+0] = (drflac_int32)left0;
pOutputSamples[i*8+1] = (drflac_int32)right0;
pOutputSamples[i*8+2] = (drflac_int32)left1;
pOutputSamples[i*8+3] = (drflac_int32)right1;
pOutputSamples[i*8+4] = (drflac_int32)left2;
pOutputSamples[i*8+5] = (drflac_int32)right2;
pOutputSamples[i*8+6] = (drflac_int32)left3;
pOutputSamples[i*8+7] = (drflac_int32)right3;
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 left = pInputSamples0U32[i] << shift0;
drflac_uint32 side = pInputSamples1U32[i] << shift1;
drflac_uint32 right = left - side;
pOutputSamples[i*2+0] = (drflac_int32)left;
pOutputSamples[i*2+1] = (drflac_int32)right;
}
}
#if defined(DRFLAC_SUPPORT_SSE2)
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamp...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
for (i = 0; i < frameCount4; ++i) {
__m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
__m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
__m128i right = _mm_sub_epi32(left, side);
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 left = pInputSamples0U32[i] << shift0;
drflac_uint32 side = pInputSamples1U32[i] << shift1;
drflac_uint32 right = left - side;
pOutputSamples[i*2+0] = (drflac_int32)left;
pOutputSamples[i*2+1] = (drflac_int32)right;
}
}
#endif
#if defined(DRFLAC_SUPPORT_NEON)
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamp...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
int32x4_t shift0_4;
int32x4_t shift1_4;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
shift0_4 = vdupq_n_s32(shift0);
shift1_4 = vdupq_n_s32(shift1);
for (i = 0; i < frameCount4; ++i) {
uint32x4_t left;
uint32x4_t side;
uint32x4_t right;
left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
right = vsubq_u32(left, side);
drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 left = pInputSamples0U32[i] << shift0;
drflac_uint32 side = pInputSamples1U32[i] << shift1;
drflac_uint32 right = left - side;
pOutputSamples[i*2+0] = (drflac_int32)left;
pOutputSamples[i*2+1] = (drflac_int32)right;
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
{
#if defined(DRFLAC_SUPPORT_SSE2)
if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#elif defined(DRFLAC_SUPPORT_NEON)
if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#endif
{
#if 0
drflac_read_pcm_frames_s32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#else
drflac_read_pcm_frames_s32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#endif
}
}
#if 0
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutp...
{
drflac_uint64 i;
for (i = 0; i < frameCount; ++i) {
drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
drflac_uint32 left = right + side;
pOutputSamples[i*2+0] = (drflac_int32)left;
pOutputSamples[i*2+1] = (drflac_int32)right;
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputS...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
drflac_uint32 left0 = right0 + side0;
drflac_uint32 left1 = right1 + side1;
drflac_uint32 left2 = right2 + side2;
drflac_uint32 left3 = right3 + side3;
pOutputSamples[i*8+0] = (drflac_int32)left0;
pOutputSamples[i*8+1] = (drflac_int32)right0;
pOutputSamples[i*8+2] = (drflac_int32)left1;
pOutputSamples[i*8+3] = (drflac_int32)right1;
pOutputSamples[i*8+4] = (drflac_int32)left2;
pOutputSamples[i*8+5] = (drflac_int32)right2;
pOutputSamples[i*8+6] = (drflac_int32)left3;
pOutputSamples[i*8+7] = (drflac_int32)right3;
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 side = pInputSamples0U32[i] << shift0;
drflac_uint32 right = pInputSamples1U32[i] << shift1;
drflac_uint32 left = right + side;
pOutputSamples[i*2+0] = (drflac_int32)left;
pOutputSamples[i*2+1] = (drflac_int32)right;
}
}
#if defined(DRFLAC_SUPPORT_SSE2)
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSam...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
for (i = 0; i < frameCount4; ++i) {
__m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
__m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
__m128i left = _mm_add_epi32(right, side);
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 side = pInputSamples0U32[i] << shift0;
drflac_uint32 right = pInputSamples1U32[i] << shift1;
drflac_uint32 left = right + side;
pOutputSamples[i*2+0] = (drflac_int32)left;
pOutputSamples[i*2+1] = (drflac_int32)right;
}
}
#endif
#if defined(DRFLAC_SUPPORT_NEON)
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSam...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
int32x4_t shift0_4;
int32x4_t shift1_4;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
shift0_4 = vdupq_n_s32(shift0);
shift1_4 = vdupq_n_s32(shift1);
for (i = 0; i < frameCount4; ++i) {
uint32x4_t side;
uint32x4_t right;
uint32x4_t left;
side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
left = vaddq_u32(right, side);
drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 side = pInputSamples0U32[i] << shift0;
drflac_uint32 right = pInputSamples1U32[i] << shift1;
drflac_uint32 left = right + side;
pOutputSamples[i*2+0] = (drflac_int32)left;
pOutputSamples[i*2+1] = (drflac_int32)right;
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
{
#if defined(DRFLAC_SUPPORT_SSE2)
if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#elif defined(DRFLAC_SUPPORT_NEON)
if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#endif
{
#if 0
drflac_read_pcm_frames_s32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#else
drflac_read_pcm_frames_s32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#endif
}
}
#if 0
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutput...
{
for (drflac_uint64 i = 0; i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSam...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_int32 shift = unusedBitsPerSample;
if (shift > 0) {
shift -= 1;
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 temp0L;
drflac_uint32 temp1L;
drflac_uint32 temp2L;
drflac_uint32 temp3L;
drflac_uint32 temp0R;
drflac_uint32 temp1R;
drflac_uint32 temp2R;
drflac_uint32 temp3R;
drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid0 = (mid0 << 1) | (side0 & 0x01);
mid1 = (mid1 << 1) | (side1 & 0x01);
mid2 = (mid2 << 1) | (side2 & 0x01);
mid3 = (mid3 << 1) | (side3 & 0x01);
temp0L = (mid0 + side0) << shift;
temp1L = (mid1 + side1) << shift;
temp2L = (mid2 + side2) << shift;
temp3L = (mid3 + side3) << shift;
temp0R = (mid0 - side0) << shift;
temp1R = (mid1 - side1) << shift;
temp2R = (mid2 - side2) << shift;
temp3R = (mid3 - side3) << shift;
pOutputSamples[i*8+0] = (drflac_int32)temp0L;
pOutputSamples[i*8+1] = (drflac_int32)temp0R;
pOutputSamples[i*8+2] = (drflac_int32)temp1L;
pOutputSamples[i*8+3] = (drflac_int32)temp1R;
pOutputSamples[i*8+4] = (drflac_int32)temp2L;
pOutputSamples[i*8+5] = (drflac_int32)temp2R;
pOutputSamples[i*8+6] = (drflac_int32)temp3L;
pOutputSamples[i*8+7] = (drflac_int32)temp3R;
}
} else {
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 temp0L;
drflac_uint32 temp1L;
drflac_uint32 temp2L;
drflac_uint32 temp3L;
drflac_uint32 temp0R;
drflac_uint32 temp1R;
drflac_uint32 temp2R;
drflac_uint32 temp3R;
drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid0 = (mid0 << 1) | (side0 & 0x01);
mid1 = (mid1 << 1) | (side1 & 0x01);
mid2 = (mid2 << 1) | (side2 & 0x01);
mid3 = (mid3 << 1) | (side3 & 0x01);
temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
pOutputSamples[i*8+0] = (drflac_int32)temp0L;
pOutputSamples[i*8+1] = (drflac_int32)temp0R;
pOutputSamples[i*8+2] = (drflac_int32)temp1L;
pOutputSamples[i*8+3] = (drflac_int32)temp1R;
pOutputSamples[i*8+4] = (drflac_int32)temp2L;
pOutputSamples[i*8+5] = (drflac_int32)temp2R;
pOutputSamples[i*8+6] = (drflac_int32)temp3L;
pOutputSamples[i*8+7] = (drflac_int32)temp3R;
}
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
}
}
#if defined(DRFLAC_SUPPORT_SSE2)
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSampl...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_int32 shift = unusedBitsPerSample;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
if (shift == 0) {
for (i = 0; i < frameCount4; ++i) {
__m128i mid;
__m128i side;
__m128i left;
__m128i right;
mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
}
} else {
shift -= 1;
for (i = 0; i < frameCount4; ++i) {
__m128i mid;
__m128i side;
__m128i left;
__m128i right;
mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
}
}
}
#endif
#if defined(DRFLAC_SUPPORT_NEON)
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSampl...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_int32 shift = unusedBitsPerSample;
int32x4_t wbpsShift0_4;
int32x4_t wbpsShift1_4;
uint32x4_t one4;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
one4 = vdupq_n_u32(1);
if (shift == 0) {
for (i = 0; i < frameCount4; ++i) {
uint32x4_t mid;
uint32x4_t side;
int32x4_t left;
int32x4_t right;
mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
}
} else {
int32x4_t shift4;
shift -= 1;
shift4 = vdupq_n_s32(shift);
for (i = 0; i < frameCount4; ++i) {
uint32x4_t mid;
uint32x4_t side;
int32x4_t left;
int32x4_t right;
mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
}
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
{
#if defined(DRFLAC_SUPPORT_SSE2)
if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#elif defined(DRFLAC_SUPPORT_NEON)
if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#endif
{
#if 0
drflac_read_pcm_frames_s32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#else
drflac_read_pcm_frames_s32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#endif
}
}
#if 0
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int3...
{
for (drflac_uint64 i = 0; i < frameCount; ++i) {
pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample));
pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample));
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* ...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
pOutputSamples[i*8+0] = (drflac_int32)tempL0;
pOutputSamples[i*8+1] = (drflac_int32)tempR0;
pOutputSamples[i*8+2] = (drflac_int32)tempL1;
pOutputSamples[i*8+3] = (drflac_int32)tempR1;
pOutputSamples[i*8+4] = (drflac_int32)tempL2;
pOutputSamples[i*8+5] = (drflac_int32)tempR2;
pOutputSamples[i*8+6] = (drflac_int32)tempL3;
pOutputSamples[i*8+7] = (drflac_int32)tempR3;
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
}
}
#if defined(DRFLAC_SUPPORT_SSE2)
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pO...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
for (i = 0; i < frameCount4; ++i) {
__m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
__m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
}
}
#endif
#if defined(DRFLAC_SUPPORT_NEON)
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pO...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
int32x4_t shift4_0 = vdupq_n_s32(shift0);
int32x4_t shift4_1 = vdupq_n_s32(shift1);
for (i = 0; i < frameCount4; ++i) {
int32x4_t left;
int32x4_t right;
left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift4_0));
right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift4_1));
drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputS...
{
#if defined(DRFLAC_SUPPORT_SSE2)
if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#elif defined(DRFLAC_SUPPORT_NEON)
if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#endif
{
#if 0
drflac_read_pcm_frames_s32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#else
drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#endif
}
}
DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut)
{
drflac_uint64 framesRead;
drflac_uint32 unusedBitsPerSample;
if (pFlac == NULL || framesToRead == 0) {
return 0;
}
if (pBufferOut == NULL) {
return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
}
DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
unusedBitsPerSample = 32 - pFlac->bitsPerSample;
framesRead = 0;
while (framesToRead > 0) {
if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
break;
}
} else {
unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
drflac_uint64 frameCountThisIteration = framesToRead;
if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
}
if (channelCount == 2) {
const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
switch (pFlac->currentFLACFrame.header.channelAssignment)
{
case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
{
drflac_read_pcm_frames_s32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
} break;
case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
{
drflac_read_pcm_frames_s32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
} break;
case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
{
drflac_read_pcm_frames_s32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
} break;
case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
default:
{
drflac_read_pcm_frames_s32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
} break;
}
} else {
drflac_uint64 i;
for (i = 0; i < frameCountThisIteration; ++i) {
unsigned int j;
for (j = 0; j < channelCount; ++j) {
pBufferOut[(i*channelCount)+j] = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
}
}
}
framesRead += frameCountThisIteration;
pBufferOut += frameCountThisIteration * channelCount;
framesToRead -= frameCountThisIteration;
pFlac->currentPCMFrame += frameCountThisIteration;
pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
}
}
return framesRead;
}
#if 0
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutpu...
{
drflac_uint64 i;
for (i = 0; i < frameCount; ++i) {
drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
drflac_uint32 right = left - side;
left >>= 16;
right >>= 16;
pOutputSamples[i*2+0] = (drflac_int16)left;
pOutputSamples[i*2+1] = (drflac_int16)right;
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSa...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
drflac_uint32 right0 = left0 - side0;
drflac_uint32 right1 = left1 - side1;
drflac_uint32 right2 = left2 - side2;
drflac_uint32 right3 = left3 - side3;
left0 >>= 16;
left1 >>= 16;
left2 >>= 16;
left3 >>= 16;
right0 >>= 16;
right1 >>= 16;
right2 >>= 16;
right3 >>= 16;
pOutputSamples[i*8+0] = (drflac_int16)left0;
pOutputSamples[i*8+1] = (drflac_int16)right0;
pOutputSamples[i*8+2] = (drflac_int16)left1;
pOutputSamples[i*8+3] = (drflac_int16)right1;
pOutputSamples[i*8+4] = (drflac_int16)left2;
pOutputSamples[i*8+5] = (drflac_int16)right2;
pOutputSamples[i*8+6] = (drflac_int16)left3;
pOutputSamples[i*8+7] = (drflac_int16)right3;
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 left = pInputSamples0U32[i] << shift0;
drflac_uint32 side = pInputSamples1U32[i] << shift1;
drflac_uint32 right = left - side;
left >>= 16;
right >>= 16;
pOutputSamples[i*2+0] = (drflac_int16)left;
pOutputSamples[i*2+1] = (drflac_int16)right;
}
}
#if defined(DRFLAC_SUPPORT_SSE2)
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamp...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
for (i = 0; i < frameCount4; ++i) {
__m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
__m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
__m128i right = _mm_sub_epi32(left, side);
left = _mm_srai_epi32(left, 16);
right = _mm_srai_epi32(right, 16);
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 left = pInputSamples0U32[i] << shift0;
drflac_uint32 side = pInputSamples1U32[i] << shift1;
drflac_uint32 right = left - side;
left >>= 16;
right >>= 16;
pOutputSamples[i*2+0] = (drflac_int16)left;
pOutputSamples[i*2+1] = (drflac_int16)right;
}
}
#endif
#if defined(DRFLAC_SUPPORT_NEON)
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamp...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
int32x4_t shift0_4;
int32x4_t shift1_4;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
shift0_4 = vdupq_n_s32(shift0);
shift1_4 = vdupq_n_s32(shift1);
for (i = 0; i < frameCount4; ++i) {
uint32x4_t left;
uint32x4_t side;
uint32x4_t right;
left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
right = vsubq_u32(left, side);
left = vshrq_n_u32(left, 16);
right = vshrq_n_u32(right, 16);
drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 left = pInputSamples0U32[i] << shift0;
drflac_uint32 side = pInputSamples1U32[i] << shift1;
drflac_uint32 right = left - side;
left >>= 16;
right >>= 16;
pOutputSamples[i*2+0] = (drflac_int16)left;
pOutputSamples[i*2+1] = (drflac_int16)right;
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
{
#if defined(DRFLAC_SUPPORT_SSE2)
if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s16__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#elif defined(DRFLAC_SUPPORT_NEON)
if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s16__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#endif
{
#if 0
drflac_read_pcm_frames_s16__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#else
drflac_read_pcm_frames_s16__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#endif
}
}
#if 0
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutp...
{
drflac_uint64 i;
for (i = 0; i < frameCount; ++i) {
drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
drflac_uint32 left = right + side;
left >>= 16;
right >>= 16;
pOutputSamples[i*2+0] = (drflac_int16)left;
pOutputSamples[i*2+1] = (drflac_int16)right;
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputS...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
drflac_uint32 left0 = right0 + side0;
drflac_uint32 left1 = right1 + side1;
drflac_uint32 left2 = right2 + side2;
drflac_uint32 left3 = right3 + side3;
left0 >>= 16;
left1 >>= 16;
left2 >>= 16;
left3 >>= 16;
right0 >>= 16;
right1 >>= 16;
right2 >>= 16;
right3 >>= 16;
pOutputSamples[i*8+0] = (drflac_int16)left0;
pOutputSamples[i*8+1] = (drflac_int16)right0;
pOutputSamples[i*8+2] = (drflac_int16)left1;
pOutputSamples[i*8+3] = (drflac_int16)right1;
pOutputSamples[i*8+4] = (drflac_int16)left2;
pOutputSamples[i*8+5] = (drflac_int16)right2;
pOutputSamples[i*8+6] = (drflac_int16)left3;
pOutputSamples[i*8+7] = (drflac_int16)right3;
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 side = pInputSamples0U32[i] << shift0;
drflac_uint32 right = pInputSamples1U32[i] << shift1;
drflac_uint32 left = right + side;
left >>= 16;
right >>= 16;
pOutputSamples[i*2+0] = (drflac_int16)left;
pOutputSamples[i*2+1] = (drflac_int16)right;
}
}
#if defined(DRFLAC_SUPPORT_SSE2)
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSam...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
for (i = 0; i < frameCount4; ++i) {
__m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
__m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
__m128i left = _mm_add_epi32(right, side);
left = _mm_srai_epi32(left, 16);
right = _mm_srai_epi32(right, 16);
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 side = pInputSamples0U32[i] << shift0;
drflac_uint32 right = pInputSamples1U32[i] << shift1;
drflac_uint32 left = right + side;
left >>= 16;
right >>= 16;
pOutputSamples[i*2+0] = (drflac_int16)left;
pOutputSamples[i*2+1] = (drflac_int16)right;
}
}
#endif
#if defined(DRFLAC_SUPPORT_NEON)
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSam...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
int32x4_t shift0_4;
int32x4_t shift1_4;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
shift0_4 = vdupq_n_s32(shift0);
shift1_4 = vdupq_n_s32(shift1);
for (i = 0; i < frameCount4; ++i) {
uint32x4_t side;
uint32x4_t right;
uint32x4_t left;
side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
left = vaddq_u32(right, side);
left = vshrq_n_u32(left, 16);
right = vshrq_n_u32(right, 16);
drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 side = pInputSamples0U32[i] << shift0;
drflac_uint32 right = pInputSamples1U32[i] << shift1;
drflac_uint32 left = right + side;
left >>= 16;
right >>= 16;
pOutputSamples[i*2+0] = (drflac_int16)left;
pOutputSamples[i*2+1] = (drflac_int16)right;
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
{
#if defined(DRFLAC_SUPPORT_SSE2)
if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s16__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#elif defined(DRFLAC_SUPPORT_NEON)
if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s16__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#endif
{
#if 0
drflac_read_pcm_frames_s16__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#else
drflac_read_pcm_frames_s16__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#endif
}
}
#if 0
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutput...
{
for (drflac_uint64 i = 0; i < frameCount; ++i) {
drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSam...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift = unusedBitsPerSample;
if (shift > 0) {
shift -= 1;
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 temp0L;
drflac_uint32 temp1L;
drflac_uint32 temp2L;
drflac_uint32 temp3L;
drflac_uint32 temp0R;
drflac_uint32 temp1R;
drflac_uint32 temp2R;
drflac_uint32 temp3R;
drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid0 = (mid0 << 1) | (side0 & 0x01);
mid1 = (mid1 << 1) | (side1 & 0x01);
mid2 = (mid2 << 1) | (side2 & 0x01);
mid3 = (mid3 << 1) | (side3 & 0x01);
temp0L = (mid0 + side0) << shift;
temp1L = (mid1 + side1) << shift;
temp2L = (mid2 + side2) << shift;
temp3L = (mid3 + side3) << shift;
temp0R = (mid0 - side0) << shift;
temp1R = (mid1 - side1) << shift;
temp2R = (mid2 - side2) << shift;
temp3R = (mid3 - side3) << shift;
temp0L >>= 16;
temp1L >>= 16;
temp2L >>= 16;
temp3L >>= 16;
temp0R >>= 16;
temp1R >>= 16;
temp2R >>= 16;
temp3R >>= 16;
pOutputSamples[i*8+0] = (drflac_int16)temp0L;
pOutputSamples[i*8+1] = (drflac_int16)temp0R;
pOutputSamples[i*8+2] = (drflac_int16)temp1L;
pOutputSamples[i*8+3] = (drflac_int16)temp1R;
pOutputSamples[i*8+4] = (drflac_int16)temp2L;
pOutputSamples[i*8+5] = (drflac_int16)temp2R;
pOutputSamples[i*8+6] = (drflac_int16)temp3L;
pOutputSamples[i*8+7] = (drflac_int16)temp3R;
}
} else {
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 temp0L;
drflac_uint32 temp1L;
drflac_uint32 temp2L;
drflac_uint32 temp3L;
drflac_uint32 temp0R;
drflac_uint32 temp1R;
drflac_uint32 temp2R;
drflac_uint32 temp3R;
drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid0 = (mid0 << 1) | (side0 & 0x01);
mid1 = (mid1 << 1) | (side1 & 0x01);
mid2 = (mid2 << 1) | (side2 & 0x01);
mid3 = (mid3 << 1) | (side3 & 0x01);
temp0L = ((drflac_int32)(mid0 + side0) >> 1);
temp1L = ((drflac_int32)(mid1 + side1) >> 1);
temp2L = ((drflac_int32)(mid2 + side2) >> 1);
temp3L = ((drflac_int32)(mid3 + side3) >> 1);
temp0R = ((drflac_int32)(mid0 - side0) >> 1);
temp1R = ((drflac_int32)(mid1 - side1) >> 1);
temp2R = ((drflac_int32)(mid2 - side2) >> 1);
temp3R = ((drflac_int32)(mid3 - side3) >> 1);
temp0L >>= 16;
temp1L >>= 16;
temp2L >>= 16;
temp3L >>= 16;
temp0R >>= 16;
temp1R >>= 16;
temp2R >>= 16;
temp3R >>= 16;
pOutputSamples[i*8+0] = (drflac_int16)temp0L;
pOutputSamples[i*8+1] = (drflac_int16)temp0R;
pOutputSamples[i*8+2] = (drflac_int16)temp1L;
pOutputSamples[i*8+3] = (drflac_int16)temp1R;
pOutputSamples[i*8+4] = (drflac_int16)temp2L;
pOutputSamples[i*8+5] = (drflac_int16)temp2R;
pOutputSamples[i*8+6] = (drflac_int16)temp3L;
pOutputSamples[i*8+7] = (drflac_int16)temp3R;
}
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
}
}
#if defined(DRFLAC_SUPPORT_SSE2)
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSampl...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift = unusedBitsPerSample;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
if (shift == 0) {
for (i = 0; i < frameCount4; ++i) {
__m128i mid;
__m128i side;
__m128i left;
__m128i right;
mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
left = _mm_srai_epi32(left, 16);
right = _mm_srai_epi32(right, 16);
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
}
} else {
shift -= 1;
for (i = 0; i < frameCount4; ++i) {
__m128i mid;
__m128i side;
__m128i left;
__m128i right;
mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
left = _mm_srai_epi32(left, 16);
right = _mm_srai_epi32(right, 16);
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
}
}
}
#endif
#if defined(DRFLAC_SUPPORT_NEON)
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSampl...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift = unusedBitsPerSample;
int32x4_t wbpsShift0_4;
int32x4_t wbpsShift1_4;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
if (shift == 0) {
for (i = 0; i < frameCount4; ++i) {
uint32x4_t mid;
uint32x4_t side;
int32x4_t left;
int32x4_t right;
mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
left = vshrq_n_s32(left, 16);
right = vshrq_n_s32(right, 16);
drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
}
} else {
int32x4_t shift4;
shift -= 1;
shift4 = vdupq_n_s32(shift);
for (i = 0; i < frameCount4; ++i) {
uint32x4_t mid;
uint32x4_t side;
int32x4_t left;
int32x4_t right;
mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
left = vshrq_n_s32(left, 16);
right = vshrq_n_s32(right, 16);
drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
}
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
{
#if defined(DRFLAC_SUPPORT_SSE2)
if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s16__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#elif defined(DRFLAC_SUPPORT_NEON)
if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s16__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#endif
{
#if 0
drflac_read_pcm_frames_s16__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#else
drflac_read_pcm_frames_s16__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#endif
}
}
#if 0
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int1...
{
for (drflac_uint64 i = 0; i < frameCount; ++i) {
pOutputSamples[i*2+0] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) >> 16);
pOutputSamples[i*2+1] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) >> 16);
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* ...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
tempL0 >>= 16;
tempL1 >>= 16;
tempL2 >>= 16;
tempL3 >>= 16;
tempR0 >>= 16;
tempR1 >>= 16;
tempR2 >>= 16;
tempR3 >>= 16;
pOutputSamples[i*8+0] = (drflac_int16)tempL0;
pOutputSamples[i*8+1] = (drflac_int16)tempR0;
pOutputSamples[i*8+2] = (drflac_int16)tempL1;
pOutputSamples[i*8+3] = (drflac_int16)tempR1;
pOutputSamples[i*8+4] = (drflac_int16)tempL2;
pOutputSamples[i*8+5] = (drflac_int16)tempR2;
pOutputSamples[i*8+6] = (drflac_int16)tempL3;
pOutputSamples[i*8+7] = (drflac_int16)tempR3;
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
}
}
#if defined(DRFLAC_SUPPORT_SSE2)
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pO...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
for (i = 0; i < frameCount4; ++i) {
__m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
__m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
left = _mm_srai_epi32(left, 16);
right = _mm_srai_epi32(right, 16);
_mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
}
}
#endif
#if defined(DRFLAC_SUPPORT_NEON)
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pO...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
int32x4_t shift0_4 = vdupq_n_s32(shift0);
int32x4_t shift1_4 = vdupq_n_s32(shift1);
for (i = 0; i < frameCount4; ++i) {
int32x4_t left;
int32x4_t right;
left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
left = vshrq_n_s32(left, 16);
right = vshrq_n_s32(right, 16);
drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputS...
{
#if defined(DRFLAC_SUPPORT_SSE2)
if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#elif defined(DRFLAC_SUPPORT_NEON)
if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_s16__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#endif
{
#if 0
drflac_read_pcm_frames_s16__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#else
drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#endif
}
}
DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut)
{
drflac_uint64 framesRead;
drflac_uint32 unusedBitsPerSample;
if (pFlac == NULL || framesToRead == 0) {
return 0;
}
if (pBufferOut == NULL) {
return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
}
DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
unusedBitsPerSample = 32 - pFlac->bitsPerSample;
framesRead = 0;
while (framesToRead > 0) {
if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
break;
}
} else {
unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
drflac_uint64 frameCountThisIteration = framesToRead;
if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
}
if (channelCount == 2) {
const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
switch (pFlac->currentFLACFrame.header.channelAssignment)
{
case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
{
drflac_read_pcm_frames_s16__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
} break;
case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
{
drflac_read_pcm_frames_s16__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
} break;
case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
{
drflac_read_pcm_frames_s16__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
} break;
case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
default:
{
drflac_read_pcm_frames_s16__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
} break;
}
} else {
drflac_uint64 i;
for (i = 0; i < frameCountThisIteration; ++i) {
unsigned int j;
for (j = 0; j < channelCount; ++j) {
drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
pBufferOut[(i*channelCount)+j] = (drflac_int16)(sampleS32 >> 16);
}
}
}
framesRead += frameCountThisIteration;
pBufferOut += frameCountThisIteration * channelCount;
framesToRead -= frameCountThisIteration;
pFlac->currentPCMFrame += frameCountThisIteration;
pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
}
}
return framesRead;
}
#if 0
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSample...
{
drflac_uint64 i;
for (i = 0; i < frameCount; ++i) {
drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
drflac_uint32 right = left - side;
pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0);
pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
float factor = 1 / 2147483648.0;
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
drflac_uint32 right0 = left0 - side0;
drflac_uint32 right1 = left1 - side1;
drflac_uint32 right2 = left2 - side2;
drflac_uint32 right3 = left3 - side3;
pOutputSamples[i*8+0] = (drflac_int32)left0 * factor;
pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
pOutputSamples[i*8+2] = (drflac_int32)left1 * factor;
pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
pOutputSamples[i*8+4] = (drflac_int32)left2 * factor;
pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
pOutputSamples[i*8+6] = (drflac_int32)left3 * factor;
pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 left = pInputSamples0U32[i] << shift0;
drflac_uint32 side = pInputSamples1U32[i] << shift1;
drflac_uint32 right = left - side;
pOutputSamples[i*2+0] = (drflac_int32)left * factor;
pOutputSamples[i*2+1] = (drflac_int32)right * factor;
}
}
#if defined(DRFLAC_SUPPORT_SSE2)
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
__m128 factor;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
factor = _mm_set1_ps(1.0f / 8388608.0f);
for (i = 0; i < frameCount4; ++i) {
__m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
__m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
__m128i right = _mm_sub_epi32(left, side);
__m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
__m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
_mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
_mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 left = pInputSamples0U32[i] << shift0;
drflac_uint32 side = pInputSamples1U32[i] << shift1;
drflac_uint32 right = left - side;
pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
}
}
#endif
#if defined(DRFLAC_SUPPORT_NEON)
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
float32x4_t factor4;
int32x4_t shift0_4;
int32x4_t shift1_4;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
factor4 = vdupq_n_f32(1.0f / 8388608.0f);
shift0_4 = vdupq_n_s32(shift0);
shift1_4 = vdupq_n_s32(shift1);
for (i = 0; i < frameCount4; ++i) {
uint32x4_t left;
uint32x4_t side;
uint32x4_t right;
float32x4_t leftf;
float32x4_t rightf;
left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
right = vsubq_u32(left, side);
leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 left = pInputSamples0U32[i] << shift0;
drflac_uint32 side = pInputSamples1U32[i] << shift1;
drflac_uint32 right = left - side;
pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
#if defined(DRFLAC_SUPPORT_SSE2)
if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_f32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#elif defined(DRFLAC_SUPPORT_NEON)
if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_f32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#endif
{
#if 0
drflac_read_pcm_frames_f32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#else
drflac_read_pcm_frames_f32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#endif
}
}
#if 0
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSampl...
{
drflac_uint64 i;
for (i = 0; i < frameCount; ++i) {
drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
drflac_uint32 left = right + side;
pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0);
pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
float factor = 1 / 2147483648.0;
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
drflac_uint32 left0 = right0 + side0;
drflac_uint32 left1 = right1 + side1;
drflac_uint32 left2 = right2 + side2;
drflac_uint32 left3 = right3 + side3;
pOutputSamples[i*8+0] = (drflac_int32)left0 * factor;
pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
pOutputSamples[i*8+2] = (drflac_int32)left1 * factor;
pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
pOutputSamples[i*8+4] = (drflac_int32)left2 * factor;
pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
pOutputSamples[i*8+6] = (drflac_int32)left3 * factor;
pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 side = pInputSamples0U32[i] << shift0;
drflac_uint32 right = pInputSamples1U32[i] << shift1;
drflac_uint32 left = right + side;
pOutputSamples[i*2+0] = (drflac_int32)left * factor;
pOutputSamples[i*2+1] = (drflac_int32)right * factor;
}
}
#if defined(DRFLAC_SUPPORT_SSE2)
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
__m128 factor;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
factor = _mm_set1_ps(1.0f / 8388608.0f);
for (i = 0; i < frameCount4; ++i) {
__m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
__m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
__m128i left = _mm_add_epi32(right, side);
__m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
__m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
_mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
_mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 side = pInputSamples0U32[i] << shift0;
drflac_uint32 right = pInputSamples1U32[i] << shift1;
drflac_uint32 left = right + side;
pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
}
}
#endif
#if defined(DRFLAC_SUPPORT_NEON)
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
float32x4_t factor4;
int32x4_t shift0_4;
int32x4_t shift1_4;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
factor4 = vdupq_n_f32(1.0f / 8388608.0f);
shift0_4 = vdupq_n_s32(shift0);
shift1_4 = vdupq_n_s32(shift1);
for (i = 0; i < frameCount4; ++i) {
uint32x4_t side;
uint32x4_t right;
uint32x4_t left;
float32x4_t leftf;
float32x4_t rightf;
side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
left = vaddq_u32(right, side);
leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 side = pInputSamples0U32[i] << shift0;
drflac_uint32 right = pInputSamples1U32[i] << shift1;
drflac_uint32 left = right + side;
pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
#if defined(DRFLAC_SUPPORT_SSE2)
if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_f32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#elif defined(DRFLAC_SUPPORT_NEON)
if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_f32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#endif
{
#if 0
drflac_read_pcm_frames_f32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#else
drflac_read_pcm_frames_f32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#endif
}
}
#if 0
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples...
{
for (drflac_uint64 i = 0; i < frameCount; ++i) {
drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (float)((((drflac_int32)(mid + side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
pOutputSamples[i*2+1] = (float)((((drflac_int32)(mid - side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift = unusedBitsPerSample;
float factor = 1 / 2147483648.0;
if (shift > 0) {
shift -= 1;
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 temp0L;
drflac_uint32 temp1L;
drflac_uint32 temp2L;
drflac_uint32 temp3L;
drflac_uint32 temp0R;
drflac_uint32 temp1R;
drflac_uint32 temp2R;
drflac_uint32 temp3R;
drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid0 = (mid0 << 1) | (side0 & 0x01);
mid1 = (mid1 << 1) | (side1 & 0x01);
mid2 = (mid2 << 1) | (side2 & 0x01);
mid3 = (mid3 << 1) | (side3 & 0x01);
temp0L = (mid0 + side0) << shift;
temp1L = (mid1 + side1) << shift;
temp2L = (mid2 + side2) << shift;
temp3L = (mid3 + side3) << shift;
temp0R = (mid0 - side0) << shift;
temp1R = (mid1 - side1) << shift;
temp2R = (mid2 - side2) << shift;
temp3R = (mid3 - side3) << shift;
pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
}
} else {
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 temp0L;
drflac_uint32 temp1L;
drflac_uint32 temp2L;
drflac_uint32 temp3L;
drflac_uint32 temp0R;
drflac_uint32 temp1R;
drflac_uint32 temp2R;
drflac_uint32 temp3R;
drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid0 = (mid0 << 1) | (side0 & 0x01);
mid1 = (mid1 << 1) | (side1 & 0x01);
mid2 = (mid2 << 1) | (side2 & 0x01);
mid3 = (mid3 << 1) | (side3 & 0x01);
temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
}
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) * factor;
pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) * factor;
}
}
#if defined(DRFLAC_SUPPORT_SSE2)
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift = unusedBitsPerSample - 8;
float factor;
__m128 factor128;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
factor = 1.0f / 8388608.0f;
factor128 = _mm_set1_ps(factor);
if (shift == 0) {
for (i = 0; i < frameCount4; ++i) {
__m128i mid;
__m128i side;
__m128i tempL;
__m128i tempR;
__m128 leftf;
__m128 rightf;
mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
tempL = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
tempR = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
_mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
_mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
}
} else {
shift -= 1;
for (i = 0; i < frameCount4; ++i) {
__m128i mid;
__m128i side;
__m128i tempL;
__m128i tempR;
__m128 leftf;
__m128 rightf;
mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
tempL = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
tempR = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
_mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
_mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
}
}
}
#endif
#if defined(DRFLAC_SUPPORT_NEON)
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift = unusedBitsPerSample - 8;
float factor;
float32x4_t factor4;
int32x4_t shift4;
int32x4_t wbps0_4;
int32x4_t wbps1_4;
DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
factor = 1.0f / 8388608.0f;
factor4 = vdupq_n_f32(factor);
wbps0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
wbps1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
if (shift == 0) {
for (i = 0; i < frameCount4; ++i) {
int32x4_t lefti;
int32x4_t righti;
float32x4_t leftf;
float32x4_t rightf;
uint32x4_t mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
uint32x4_t side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
lefti = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
righti = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
}
} else {
shift -= 1;
shift4 = vdupq_n_s32(shift);
for (i = 0; i < frameCount4; ++i) {
uint32x4_t mid;
uint32x4_t side;
int32x4_t lefti;
int32x4_t righti;
float32x4_t leftf;
float32x4_t rightf;
mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
lefti = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
righti = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
mid = (mid << 1) | (side & 0x01);
pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
}
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
#if defined(DRFLAC_SUPPORT_SSE2)
if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_f32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#elif defined(DRFLAC_SUPPORT_NEON)
if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_f32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#endif
{
#if 0
drflac_read_pcm_frames_f32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#else
drflac_read_pcm_frames_f32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#endif
}
}
#if 0
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOut...
{
for (drflac_uint64 i = 0; i < frameCount; ++i) {
pOutputSamples[i*2+0] = (float)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) / 2147483648.0);
pOutputSamples[i*2+1] = (float)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) / 2147483648.0);
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutput...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
float factor = 1 / 2147483648.0;
for (i = 0; i < frameCount4; ++i) {
drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
pOutputSamples[i*8+0] = (drflac_int32)tempL0 * factor;
pOutputSamples[i*8+1] = (drflac_int32)tempR0 * factor;
pOutputSamples[i*8+2] = (drflac_int32)tempL1 * factor;
pOutputSamples[i*8+3] = (drflac_int32)tempR1 * factor;
pOutputSamples[i*8+4] = (drflac_int32)tempL2 * factor;
pOutputSamples[i*8+5] = (drflac_int32)tempR2 * factor;
pOutputSamples[i*8+6] = (drflac_int32)tempL3 * factor;
pOutputSamples[i*8+7] = (drflac_int32)tempR3 * factor;
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
}
}
#if defined(DRFLAC_SUPPORT_SSE2)
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSa...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
float factor = 1.0f / 8388608.0f;
__m128 factor128 = _mm_set1_ps(factor);
for (i = 0; i < frameCount4; ++i) {
__m128i lefti;
__m128i righti;
__m128 leftf;
__m128 rightf;
lefti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
righti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
leftf = _mm_mul_ps(_mm_cvtepi32_ps(lefti), factor128);
rightf = _mm_mul_ps(_mm_cvtepi32_ps(righti), factor128);
_mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
_mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
}
}
#endif
#if defined(DRFLAC_SUPPORT_NEON)
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSa...
{
drflac_uint64 i;
drflac_uint64 frameCount4 = frameCount >> 2;
const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
float factor = 1.0f / 8388608.0f;
float32x4_t factor4 = vdupq_n_f32(factor);
int32x4_t shift0_4 = vdupq_n_s32(shift0);
int32x4_t shift1_4 = vdupq_n_s32(shift1);
for (i = 0; i < frameCount4; ++i) {
int32x4_t lefti;
int32x4_t righti;
float32x4_t leftf;
float32x4_t rightf;
lefti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
righti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
}
for (i = (frameCount4 << 2); i < frameCount; ++i) {
pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
}
}
#endif
static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
{
#if defined(DRFLAC_SUPPORT_SSE2)
if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#elif defined(DRFLAC_SUPPORT_NEON)
if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
drflac_read_pcm_frames_f32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
} else
#endif
{
#if 0
drflac_read_pcm_frames_f32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#else
drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
#endif
}
}
DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut)
{
drflac_uint64 framesRead;
drflac_uint32 unusedBitsPerSample;
if (pFlac == NULL || framesToRead == 0) {
return 0;
}
if (pBufferOut == NULL) {
return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
}
DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
unusedBitsPerSample = 32 - pFlac->bitsPerSample;
framesRead = 0;
while (framesToRead > 0) {
if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
break;
}
} else {
unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
drflac_uint64 frameCountThisIteration = framesToRead;
if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
}
if (channelCount == 2) {
const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
switch (pFlac->currentFLACFrame.header.channelAssignment)
{
case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
{
drflac_read_pcm_frames_f32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
} break;
case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
{
drflac_read_pcm_frames_f32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
} break;
case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
{
drflac_read_pcm_frames_f32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
} break;
case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
default:
{
drflac_read_pcm_frames_f32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
} break;
}
} else {
drflac_uint64 i;
for (i = 0; i < frameCountThisIteration; ++i) {
unsigned int j;
for (j = 0; j < channelCount; ++j) {
drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
pBufferOut[(i*channelCount)+j] = (float)(sampleS32 / 2147483648.0);
}
}
}
framesRead += frameCountThisIteration;
pBufferOut += frameCountThisIteration * channelCount;
framesToRead -= frameCountThisIteration;
pFlac->currentPCMFrame += frameCountThisIteration;
pFlac->currentFLACFrame.pcmFramesRemaining -= (unsigned int)frameCountThisIteration;
}
}
return framesRead;
}
DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
{
if (pFlac == NULL) {
return DRFLAC_FALSE;
}
if (pFlac->currentPCMFrame == pcmFrameIndex) {
return DRFLAC_TRUE;
}
if (pFlac->firstFLACFramePosInBytes == 0) {
return DRFLAC_FALSE;
}
if (pcmFrameIndex == 0) {
pFlac->currentPCMFrame = 0;
return drflac__seek_to_first_frame(pFlac);
} else {
drflac_bool32 wasSuccessful = DRFLAC_FALSE;
if (pcmFrameIndex > pFlac->totalPCMFrameCount) {
pcmFrameIndex = pFlac->totalPCMFrameCount;
}
if (pcmFrameIndex > pFlac->currentPCMFrame) {
drflac_uint32 offset = (drflac_uint32)(pcmFrameIndex - pFlac->currentPCMFrame);
if (pFlac->currentFLACFrame.pcmFramesRemaining > offset) {
pFlac->currentFLACFrame.pcmFramesRemaining -= offset;
pFlac->currentPCMFrame = pcmFrameIndex;
return DRFLAC_TRUE;
}
} else {
drflac_uint32 offsetAbs = (drflac_uint32)(pFlac->currentPCMFrame - pcmFrameIndex);
drflac_uint32 currentFLACFramePCMFrameCount = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
drflac_uint32 currentFLACFramePCMFramesConsumed = currentFLACFramePCMFrameCount - pFlac->currentFLACFrame.pcmFramesRemaining;
if (currentFLACFramePCMFramesConsumed > offsetAbs) {
pFlac->currentFLACFrame.pcmFramesRemaining += offsetAbs;
pFlac->currentPCMFrame = pcmFrameIndex;
return DRFLAC_TRUE;
}
}
#ifndef DR_FLAC_NO_OGG
if (pFlac->container == drflac_container_ogg)
{
wasSuccessful = drflac_ogg__seek_to_pcm_frame(pFlac, pcmFrameIndex);
}
else
#endif
{
if (!pFlac->_noSeekTableSeek) {
wasSuccessful = drflac__seek_to_pcm_frame__seek_table(pFlac, pcmFrameIndex);
}
#if !defined(DR_FLAC_NO_CRC)
if (!wasSuccessful && !pFlac->_noBinarySearchSeek && pFlac->totalPCMFrameCount > 0) {
wasSuccessful = drflac__seek_to_pcm_frame__binary_search(pFlac, pcmFrameIndex);
}
#endif
if (!wasSuccessful && !pFlac->_noBruteForceSeek) {
wasSuccessful = drflac__seek_to_pcm_frame__brute_force(pFlac, pcmFrameIndex);
}
}
pFlac->currentPCMFrame = pcmFrameIndex;
return wasSuccessful;
}
}
#if defined(SIZE_MAX)
#define DRFLAC_SIZE_MAX SIZE_MAX
#else
#if defined(DRFLAC_64BIT)
#define DRFLAC_SIZE_MAX ((drflac_uint64)0xFFFFFFFFFFFFFFFF)
#else
#define DRFLAC_SIZE_MAX 0xFFFFFFFF
#endif
#endif
#define DRFLAC_DEFINE_FULL_READ_AND_CLOSE(extension, type) \
static type* drflac__full_read_and_close_ ## extension (drflac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut)\
{ \
type* pSampleData = NULL; \
drflac_uint64 totalPCMFrameCount; \
\
DRFLAC_ASSERT(pFlac != NULL); \
\
totalPCMFrameCount = pFlac->totalPCMFrameCount; \
\
if (totalPCMFrameCount == 0) { \
type buffer[4096]; \
drflac_uint64 pcmFramesRead; \
size_t sampleDataBufferSize = sizeof(buffer); \
\
pSampleData = (type*)drflac__malloc_from_callbacks(sampleDataBufferSize, &pFlac->allocationCallbacks); \
if (pSampleData == NULL) { \
goto on_error; \
} \
\
while ((pcmFramesRead = (drflac_uint64)drflac_read_pcm_frames_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0])/pFlac->channels, buffer)) > 0) { \
if (((totalPCMFrameCount + pcmFramesRead) * pFlac->channels * sizeof(type)) > sampleDataBufferSize) { \
type* pNewSampleData; \
size_t newSampleDataBufferSize; \
\
newSampleDataBufferSize = sampleDataBufferSize * 2; \
pNewSampleData = (type*)drflac__realloc_from_callbacks(pSampleData, newSampleDataBufferSize, sampleDataBufferSize, &pFlac->allocationCallbacks); \
if (pNewSampleData == NULL) { \
drflac__free_from_callbacks(pSampleData, &pFlac->allocationCallbacks); \
goto on_error; \
} \
\
sampleDataBufferSize = newSampleDataBufferSize; \
pSampleData = pNewSampleData; \
} \
\
DRFLAC_COPY_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), buffer, (size_t)(pcmFramesRead*pFlac->channels*sizeof(type))); \
totalPCMFrameCount += pcmFramesRead; \
} \
\
\
DRFLAC_ZERO_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), (size_t)(sampleDataBufferSize - totalPCMFrameCount*pFlac->channels*sizeof(type))); \
} else { \
drflac_uint64 dataSize = totalPCMFrameCount*pFlac->channels*sizeof(type); \
if (dataSize > DRFLAC_SIZE_MAX) { \
goto on_error; \
} \
\
pSampleData = (type*)drflac__malloc_from_callbacks((size_t)dataSize, &pFlac->allocationCallbacks); \
if (pSampleData == NULL) { \
goto on_error; \
} \
\
totalPCMFrameCount = drflac_read_pcm_frames_##extension(pFlac, pFlac->totalPCMFrameCount, pSampleData); \
} \
\
if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \
if (channelsOut) *channelsOut = pFlac->channels; \
if (totalPCMFrameCountOut) *totalPCMFrameCountOut = totalPCMFrameCount; \
\
drflac_close(pFlac); \
return pSampleData; \
\
on_error: \
drflac_close(pFlac); \
return NULL; \
}
DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s32, drflac_int32)
DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s16, drflac_int16)
DRFLAC_DEFINE_FULL_READ_AND_CLOSE(f32, float)
DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_call...
{
drflac* pFlac;
if (channelsOut) {
*channelsOut = 0;
}
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (totalPCMFrameCountOut) {
*totalPCMFrameCountOut = 0;
}
pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
if (pFlac == NULL) {
return NULL;
}
return drflac__full_read_and_close_s32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
}
DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_call...
{
drflac* pFlac;
if (channelsOut) {
*channelsOut = 0;
}
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (totalPCMFrameCountOut) {
*totalPCMFrameCountOut = 0;
}
pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
if (pFlac == NULL) {
return NULL;
}
return drflac__full_read_and_close_s16(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
}
DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* ...
{
drflac* pFlac;
if (channelsOut) {
*channelsOut = 0;
}
if (sampleRateOut) {
*sampleRateOut = 0;
}
if (totalPCMFrameCountOut) {
*totalPCMFrameCountOut = 0;
}
pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
if (pFlac == NULL) {
return NULL;
}
return drflac__full_read_and_close_f32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
}
#ifndef DR_FLAC_NO_STDIO
DRFLAC_API drflac_int32* drflac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
{
drflac* pFlac;
if (sampleRate) {
*sampleRate = 0;
}
if (channels) {
*channels = 0;
}
if (totalPCMFrameCount) {
*totalPCMFrameCount = 0;
}
pFlac = drflac_open_file(filename, pAllocationCallbacks);
if (pFlac == NULL) {
return NULL;
}
return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
}
DRFLAC_API drflac_int16* drflac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
{
drflac* pFlac;
if (sampleRate) {
*sampleRate = 0;
}
if (channels) {
*channels = 0;
}
if (totalPCMFrameCount) {
*totalPCMFrameCount = 0;
}
pFlac = drflac_open_file(filename, pAllocationCallbacks);
if (pFlac == NULL) {
return NULL;
}
return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
}
DRFLAC_API float* drflac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
{
drflac* pFlac;
if (sampleRate) {
*sampleRate = 0;
}
if (channels) {
*channels = 0;
}
if (totalPCMFrameCount) {
*totalPCMFrameCount = 0;
}
pFlac = drflac_open_file(filename, pAllocationCallbacks);
if (pFlac == NULL) {
return NULL;
}
return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
}
#endif
DRFLAC_API drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
{
drflac* pFlac;
if (sampleRate) {
*sampleRate = 0;
}
if (channels) {
*channels = 0;
}
if (totalPCMFrameCount) {
*totalPCMFrameCount = 0;
}
pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
if (pFlac == NULL) {
return NULL;
}
return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
}
DRFLAC_API drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
{
drflac* pFlac;
if (sampleRate) {
*sampleRate = 0;
}
if (channels) {
*channels = 0;
}
if (totalPCMFrameCount) {
*totalPCMFrameCount = 0;
}
pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
if (pFlac == NULL) {
return NULL;
}
return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
}
DRFLAC_API float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
{
drflac* pFlac;
if (sampleRate) {
*sampleRate = 0;
}
if (channels) {
*channels = 0;
}
if (totalPCMFrameCount) {
*totalPCMFrameCount = 0;
}
pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
if (pFlac == NULL) {
return NULL;
}
return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
}
DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
{
if (pAllocationCallbacks != NULL) {
drflac__free_from_callbacks(p, pAllocationCallbacks);
} else {
drflac__free_default(p, NULL);
}
}
DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments)
{
if (pIter == NULL) {
return;
}
pIter->countRemaining = commentCount;
pIter->pRunningData = (const char*)pComments;
}
DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut)
{
drflac_int32 length;
const char* pComment;
if (pCommentLengthOut) {
*pCommentLengthOut = 0;
}
if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
return NULL;
}
length = drflac__le2host_32(*(const drflac_uint32*)pIter->pRunningData);
pIter->pRunningData += 4;
pComment = pIter->pRunningData;
pIter->pRunningData += length;
pIter->countRemaining -= 1;
if (pCommentLengthOut) {
*pCommentLengthOut = length;
}
return pComment;
}
DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData)
{
if (pIter == NULL) {
return;
}
pIter->countRemaining = trackCount;
pIter->pRunningData = (const char*)pTrackData;
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
drmp3_uint8 table_select[3], region_count[3], subblock_gain[3];
drmp3_uint8 preflag, scalefac_scale, count1_table, scfsi;
} drmp3_L3_gr_info;
typedef struct
{
drmp3_bs bs;
drmp3_uint8 maindata[DRMP3_MAX_BITRESERVOIR_BYTES + DRMP3_MAX_L3_FRAME_PAYLOAD_BYTES];
drmp3_L3_gr_info gr_info[4];
float grbuf[2][576], scf[40], syn[18 + 15][2*32];
drmp3_uint8 ist_pos[2][39];
} drmp3dec_scratch;
static void drmp3_bs_init(drmp3_bs *bs, const drmp3_uint8 *data, int bytes)
{
bs->buf = data;
bs->pos = 0;
bs->limit = bytes*8;
}
static drmp3_uint32 drmp3_bs_get_bits(drmp3_bs *bs, int n)
{
drmp3_uint32 next, cache = 0, s = bs->pos & 7;
int shl = n + s;
const drmp3_uint8 *p = bs->buf + (bs->pos >> 3);
if ((bs->pos += n) > bs->limit)
return 0;
next = *p++ & (255 >> s);
while ((shl -= 8) > 0)
{
cache |= next << shl;
next = *p++;
}
return cache | (next >> -shl);
}
static int drmp3_hdr_valid(const drmp3_uint8 *h)
{
return h[0] == 0xff &&
((h[1] & 0xF0) == 0xf0 || (h[1] & 0xFE) == 0xe2) &&
(DRMP3_HDR_GET_LAYER(h) != 0) &&
(DRMP3_HDR_GET_BITRATE(h) != 15) &&
(DRMP3_HDR_GET_SAMPLE_RATE(h) != 3);
}
static int drmp3_hdr_compare(const drmp3_uint8 *h1, const drmp3_uint8 *h2)
{
return drmp3_hdr_valid(h2) &&
((h1[1] ^ h2[1]) & 0xFE) == 0 &&
((h1[2] ^ h2[2]) & 0x0C) == 0 &&
!(DRMP3_HDR_IS_FREE_FORMAT(h1) ^ DRMP3_HDR_IS_FREE_FORMAT(h2));
}
static unsigned drmp3_hdr_bitrate_kbps(const drmp3_uint8 *h)
{
static const drmp3_uint8 halfrate[2][3][15] = {
{ { 0,4,8,12,16,20,24,28,32,40,48,56,64,72,80 }, { 0,4,8,12,16,20,24,28,32,40,48,56,64,72,80 }, { 0,16,24,28,32,40,48,56,64,72,80,88,96,112,128 } },
{ { 0,16,20,24,28,32,40,48,56,64,80,96,112,128,160 }, { 0,16,24,28,32,40,48,56,64,80,96,112,128,160,192 }, { 0,16,32,48,64,80,96,112,128,144,160,176,192,208,224 } },
};
return 2*halfrate[!!DRMP3_HDR_TEST_MPEG1(h)][DRMP3_HDR_GET_LAYER(h) - 1][DRMP3_HDR_GET_BITRATE(h)];
}
static unsigned drmp3_hdr_sample_rate_hz(const drmp3_uint8 *h)
{
static const unsigned g_hz[3] = { 44100, 48000, 32000 };
return g_hz[DRMP3_HDR_GET_SAMPLE_RATE(h)] >> (int)!DRMP3_HDR_TEST_MPEG1(h) >> (int)!DRMP3_HDR_TEST_NOT_MPEG25(h);
}
static unsigned drmp3_hdr_frame_samples(const drmp3_uint8 *h)
{
return DRMP3_HDR_IS_LAYER_1(h) ? 384 : (1152 >> (int)DRMP3_HDR_IS_FRAME_576(h));
}
static int drmp3_hdr_frame_bytes(const drmp3_uint8 *h, int free_format_size)
{
int frame_bytes = drmp3_hdr_frame_samples(h)*drmp3_hdr_bitrate_kbps(h)*125/drmp3_hdr_sample_rate_hz(h);
if (DRMP3_HDR_IS_LAYER_1(h))
{
frame_bytes &= ~3;
}
return frame_bytes ? frame_bytes : free_format_size;
}
static int drmp3_hdr_padding(const drmp3_uint8 *h)
{
return DRMP3_HDR_TEST_PADDING(h) ? (DRMP3_HDR_IS_LAYER_1(h) ? 4 : 1) : 0;
}
#ifndef DR_MP3_ONLY_MP3
static const drmp3_L12_subband_alloc *drmp3_L12_subband_alloc_table(const drmp3_uint8 *hdr, drmp3_L12_scale_info *sci)
{
const drmp3_L12_subband_alloc *alloc;
int mode = DRMP3_HDR_GET_STEREO_MODE(hdr);
int nbands, stereo_bands = (mode == DRMP3_MODE_MONO) ? 0 : (mode == DRMP3_MODE_JOINT_STEREO) ? (DRMP3_HDR_GET_STEREO_MODE_EXT(hdr) << 2) + 4 : 32;
if (DRMP3_HDR_IS_LAYER_1(hdr))
{
static const drmp3_L12_subband_alloc g_alloc_L1[] = { { 76, 4, 32 } };
alloc = g_alloc_L1;
nbands = 32;
} else if (!DRMP3_HDR_TEST_MPEG1(hdr))
{
static const drmp3_L12_subband_alloc g_alloc_L2M2[] = { { 60, 4, 4 }, { 44, 3, 7 }, { 44, 2, 19 } };
alloc = g_alloc_L2M2;
nbands = 30;
} else
{
static const drmp3_L12_subband_alloc g_alloc_L2M1[] = { { 0, 4, 3 }, { 16, 4, 8 }, { 32, 3, 12 }, { 40, 2, 7 } };
int sample_rate_idx = DRMP3_HDR_GET_SAMPLE_RATE(hdr);
unsigned kbps = drmp3_hdr_bitrate_kbps(hdr) >> (int)(mode != DRMP3_MODE_MONO);
if (!kbps)
{
kbps = 192;
}
alloc = g_alloc_L2M1;
nbands = 27;
if (kbps < 56)
{
static const drmp3_L12_subband_alloc g_alloc_L2M1_lowrate[] = { { 44, 4, 2 }, { 44, 3, 10 } };
alloc = g_alloc_L2M1_lowrate;
nbands = sample_rate_idx == 2 ? 12 : 8;
} else if (kbps >= 96 && sample_rate_idx != 1)
{
nbands = 30;
}
}
sci->total_bands = (drmp3_uint8)nbands;
sci->stereo_bands = (drmp3_uint8)DRMP3_MIN(stereo_bands, nbands);
return alloc;
}
static void drmp3_L12_read_scalefactors(drmp3_bs *bs, drmp3_uint8 *pba, drmp3_uint8 *scfcod, int bands, float *scf)
{
static const float g_deq_L12[18*3] = {
#define DRMP3_DQ(x) 9.53674316e-07f/x, 7.56931807e-07f/x, 6.00777173e-07f/x
DRMP3_DQ(3),DRMP3_DQ(7),DRMP3_DQ(15),DRMP3_DQ(31),DRMP3_DQ(63),DRMP3_DQ(127),DRMP3_DQ(255),DRMP3_DQ(511),DRMP3_DQ(1023),DRMP3_DQ(2047),DRMP3_DQ(4095),DRMP3_DQ(8191),DRMP3_DQ(16383),DRMP3_DQ(32767),DRMP3_DQ(65535),DRMP3_DQ(3),DRMP3_DQ(5),DRMP3...
};
int i, m;
for (i = 0; i < bands; i++)
{
float s = 0;
int ba = *pba++;
int mask = ba ? 4 + ((19 >> scfcod[i]) & 3) : 0;
for (m = 4; m; m >>= 1)
{
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
float ovl = overlap[i];
float sum = co[i]*g_twid3[3 + i] + si[i]*g_twid3[0 + i];
overlap[i] = co[i]*g_twid3[0 + i] - si[i]*g_twid3[3 + i];
dst[i] = ovl*g_twid3[2 - i] - sum*g_twid3[5 - i];
dst[5 - i] = ovl*g_twid3[5 - i] + sum*g_twid3[2 - i];
}
}
static void drmp3_L3_imdct_short(float *grbuf, float *overlap, int nbands)
{
for (;nbands > 0; nbands--, overlap += 9, grbuf += 18)
{
float tmp[18];
memcpy(tmp, grbuf, sizeof(tmp));
memcpy(grbuf, overlap, 6*sizeof(float));
drmp3_L3_imdct12(tmp, grbuf + 6, overlap + 6);
drmp3_L3_imdct12(tmp + 1, grbuf + 12, overlap + 6);
drmp3_L3_imdct12(tmp + 2, overlap, overlap + 6);
}
}
static void drmp3_L3_change_sign(float *grbuf)
{
int b, i;
for (b = 0, grbuf += 18; b < 32; b += 2, grbuf += 36)
for (i = 1; i < 18; i += 2)
grbuf[i] = -grbuf[i];
}
static void drmp3_L3_imdct_gr(float *grbuf, float *overlap, unsigned block_type, unsigned n_long_bands)
{
static const float g_mdct_window[2][18] = {
{ 0.99904822f,0.99144486f,0.97629601f,0.95371695f,0.92387953f,0.88701083f,0.84339145f,0.79335334f,0.73727734f,0.04361938f,0.13052619f,0.21643961f,0.30070580f,0.38268343f,0.46174861f,0.53729961f,0.60876143f,0.67559021f },
{ 1,1,1,1,1,1,0.99144486f,0.92387953f,0.79335334f,0,0,0,0,0,0,0.13052619f,0.38268343f,0.60876143f }
};
if (n_long_bands)
{
drmp3_L3_imdct36(grbuf, overlap, g_mdct_window[0], n_long_bands);
grbuf += 18*n_long_bands;
overlap += 9*n_long_bands;
}
if (block_type == DRMP3_SHORT_BLOCK_TYPE)
drmp3_L3_imdct_short(grbuf, overlap, 32 - n_long_bands);
else
drmp3_L3_imdct36(grbuf, overlap, g_mdct_window[block_type == DRMP3_STOP_BLOCK_TYPE], 32 - n_long_bands);
}
static void drmp3_L3_save_reservoir(drmp3dec *h, drmp3dec_scratch *s)
{
int pos = (s->bs.pos + 7)/8u;
int remains = s->bs.limit/8u - pos;
if (remains > DRMP3_MAX_BITRESERVOIR_BYTES)
{
pos += remains - DRMP3_MAX_BITRESERVOIR_BYTES;
remains = DRMP3_MAX_BITRESERVOIR_BYTES;
}
if (remains > 0)
{
memmove(h->reserv_buf, s->maindata + pos, remains);
}
h->reserv = remains;
}
static int drmp3_L3_restore_reservoir(drmp3dec *h, drmp3_bs *bs, drmp3dec_scratch *s, int main_data_begin)
{
int frame_bytes = (bs->limit - bs->pos)/8;
int bytes_have = DRMP3_MIN(h->reserv, main_data_begin);
memcpy(s->maindata, h->reserv_buf + DRMP3_MAX(0, h->reserv - main_data_begin), DRMP3_MIN(h->reserv, main_data_begin));
memcpy(s->maindata + bytes_have, bs->buf + bs->pos/8, frame_bytes);
drmp3_bs_init(&s->bs, s->maindata, bytes_have + frame_bytes);
return h->reserv >= main_data_begin;
}
static void drmp3_L3_decode(drmp3dec *h, drmp3dec_scratch *s, drmp3_L3_gr_info *gr_info, int nch)
{
int ch;
for (ch = 0; ch < nch; ch++)
{
int layer3gr_limit = s->bs.pos + gr_info[ch].part_23_length;
drmp3_L3_decode_scalefactors(h->header, s->ist_pos[ch], &s->bs, gr_info + ch, s->scf, ch);
drmp3_L3_huffman(s->grbuf[ch], &s->bs, gr_info + ch, s->scf, layer3gr_limit);
}
if (DRMP3_HDR_TEST_I_STEREO(h->header))
{
drmp3_L3_intensity_stereo(s->grbuf[0], s->ist_pos[1], gr_info, h->header);
} else if (DRMP3_HDR_IS_MS_STEREO(h->header))
{
drmp3_L3_midside_stereo(s->grbuf[0], 576);
}
for (ch = 0; ch < nch; ch++, gr_info++)
{
int aa_bands = 31;
int n_long_bands = (gr_info->mixed_block_flag ? 2 : 0) << (int)(DRMP3_HDR_GET_MY_SAMPLE_RATE(h->header) == 2);
if (gr_info->n_short_sfb)
{
aa_bands = n_long_bands - 1;
drmp3_L3_reorder(s->grbuf[ch] + n_long_bands*18, s->syn[0], gr_info->sfbtab + gr_info->n_long_sfb);
}
drmp3_L3_antialias(s->grbuf[ch], aa_bands);
drmp3_L3_imdct_gr(s->grbuf[ch], h->mdct_overlap[ch], gr_info->block_type, n_long_bands);
drmp3_L3_change_sign(s->grbuf[ch]);
}
}
static void drmp3d_DCT_II(float *grbuf, int n)
{
static const float g_sec[24] = {
10.19000816f,0.50060302f,0.50241929f,3.40760851f,0.50547093f,0.52249861f,2.05778098f,0.51544732f,0.56694406f,1.48416460f,0.53104258f,0.64682180f,1.16943991f,0.55310392f,0.78815460f,0.97256821f,0.58293498f,1.06067765f,0.83934963f,0.62250412f,1...
};
int i, k = 0;
#if DRMP3_HAVE_SIMD
if (drmp3_have_simd()) for (; k < n; k += 4)
{
drmp3_f4 t[4][8], *x;
float *y = grbuf + k;
for (x = t[0], i = 0; i < 8; i++, x++)
{
drmp3_f4 x0 = DRMP3_VLD(&y[i*18]);
drmp3_f4 x1 = DRMP3_VLD(&y[(15 - i)*18]);
drmp3_f4 x2 = DRMP3_VLD(&y[(16 + i)*18]);
drmp3_f4 x3 = DRMP3_VLD(&y[(31 - i)*18]);
drmp3_f4 t0 = DRMP3_VADD(x0, x3);
drmp3_f4 t1 = DRMP3_VADD(x1, x2);
drmp3_f4 t2 = DRMP3_VMUL_S(DRMP3_VSUB(x1, x2), g_sec[3*i + 0]);
drmp3_f4 t3 = DRMP3_VMUL_S(DRMP3_VSUB(x0, x3), g_sec[3*i + 1]);
x[0] = DRMP3_VADD(t0, t1);
x[8] = DRMP3_VMUL_S(DRMP3_VSUB(t0, t1), g_sec[3*i + 2]);
x[16] = DRMP3_VADD(t3, t2);
x[24] = DRMP3_VMUL_S(DRMP3_VSUB(t3, t2), g_sec[3*i + 2]);
}
for (x = t[0], i = 0; i < 4; i++, x += 8)
{
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
#endif
#endif
}
} else
#endif
#ifdef DR_MP3_ONLY_SIMD
{}
#else
for (i = 14; i >= 0; i--)
{
#define DRMP3_LOAD(k) float w0 = *w++; float w1 = *w++; float *vz = &zlin[4*i - k*64]; float *vy = &zlin[4*i - (15 - k)*64];
#define DRMP3_S0(k) { int j; DRMP3_LOAD(k); for (j = 0; j < 4; j++) b[j] = vz[j]*w1 + vy[j]*w0, a[j] = vz[j]*w0 - vy[j]*w1; }
#define DRMP3_S1(k) { int j; DRMP3_LOAD(k); for (j = 0; j < 4; j++) b[j] += vz[j]*w1 + vy[j]*w0, a[j] += vz[j]*w0 - vy[j]*w1; }
#define DRMP3_S2(k) { int j; DRMP3_LOAD(k); for (j = 0; j < 4; j++) b[j] += vz[j]*w1 + vy[j]*w0, a[j] += vy[j]*w1 - vz[j]*w0; }
float a[4], b[4];
zlin[4*i] = xl[18*(31 - i)];
zlin[4*i + 1] = xr[18*(31 - i)];
zlin[4*i + 2] = xl[1 + 18*(31 - i)];
zlin[4*i + 3] = xr[1 + 18*(31 - i)];
zlin[4*(i + 16)] = xl[1 + 18*(1 + i)];
zlin[4*(i + 16) + 1] = xr[1 + 18*(1 + i)];
zlin[4*(i - 16) + 2] = xl[18*(1 + i)];
zlin[4*(i - 16) + 3] = xr[18*(1 + i)];
DRMP3_S0(0) DRMP3_S2(1) DRMP3_S1(2) DRMP3_S2(3) DRMP3_S1(4) DRMP3_S2(5) DRMP3_S1(6) DRMP3_S2(7)
dstr[(15 - i)*nch] = drmp3d_scale_pcm(a[1]);
dstr[(17 + i)*nch] = drmp3d_scale_pcm(b[1]);
dstl[(15 - i)*nch] = drmp3d_scale_pcm(a[0]);
dstl[(17 + i)*nch] = drmp3d_scale_pcm(b[0]);
dstr[(47 - i)*nch] = drmp3d_scale_pcm(a[3]);
dstr[(49 + i)*nch] = drmp3d_scale_pcm(b[3]);
dstl[(47 - i)*nch] = drmp3d_scale_pcm(a[2]);
dstl[(49 + i)*nch] = drmp3d_scale_pcm(b[2]);
}
#endif
}
static void drmp3d_synth_granule(float *qmf_state, float *grbuf, int nbands, int nch, drmp3d_sample_t *pcm, float *lins)
{
int i;
for (i = 0; i < nch; i++)
{
drmp3d_DCT_II(grbuf + 576*i, nbands);
}
memcpy(lins, qmf_state, sizeof(float)*15*64);
for (i = 0; i < nbands; i += 2)
{
drmp3d_synth(grbuf + i, pcm + 32*nch*i, nch, lins + i*64);
}
#ifndef DR_MP3_NONSTANDARD_BUT_LOGICAL
if (nch == 1)
{
for (i = 0; i < 15*64; i += 2)
{
qmf_state[i] = lins[nbands*64 + i];
}
} else
#endif
{
memcpy(qmf_state, lins + nbands*64, sizeof(float)*15*64);
}
}
static int drmp3d_match_frame(const drmp3_uint8 *hdr, int mp3_bytes, int frame_bytes)
{
int i, nmatch;
for (i = 0, nmatch = 0; nmatch < DRMP3_MAX_FRAME_SYNC_MATCHES; nmatch++)
{
i += drmp3_hdr_frame_bytes(hdr + i, frame_bytes) + drmp3_hdr_padding(hdr + i);
if (i + DRMP3_HDR_SIZE > mp3_bytes)
return nmatch > 0;
if (!drmp3_hdr_compare(hdr, hdr + i))
return 0;
}
return 1;
}
static int drmp3d_find_frame(const drmp3_uint8 *mp3, int mp3_bytes, int *free_format_bytes, int *ptr_frame_bytes)
{
int i, k;
for (i = 0; i < mp3_bytes - DRMP3_HDR_SIZE; i++, mp3++)
{
if (drmp3_hdr_valid(mp3))
{
int frame_bytes = drmp3_hdr_frame_bytes(mp3, *free_format_bytes);
int frame_and_padding = frame_bytes + drmp3_hdr_padding(mp3);
for (k = DRMP3_HDR_SIZE; !frame_bytes && k < DRMP3_MAX_FREE_FORMAT_FRAME_SIZE && i + 2*k < mp3_bytes - DRMP3_HDR_SIZE; k++)
{
if (drmp3_hdr_compare(mp3, mp3 + k))
{
int fb = k - drmp3_hdr_padding(mp3);
int nextfb = fb + drmp3_hdr_padding(mp3 + k);
if (i + k + nextfb + DRMP3_HDR_SIZE > mp3_bytes || !drmp3_hdr_compare(mp3, mp3 + k + nextfb))
continue;
frame_and_padding = k;
frame_bytes = fb;
*free_format_bytes = fb;
}
}
if ((frame_bytes && i + frame_and_padding <= mp3_bytes &&
drmp3d_match_frame(mp3, mp3_bytes - i, frame_bytes)) ||
(!i && frame_and_padding == mp3_bytes))
{
*ptr_frame_bytes = frame_and_padding;
return i;
}
*free_format_bytes = 0;
}
}
*ptr_frame_bytes = 0;
return mp3_bytes;
}
DRMP3_API void drmp3dec_init(drmp3dec *dec)
{
dec->header[0] = 0;
}
DRMP3_API int drmp3dec_decode_frame(drmp3dec *dec, const drmp3_uint8 *mp3, int mp3_bytes, void *pcm, drmp3dec_frame_info *info)
{
int i = 0, igr, frame_size = 0, success = 1;
const drmp3_uint8 *hdr;
drmp3_bs bs_frame[1];
drmp3dec_scratch scratch;
if (mp3_bytes > 4 && dec->header[0] == 0xff && drmp3_hdr_compare(dec->header, mp3))
{
frame_size = drmp3_hdr_frame_bytes(mp3, dec->free_format_bytes) + drmp3_hdr_padding(mp3);
if (frame_size != mp3_bytes && (frame_size + DRMP3_HDR_SIZE > mp3_bytes || !drmp3_hdr_compare(mp3, mp3 + frame_size)))
{
frame_size = 0;
}
}
if (!frame_size)
{
memset(dec, 0, sizeof(drmp3dec));
i = drmp3d_find_frame(mp3, mp3_bytes, &dec->free_format_bytes, &frame_size);
if (!frame_size || i + frame_size > mp3_bytes)
{
info->frame_bytes = i;
return 0;
}
}
hdr = mp3 + i;
memcpy(dec->header, hdr, DRMP3_HDR_SIZE);
info->frame_bytes = i + frame_size;
info->channels = DRMP3_HDR_IS_MONO(hdr) ? 1 : 2;
info->hz = drmp3_hdr_sample_rate_hz(hdr);
info->layer = 4 - DRMP3_HDR_GET_LAYER(hdr);
info->bitrate_kbps = drmp3_hdr_bitrate_kbps(hdr);
drmp3_bs_init(bs_frame, hdr + DRMP3_HDR_SIZE, frame_size - DRMP3_HDR_SIZE);
if (DRMP3_HDR_IS_CRC(hdr))
{
drmp3_bs_get_bits(bs_frame, 16);
}
if (info->layer == 3)
{
int main_data_begin = drmp3_L3_read_side_info(bs_frame, scratch.gr_info, hdr);
if (main_data_begin < 0 || bs_frame->pos > bs_frame->limit)
{
drmp3dec_init(dec);
return 0;
}
success = drmp3_L3_restore_reservoir(dec, bs_frame, &scratch, main_data_begin);
if (success && pcm != NULL)
{
for (igr = 0; igr < (DRMP3_HDR_TEST_MPEG1(hdr) ? 2 : 1); igr++, pcm = DRMP3_OFFSET_PTR(pcm, sizeof(drmp3d_sample_t)*576*info->channels))
{
memset(scratch.grbuf[0], 0, 576*2*sizeof(float));
drmp3_L3_decode(dec, &scratch, scratch.gr_info + igr*info->channels, info->channels);
drmp3d_synth_granule(dec->qmf_state, scratch.grbuf[0], 18, info->channels, (drmp3d_sample_t*)pcm, scratch.syn[0]);
}
}
drmp3_L3_save_reservoir(dec, &scratch);
} else
{
#ifdef DR_MP3_ONLY_MP3
return 0;
#else
drmp3_L12_scale_info sci[1];
if (pcm == NULL) {
return drmp3_hdr_frame_samples(hdr);
}
drmp3_L12_read_scale_info(hdr, bs_frame, sci);
memset(scratch.grbuf[0], 0, 576*2*sizeof(float));
for (i = 0, igr = 0; igr < 3; igr++)
{
if (12 == (i += drmp3_L12_dequantize_granule(scratch.grbuf[0] + i, bs_frame, sci, info->layer | 1)))
{
i = 0;
drmp3_L12_apply_scf_384(sci, sci->scf + igr, scratch.grbuf[0]);
drmp3d_synth_granule(dec->qmf_state, scratch.grbuf[0], 12, info->channels, (drmp3d_sample_t*)pcm, scratch.syn[0]);
memset(scratch.grbuf[0], 0, 576*2*sizeof(float));
pcm = DRMP3_OFFSET_PTR(pcm, sizeof(drmp3d_sample_t)*384*info->channels);
}
if (bs_frame->pos > bs_frame->limit)
{
drmp3dec_init(dec);
return 0;
}
}
#endif
}
return success*drmp3_hdr_frame_samples(dec->header);
}
DRMP3_API void drmp3dec_f32_to_s16(const float *in, drmp3_int16 *out, size_t num_samples)
{
size_t i = 0;
#if DRMP3_HAVE_SIMD
size_t aligned_count = num_samples & ~7;
for(; i < aligned_count; i+=8)
{
drmp3_f4 scale = DRMP3_VSET(32768.0f);
drmp3_f4 a = DRMP3_VMUL(DRMP3_VLD(&in[i ]), scale);
drmp3_f4 b = DRMP3_VMUL(DRMP3_VLD(&in[i+4]), scale);
#if DRMP3_HAVE_SSE
drmp3_f4 s16max = DRMP3_VSET( 32767.0f);
drmp3_f4 s16min = DRMP3_VSET(-32768.0f);
__m128i pcm8 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(a, s16max), s16min)),
_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(b, s16max), s16min)));
out[i ] = (drmp3_int16)_mm_extract_epi16(pcm8, 0);
out[i+1] = (drmp3_int16)_mm_extract_epi16(pcm8, 1);
out[i+2] = (drmp3_int16)_mm_extract_epi16(pcm8, 2);
out[i+3] = (drmp3_int16)_mm_extract_epi16(pcm8, 3);
out[i+4] = (drmp3_int16)_mm_extract_epi16(pcm8, 4);
out[i+5] = (drmp3_int16)_mm_extract_epi16(pcm8, 5);
out[i+6] = (drmp3_int16)_mm_extract_epi16(pcm8, 6);
out[i+7] = (drmp3_int16)_mm_extract_epi16(pcm8, 7);
#else
int16x4_t pcma, pcmb;
a = DRMP3_VADD(a, DRMP3_VSET(0.5f));
b = DRMP3_VADD(b, DRMP3_VSET(0.5f));
pcma = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(a), vreinterpretq_s32_u32(vcltq_f32(a, DRMP3_VSET(0)))));
pcmb = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(b), vreinterpretq_s32_u32(vcltq_f32(b, DRMP3_VSET(0)))));
vst1_lane_s16(out+i , pcma, 0);
vst1_lane_s16(out+i+1, pcma, 1);
vst1_lane_s16(out+i+2, pcma, 2);
vst1_lane_s16(out+i+3, pcma, 3);
vst1_lane_s16(out+i+4, pcmb, 0);
vst1_lane_s16(out+i+5, pcmb, 1);
vst1_lane_s16(out+i+6, pcmb, 2);
vst1_lane_s16(out+i+7, pcmb, 3);
#endif
}
#endif
for(; i < num_samples; i++)
{
float sample = in[i] * 32768.0f;
if (sample >= 32766.5)
out[i] = (drmp3_int16) 32767;
else if (sample <= -32767.5)
out[i] = (drmp3_int16)-32768;
else
{
short s = (drmp3_int16)(sample + .5f);
s -= (s < 0);
out[i] = s;
}
}
}
#include <math.h>
#if defined(SIZE_MAX)
#define DRMP3_SIZE_MAX SIZE_MAX
#else
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
if (pAllocationCallbacks->onFree != NULL) {
pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
}
}
static drmp3_allocation_callbacks drmp3_copy_allocation_callbacks_or_defaults(const drmp3_allocation_callbacks* pAllocationCallbacks)
{
if (pAllocationCallbacks != NULL) {
return *pAllocationCallbacks;
} else {
drmp3_allocation_callbacks allocationCallbacks;
allocationCallbacks.pUserData = NULL;
allocationCallbacks.onMalloc = drmp3__malloc_default;
allocationCallbacks.onRealloc = drmp3__realloc_default;
allocationCallbacks.onFree = drmp3__free_default;
return allocationCallbacks;
}
}
static size_t drmp3__on_read(drmp3* pMP3, void* pBufferOut, size_t bytesToRead)
{
size_t bytesRead = pMP3->onRead(pMP3->pUserData, pBufferOut, bytesToRead);
pMP3->streamCursor += bytesRead;
return bytesRead;
}
static drmp3_bool32 drmp3__on_seek(drmp3* pMP3, int offset, drmp3_seek_origin origin)
{
DRMP3_ASSERT(offset >= 0);
if (!pMP3->onSeek(pMP3->pUserData, offset, origin)) {
return DRMP3_FALSE;
}
if (origin == drmp3_seek_origin_start) {
pMP3->streamCursor = (drmp3_uint64)offset;
} else {
pMP3->streamCursor += offset;
}
return DRMP3_TRUE;
}
static drmp3_bool32 drmp3__on_seek_64(drmp3* pMP3, drmp3_uint64 offset, drmp3_seek_origin origin)
{
if (offset <= 0x7FFFFFFF) {
return drmp3__on_seek(pMP3, (int)offset, origin);
}
if (!drmp3__on_seek(pMP3, 0x7FFFFFFF, drmp3_seek_origin_start)) {
return DRMP3_FALSE;
}
offset -= 0x7FFFFFFF;
while (offset > 0) {
if (offset <= 0x7FFFFFFF) {
if (!drmp3__on_seek(pMP3, (int)offset, drmp3_seek_origin_current)) {
return DRMP3_FALSE;
}
offset = 0;
} else {
if (!drmp3__on_seek(pMP3, 0x7FFFFFFF, drmp3_seek_origin_current)) {
return DRMP3_FALSE;
}
offset -= 0x7FFFFFFF;
}
}
return DRMP3_TRUE;
}
static drmp3_uint32 drmp3_decode_next_frame_ex__callbacks(drmp3* pMP3, drmp3d_sample_t* pPCMFrames)
{
drmp3_uint32 pcmFramesRead = 0;
DRMP3_ASSERT(pMP3 != NULL);
DRMP3_ASSERT(pMP3->onRead != NULL);
if (pMP3->atEnd) {
return 0;
}
for (;;) {
drmp3dec_frame_info info;
if (pMP3->dataSize < DRMP3_MIN_DATA_CHUNK_SIZE) {
size_t bytesRead;
if (pMP3->pData != NULL) {
memmove(pMP3->pData, pMP3->pData + pMP3->dataConsumed, pMP3->dataSize);
}
pMP3->dataConsumed = 0;
if (pMP3->dataCapacity < DRMP3_DATA_CHUNK_SIZE) {
drmp3_uint8* pNewData;
size_t newDataCap;
newDataCap = DRMP3_DATA_CHUNK_SIZE;
pNewData = (drmp3_uint8*)drmp3__realloc_from_callbacks(pMP3->pData, newDataCap, pMP3->dataCapacity, &pMP3->allocationCallbacks);
if (pNewData == NULL) {
return 0;
}
pMP3->pData = pNewData;
pMP3->dataCapacity = newDataCap;
}
bytesRead = drmp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize));
if (bytesRead == 0) {
if (pMP3->dataSize == 0) {
pMP3->atEnd = DRMP3_TRUE;
return 0;
}
}
pMP3->dataSize += bytesRead;
}
if (pMP3->dataSize > INT_MAX) {
pMP3->atEnd = DRMP3_TRUE;
return 0;
}
pcmFramesRead = drmp3dec_decode_frame(&pMP3->decoder, pMP3->pData + pMP3->dataConsumed, (int)pMP3->dataSize, pPCMFrames, &info);
if (info.frame_bytes > 0) {
pMP3->dataConsumed += (size_t)info.frame_bytes;
pMP3->dataSize -= (size_t)info.frame_bytes;
}
if (pcmFramesRead > 0) {
pcmFramesRead = drmp3_hdr_frame_samples(pMP3->decoder.header);
pMP3->pcmFramesConsumedInMP3Frame = 0;
pMP3->pcmFramesRemainingInMP3Frame = pcmFramesRead;
pMP3->mp3FrameChannels = info.channels;
pMP3->mp3FrameSampleRate = info.hz;
break;
} else if (info.frame_bytes == 0) {
size_t bytesRead;
memmove(pMP3->pData, pMP3->pData + pMP3->dataConsumed, pMP3->dataSize);
pMP3->dataConsumed = 0;
if (pMP3->dataCapacity == pMP3->dataSize) {
drmp3_uint8* pNewData;
size_t newDataCap;
newDataCap = pMP3->dataCapacity + DRMP3_DATA_CHUNK_SIZE;
pNewData = (drmp3_uint8*)drmp3__realloc_from_callbacks(pMP3->pData, newDataCap, pMP3->dataCapacity, &pMP3->allocationCallbacks);
if (pNewData == NULL) {
return 0;
}
pMP3->pData = pNewData;
pMP3->dataCapacity = newDataCap;
}
bytesRead = drmp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize));
if (bytesRead == 0) {
pMP3->atEnd = DRMP3_TRUE;
return 0;
}
pMP3->dataSize += bytesRead;
}
};
return pcmFramesRead;
}
static drmp3_uint32 drmp3_decode_next_frame_ex__memory(drmp3* pMP3, drmp3d_sample_t* pPCMFrames)
{
drmp3_uint32 pcmFramesRead = 0;
drmp3dec_frame_info info;
DRMP3_ASSERT(pMP3 != NULL);
DRMP3_ASSERT(pMP3->memory.pData != NULL);
if (pMP3->atEnd) {
return 0;
}
pcmFramesRead = drmp3dec_decode_frame(&pMP3->decoder, pMP3->memory.pData + pMP3->memory.currentReadPos, (int)(pMP3->memory.dataSize - pMP3->memory.currentReadPos), pPCMFrames, &info);
if (pcmFramesRead > 0) {
pMP3->pcmFramesConsumedInMP3Frame = 0;
pMP3->pcmFramesRemainingInMP3Frame = pcmFramesRead;
pMP3->mp3FrameChannels = info.channels;
pMP3->mp3FrameSampleRate = info.hz;
}
pMP3->memory.currentReadPos += (size_t)info.frame_bytes;
return pcmFramesRead;
}
static drmp3_uint32 drmp3_decode_next_frame_ex(drmp3* pMP3, drmp3d_sample_t* pPCMFrames)
{
if (pMP3->memory.pData != NULL && pMP3->memory.dataSize > 0) {
return drmp3_decode_next_frame_ex__memory(pMP3, pPCMFrames);
} else {
return drmp3_decode_next_frame_ex__callbacks(pMP3, pPCMFrames);
}
}
static drmp3_uint32 drmp3_decode_next_frame(drmp3* pMP3)
{
DRMP3_ASSERT(pMP3 != NULL);
return drmp3_decode_next_frame_ex(pMP3, (drmp3d_sample_t*)pMP3->pcmFrames);
}
#if 0
static drmp3_uint32 drmp3_seek_next_frame(drmp3* pMP3)
{
drmp3_uint32 pcmFrameCount;
DRMP3_ASSERT(pMP3 != NULL);
pcmFrameCount = drmp3_decode_next_frame_ex(pMP3, NULL);
if (pcmFrameCount == 0) {
return 0;
}
pMP3->currentPCMFrame += pcmFrameCount;
pMP3->pcmFramesConsumedInMP3Frame = pcmFrameCount;
pMP3->pcmFramesRemainingInMP3Frame = 0;
return pcmFrameCount;
}
#endif
static drmp3_bool32 drmp3_init_internal(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_allocation_callbacks* pAllocationCallbacks)
{
DRMP3_ASSERT(pMP3 != NULL);
DRMP3_ASSERT(onRead != NULL);
drmp3dec_init(&pMP3->decoder);
pMP3->onRead = onRead;
pMP3->onSeek = onSeek;
pMP3->pUserData = pUserData;
pMP3->allocationCallbacks = drmp3_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
if (pMP3->allocationCallbacks.onFree == NULL || (pMP3->allocationCallbacks.onMalloc == NULL && pMP3->allocationCallbacks.onRealloc == NULL)) {
return DRMP3_FALSE;
}
if (!drmp3_decode_next_frame(pMP3)) {
drmp3_uninit(pMP3);
return DRMP3_FALSE;
}
pMP3->channels = pMP3->mp3FrameChannels;
pMP3->sampleRate = pMP3->mp3FrameSampleRate;
return DRMP3_TRUE;
}
DRMP3_API drmp3_bool32 drmp3_init(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_allocation_callbacks* pAllocationCallbacks)
{
if (pMP3 == NULL || onRead == NULL) {
return DRMP3_FALSE;
}
DRMP3_ZERO_OBJECT(pMP3);
return drmp3_init_internal(pMP3, onRead, onSeek, pUserData, pAllocationCallbacks);
}
static size_t drmp3__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead)
{
drmp3* pMP3 = (drmp3*)pUserData;
size_t bytesRemaining;
DRMP3_ASSERT(pMP3 != NULL);
DRMP3_ASSERT(pMP3->memory.dataSize >= pMP3->memory.currentReadPos);
bytesRemaining = pMP3->memory.dataSize - pMP3->memory.currentReadPos;
if (bytesToRead > bytesRemaining) {
bytesToRead = bytesRemaining;
}
if (bytesToRead > 0) {
DRMP3_COPY_MEMORY(pBufferOut, pMP3->memory.pData + pMP3->memory.currentReadPos, bytesToRead);
pMP3->memory.currentReadPos += bytesToRead;
}
return bytesToRead;
}
static drmp3_bool32 drmp3__on_seek_memory(void* pUserData, int byteOffset, drmp3_seek_origin origin)
{
drmp3* pMP3 = (drmp3*)pUserData;
DRMP3_ASSERT(pMP3 != NULL);
if (origin == drmp3_seek_origin_current) {
if (byteOffset > 0) {
if (pMP3->memory.currentReadPos + byteOffset > pMP3->memory.dataSize) {
byteOffset = (int)(pMP3->memory.dataSize - pMP3->memory.currentReadPos);
}
} else {
if (pMP3->memory.currentReadPos < (size_t)-byteOffset) {
byteOffset = -(int)pMP3->memory.currentReadPos;
}
}
pMP3->memory.currentReadPos += byteOffset;
} else {
if ((drmp3_uint32)byteOffset <= pMP3->memory.dataSize) {
pMP3->memory.currentReadPos = byteOffset;
} else {
pMP3->memory.currentReadPos = pMP3->memory.dataSize;
}
}
return DRMP3_TRUE;
}
DRMP3_API drmp3_bool32 drmp3_init_memory(drmp3* pMP3, const void* pData, size_t dataSize, const drmp3_allocation_callbacks* pAllocationCallbacks)
{
if (pMP3 == NULL) {
return DRMP3_FALSE;
}
share/public_html/static/music_inc/src/miniaudio.h view on Meta::CPAN
}
#endif
DRMP3_API void drmp3_uninit(drmp3* pMP3)
{
if (pMP3 == NULL) {
return;
}
#ifndef DR_MP3_NO_STDIO
if (pMP3->onRead == drmp3__on_read_stdio) {
fclose((FILE*)pMP3->pUserData);
}
#endif
drmp3__free_from_callbacks(pMP3->pData, &pMP3->allocationCallbacks);
}
#if defined(DR_MP3_FLOAT_OUTPUT)
static void drmp3_f32_to_s16(drmp3_int16* dst, const float* src, drmp3_uint64 sampleCount)
{
drmp3_uint64 i;
drmp3_uint64 i4;
drmp3_uint64 sampleCount4;
i = 0;
sampleCount4 = sampleCount >> 2;
for (i4 = 0; i4 < sampleCount4; i4 += 1) {
float x0 = src[i+0];
float x1 = src[i+1];
float x2 = src[i+2];
float x3 = src[i+3];
x0 = ((x0 < -1) ? -1 : ((x0 > 1) ? 1 : x0));
x1 = ((x1 < -1) ? -1 : ((x1 > 1) ? 1 : x1));
x2 = ((x2 < -1) ? -1 : ((x2 > 1) ? 1 : x2));
x3 = ((x3 < -1) ? -1 : ((x3 > 1) ? 1 : x3));
x0 = x0 * 32767.0f;
x1 = x1 * 32767.0f;
x2 = x2 * 32767.0f;
x3 = x3 * 32767.0f;
dst[i+0] = (drmp3_int16)x0;
dst[i+1] = (drmp3_int16)x1;
dst[i+2] = (drmp3_int16)x2;
dst[i+3] = (drmp3_int16)x3;
i += 4;
}
for (; i < sampleCount; i += 1) {
float x = src[i];
x = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
x = x * 32767.0f;
dst[i] = (drmp3_int16)x;
}
}
#endif
#if !defined(DR_MP3_FLOAT_OUTPUT)
static void drmp3_s16_to_f32(float* dst, const drmp3_int16* src, drmp3_uint64 sampleCount)
{
drmp3_uint64 i;
for (i = 0; i < sampleCount; i += 1) {
float x = (float)src[i];
x = x * 0.000030517578125f;
dst[i] = x;
}
}
#endif
static drmp3_uint64 drmp3_read_pcm_frames_raw(drmp3* pMP3, drmp3_uint64 framesToRead, void* pBufferOut)
{
drmp3_uint64 totalFramesRead = 0;
DRMP3_ASSERT(pMP3 != NULL);
DRMP3_ASSERT(pMP3->onRead != NULL);
while (framesToRead > 0) {
drmp3_uint32 framesToConsume = (drmp3_uint32)DRMP3_MIN(pMP3->pcmFramesRemainingInMP3Frame, framesToRead);
if (pBufferOut != NULL) {
#if defined(DR_MP3_FLOAT_OUTPUT)
float* pFramesOutF32 = (float*)DRMP3_OFFSET_PTR(pBufferOut, sizeof(float) * totalFramesRead * pMP3->channels);
float* pFramesInF32 = (float*)DRMP3_OFFSET_PTR(&pMP3->pcmFrames[0], sizeof(float) * pMP3->pcmFramesConsumedInMP3Frame * pMP3->mp3FrameChannels);
DRMP3_COPY_MEMORY(pFramesOutF32, pFramesInF32, sizeof(float) * framesToConsume * pMP3->channels);
#else
drmp3_int16* pFramesOutS16 = (drmp3_int16*)DRMP3_OFFSET_PTR(pBufferOut, sizeof(drmp3_int16) * totalFramesRead * pMP3->channels);
drmp3_int16* pFramesInS16 = (drmp3_int16*)DRMP3_OFFSET_PTR(&pMP3->pcmFrames[0], sizeof(drmp3_int16) * pMP3->pcmFramesConsumedInMP3Frame * pMP3->mp3FrameChannels);
DRMP3_COPY_MEMORY(pFramesOutS16, pFramesInS16, sizeof(drmp3_int16) * framesToConsume * pMP3->channels);
#endif
}
pMP3->currentPCMFrame += framesToConsume;
pMP3->pcmFramesConsumedInMP3Frame += framesToConsume;
pMP3->pcmFramesRemainingInMP3Frame -= framesToConsume;
totalFramesRead += framesToConsume;
framesToRead -= framesToConsume;
if (framesToRead == 0) {
break;
}
DRMP3_ASSERT(pMP3->pcmFramesRemainingInMP3Frame == 0);
if (drmp3_decode_next_frame(pMP3) == 0) {
break;
}
}
return totalFramesRead;
}
DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_f32(drmp3* pMP3, drmp3_uint64 framesToRead, float* pBufferOut)
{
if (pMP3 == NULL || pMP3->onRead == NULL) {
return 0;
}
#if defined(DR_MP3_FLOAT_OUTPUT)
return drmp3_read_pcm_frames_raw(pMP3, framesToRead, pBufferOut);
#else
{
drmp3_int16 pTempS16[8192];
drmp3_uint64 totalPCMFramesRead = 0;
while (totalPCMFramesRead < framesToRead) {
drmp3_uint64 framesJustRead;
drmp3_uint64 framesRemaining = framesToRead - totalPCMFramesRead;
drmp3_uint64 framesToReadNow = DRMP3_COUNTOF(pTempS16) / pMP3->channels;
if (framesToReadNow > framesRemaining) {
framesToReadNow = framesRemaining;
}
framesJustRead = drmp3_read_pcm_frames_raw(pMP3, framesToReadNow, pTempS16);
if (framesJustRead == 0) {
break;
}
drmp3_s16_to_f32((float*)DRMP3_OFFSET_PTR(pBufferOut, sizeof(float) * totalPCMFramesRead * pMP3->channels), pTempS16, framesJustRead * pMP3->channels);
totalPCMFramesRead += framesJustRead;
}
return totalPCMFramesRead;
}
#endif
}
DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_s16(drmp3* pMP3, drmp3_uint64 framesToRead, drmp3_int16* pBufferOut)
{
if (pMP3 == NULL || pMP3->onRead == NULL) {
return 0;
}
#if !defined(DR_MP3_FLOAT_OUTPUT)
return drmp3_read_pcm_frames_raw(pMP3, framesToRead, pBufferOut);
#else
{
float pTempF32[4096];
drmp3_uint64 totalPCMFramesRead = 0;
while (totalPCMFramesRead < framesToRead) {
drmp3_uint64 framesJustRead;
drmp3_uint64 framesRemaining = framesToRead - totalPCMFramesRead;
drmp3_uint64 framesToReadNow = DRMP3_COUNTOF(pTempF32) / pMP3->channels;
if (framesToReadNow > framesRemaining) {
framesToReadNow = framesRemaining;
}
framesJustRead = drmp3_read_pcm_frames_raw(pMP3, framesToReadNow, pTempF32);
if (framesJustRead == 0) {
break;
}
drmp3_f32_to_s16((drmp3_int16*)DRMP3_OFFSET_PTR(pBufferOut, sizeof(drmp3_int16) * totalPCMFramesRead * pMP3->channels), pTempF32, framesJustRead * pMP3->channels);
totalPCMFramesRead += framesJustRead;
}
return totalPCMFramesRead;
}
#endif
}
static void drmp3_reset(drmp3* pMP3)
{
DRMP3_ASSERT(pMP3 != NULL);
pMP3->pcmFramesConsumedInMP3Frame = 0;
pMP3->pcmFramesRemainingInMP3Frame = 0;
pMP3->currentPCMFrame = 0;
pMP3->dataSize = 0;
pMP3->atEnd = DRMP3_FALSE;
drmp3dec_init(&pMP3->decoder);
}
static drmp3_bool32 drmp3_seek_to_start_of_stream(drmp3* pMP3)
{
DRMP3_ASSERT(pMP3 != NULL);
DRMP3_ASSERT(pMP3->onSeek != NULL);
if (!drmp3__on_seek(pMP3, 0, drmp3_seek_origin_start)) {
return DRMP3_FALSE;
}
drmp3_reset(pMP3);
return DRMP3_TRUE;
}
static drmp3_bool32 drmp3_seek_forward_by_pcm_frames__brute_force(drmp3* pMP3, drmp3_uint64 frameOffset)
{
drmp3_uint64 framesRead;
#if defined(DR_MP3_FLOAT_OUTPUT)
framesRead = drmp3_read_pcm_frames_f32(pMP3, frameOffset, NULL);
#else
framesRead = drmp3_read_pcm_frames_s16(pMP3, frameOffset, NULL);
#endif
if (framesRead != frameOffset) {
return DRMP3_FALSE;
}
return DRMP3_TRUE;
}
static drmp3_bool32 drmp3_seek_to_pcm_frame__brute_force(drmp3* pMP3, drmp3_uint64 frameIndex)
{
DRMP3_ASSERT(pMP3 != NULL);
if (frameIndex == pMP3->currentPCMFrame) {
return DRMP3_TRUE;
}
if (frameIndex < pMP3->currentPCMFrame) {
if (!drmp3_seek_to_start_of_stream(pMP3)) {
return DRMP3_FALSE;
}
}
DRMP3_ASSERT(frameIndex >= pMP3->currentPCMFrame);
return drmp3_seek_forward_by_pcm_frames__brute_force(pMP3, (frameIndex - pMP3->currentPCMFrame));
}
static drmp3_bool32 drmp3_find_closest_seek_point(drmp3* pMP3, drmp3_uint64 frameIndex, drmp3_uint32* pSeekPointIndex)
{
drmp3_uint32 iSeekPoint;
DRMP3_ASSERT(pSeekPointIndex != NULL);
*pSeekPointIndex = 0;
if (frameIndex < pMP3->pSeekPoints[0].pcmFrameIndex) {
return DRMP3_FALSE;
}
for (iSeekPoint = 0; iSeekPoint < pMP3->seekPointCount; ++iSeekPoint) {
if (pMP3->pSeekPoints[iSeekPoint].pcmFrameIndex > frameIndex) {
break;
}
*pSeekPointIndex = iSeekPoint;
}
return DRMP3_TRUE;
}
static drmp3_bool32 drmp3_seek_to_pcm_frame__seek_table(drmp3* pMP3, drmp3_uint64 frameIndex)
{
drmp3_seek_point seekPoint;
drmp3_uint32 priorSeekPointIndex;
drmp3_uint16 iMP3Frame;
drmp3_uint64 leftoverFrames;
DRMP3_ASSERT(pMP3 != NULL);
DRMP3_ASSERT(pMP3->pSeekPoints != NULL);
DRMP3_ASSERT(pMP3->seekPointCount > 0);
if (drmp3_find_closest_seek_point(pMP3, frameIndex, &priorSeekPointIndex)) {
seekPoint = pMP3->pSeekPoints[priorSeekPointIndex];
} else {
seekPoint.seekPosInBytes = 0;
seekPoint.pcmFrameIndex = 0;
seekPoint.mp3FramesToDiscard = 0;
seekPoint.pcmFramesToDiscard = 0;
}
if (!drmp3__on_seek_64(pMP3, seekPoint.seekPosInBytes, drmp3_seek_origin_start)) {
return DRMP3_FALSE;
}
drmp3_reset(pMP3);
for (iMP3Frame = 0; iMP3Frame < seekPoint.mp3FramesToDiscard; ++iMP3Frame) {
drmp3_uint32 pcmFramesRead;
drmp3d_sample_t* pPCMFrames;
pPCMFrames = NULL;
if (iMP3Frame == seekPoint.mp3FramesToDiscard-1) {
pPCMFrames = (drmp3d_sample_t*)pMP3->pcmFrames;
}
pcmFramesRead = drmp3_decode_next_frame_ex(pMP3, pPCMFrames);
if (pcmFramesRead == 0) {
return DRMP3_FALSE;
}
}
pMP3->currentPCMFrame = seekPoint.pcmFrameIndex - seekPoint.pcmFramesToDiscard;
leftoverFrames = frameIndex - pMP3->currentPCMFrame;
return drmp3_seek_forward_by_pcm_frames__brute_force(pMP3, leftoverFrames);
}
DRMP3_API drmp3_bool32 drmp3_seek_to_pcm_frame(drmp3* pMP3, drmp3_uint64 frameIndex)
{
if (pMP3 == NULL || pMP3->onSeek == NULL) {
return DRMP3_FALSE;
}
if (frameIndex == 0) {
return drmp3_seek_to_start_of_stream(pMP3);
}
if (pMP3->pSeekPoints != NULL && pMP3->seekPointCount > 0) {
return drmp3_seek_to_pcm_frame__seek_table(pMP3, frameIndex);
} else {
return drmp3_seek_to_pcm_frame__brute_force(pMP3, frameIndex);
}
}
DRMP3_API drmp3_bool32 drmp3_get_mp3_and_pcm_frame_count(drmp3* pMP3, drmp3_uint64* pMP3FrameCount, drmp3_uint64* pPCMFrameCount)
{
drmp3_uint64 currentPCMFrame;
drmp3_uint64 totalPCMFrameCount;
drmp3_uint64 totalMP3FrameCount;
if (pMP3 == NULL) {
return DRMP3_FALSE;
}
if (pMP3->onSeek == NULL) {
return DRMP3_FALSE;
}
currentPCMFrame = pMP3->currentPCMFrame;
if (!drmp3_seek_to_start_of_stream(pMP3)) {
return DRMP3_FALSE;
}
totalPCMFrameCount = 0;
totalMP3FrameCount = 0;
for (;;) {
drmp3_uint32 pcmFramesInCurrentMP3Frame;
pcmFramesInCurrentMP3Frame = drmp3_decode_next_frame_ex(pMP3, NULL);
if (pcmFramesInCurrentMP3Frame == 0) {
break;
}
totalPCMFrameCount += pcmFramesInCurrentMP3Frame;
totalMP3FrameCount += 1;
}
if (!drmp3_seek_to_start_of_stream(pMP3)) {
return DRMP3_FALSE;
}
if (!drmp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) {
return DRMP3_FALSE;
}
if (pMP3FrameCount != NULL) {
*pMP3FrameCount = totalMP3FrameCount;
}
if (pPCMFrameCount != NULL) {
*pPCMFrameCount = totalPCMFrameCount;
}
return DRMP3_TRUE;
}
DRMP3_API drmp3_uint64 drmp3_get_pcm_frame_count(drmp3* pMP3)
{
drmp3_uint64 totalPCMFrameCount;
if (!drmp3_get_mp3_and_pcm_frame_count(pMP3, NULL, &totalPCMFrameCount)) {
return 0;
}
return totalPCMFrameCount;
}
DRMP3_API drmp3_uint64 drmp3_get_mp3_frame_count(drmp3* pMP3)
{
drmp3_uint64 totalMP3FrameCount;
if (!drmp3_get_mp3_and_pcm_frame_count(pMP3, &totalMP3FrameCount, NULL)) {
return 0;
}
return totalMP3FrameCount;
}
static void drmp3__accumulate_running_pcm_frame_count(drmp3* pMP3, drmp3_uint32 pcmFrameCountIn, drmp3_uint64* pRunningPCMFrameCount, float* pRunningPCMFrameCountFractionalPart)
{
float srcRatio;
float pcmFrameCountOutF;
drmp3_uint32 pcmFrameCountOut;
srcRatio = (float)pMP3->mp3FrameSampleRate / (float)pMP3->sampleRate;
DRMP3_ASSERT(srcRatio > 0);
pcmFrameCountOutF = *pRunningPCMFrameCountFractionalPart + (pcmFrameCountIn / srcRatio);
pcmFrameCountOut = (drmp3_uint32)pcmFrameCountOutF;
*pRunningPCMFrameCountFractionalPart = pcmFrameCountOutF - pcmFrameCountOut;
*pRunningPCMFrameCount += pcmFrameCountOut;
}
typedef struct
{
drmp3_uint64 bytePos;
drmp3_uint64 pcmFrameIndex;
} drmp3__seeking_mp3_frame_info;
DRMP3_API drmp3_bool32 drmp3_calculate_seek_points(drmp3* pMP3, drmp3_uint32* pSeekPointCount, drmp3_seek_point* pSeekPoints)
{
drmp3_uint32 seekPointCount;
drmp3_uint64 currentPCMFrame;
drmp3_uint64 totalMP3FrameCount;
drmp3_uint64 totalPCMFrameCount;
if (pMP3 == NULL || pSeekPointCount == NULL || pSeekPoints == NULL) {
return DRMP3_FALSE;
}
seekPointCount = *pSeekPointCount;
if (seekPointCount == 0) {
return DRMP3_FALSE;
}
currentPCMFrame = pMP3->currentPCMFrame;
if (!drmp3_get_mp3_and_pcm_frame_count(pMP3, &totalMP3FrameCount, &totalPCMFrameCount)) {
return DRMP3_FALSE;
}
if (totalMP3FrameCount < DRMP3_SEEK_LEADING_MP3_FRAMES+1) {
seekPointCount = 1;
pSeekPoints[0].seekPosInBytes = 0;
pSeekPoints[0].pcmFrameIndex = 0;
pSeekPoints[0].mp3FramesToDiscard = 0;
pSeekPoints[0].pcmFramesToDiscard = 0;
} else {
drmp3_uint64 pcmFramesBetweenSeekPoints;
drmp3__seeking_mp3_frame_info mp3FrameInfo[DRMP3_SEEK_LEADING_MP3_FRAMES+1];
drmp3_uint64 runningPCMFrameCount = 0;
float runningPCMFrameCountFractionalPart = 0;
drmp3_uint64 nextTargetPCMFrame;
drmp3_uint32 iMP3Frame;
drmp3_uint32 iSeekPoint;
if (seekPointCount > totalMP3FrameCount-1) {
seekPointCount = (drmp3_uint32)totalMP3FrameCount-1;
}
pcmFramesBetweenSeekPoints = totalPCMFrameCount / (seekPointCount+1);
if (!drmp3_seek_to_start_of_stream(pMP3)) {
return DRMP3_FALSE;
}
for (iMP3Frame = 0; iMP3Frame < DRMP3_SEEK_LEADING_MP3_FRAMES+1; ++iMP3Frame) {
drmp3_uint32 pcmFramesInCurrentMP3FrameIn;
DRMP3_ASSERT(pMP3->streamCursor >= pMP3->dataSize);
mp3FrameInfo[iMP3Frame].bytePos = pMP3->streamCursor - pMP3->dataSize;
mp3FrameInfo[iMP3Frame].pcmFrameIndex = runningPCMFrameCount;
pcmFramesInCurrentMP3FrameIn = drmp3_decode_next_frame_ex(pMP3, NULL);
if (pcmFramesInCurrentMP3FrameIn == 0) {
return DRMP3_FALSE;
}
drmp3__accumulate_running_pcm_frame_count(pMP3, pcmFramesInCurrentMP3FrameIn, &runningPCMFrameCount, &runningPCMFrameCountFractionalPart);
}
nextTargetPCMFrame = 0;
for (iSeekPoint = 0; iSeekPoint < seekPointCount; ++iSeekPoint) {
nextTargetPCMFrame += pcmFramesBetweenSeekPoints;
for (;;) {
if (nextTargetPCMFrame < runningPCMFrameCount) {
pSeekPoints[iSeekPoint].seekPosInBytes = mp3FrameInfo[0].bytePos;
pSeekPoints[iSeekPoint].pcmFrameIndex = nextTargetPCMFrame;
pSeekPoints[iSeekPoint].mp3FramesToDiscard = DRMP3_SEEK_LEADING_MP3_FRAMES;
pSeekPoints[iSeekPoint].pcmFramesToDiscard = (drmp3_uint16)(nextTargetPCMFrame - mp3FrameInfo[DRMP3_SEEK_LEADING_MP3_FRAMES-1].pcmFrameIndex);
break;
} else {
size_t i;
drmp3_uint32 pcmFramesInCurrentMP3FrameIn;
for (i = 0; i < DRMP3_COUNTOF(mp3FrameInfo)-1; ++i) {
mp3FrameInfo[i] = mp3FrameInfo[i+1];
}
mp3FrameInfo[DRMP3_COUNTOF(mp3FrameInfo)-1].bytePos = pMP3->streamCursor - pMP3->dataSize;
mp3FrameInfo[DRMP3_COUNTOF(mp3FrameInfo)-1].pcmFrameIndex = runningPCMFrameCount;
pcmFramesInCurrentMP3FrameIn = drmp3_decode_next_frame_ex(pMP3, NULL);
if (pcmFramesInCurrentMP3FrameIn == 0) {
pSeekPoints[iSeekPoint].seekPosInBytes = mp3FrameInfo[0].bytePos;
pSeekPoints[iSeekPoint].pcmFrameIndex = nextTargetPCMFrame;
pSeekPoints[iSeekPoint].mp3FramesToDiscard = DRMP3_SEEK_LEADING_MP3_FRAMES;
pSeekPoints[iSeekPoint].pcmFramesToDiscard = (drmp3_uint16)(nextTargetPCMFrame - mp3FrameInfo[DRMP3_SEEK_LEADING_MP3_FRAMES-1].pcmFrameIndex);
break;
}
drmp3__accumulate_running_pcm_frame_count(pMP3, pcmFramesInCurrentMP3FrameIn, &runningPCMFrameCount, &runningPCMFrameCountFractionalPart);
}
}
}
if (!drmp3_seek_to_start_of_stream(pMP3)) {
return DRMP3_FALSE;
}
if (!drmp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) {
return DRMP3_FALSE;
}
}
*pSeekPointCount = seekPointCount;
return DRMP3_TRUE;
}
DRMP3_API drmp3_bool32 drmp3_bind_seek_table(drmp3* pMP3, drmp3_uint32 seekPointCount, drmp3_seek_point* pSeekPoints)
{
if (pMP3 == NULL) {
return DRMP3_FALSE;
}
if (seekPointCount == 0 || pSeekPoints == NULL) {
pMP3->seekPointCount = 0;
pMP3->pSeekPoints = NULL;
} else {
pMP3->seekPointCount = seekPointCount;
pMP3->pSeekPoints = pSeekPoints;
}
return DRMP3_TRUE;
}
static float* drmp3__full_read_and_close_f32(drmp3* pMP3, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount)
{
drmp3_uint64 totalFramesRead = 0;
drmp3_uint64 framesCapacity = 0;
float* pFrames = NULL;
float temp[4096];
DRMP3_ASSERT(pMP3 != NULL);
for (;;) {
drmp3_uint64 framesToReadRightNow = DRMP3_COUNTOF(temp) / pMP3->channels;
drmp3_uint64 framesJustRead = drmp3_read_pcm_frames_f32(pMP3, framesToReadRightNow, temp);
if (framesJustRead == 0) {
break;
}
if (framesCapacity < totalFramesRead + framesJustRead) {
drmp3_uint64 oldFramesBufferSize;
drmp3_uint64 newFramesBufferSize;
drmp3_uint64 newFramesCap;
float* pNewFrames;
newFramesCap = framesCapacity * 2;
if (newFramesCap < totalFramesRead + framesJustRead) {
newFramesCap = totalFramesRead + framesJustRead;
}
oldFramesBufferSize = framesCapacity * pMP3->channels * sizeof(float);
newFramesBufferSize = newFramesCap * pMP3->channels * sizeof(float);
if (newFramesBufferSize > DRMP3_SIZE_MAX) {
break;
}
pNewFrames = (float*)drmp3__realloc_from_callbacks(pFrames, (size_t)newFramesBufferSize, (size_t)oldFramesBufferSize, &pMP3->allocationCallbacks);
if (pNewFrames == NULL) {
drmp3__free_from_callbacks(pFrames, &pMP3->allocationCallbacks);
break;
}
pFrames = pNewFrames;
framesCapacity = newFramesCap;
}
DRMP3_COPY_MEMORY(pFrames + totalFramesRead*pMP3->channels, temp, (size_t)(framesJustRead*pMP3->channels*sizeof(float)));
totalFramesRead += framesJustRead;
if (framesJustRead != framesToReadRightNow) {
break;
}
}
if (pConfig != NULL) {
pConfig->channels = pMP3->channels;
pConfig->sampleRate = pMP3->sampleRate;
}
drmp3_uninit(pMP3);
if (pTotalFrameCount) {
*pTotalFrameCount = totalFramesRead;
}
return pFrames;
}
static drmp3_int16* drmp3__full_read_and_close_s16(drmp3* pMP3, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount)
{
drmp3_uint64 totalFramesRead = 0;
drmp3_uint64 framesCapacity = 0;
drmp3_int16* pFrames = NULL;
drmp3_int16 temp[4096];
DRMP3_ASSERT(pMP3 != NULL);
for (;;) {
drmp3_uint64 framesToReadRightNow = DRMP3_COUNTOF(temp) / pMP3->channels;
drmp3_uint64 framesJustRead = drmp3_read_pcm_frames_s16(pMP3, framesToReadRightNow, temp);
if (framesJustRead == 0) {
break;
}
if (framesCapacity < totalFramesRead + framesJustRead) {
drmp3_uint64 newFramesBufferSize;
drmp3_uint64 oldFramesBufferSize;
drmp3_uint64 newFramesCap;
drmp3_int16* pNewFrames;
newFramesCap = framesCapacity * 2;
if (newFramesCap < totalFramesRead + framesJustRead) {
newFramesCap = totalFramesRead + framesJustRead;
}
oldFramesBufferSize = framesCapacity * pMP3->channels * sizeof(drmp3_int16);
newFramesBufferSize = newFramesCap * pMP3->channels * sizeof(drmp3_int16);
if (newFramesBufferSize > DRMP3_SIZE_MAX) {
break;
}
pNewFrames = (drmp3_int16*)drmp3__realloc_from_callbacks(pFrames, (size_t)newFramesBufferSize, (size_t)oldFramesBufferSize, &pMP3->allocationCallbacks);
if (pNewFrames == NULL) {
drmp3__free_from_callbacks(pFrames, &pMP3->allocationCallbacks);
break;
}
pFrames = pNewFrames;
framesCapacity = newFramesCap;
}
DRMP3_COPY_MEMORY(pFrames + totalFramesRead*pMP3->channels, temp, (size_t)(framesJustRead*pMP3->channels*sizeof(drmp3_int16)));
totalFramesRead += framesJustRead;
if (framesJustRead != framesToReadRightNow) {
break;
}
}
if (pConfig != NULL) {
pConfig->channels = pMP3->channels;
pConfig->sampleRate = pMP3->sampleRate;
}
drmp3_uninit(pMP3);
if (pTotalFrameCount) {
*pTotalFrameCount = totalFramesRead;
}
return pFrames;
}
DRMP3_API float* drmp3_open_and_read_pcm_frames_f32(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
{
drmp3 mp3;
if (!drmp3_init(&mp3, onRead, onSeek, pUserData, pAllocationCallbacks)) {
return NULL;
}
return drmp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount);
}
DRMP3_API drmp3_int16* drmp3_open_and_read_pcm_frames_s16(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
{
drmp3 mp3;
if (!drmp3_init(&mp3, onRead, onSeek, pUserData, pAllocationCallbacks)) {
return NULL;
}
return drmp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount);
}
DRMP3_API float* drmp3_open_memory_and_read_pcm_frames_f32(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
{
drmp3 mp3;
if (!drmp3_init_memory(&mp3, pData, dataSize, pAllocationCallbacks)) {
return NULL;
}
return drmp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount);
}
DRMP3_API drmp3_int16* drmp3_open_memory_and_read_pcm_frames_s16(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
{
drmp3 mp3;
if (!drmp3_init_memory(&mp3, pData, dataSize, pAllocationCallbacks)) {
return NULL;
}
return drmp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount);
}
#ifndef DR_MP3_NO_STDIO
DRMP3_API float* drmp3_open_file_and_read_pcm_frames_f32(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
{
drmp3 mp3;
if (!drmp3_init_file(&mp3, filePath, pAllocationCallbacks)) {
return NULL;
}
return drmp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount);
}
DRMP3_API drmp3_int16* drmp3_open_file_and_read_pcm_frames_s16(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
{
drmp3 mp3;
if (!drmp3_init_file(&mp3, filePath, pAllocationCallbacks)) {
return NULL;
}
return drmp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount);
}
#endif
DRMP3_API void* drmp3_malloc(size_t sz, const drmp3_allocation_callbacks* pAllocationCallbacks)
{
if (pAllocationCallbacks != NULL) {
return drmp3__malloc_from_callbacks(sz, pAllocationCallbacks);
} else {
return drmp3__malloc_default(sz, NULL);
}
}
DRMP3_API void drmp3_free(void* p, const drmp3_allocation_callbacks* pAllocationCallbacks)
{
if (pAllocationCallbacks != NULL) {
drmp3__free_from_callbacks(p, pAllocationCallbacks);
} else {
drmp3__free_default(p, NULL);
}
}
#endif
/* dr_mp3_c end */
#endif /* DRMP3_IMPLEMENTATION */
#endif /* MA_NO_MP3 */
/* End globally disabled warnings. */
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#endif /* miniaudio_c */
#endif /* MINIAUDIO_IMPLEMENTATION */
/*
RELEASE NOTES - VERSION 0.10.x
==============================
Version 0.10 includes major API changes and refactoring, mostly concerned with the data conversion system. Data conversion is performed internally to convert
audio data between the format requested when initializing the `ma_device` object and the format of the internal device used by the backend. The same applies
to the `ma_decoder` object. The previous design has several design flaws and missing features which necessitated a complete redesign.
Changes to Data Conversion
--------------------------
The previous data conversion system used callbacks to deliver input data for conversion. This design works well in some specific situations, but in other
situations it has some major readability and maintenance issues. The decision was made to replace this with a more iterative approach where you just pass in a
pointer to the input data directly rather than dealing with a callback.
The following are the data conversion APIs that have been removed and their replacements:
- ma_format_converter -> ma_convert_pcm_frames_format()
- ma_channel_router -> ma_channel_converter
- ma_src -> ma_resampler
- ma_pcm_converter -> ma_data_converter
The previous conversion APIs accepted a callback in their configs. There are no longer any callbacks to deal with. Instead you just pass the data into the
`*_process_pcm_frames()` function as a pointer to a buffer.
The simplest aspect of data conversion is sample format conversion. To convert between two formats, just call `ma_convert_pcm_frames_format()`. Channel
conversion is also simple which you can do with `ma_channel_converter` via `ma_channel_converter_process_pcm_frames()`.
Resampling is more complicated because the number of output frames that are processed is different to the number of input frames that are consumed. When you
call `ma_resampler_process_pcm_frames()` you need to pass in the number of input frames available for processing and the number of output frames you want to
output. Upon returning they will receive the number of input frames that were consumed and the number of output frames that were generated.
The `ma_data_converter` API is a wrapper around format, channel and sample rate conversion and handles all of the data conversion you'll need which probably
makes it the best option if you need to do data conversion.
In addition to changes to the API design, a few other changes have been made to the data conversion pipeline:
- The sinc resampler has been removed. This was completely broken and never actually worked properly.
- The linear resampler now uses low-pass filtering to remove aliasing. The quality of the low-pass filter can be controlled via the resampler config with the
`lpfOrder` option, which has a maximum value of MA_MAX_FILTER_ORDER.
- Data conversion now supports s16 natively which runs through a fixed point pipeline. Previously everything needed to be converted to floating point before
processing, whereas now both s16 and f32 are natively supported. Other formats still require conversion to either s16 or f32 prior to processing, however
`ma_data_converter` will handle this for you.
Custom Memory Allocators
------------------------
miniaudio has always supported macro level customization for memory allocation via MA_MALLOC, MA_REALLOC and MA_FREE, however some scenarios require more
flexibility by allowing a user data pointer to be passed to the custom allocation routines. Support for this has been added to version 0.10 via the
`ma_allocation_callbacks` structure. Anything making use of heap allocations has been updated to accept this new structure.
The `ma_context_config` structure has been updated with a new member called `allocationCallbacks`. Leaving this set to it's defaults returned by
`ma_context_config_init()` will cause it to use MA_MALLOC, MA_REALLOC and MA_FREE. Likewise, The `ma_decoder_config` structure has been updated in the same
way, and leaving everything as-is after `ma_decoder_config_init()` will cause it to use the same defaults.
The following APIs have been updated to take a pointer to a `ma_allocation_callbacks` object. Setting this parameter to NULL will cause it to use defaults.
Otherwise they will use the relevant callback in the structure.
- ma_malloc()
- ma_realloc()
- ma_free()
- ma_aligned_malloc()
- ma_aligned_free()
- ma_rb_init() / ma_rb_init_ex()
- ma_pcm_rb_init() / ma_pcm_rb_init_ex()
Note that you can continue to use MA_MALLOC, MA_REALLOC and MA_FREE as per normal. These will continue to be used by default if you do not specify custom
allocation callbacks.
Buffer and Period Configuration Changes
---------------------------------------
The way in which the size of the internal buffer and periods are specified in the device configuration have changed. In previous versions, the config variables
`bufferSizeInFrames` and `bufferSizeInMilliseconds` defined the size of the entire buffer, with the size of a period being the size of this variable divided by
the period count. This became confusing because people would expect the value of `bufferSizeInFrames` or `bufferSizeInMilliseconds` to independantly determine
latency, when in fact it was that value divided by the period count that determined it. These variables have been removed and replaced with new ones called
`periodSizeInFrames` and `periodSizeInMilliseconds`.
These new configuration variables work in the same way as their predecessors in that if one is set to 0, the other will be used, but the main difference is
that you now set these to you desired latency rather than the size of the entire buffer. The benefit of this is that it's much easier and less confusing to
configure latency.
The following unused APIs have been removed:
ma_get_default_buffer_size_in_milliseconds()
ma_get_default_buffer_size_in_frames()
The following macros have been removed:
MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY
MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE
Other API Changes
-----------------
Other less major API changes have also been made in version 0.10.
`ma_device_set_stop_callback()` has been removed. If you require a stop callback, you must now set it via the device config just like the data callback.
The `ma_sine_wave` API has been replaced with a more general API called `ma_waveform`. This supports generation of different types of waveforms, including
sine, square, triangle and sawtooth. Use `ma_waveform_init()` in place of `ma_sine_wave_init()` to initialize the waveform object. This takes a configuration
object called `ma_waveform_config` which defines the properties of the waveform. Use `ma_waveform_config_init()` to initialize a `ma_waveform_config` object.
Use `ma_waveform_read_pcm_frames()` in place of `ma_sine_wave_read_f32()` and `ma_sine_wave_read_f32_ex()`.
`ma_convert_frames()` and `ma_convert_frames_ex()` have been changed. Both of these functions now take a new parameter called `frameCountOut` which specifies
the size of the output buffer in PCM frames. This has been added for safety. In addition to this, the parameters for `ma_convert_frames_ex()` have changed to
take a pointer to a `ma_data_converter_config` object to specify the input and output formats to convert between. This was done to make it more flexible, to
prevent the parameter list getting too long, and to prevent API breakage whenever a new conversion property is added.
`ma_calculate_frame_count_after_src()` has been renamed to `ma_calculate_frame_count_after_resampling()` for consistency with the new `ma_resampler` API.
Filters
-------
The following filters have been added:
|-------------|-------------------------------------------------------------------|
| API | Description |
|-------------|-------------------------------------------------------------------|
| ma_biquad | Biquad filter (transposed direct form 2) |
| ma_lpf1 | First order low-pass filter |
| ma_lpf2 | Second order low-pass filter |
| ma_lpf | High order low-pass filter (Butterworth) |
| ma_hpf1 | First order high-pass filter |
| ma_hpf2 | Second order high-pass filter |
| ma_hpf | High order high-pass filter (Butterworth) |
| ma_bpf2 | Second order band-pass filter |
| ma_bpf | High order band-pass filter |
| ma_peak2 | Second order peaking filter |
| ma_notch2 | Second order notching filter |
| ma_loshelf2 | Second order low shelf filter |
| ma_hishelf2 | Second order high shelf filter |
|-------------|-------------------------------------------------------------------|
These filters all support 32-bit floating point and 16-bit signed integer formats natively. Other formats need to be converted beforehand.
Sine, Square, Triangle and Sawtooth Waveforms
---------------------------------------------
Previously miniaudio supported only sine wave generation. This has now been generalized to support sine, square, triangle and sawtooth waveforms. The old
`ma_sine_wave` API has been removed and replaced with the `ma_waveform` API. Use `ma_waveform_config_init()` to initialize a config object, and then pass it
into `ma_waveform_init()`. Then use `ma_waveform_read_pcm_frames()` to read PCM data.
Noise Generation
----------------
A noise generation API has been added. This is used via the `ma_noise` API. Currently white, pink and Brownian noise is supported. The `ma_noise` API is
similar to the waveform API. Use `ma_noise_config_init()` to initialize a config object, and then pass it into `ma_noise_init()` to initialize a `ma_noise`
object. Then use `ma_noise_read_pcm_frames()` to read PCM data.
Miscellaneous Changes
---------------------
The MA_NO_STDIO option has been removed. This would disable file I/O APIs, however this has proven to be too hard to maintain for it's perceived value and was
therefore removed.
Internal functions have all been made static where possible. If you get warnings about unused functions, please submit a bug report.
The `ma_device` structure is no longer defined as being aligned to MA_SIMD_ALIGNMENT. This resulted in a possible crash when allocating a `ma_device` object on
the heap, but not aligning it to MA_SIMD_ALIGNMENT. This crash would happen due to the compiler seeing the alignment specified on the structure and assuming it
was always aligned as such and thinking it was safe to emit alignment-dependant SIMD instructions. Since miniaudio's philosophy is for things to just work,
this has been removed from all structures.
Results codes have been overhauled. Unnecessary result codes have been removed, and some have been renumbered for organisation purposes. If you are are binding
maintainer you will need to update your result codes. Support has also been added for retrieving a human readable description of a given result code via the
`ma_result_description()` API.
ALSA: The automatic format conversion, channel conversion and resampling performed by ALSA is now disabled by default as they were causing some compatibility
issues with certain devices and configurations. These can be individually enabled via the device config:
```c
deviceConfig.alsa.noAutoFormat = MA_TRUE;
deviceConfig.alsa.noAutoChannels = MA_TRUE;
deviceConfig.alsa.noAutoResample = MA_TRUE;
```
*/
/*
RELEASE NOTES - VERSION 0.9.x
=============================
Version 0.9 includes major API changes, centered mostly around full-duplex and the rebrand to "miniaudio". Before I go into detail about the major changes I
would like to apologize. I know it's annoying dealing with breaking API changes, but I think it's best to get these changes out of the way now while the
library is still relatively young and unknown.
There's been a lot of refactoring with this release so there's a good chance a few bugs have been introduced. I apologize in advance for this. You may want to
hold off on upgrading for the short term if you're worried. If mini_al v0.8.14 works for you, and you don't need full-duplex support, you can avoid upgrading
(though you won't be getting future bug fixes).
Rebranding to "miniaudio"
-------------------------
The decision was made to rename mini_al to miniaudio. Don't worry, it's the same project. The reason for this is simple:
1) Having the word "audio" in the title makes it immediately clear that the library is related to audio; and
2) I don't like the look of the underscore.
This rebrand has necessitated a change in namespace from "mal" to "ma". I know this is annoying, and I apologize, but it's better to get this out of the road
now rather than later. Also, since there are necessary API changes for full-duplex support I think it's better to just get the namespace change over and done
with at the same time as the full-duplex changes. I'm hoping this will be the last of the major API changes. Fingers crossed!
The implementation define is now "#define MINIAUDIO_IMPLEMENTATION". You can also use "#define MA_IMPLEMENTATION" if that's your preference.
Full-Duplex Support
-------------------
The major feature added to version 0.9 is full-duplex. This has necessitated a few API changes.
1) The data callback has now changed. Previously there was one type of callback for playback and another for capture. I wanted to avoid a third callback just
for full-duplex so the decision was made to break this API and unify the callbacks. Now, there is just one callback which is the same for all three modes
(playback, capture, duplex). The new callback looks like the following:
void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount);
This callback allows you to move data straight out of the input buffer and into the output buffer in full-duplex mode. In playback-only mode, pInput will be
null. Likewise, pOutput will be null in capture-only mode. The sample count is no longer returned from the callback since it's not necessary for miniaudio
anymore.
2) The device config needed to change in order to support full-duplex. Full-duplex requires the ability to allow the client to choose a different PCM format
for the playback and capture sides. The old ma_device_config object simply did not allow this and needed to change. With these changes you now specify the
device ID, format, channels, channel map and share mode on a per-playback and per-capture basis (see example below). The sample rate must be the same for
playback and capture.
Since the device config API has changed I have also decided to take the opportunity to simplify device initialization. Now, the device ID, device type and
callback user data are set in the config. ma_device_init() is now simplified down to taking just the context, device config and a pointer to the device
object being initialized. The rationale for this change is that it just makes more sense to me that these are set as part of the config like everything
else.
Example device initialization:
ma_device_config config = ma_device_config_init(ma_device_type_duplex); // Or ma_device_type_playback or ma_device_type_capture.
config.playback.pDeviceID = &myPlaybackDeviceID; // Or NULL for the default playback device.
config.playback.format = ma_format_f32;
config.playback.channels = 2;
config.capture.pDeviceID = &myCaptureDeviceID; // Or NULL for the default capture device.
config.capture.format = ma_format_s16;
config.capture.channels = 1;
config.sampleRate = 44100;
config.dataCallback = data_callback;
config.pUserData = &myUserData;
result = ma_device_init(&myContext, &config, &device);
if (result != MA_SUCCESS) {
... handle error ...
}
Note that the "onDataCallback" member of ma_device_config has been renamed to "dataCallback". Also, "onStopCallback" has been renamed to "stopCallback".
This is the first pass for full-duplex and there is a known bug. You will hear crackling on the following backends when sample rate conversion is required for
the playback device:
- Core Audio
- JACK
- AAudio
- OpenSL
- WebAudio
In addition to the above, not all platforms have been absolutely thoroughly tested simply because I lack the hardware for such thorough testing. If you
experience a bug, an issue report on GitHub or an email would be greatly appreciated (and a sample program that reproduces the issue if possible).
Other API Changes
-----------------
In addition to the above, the following API changes have been made:
- The log callback is no longer passed to ma_context_config_init(). Instead you need to set it manually after initialization.
- The onLogCallback member of ma_context_config has been renamed to "logCallback".
- The log callback now takes a logLevel parameter. The new callback looks like: void log_callback(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message)
- You can use ma_log_level_to_string() to convert the logLevel to human readable text if you want to log it.
- Some APIs have been renamed:
- mal_decoder_read() -> ma_decoder_read_pcm_frames()
- mal_decoder_seek_to_frame() -> ma_decoder_seek_to_pcm_frame()
- mal_sine_wave_read() -> ma_sine_wave_read_f32()
- mal_sine_wave_read_ex() -> ma_sine_wave_read_f32_ex()
- Some APIs have been removed:
- mal_device_get_buffer_size_in_bytes()
- mal_device_set_recv_callback()
- mal_device_set_send_callback()
- mal_src_set_input_sample_rate()
- mal_src_set_output_sample_rate()
- Error codes have been rearranged. If you're a binding maintainer you will need to update.
- The ma_backend enums have been rearranged to priority order. The rationale for this is to simplify automatic backend selection and to make it easier to see
the priority. If you're a binding maintainer you will need to update.
- ma_dsp has been renamed to ma_pcm_converter. The rationale for this change is that I'm expecting "ma_dsp" to conflict with some future planned high-level
APIs.
- For functions that take a pointer/count combo, such as ma_decoder_read_pcm_frames(), the parameter order has changed so that the pointer comes before the
count. The rationale for this is to keep it consistent with things like memcpy().
Miscellaneous Changes
---------------------
The following miscellaneous changes have also been made.
- The AAudio backend has been added for Android 8 and above. This is Android's new "High-Performance Audio" API. (For the record, this is one of the nicest
audio APIs out there, just behind the BSD audio APIs).
- The WebAudio backend has been added. This is based on ScriptProcessorNode. This removes the need for SDL.
- The SDL and OpenAL backends have been removed. These were originally implemented to add support for platforms for which miniaudio was not explicitly
supported. These are no longer needed and have therefore been removed.
- Device initialization now fails if the requested share mode is not supported. If you ask for exclusive mode, you either get an exclusive mode device, or an
error. The rationale for this change is to give the client more control over how to handle cases when the desired shared mode is unavailable.
- A lock-free ring buffer API has been added. There are two varients of this. "ma_rb" operates on bytes, whereas "ma_pcm_rb" operates on PCM frames.
- The library is now licensed as a choice of Public Domain (Unlicense) _or_ MIT-0 (No Attribution) which is the same as MIT, but removes the attribution
requirement. The rationale for this is to support countries that don't recognize public domain.
*/
/*
REVISION HISTORY
================
v0.10.21 - 2020-10-30
- Add ma_is_backend_enabled() and ma_get_enabled_backends() for retrieving enabled backends at run-time.
- WASAPI: Fix a copy and paste bug relating to loopback mode.
- Core Audio: Fix a bug when using multiple contexts.
- Core Audio: Fix a compilation warning.
- Core Audio: Improvements to sample rate selection.
- Core Audio: Improvements to format/channels/rate selection when requesting defaults.
- Core Audio: Add notes regarding the Apple notarization process.
- Fix some bugs due to null pointer dereferences.
v0.10.20 - 2020-10-06
- Fix build errors with UWP.
- Minor documentation updates.
v0.10.19 - 2020-09-22
- WASAPI: Return an error when exclusive mode is requested, but the native format is not supported by miniaudio.
- Fix a bug where ma_decoder_seek_to_pcm_frames() never returns MA_SUCCESS even though it was successful.
- Store the sample rate in the `ma_lpf` and `ma_hpf` structures.
v0.10.18 - 2020-08-30
- Fix build errors with VC6.
- Fix a bug in channel converter for s32 format.
- Change channel converter configs to use the default channel map instead of a blank channel map when no channel map is specified when initializing the
config. This fixes an issue where the optimized mono expansion path would never get used.
- Use a more appropriate default format for FLAC decoders. This will now use ma_format_s16 when the FLAC is encoded as 16-bit.
- Update FLAC decoder.
- Update links to point to the new repository location (https://github.com/mackron/miniaudio).
v0.10.17 - 2020-08-28
- Fix an error where the WAV codec is incorrectly excluded from the build depending on which compile time options are set.
- Fix a bug in ma_audio_buffer_read_pcm_frames() where it isn't returning the correct number of frames processed.
- Fix compilation error on Android.
- Core Audio: Fix a bug with full-duplex mode.
- Add ma_decoder_get_cursor_in_pcm_frames().
- Update WAV codec.
v0.10.16 - 2020-08-14
- WASAPI: Fix a potential crash due to using an uninitialized variable.
- OpenSL: Enable runtime linking.
- OpenSL: Fix a multithreading bug when initializing and uninitializing multiple contexts at the same time.
- iOS: Improvements to device enumeration.
- Fix a crash in ma_data_source_read_pcm_frames() when the output frame count parameter is NULL.
- Fix a bug in ma_data_source_read_pcm_frames() where looping doesn't work.
- Fix some compilation warnings on Windows when both DirectSound and WinMM are disabled.
- Fix some compilation warnings when no decoders are enabled.
- Add ma_audio_buffer_get_available_frames().
- Add ma_decoder_get_available_frames().
- Add sample rate to ma_data_source_get_data_format().
- Change volume APIs to take 64-bit frame counts.
- Updates to documentation.
v0.10.15 - 2020-07-15
- Fix a bug when converting bit-masked channel maps to miniaudio channel maps. This affects the WASAPI and OpenSL backends.
v0.10.14 - 2020-07-14
- Fix compilation errors on Android.
- Fix compilation errors with -march=armv6.
- Updates to the documentation.
v0.10.13 - 2020-07-11
- Fix some potential buffer overflow errors with channel maps when channel counts are greater than MA_MAX_CHANNELS.
- Fix compilation error on Emscripten.
- Silence some unused function warnings.
- Increase the default buffer size on the Web Audio backend. This fixes glitching issues on some browsers.
- Bring FLAC decoder up-to-date with dr_flac.
- Bring MP3 decoder up-to-date with dr_mp3.
v0.10.12 - 2020-07-04
- Fix compilation errors on the iOS build.
v0.10.11 - 2020-06-28
- Fix some bugs with device tracking on Core Audio.
- Updates to documentation.
v0.10.10 - 2020-06-26
- Add include guard for the implementation section.
- Mark ma_device_sink_info_callback() as static.
- Fix compilation errors with MA_NO_DECODING and MA_NO_ENCODING.
- Fix compilation errors with MA_NO_DEVICE_IO
v0.10.9 - 2020-06-24
- Amalgamation of dr_wav, dr_flac and dr_mp3. With this change, including the header section of these libraries before the implementation of miniaudio is no
longer required. Decoding of WAV, FLAC and MP3 should be supported seamlessly without any additional libraries. Decoders can be excluded from the build
with the following options:
- MA_NO_WAV
- MA_NO_FLAC
- MA_NO_MP3
If you get errors about multiple definitions you need to either enable the options above, move the implementation of dr_wav, dr_flac and/or dr_mp3 to before
the implementation of miniaudio, or update dr_wav, dr_flac and/or dr_mp3.
- Changes to the internal atomics library. This has been replaced with c89atomic.h which is embedded within this file.
- Fix a bug when a decoding backend reports configurations outside the limits of miniaudio's decoder abstraction.
- Fix the UWP build.
- Fix the Core Audio build.
- Fix the -std=c89 build on GCC.
v0.10.8 - 2020-06-22
- Remove dependency on ma_context from mutexes.
- Change ma_data_source_read_pcm_frames() to return a result code and output the frames read as an output parameter.
- Change ma_data_source_seek_pcm_frames() to return a result code and output the frames seeked as an output parameter.
- Change ma_audio_buffer_unmap() to return MA_AT_END when the end has been reached. This should be considered successful.
- Change playback.pDeviceID and capture.pDeviceID to constant pointers in ma_device_config.
- Add support for initializing decoders from a virtual file system object. This is achieved via the ma_vfs API and allows the application to customize file
IO for the loading and reading of raw audio data. Passing in NULL for the VFS will use defaults. New APIs:
- ma_decoder_init_vfs()
- ma_decoder_init_vfs_wav()
- ma_decoder_init_vfs_flac()
- ma_decoder_init_vfs_mp3()
- ma_decoder_init_vfs_vorbis()
- ma_decoder_init_vfs_w()
- ma_decoder_init_vfs_wav_w()
- ma_decoder_init_vfs_flac_w()
- ma_decoder_init_vfs_mp3_w()
- ma_decoder_init_vfs_vorbis_w()
- Add support for memory mapping to ma_data_source.
- ma_data_source_map()
- ma_data_source_unmap()
- Add ma_offset_pcm_frames_ptr() and ma_offset_pcm_frames_const_ptr() which can be used for offsetting a pointer by a specified number of PCM frames.
- Add initial implementation of ma_yield() which is useful for spin locks which will be used in some upcoming work.
- Add documentation for log levels.
- The ma_event API has been made public in preparation for some uncoming work.
- Fix a bug in ma_decoder_seek_to_pcm_frame() where the internal sample rate is not being taken into account for determining the seek location.
- Fix some bugs with the linear resampler when dynamically changing the sample rate.
- Fix compilation errors with MA_NO_DEVICE_IO.
- Fix some warnings with GCC and -std=c89.
- Fix some formatting warnings with GCC and -Wall and -Wpedantic.
- Fix some warnings with VC6.
- Minor optimization to ma_copy_pcm_frames(). This is now a no-op when the input and output buffers are the same.
v0.10.7 - 2020-05-25
- Fix a compilation error in the C++ build.
- Silence a warning.
v0.10.6 - 2020-05-24
- Change ma_clip_samples_f32() and ma_clip_pcm_frames_f32() to take a 64-bit sample/frame count.
- Change ma_zero_pcm_frames() to clear to 128 for ma_format_u8.
- Add ma_silence_pcm_frames() which replaces ma_zero_pcm_frames(). ma_zero_pcm_frames() will be removed in version 0.11.
- Add support for u8, s24 and s32 formats to ma_channel_converter.
- Add compile-time and run-time version querying.
- MA_VERSION_MINOR
- MA_VERSION_MAJOR
- MA_VERSION_REVISION
- MA_VERSION_STRING
- ma_version()
- ma_version_string()
- Add ma_audio_buffer for reading raw audio data directly from memory.
- Fix a bug in shuffle mode in ma_channel_converter.
- Fix compilation errors in certain configurations for ALSA and PulseAudio.
- The data callback now initializes the output buffer to 128 when the playback sample format is ma_format_u8.
v0.10.5 - 2020-05-05
- Change ma_zero_pcm_frames() to take a 64-bit frame count.
- Add ma_copy_pcm_frames().
- Add MA_NO_GENERATION build option to exclude the `ma_waveform` and `ma_noise` APIs from the build.
- Add support for formatted logging to the VC6 build.
- Fix a crash in the linear resampler when LPF order is 0.
- Fix compilation errors and warnings with older versions of Visual Studio.
- Minor documentation updates.
v0.10.4 - 2020-04-12
- Fix a data conversion bug when converting from the client format to the native device format.
v0.10.3 - 2020-04-07
- Bring up to date with breaking changes to dr_mp3.
- Remove MA_NO_STDIO. This was causing compilation errors and the maintenance cost versus practical benefit is no longer worthwhile.
- Fix a bug with data conversion where it was unnecessarily converting to s16 or f32 and then straight back to the original format.
- Fix compilation errors and warnings with Visual Studio 2005.
- ALSA: Disable ALSA's automatic data conversion by default and add configuration options to the device config:
- alsa.noAutoFormat
- alsa.noAutoChannels
- alsa.noAutoResample
- WASAPI: Add some overrun recovery for ma_device_type_capture devices.
v0.10.2 - 2020-03-22
- Decorate some APIs with MA_API which were missed in the previous version.
- Fix a bug in ma_linear_resampler_set_rate() and ma_linear_resampler_set_rate_ratio().
v0.10.1 - 2020-03-17
- Add MA_API decoration. This can be customized by defining it before including miniaudio.h.
- Fix a bug where opening a file would return a success code when in fact it failed.
- Fix compilation errors with Visual Studio 6 and 2003.
- Fix warnings on macOS.
v0.10.0 - 2020-03-07
- API CHANGE: Refactor data conversion APIs
- ma_format_converter has been removed. Use ma_convert_pcm_frames_format() instead.
- ma_channel_router has been replaced with ma_channel_converter.
- ma_src has been replaced with ma_resampler
- ma_pcm_converter has been replaced with ma_data_converter
- API CHANGE: Add support for custom memory allocation callbacks. The following APIs have been updated to take an extra parameter for the allocation
callbacks:
- ma_malloc()
- ma_realloc()
- ma_free()
- ma_aligned_malloc()
- ma_aligned_free()
- ma_rb_init() / ma_rb_init_ex()
- ma_pcm_rb_init() / ma_pcm_rb_init_ex()
- API CHANGE: Simplify latency specification in device configurations. The bufferSizeInFrames and bufferSizeInMilliseconds parameters have been replaced with
periodSizeInFrames and periodSizeInMilliseconds respectively. The previous variables defined the size of the entire buffer, whereas the new ones define the
size of a period. The following APIs have been removed since they are no longer relevant:
- ma_get_default_buffer_size_in_milliseconds()
- ma_get_default_buffer_size_in_frames()
- API CHANGE: ma_device_set_stop_callback() has been removed. If you require a stop callback, you must now set it via the device config just like the data
callback.
- API CHANGE: The ma_sine_wave API has been replaced with ma_waveform. The following APIs have been removed:
- ma_sine_wave_init()
- ma_sine_wave_read_f32()
- ma_sine_wave_read_f32_ex()
- API CHANGE: ma_convert_frames() has been updated to take an extra parameter which is the size of the output buffer in PCM frames. Parameters have also been
reordered.
- API CHANGE: ma_convert_frames_ex() has been changed to take a pointer to a ma_data_converter_config object to specify the input and output formats to
convert between.
- API CHANGE: ma_calculate_frame_count_after_src() has been renamed to ma_calculate_frame_count_after_resampling().
- Add support for the following filters:
- Biquad (ma_biquad)
- First order low-pass (ma_lpf1)
- Second order low-pass (ma_lpf2)
- Low-pass with configurable order (ma_lpf)
- First order high-pass (ma_hpf1)
- Second order high-pass (ma_hpf2)
- High-pass with configurable order (ma_hpf)
- Second order band-pass (ma_bpf2)
- Band-pass with configurable order (ma_bpf)
- Second order peaking EQ (ma_peak2)
- Second order notching (ma_notch2)
- Second order low shelf (ma_loshelf2)
- Second order high shelf (ma_hishelf2)
- Add waveform generation API (ma_waveform) with support for the following:
- Sine
- Square
- Triangle
- Sawtooth
- Add noise generation API (ma_noise) with support for the following:
- White
- Pink
- Brownian
- Add encoding API (ma_encoder). This only supports outputting to WAV files via dr_wav.
- Add ma_result_description() which is used to retrieve a human readable description of a given result code.
- Result codes have been changed. Binding maintainers will need to update their result code constants.
- More meaningful result codes are now returned when a file fails to open.
- Internal functions have all been made static where possible.
- Fix potential crash when ma_device object's are not aligned to MA_SIMD_ALIGNMENT.
- Fix a bug in ma_decoder_get_length_in_pcm_frames() where it was returning the length based on the internal sample rate rather than the output sample rate.
- Fix bugs in some backends where the device is not drained properly in ma_device_stop().
- Improvements to documentation.
v0.9.10 - 2020-01-15
- Fix compilation errors due to #if/#endif mismatches.
- WASAPI: Fix a bug where automatic stream routing is being performed for devices that are initialized with an explicit device ID.
- iOS: Fix a crash on device uninitialization.
v0.9.9 - 2020-01-09
- Fix compilation errors with MinGW.
- Fix compilation errors when compiling on Apple platforms.
- WASAPI: Add support for disabling hardware offloading.
- WASAPI: Add support for disabling automatic stream routing.
- Core Audio: Fix bugs in the case where the internal device uses deinterleaved buffers.
- Core Audio: Add support for controlling the session category (AVAudioSessionCategory) and options (AVAudioSessionCategoryOptions).
- JACK: Fix bug where incorrect ports are connected.
v0.9.8 - 2019-10-07
- WASAPI: Fix a potential deadlock when starting a full-duplex device.
- WASAPI: Enable automatic resampling by default. Disable with config.wasapi.noAutoConvertSRC.
- Core Audio: Fix bugs with automatic stream routing.
- Add support for controlling whether or not the content of the output buffer passed in to the data callback is pre-initialized
to zero. By default it will be initialized to zero, but this can be changed by setting noPreZeroedOutputBuffer in the device
config. Setting noPreZeroedOutputBuffer to true will leave the contents undefined.
- Add support for clipping samples after the data callback has returned. 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.
- Add support for master volume control for devices.
- Use ma_device_set_master_volume() to set the volume to a factor between 0 and 1, where 0 is silence and 1 is full volume.
- Use ma_device_set_master_gain_db() to set the volume in decibels where 0 is full volume and < 0 reduces the volume.
- Fix warnings emitted by GCC when `__inline__` is undefined or defined as nothing.
v0.9.7 - 2019-08-28
- Add support for loopback mode (WASAPI only).
- To use this, set the device type to ma_device_type_loopback, and then fill out the capture section of the device config.
- If you need to capture from a specific output device, set the capture device ID to that of a playback device.
- Fix a crash when an error is posted in ma_device_init().
- Fix a compilation error when compiling for ARM architectures.
- Fix a bug with the audio(4) backend where the device is incorrectly being opened in non-blocking mode.
- Fix memory leaks in the Core Audio backend.
- Minor refactoring to the WinMM, ALSA, PulseAudio, OSS, audio(4), sndio and null backends.
v0.9.6 - 2019-08-04
- Add support for loading decoders using a wchar_t string for file paths.
- Don't trigger an assert when ma_device_start() is called on a device that is already started. This will now log a warning
and return MA_INVALID_OPERATION. The same applies for ma_device_stop().
- Try fixing an issue with PulseAudio taking a long time to start playback.
- Fix a bug in ma_convert_frames() and ma_convert_frames_ex().
- Fix memory leaks in the WASAPI backend.
- Fix a compilation error with Visual Studio 2010.
v0.9.5 - 2019-05-21
- Add logging to ma_dlopen() and ma_dlsym().
- Add ma_decoder_get_length_in_pcm_frames().
- Fix a bug with capture on the OpenSL|ES backend.
- Fix a bug with the ALSA backend where a device would not restart after being stopped.
v0.9.4 - 2019-05-06
- Add support for C89. With this change, miniaudio should compile clean with GCC/Clang with "-std=c89 -ansi -pedantic" and
Microsoft compilers back to VC6. Other compilers should also work, but have not been tested.
v0.9.3 - 2019-04-19
- Fix compiler errors on GCC when compiling with -std=c99.
v0.9.2 - 2019-04-08
- Add support for per-context user data.
- Fix a potential bug with context configs.
- Fix some bugs with PulseAudio.
v0.9.1 - 2019-03-17
- Fix a bug where the output buffer is not getting zeroed out before calling the data callback. This happens when
the device is running in passthrough mode (not doing any data conversion).
- Fix an issue where the data callback is getting called too frequently on the WASAPI and DirectSound backends.
- Fix error on the UWP build.
- Fix a build error on Apple platforms.
v0.9 - 2019-03-06
- Rebranded to "miniaudio". All namespaces have been renamed from "mal" to "ma".
- API CHANGE: ma_device_init() and ma_device_config_init() have changed significantly:
- The device type, device ID and user data pointer have moved from ma_device_init() to the config.
- All variations of ma_device_config_init_*() have been removed in favor of just ma_device_config_init().
- ma_device_config_init() now takes only one parameter which is the device type. All other properties need
to be set on the returned object directly.
- The onDataCallback and onStopCallback members of ma_device_config have been renamed to "dataCallback"
and "stopCallback".
- The ID of the physical device is now split into two: one for the playback device and the other for the
capture device. This is required for full-duplex. These are named "pPlaybackDeviceID" and "pCaptureDeviceID".
- API CHANGE: The data callback has changed. It now uses a unified callback for all device types rather than
being separate for each. It now takes two pointers - one containing input data and the other output data. This
design in required for full-duplex. The return value is now void instead of the number of frames written. The
new callback looks like the following:
void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount);
- API CHANGE: Remove the log callback parameter from ma_context_config_init(). With this change,
ma_context_config_init() now takes no parameters and the log callback is set via the structure directly. The
new policy for config initialization is that only mandatory settings are passed in to *_config_init(). The
"onLog" member of ma_context_config has been renamed to "logCallback".
- API CHANGE: Remove ma_device_get_buffer_size_in_bytes().
- API CHANGE: Rename decoding APIs to "pcm_frames" convention.
- mal_decoder_read() -> ma_decoder_read_pcm_frames()
- mal_decoder_seek_to_frame() -> ma_decoder_seek_to_pcm_frame()
- API CHANGE: Rename sine wave reading APIs to f32 convention.
- mal_sine_wave_read() -> ma_sine_wave_read_f32()
- mal_sine_wave_read_ex() -> ma_sine_wave_read_f32_ex()
- API CHANGE: Remove some deprecated APIs
- mal_device_set_recv_callback()
- mal_device_set_send_callback()
- mal_src_set_input_sample_rate()
- mal_src_set_output_sample_rate()
- API CHANGE: Add log level to the log callback. New signature:
- void on_log(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message)
- API CHANGE: Changes to result codes. Constants have changed and unused codes have been removed. If you're
a binding mainainer you will need to update your result code constants.
- API CHANGE: Change the order of the ma_backend enums to priority order. If you are a binding maintainer, you
will need to update.
- API CHANGE: Rename mal_dsp to ma_pcm_converter. All functions have been renamed from mal_dsp_*() to
ma_pcm_converter_*(). All structures have been renamed from mal_dsp* to ma_pcm_converter*.
- API CHANGE: Reorder parameters of ma_decoder_read_pcm_frames() to be consistent with the new parameter order scheme.
- The resampling algorithm has been changed from sinc to linear. The rationale for this is that the sinc implementation
is too inefficient right now. This will hopefully be improved at a later date.
- Device initialization will no longer fall back to shared mode if exclusive mode is requested but is unusable.
With this change, if you request an device in exclusive mode, but exclusive mode is not supported, it will not
automatically fall back to shared mode. The client will need to reinitialize the device in shared mode if that's
what they want.
- Add ring buffer API. This is ma_rb and ma_pcm_rb, the difference being that ma_rb operates on bytes and
ma_pcm_rb operates on PCM frames.
- Add Web Audio backend. This is used when compiling with Emscripten. The SDL backend, which was previously
used for web support, will be removed in a future version.
- Add AAudio backend (Android Audio). This is the new priority backend for Android. Support for AAudio starts
with Android 8. OpenSL|ES is used as a fallback for older versions of Android.
- Remove OpenAL and SDL backends.
- Fix a possible deadlock when rapidly stopping the device after it has started.
- Update documentation.
- Change licensing to a choice of public domain _or_ MIT-0 (No Attribution).
v0.8.14 - 2018-12-16
- Core Audio: Fix a bug where the device state is not set correctly after stopping.
- Add support for custom weights to the channel router.
- Update decoders to use updated APIs in dr_flac, dr_mp3 and dr_wav.
v0.8.13 - 2018-12-04
- Core Audio: Fix a bug with channel mapping.
- Fix a bug with channel routing where the back/left and back/right channels have the wrong weight.
v0.8.12 - 2018-11-27
- Drop support for SDL 1.2. The Emscripten build now requires "-s USE_SDL=2".
- Fix a linking error with ALSA.
- Fix a bug on iOS where the device name is not set correctly.
v0.8.11 - 2018-11-21
- iOS bug fixes.
- Minor tweaks to PulseAudio.
v0.8.10 - 2018-10-21
- Core Audio: Fix a hang when uninitializing a device.
- Fix a bug where an incorrect value is returned from mal_device_stop().
v0.8.9 - 2018-09-28
- Fix a bug with the SDL backend where device initialization fails.
v0.8.8 - 2018-09-14
- Fix Linux build with the ALSA backend.
- Minor documentation fix.
v0.8.7 - 2018-09-12
- Fix a bug with UWP detection.
v0.8.6 - 2018-08-26
- Automatically switch the internal device when the default device is unplugged. Note that this is still in the
early stages and not all backends handle this the same way. As of this version, this will not detect a default
device switch when changed from the operating system's audio preferences (unless the backend itself handles
this automatically). This is not supported in exclusive mode.
- WASAPI and Core Audio: Add support for stream routing. When the application is using a default device and the
user switches the default device via the operating system's audio preferences, miniaudio will automatically switch
the internal device to the new default. This is not supported in exclusive mode.
- WASAPI: Add support for hardware offloading via IAudioClient2. Only supported on Windows 8 and newer.
- WASAPI: Add support for low-latency shared mode via IAudioClient3. Only supported on Windows 10 and newer.
- Add support for compiling the UWP build as C.
- mal_device_set_recv_callback() and mal_device_set_send_callback() have been deprecated. You must now set this
when the device is initialized with mal_device_init*(). These will be removed in version 0.9.0.
v0.8.5 - 2018-08-12
- Add support for specifying the size of a device's buffer in milliseconds. You can still set the buffer size in
frames if that suits you. When bufferSizeInFrames is 0, bufferSizeInMilliseconds will be used. If both are non-0
then bufferSizeInFrames will take priority. If both are set to 0 the default buffer size is used.
- Add support for the audio(4) backend to OpenBSD.
- Fix a bug with the ALSA backend that was causing problems on Raspberry Pi. This significantly improves the
Raspberry Pi experience.
- Fix a bug where an incorrect number of samples is returned from sinc resampling.
- Add support for setting the value to be passed to internal calls to CoInitializeEx().
- WASAPI and WinMM: Stop the device when it is unplugged.
v0.8.4 - 2018-08-06
- Add sndio backend for OpenBSD.
- Add audio(4) backend for NetBSD.
- Drop support for the OSS backend on everything except FreeBSD and DragonFly BSD.
- Formats are now native-endian (were previously little-endian).
- Mark some APIs as deprecated:
- mal_src_set_input_sample_rate() and mal_src_set_output_sample_rate() are replaced with mal_src_set_sample_rate().
- mal_dsp_set_input_sample_rate() and mal_dsp_set_output_sample_rate() are replaced with mal_dsp_set_sample_rate().
- Fix a bug when capturing using the WASAPI backend.
- Fix some aliasing issues with resampling, specifically when increasing the sample rate.
- Fix warnings.
v0.8.3 - 2018-07-15
- Fix a crackling bug when resampling in capture mode.
- Core Audio: Fix a bug where capture does not work.
- ALSA: Fix a bug where the worker thread can get stuck in an infinite loop.
- PulseAudio: Fix a bug where mal_context_init() succeeds when PulseAudio is unusable.
- JACK: Fix a bug where mal_context_init() succeeds when JACK is unusable.
v0.8.2 - 2018-07-07
- Fix a bug on macOS with Core Audio where the internal callback is not called.
v0.8.1 - 2018-07-06
- Fix compilation errors and warnings.
v0.8 - 2018-07-05
- Changed MAL_IMPLEMENTATION to MINI_AL_IMPLEMENTATION for consistency with other libraries. The old
way is still supported for now, but you should update as it may be removed in the future.
- API CHANGE: Replace device enumeration APIs. mal_enumerate_devices() has been replaced with
mal_context_get_devices(). An additional low-level device enumration API has been introduced called
mal_context_enumerate_devices() which uses a callback to report devices.
- API CHANGE: Rename mal_get_sample_size_in_bytes() to mal_get_bytes_per_sample() and add
mal_get_bytes_per_frame().
- API CHANGE: Replace mal_device_config.preferExclusiveMode with mal_device_config.shareMode.
- This new config can be set to mal_share_mode_shared (default) or mal_share_mode_exclusive.
- API CHANGE: Remove excludeNullDevice from mal_context_config.alsa.
- API CHANGE: Rename MAL_MAX_SAMPLE_SIZE_IN_BYTES to MAL_MAX_PCM_SAMPLE_SIZE_IN_BYTES.
- API CHANGE: Change the default channel mapping to the standard Microsoft mapping.
- API CHANGE: Remove backend-specific result codes.
- API CHANGE: Changes to the format conversion APIs (mal_pcm_f32_to_s16(), etc.)
- Add support for Core Audio (Apple).
- Add support for PulseAudio.
- This is the highest priority backend on Linux (higher priority than ALSA) since it is commonly
installed by default on many of the popular distros and offer's more seamless integration on
platforms where PulseAudio is used. In addition, if PulseAudio is installed and running (which
is extremely common), it's better to just use PulseAudio directly rather than going through the
"pulse" ALSA plugin (which is what the "default" ALSA device is likely set to).
- Add support for JACK.
- Remove dependency on asound.h for the ALSA backend. This means the ALSA development packages are no
longer required to build miniaudio.
- Remove dependency on dsound.h for the DirectSound backend. This fixes build issues with some
distributions of MinGW.
- Remove dependency on audioclient.h for the WASAPI backend. This fixes build issues with some
distributions of MinGW.
- Add support for dithering to format conversion.
- Add support for configuring the priority of the worker thread.
- Add a sine wave generator.
- Improve efficiency of sample rate conversion.
- Introduce the notion of standard channel maps. Use mal_get_standard_channel_map().
- Introduce the notion of default device configurations. A default config uses the same configuration
as the backend's internal device, and as such results in a pass-through data transmission pipeline.
- Add support for passing in NULL for the device config in mal_device_init(), which uses a default
config. This requires manually calling mal_device_set_send/recv_callback().
- Add support for decoding from raw PCM data (mal_decoder_init_raw(), etc.)
- Make mal_device_init_ex() more robust.
- Make some APIs more const-correct.
- Fix errors with SDL detection on Apple platforms.
- Fix errors with OpenAL detection.
- Fix some memory leaks.
- Fix a bug with opening decoders from memory.
- Early work on SSE2, AVX2 and NEON optimizations.
- Miscellaneous bug fixes.
- Documentation updates.
v0.7 - 2018-02-25
- API CHANGE: Change mal_src_read_frames() and mal_dsp_read_frames() to use 64-bit sample counts.
- Add decoder APIs for loading WAV, FLAC, Vorbis and MP3 files.
- Allow opening of devices without a context.
- In this case the context is created and managed internally by the device.
- Change the default channel mapping to the same as that used by FLAC.
- Fix build errors with macOS.
v0.6c - 2018-02-12
- Fix build errors with BSD/OSS.
v0.6b - 2018-02-03
- Fix some warnings when compiling with Visual C++.
v0.6a - 2018-01-26
- Fix errors with channel mixing when increasing the channel count.
- Improvements to the build system for the OpenAL backend.
- Documentation fixes.
v0.6 - 2017-12-08
- API CHANGE: Expose and improve mutex APIs. If you were using the mutex APIs before this version you'll
need to update.
- API CHANGE: SRC and DSP callbacks now take a pointer to a mal_src and mal_dsp object respectively.
- API CHANGE: Improvements to event and thread APIs. These changes make these APIs more consistent.
- Add support for SDL and Emscripten.
- Simplify the build system further for when development packages for various backends are not installed.
With this change, when the compiler supports __has_include, backends without the relevant development
packages installed will be ignored. This fixes the build for old versions of MinGW.
- Fixes to the Android build.
- Add mal_convert_frames(). This is a high-level helper API for performing a one-time, bulk conversion of
audio data to a different format.
- Improvements to f32 -> u8/s16/s24/s32 conversion routines.
- Fix a bug where the wrong value is returned from mal_device_start() for the OpenSL backend.
- Fixes and improvements for Raspberry Pi.
- Warning fixes.
v0.5 - 2017-11-11
- API CHANGE: The mal_context_init() function now takes a pointer to a mal_context_config object for
configuring the context. The works in the same kind of way as the device config. The rationale for this
change is to give applications better control over context-level properties, add support for backend-
specific configurations, and support extensibility without breaking the API.
- API CHANGE: The alsa.preferPlugHW device config variable has been removed since it's not really useful for
anything anymore.
- ALSA: By default, device enumeration will now only enumerate over unique card/device pairs. Applications
can enable verbose device enumeration by setting the alsa.useVerboseDeviceEnumeration context config
variable.
- ALSA: When opening a device in shared mode (the default), the dmix/dsnoop plugin will be prioritized. If
this fails it will fall back to the hw plugin. With this change the preferExclusiveMode config is now
honored. Note that this does not happen when alsa.useVerboseDeviceEnumeration is set to true (see above)
which is by design.
- ALSA: Add support for excluding the "null" device using the alsa.excludeNullDevice context config variable.
- ALSA: Fix a bug with channel mapping which causes an assertion to fail.
- Fix errors with enumeration when pInfo is set to NULL.
- OSS: Fix a bug when starting a device when the client sends 0 samples for the initial buffer fill.
v0.4 - 2017-11-05
- API CHANGE: The log callback is now per-context rather than per-device and as is thus now passed to
mal_context_init(). The rationale for this change is that it allows applications to capture diagnostic
messages at the context level. Previously this was only available at the device level.
- API CHANGE: The device config passed to mal_device_init() is now const.
- Added support for OSS which enables support on BSD platforms.
- Added support for WinMM (waveOut/waveIn).
- Added support for UWP (Universal Windows Platform) applications. Currently C++ only.
- Added support for exclusive mode for selected backends. Currently supported on WASAPI.
- POSIX builds no longer require explicit linking to libpthread (-lpthread).
- ALSA: Explicit linking to libasound (-lasound) is no longer required.
- ALSA: Latency improvements.
- ALSA: Use MMAP mode where available. This can be disabled with the alsa.noMMap config.
- ALSA: Use "hw" devices instead of "plughw" devices by default. This can be disabled with the
alsa.preferPlugHW config.
- WASAPI is now the highest priority backend on Windows platforms.
- Fixed an error with sample rate conversion which was causing crackling when capturing.
- Improved error handling.
- Improved compiler support.
- Miscellaneous bug fixes.
v0.3 - 2017-06-19
- API CHANGE: Introduced the notion of a context. The context is the highest level object and is required for
enumerating and creating devices. Now, applications must first create a context, and then use that to
enumerate and create devices. The reason for this change is to ensure device enumeration and creation is
tied to the same backend. In addition, some backends are better suited to this design.
- API CHANGE: Removed the rewinding APIs because they're too inconsistent across the different backends, hard
to test and maintain, and just generally unreliable.
- Added helper APIs for initializing mal_device_config objects.
- Null Backend: Fixed a crash when recording.
- Fixed build for UWP.
- Added support for f32 formats to the OpenSL|ES backend.
- Added initial implementation of the WASAPI backend.
- Added initial implementation of the OpenAL backend.
- Added support for low quality linear sample rate conversion.