Productionize polished cosmoaudio library

This change introduces comsoaudio v1. We're using a new strategy when it
comes to dynamic linking of dso files and building miniaudio device code
which I think will be fast and stable in the long run. You now have your
choice of reading/writing to the internal ring buffer abstraction or you
can specify a device-driven callback function instead. It's now possible
to not open the microphone when you don't need it since touching the mic
causes security popups to happen. The DLL is now built statically, so it
only needs to depend on kernel32. Our NES terminal emulator now uses the
cosmoaudio library and is confirmed to be working on Windows, Mac, Linux
This commit is contained in:
Justine Tunney 2024-09-07 03:30:49 -07:00
parent c66abd7260
commit dc579b79cd
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
13 changed files with 640 additions and 470 deletions

View file

@ -17,13 +17,17 @@
PERFORMANCE OF THIS SOFTWARE.
*/
#include "dsp/audio/cosmoaudio/cosmoaudio.h"
#include "dsp/audio/describe.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/struct/timespec.h"
#include "libc/dce.h"
#include "libc/dlopen/dlfcn.h"
#include "libc/errno.h"
#include "libc/intrin/describeflags.h"
#include "libc/intrin/strace.h"
#include "libc/limits.h"
#include "libc/macros.h"
#include "libc/proc/posix_spawn.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
@ -31,6 +35,10 @@
#include "libc/temp.h"
#include "libc/thread/thread.h"
#define COSMOAUDIO_MINIMUM_VERISON 1
#define COSMOAUDIO_DSO_NAME "cosmoaudio." STRINGIFY(COSMOAUDIO_MINIMUM_VERISON)
__static_yoink("dsp/audio/cosmoaudio/miniaudio.h");
__static_yoink("dsp/audio/cosmoaudio/cosmoaudio.h");
__static_yoink("dsp/audio/cosmoaudio/cosmoaudio.c");
@ -53,7 +61,7 @@ static struct {
typeof(cosmoaudio_read) *read;
} g_audio;
static const char *get_tmp_dir(void) {
static const char *cosmoaudio_tmp_dir(void) {
const char *tmpdir;
if (!(tmpdir = getenv("TMPDIR")) || !*tmpdir)
if (!(tmpdir = getenv("HOME")) || !*tmpdir)
@ -61,18 +69,18 @@ static const char *get_tmp_dir(void) {
return tmpdir;
}
static bool get_app_dir(char *path, size_t size) {
strlcpy(path, get_tmp_dir(), size);
static bool cosmoaudio_app_dir(char *path, size_t size) {
strlcpy(path, cosmoaudio_tmp_dir(), size);
strlcat(path, "/.cosmo/", size);
if (makedirs(path, 0755))
return false;
return true;
}
static bool get_dso_path(char *path, size_t size) {
if (!get_app_dir(path, size))
static bool cosmoaudio_dso_path(char *path, size_t size) {
if (!cosmoaudio_app_dir(path, size))
return false;
strlcat(path, "cosmoaudio", size);
strlcat(path, COSMOAUDIO_DSO_NAME, size);
if (IsWindows()) {
strlcat(path, ".dll", size);
} else if (IsXnu()) {
@ -83,86 +91,7 @@ static bool get_dso_path(char *path, size_t size) {
return true;
}
static int is_file_newer_than_time(const char *path, const char *other) {
struct stat st1, st2;
if (stat(path, &st1))
// PATH should always exist when calling this function
return -1;
if (stat(other, &st2)) {
if (errno == ENOENT) {
// PATH should replace OTHER because OTHER doesn't exist yet
return true;
} else {
// some other error happened, so we can't do anything
return -1;
}
}
// PATH should replace OTHER if PATH was modified more recently
return timespec_cmp(st1.st_mtim, st2.st_mtim) > 0;
}
static int is_file_newer_than_bytes(const char *path, const char *other) {
int other_fd;
if ((other_fd = open(other, O_RDONLY | O_CLOEXEC)) == -1) {
if (errno == ENOENT) {
return true;
} else {
return -1;
}
}
int path_fd;
if ((path_fd = open(path, O_RDONLY | O_CLOEXEC)) == -1) {
close(other_fd);
return -1;
}
int res;
long i = 0;
for (;;) {
char path_buf[512];
ssize_t path_rc = pread(path_fd, path_buf, sizeof(path_buf), i);
if (path_rc == -1) {
res = -1;
break;
}
char other_buf[512];
ssize_t other_rc = pread(other_fd, other_buf, sizeof(other_buf), i);
if (other_rc == -1) {
res = -1;
break;
}
if (!path_rc || !other_rc) {
if (!path_rc && !other_rc)
res = false;
else
res = true;
break;
}
size_t size = path_rc;
if (other_rc < path_rc)
size = other_rc;
if (memcmp(path_buf, other_buf, size)) {
res = true;
break;
}
i += size;
}
if (close(path_fd))
res = -1;
if (close(other_fd))
res = -1;
return res;
}
static int is_file_newer_than(const char *path, const char *other) {
if (startswith(path, "/zip/"))
// to keep builds deterministic, embedded zip files always have
// the same timestamp from back in 2022 when it was implemented
return is_file_newer_than_bytes(path, other);
else
return is_file_newer_than_time(path, other);
}
static bool extract(const char *zip, const char *to) {
static bool cosmoaudio_extract(const char *zip, const char *to) {
int fdin, fdout;
char stage[PATH_MAX];
strlcpy(stage, to, sizeof(stage));
@ -170,9 +99,8 @@ static bool extract(const char *zip, const char *to) {
errno = ENAMETOOLONG;
return false;
}
if ((fdout = mkostemp(stage, O_CLOEXEC)) == -1) {
if ((fdout = mkostemp(stage, O_CLOEXEC)) == -1)
return false;
}
if ((fdin = open(zip, O_RDONLY | O_CLOEXEC)) == -1) {
close(fdout);
unlink(stage);
@ -200,114 +128,104 @@ static bool extract(const char *zip, const char *to) {
return true;
}
static bool deploy(const char *dso) {
switch (is_file_newer_than("/zip/dsp/audio/cosmoaudio/cosmoaudio.dll", dso)) {
case 0:
return true;
case 1:
return extract("/zip/dsp/audio/cosmoaudio/cosmoaudio.dll", dso);
default:
return false;
}
}
static bool cosmoaudio_build(const char *dso) {
static bool build(const char *dso) {
// extract source code
// extract sauce
char src[PATH_MAX];
bool needs_rebuild = false;
for (int i = 0; i < sizeof(srcs) / sizeof(*srcs); ++i) {
get_app_dir(src, PATH_MAX);
if (!cosmoaudio_app_dir(src, PATH_MAX))
return false;
strlcat(src, srcs[i].name, sizeof(src));
switch (is_file_newer_than(srcs[i].zip, src)) {
case -1:
return false;
case 0:
break;
case 1:
needs_rebuild = true;
if (!extract(srcs[i].zip, src))
return false;
break;
default:
__builtin_unreachable();
}
if (!cosmoaudio_extract(srcs[i].zip, src))
return false;
}
// determine if we need to build
if (!needs_rebuild) {
switch (is_file_newer_than(src, dso)) {
case -1:
return false;
case 0:
break;
case 1:
needs_rebuild = true;
break;
default:
__builtin_unreachable();
}
// create temporary name for compiled dso
// it'll ensure build operation is atomic
int fd;
char tmpdso[PATH_MAX];
strlcpy(tmpdso, dso, sizeof(tmpdso));
strlcat(tmpdso, ".XXXXXX", sizeof(tmpdso));
if ((fd = mkostemp(tmpdso, O_CLOEXEC)) != -1) {
close(fd);
} else {
return false;
}
// compile dynamic shared object
if (needs_rebuild) {
int fd;
char tmpdso[PATH_MAX];
strlcpy(tmpdso, dso, sizeof(tmpdso));
strlcat(tmpdso, ".XXXXXX", sizeof(tmpdso));
if ((fd = mkostemp(tmpdso, O_CLOEXEC)) != -1) {
close(fd);
} else {
// build cosmoaudio with host c compiler
char *args[] = {
"cc", //
"-w", //
"-I.", //
"-O2", //
"-fPIC", //
"-shared", //
"-pthread", //
"-DNDEBUG", //
IsAarch64() ? "-ffixed-x28" : "-DIGNORE1", //
src, //
"-o", //
tmpdso, //
"-lm", //
IsNetbsd() ? 0 : "-ldl", //
NULL,
};
int pid, ws;
errno_t err = posix_spawnp(&pid, args[0], NULL, NULL, args, environ);
if (err)
return false;
while (waitpid(pid, &ws, 0) == -1)
if (errno != EINTR)
return false;
}
char *args[] = {
"cc", //
"-I.", //
"-O2", //
"-fPIC", //
"-shared", //
"-pthread", //
"-DNDEBUG", //
IsAarch64() ? "-ffixed-x28" : "-DIGNORE1", //
src, //
"-o", //
tmpdso, //
"-ldl", //
"-lm", //
NULL,
};
int pid, ws;
errno_t err = posix_spawnp(&pid, "cc", NULL, NULL, args, environ);
if (err)
return false;
while (waitpid(pid, &ws, 0) == -1) {
if (errno != EINTR)
return false;
}
if (ws)
return false;
if (rename(tmpdso, dso))
return false;
}
if (ws)
return false;
// move dso to its final destination
if (rename(tmpdso, dso))
return false;
return true;
}
static void *cosmoaudio_dlopen(const char *name) {
void *handle;
if ((handle = cosmo_dlopen(name, RTLD_NOW))) {
typeof(cosmoaudio_version) *version;
if ((version = cosmo_dlsym(handle, "cosmoaudio_version")))
if (version() >= COSMOAUDIO_MINIMUM_VERISON)
return handle;
cosmo_dlclose(handle);
}
return 0;
}
static void cosmoaudio_setup(void) {
void *handle;
if (!(handle = cosmo_dlopen("cosmoaudio.so", RTLD_LOCAL))) {
if (issetugid())
return;
if (IsOpenbsd())
return; // no dlopen support yet
if (IsXnu() && !IsXnuSilicon())
return; // no dlopen support yet
if (!(handle = cosmoaudio_dlopen(COSMOAUDIO_DSO_NAME ".so")) &&
!(handle = cosmoaudio_dlopen("lib" COSMOAUDIO_DSO_NAME ".so")) &&
!(handle = cosmoaudio_dlopen("cosmoaudio.so")) &&
!(handle = cosmoaudio_dlopen("libcosmoaudio.so"))) {
char dso[PATH_MAX];
if (!get_dso_path(dso, sizeof(dso)))
if (!cosmoaudio_dso_path(dso, sizeof(dso)))
return;
if (IsWindows())
if (deploy(dso))
if ((handle = cosmo_dlopen(dso, RTLD_LOCAL)))
if ((handle = cosmoaudio_dlopen(dso)))
goto WeAreGood;
if (IsWindows()) {
if (cosmoaudio_extract("/zip/dsp/audio/cosmoaudio/cosmoaudio.dll", dso)) {
if ((handle = cosmoaudio_dlopen(dso))) {
goto WeAreGood;
if (!build(dso))
} else {
return;
}
}
}
if (!cosmoaudio_build(dso))
return;
if (!(handle = cosmo_dlopen(dso, RTLD_LOCAL)))
if (!(handle = cosmoaudio_dlopen(dso)))
return;
}
WeAreGood:
@ -321,33 +239,59 @@ static void cosmoaudio_init(void) {
pthread_once(&g_audio.once, cosmoaudio_setup);
}
COSMOAUDIO_ABI int cosmoaudio_open(struct CosmoAudio **cap, int sampleRate,
int channels) {
COSMOAUDIO_ABI int cosmoaudio_open(
struct CosmoAudio **out_ca, const struct CosmoAudioOpenOptions *options) {
int status;
char sbuf[32];
char dbuf[256];
cosmoaudio_init();
if (!g_audio.open)
return COSMOAUDIO_ERROR;
return g_audio.open(cap, sampleRate, channels);
if (g_audio.open)
status = g_audio.open(out_ca, options);
else
status = COSMOAUDIO_ELINK;
STRACE("cosmoaudio_open([%p], %s) → %s",
out_ca ? *out_ca : (struct CosmoAudio *)-1,
cosmoaudio_describe_open_options(dbuf, sizeof(dbuf), options),
cosmoaudio_describe_status(sbuf, sizeof(sbuf), status));
return status;
}
COSMOAUDIO_ABI int cosmoaudio_close(struct CosmoAudio *ca) {
cosmoaudio_init();
if (!g_audio.close)
return COSMOAUDIO_ERROR;
return g_audio.close(ca);
int status;
char sbuf[32];
if (g_audio.close)
status = g_audio.close(ca);
else
status = COSMOAUDIO_ELINK;
STRACE("cosmoaudio_close(%p) → %s", ca,
cosmoaudio_describe_status(sbuf, sizeof(sbuf), status));
return status;
}
COSMOAUDIO_ABI int cosmoaudio_write(struct CosmoAudio *ca, const float *data,
int frames) {
cosmoaudio_init();
if (!g_audio.write)
return COSMOAUDIO_ERROR;
return g_audio.write(ca, data, frames);
int status;
char sbuf[32];
if (g_audio.write)
status = g_audio.write(ca, data, frames);
else
status = COSMOAUDIO_ELINK;
if (frames <= 0 || frames >= 160)
DATATRACE("cosmoaudio_write(%p, %p, %d) → %s", ca, data, frames,
cosmoaudio_describe_status(sbuf, sizeof(sbuf), status));
return status;
}
COSMOAUDIO_ABI int cosmoaudio_read(struct CosmoAudio *ca, float *data,
int frames) {
cosmoaudio_init();
if (!g_audio.read)
return COSMOAUDIO_ERROR;
return g_audio.read(ca, data, frames);
int status;
char sbuf[32];
if (g_audio.read)
status = g_audio.read(ca, data, frames);
else
status = COSMOAUDIO_ELINK;
if (frames <= 0 || frames >= 160)
DATATRACE("cosmoaudio_read(%p, %p, %d) → %s", ca, data, frames,
cosmoaudio_describe_status(sbuf, sizeof(sbuf), status));
return status;
}

View file

@ -19,7 +19,7 @@ TEST_LIBS=OneCore.lib
# Compiler flags
CFLAGS_COMMON=/nologo /W4 /Gy /EHsc
CFLAGS_DEBUG=/Od /Zi /MDd /D_DEBUG
CFLAGS_RELEASE=/O2 /MD /DNDEBUG
CFLAGS_RELEASE=/O2 /MT /DNDEBUG
!IF "$(MODE)"=="debug"
CFLAGS=$(CFLAGS_COMMON) $(CFLAGS_DEBUG)

View file

@ -1,3 +1,18 @@
// Copyright 2024 Justine Alexandra Roberts Tunney
//
// Permission to use, copy, modify, and/or distribute this software for
// any purpose with or without fee is hereby granted, provided that the
// above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
// WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
// AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
// DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
// PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#define COSMOAUDIO_BUILD
#include "cosmoaudio.h"
#include <stdio.h>
@ -7,6 +22,10 @@
#define MA_STATIC
#define MA_NO_DECODING
#define MA_NO_ENCODING
#define MA_NO_ENGINE
#define MA_NO_GENERATION
#define MA_NO_NODE_GRAPH
#define MA_NO_RESOURCE_MANAGER
#ifdef NDEBUG
#define MA_DR_MP3_NO_STDIO
#endif
@ -25,6 +44,10 @@ struct CosmoAudio {
ma_pcm_rb output;
ma_uint32 sampleRate;
ma_uint32 channels;
ma_uint32 periods;
enum CosmoAudioDeviceType deviceType;
cosmoaudio_data_callback_f* dataCallback;
void* argument;
};
static int read_ring_buffer(ma_pcm_rb* rb, float* pOutput, ma_uint32 frameCount,
@ -88,8 +111,15 @@ static int write_ring_buffer(ma_pcm_rb* rb, const float* pInput,
static void data_callback_f32(ma_device* pDevice, float* pOutput,
const float* pInput, ma_uint32 frameCount) {
struct CosmoAudio* ca = (struct CosmoAudio*)pDevice->pUserData;
read_ring_buffer(&ca->output, pOutput, frameCount, ca->channels);
write_ring_buffer(&ca->input, pInput, frameCount, ca->channels);
if (ca->dataCallback) {
ca->dataCallback(ca, pOutput, pInput, frameCount, ca->channels,
ca->argument);
} else {
if (ca->deviceType & kCosmoAudioDeviceTypePlayback)
read_ring_buffer(&ca->output, pOutput, frameCount, ca->channels);
if (ca->deviceType & kCosmoAudioDeviceTypeCapture)
write_ring_buffer(&ca->input, pInput, frameCount, ca->channels);
}
}
static void data_callback(ma_device* pDevice, void* pOutput, const void* pInput,
@ -97,34 +127,72 @@ static void data_callback(ma_device* pDevice, void* pOutput, const void* pInput,
data_callback_f32(pDevice, (float*)pOutput, (const float*)pInput, frameCount);
}
/**
* Returns current version of cosmo audio library.
*/
COSMOAUDIO_ABI int cosmoaudio_version(void) {
return 1;
}
/**
* Opens access to speaker and microphone.
*
* @param cap will receive pointer to allocated CosmoAudio object on success,
* which must be freed by caller with cosmoaudio_close()
* @param sampleRate is sample rate in Hz, e.g. 44100
* @param channels is number of channels (1 for mono, 2 for stereo)
* @param out_ca will receive pointer to allocated CosmoAudio object,
* which must be freed by caller with cosmoaudio_close(); if this
* function fails, then this will receive a NULL pointer value so
* that cosmoaudio_close(), cosmoaudio_write() etc. can be called
* without crashing if no error checking is performed
* @return 0 on success, or negative error code on failure
*/
COSMOAUDIO_ABI int cosmoaudio_open(struct CosmoAudio** cap, int sampleRate,
int channels) {
COSMOAUDIO_ABI int cosmoaudio_open( //
struct CosmoAudio** out_ca, //
const struct CosmoAudioOpenOptions* options) {
// Validate arguments.
if (!out_ca)
return COSMOAUDIO_EINVAL;
*out_ca = NULL;
if (!options)
return COSMOAUDIO_EINVAL;
if (options->sizeofThis < (int)sizeof(struct CosmoAudioOpenOptions))
return COSMOAUDIO_EINVAL;
if (options->periods < 0)
return COSMOAUDIO_EINVAL;
if (options->sampleRate < 8000)
return COSMOAUDIO_EINVAL;
if (options->channels < 1)
return COSMOAUDIO_EINVAL;
if (!options->deviceType)
return COSMOAUDIO_EINVAL;
if (options->deviceType &
~(kCosmoAudioDeviceTypePlayback | kCosmoAudioDeviceTypeCapture))
return COSMOAUDIO_EINVAL;
// Allocate cosmo audio object.
struct CosmoAudio* ca;
if (!(ca = (struct CosmoAudio*)malloc(sizeof(struct CosmoAudio))))
if (!(ca = (struct CosmoAudio*)calloc(1, sizeof(struct CosmoAudio))))
return COSMOAUDIO_ERROR;
ca->channels = channels;
ca->sampleRate = sampleRate;
ca->channels = options->channels;
ca->sampleRate = options->sampleRate;
ca->deviceType = options->deviceType;
ca->periods = options->periods ? options->periods : 10;
ca->dataCallback = options->dataCallback;
ca->argument = options->argument;
// Initialize device.
ma_result result;
ma_device_config deviceConfig = ma_device_config_init(ma_device_type_duplex);
deviceConfig.sampleRate = sampleRate;
deviceConfig.capture.channels = channels;
deviceConfig.capture.format = ma_format_f32;
deviceConfig.capture.shareMode = ma_share_mode_shared;
deviceConfig.playback.channels = channels;
deviceConfig.playback.format = ma_format_f32;
ma_device_config deviceConfig;
deviceConfig = ma_device_config_init(ca->deviceType);
deviceConfig.sampleRate = ca->sampleRate;
if (ca->deviceType & kCosmoAudioDeviceTypeCapture) {
deviceConfig.capture.channels = ca->channels;
deviceConfig.capture.format = ma_format_f32;
deviceConfig.capture.shareMode = ma_share_mode_shared;
}
if (ca->deviceType & kCosmoAudioDeviceTypePlayback) {
deviceConfig.playback.channels = ca->channels;
deviceConfig.playback.format = ma_format_f32;
}
deviceConfig.dataCallback = data_callback;
deviceConfig.pUserData = ca;
result = ma_device_init(NULL, &deviceConfig, &ca->device);
@ -134,51 +202,67 @@ COSMOAUDIO_ABI int cosmoaudio_open(struct CosmoAudio** cap, int sampleRate,
}
// Initialize the speaker ring buffer.
result = ma_pcm_rb_init(ma_format_f32, channels,
ca->device.playback.internalPeriodSizeInFrames * 10,
NULL, NULL, &ca->output);
if (result != MA_SUCCESS) {
ma_device_uninit(&ca->device);
free(ca);
return COSMOAUDIO_ERROR;
if (!ca->dataCallback && (ca->deviceType & kCosmoAudioDeviceTypePlayback)) {
result = ma_pcm_rb_init(
ma_format_f32, ca->channels,
ca->device.playback.internalPeriodSizeInFrames * ca->periods, NULL,
NULL, &ca->output);
if (result != MA_SUCCESS) {
ma_device_uninit(&ca->device);
free(ca);
return COSMOAUDIO_ERROR;
}
ma_pcm_rb_set_sample_rate(&ca->output, ca->sampleRate);
}
ma_pcm_rb_set_sample_rate(&ca->output, sampleRate);
// Initialize the microphone ring buffer.
result = ma_pcm_rb_init(ma_format_f32, channels,
ca->device.capture.internalPeriodSizeInFrames * 10,
NULL, NULL, &ca->input);
if (result != MA_SUCCESS) {
ma_pcm_rb_uninit(&ca->output);
ma_device_uninit(&ca->device);
free(ca);
return COSMOAUDIO_ERROR;
if (!ca->dataCallback && (ca->deviceType & kCosmoAudioDeviceTypeCapture)) {
result = ma_pcm_rb_init(
ma_format_f32, ca->channels,
ca->device.capture.internalPeriodSizeInFrames * ca->periods, NULL, NULL,
&ca->input);
if (result != MA_SUCCESS) {
if (!ca->dataCallback && (ca->deviceType & kCosmoAudioDeviceTypePlayback))
ma_pcm_rb_uninit(&ca->output);
ma_device_uninit(&ca->device);
free(ca);
return COSMOAUDIO_ERROR;
}
ma_pcm_rb_set_sample_rate(&ca->output, ca->sampleRate);
}
ma_pcm_rb_set_sample_rate(&ca->output, sampleRate);
// Start audio playback.
if (ma_device_start(&ca->device) != MA_SUCCESS) {
ma_pcm_rb_uninit(&ca->input);
ma_pcm_rb_uninit(&ca->output);
if (!ca->dataCallback && (ca->deviceType & kCosmoAudioDeviceTypeCapture))
ma_pcm_rb_uninit(&ca->input);
if (!ca->dataCallback && (ca->deviceType & kCosmoAudioDeviceTypePlayback))
ma_pcm_rb_uninit(&ca->output);
ma_device_uninit(&ca->device);
free(ca);
return COSMOAUDIO_ERROR;
}
*cap = ca;
*out_ca = ca;
return COSMOAUDIO_SUCCESS;
}
/**
* Closes audio device and frees all associated resources.
*
* Calling this function twice on the same object will result in
* undefined behavior.
*
* @param ca is CosmoAudio object returned earlier by cosmoaudio_open()
* @return 0 on success, or negative error code on failure
*/
COSMOAUDIO_ABI int cosmoaudio_close(struct CosmoAudio* ca) {
if (!ca)
return COSMOAUDIO_EINVAL;
ma_device_uninit(&ca->device);
ma_pcm_rb_uninit(&ca->output);
ma_pcm_rb_uninit(&ca->input);
if (!ca->dataCallback && (ca->deviceType & kCosmoAudioDeviceTypePlayback))
ma_pcm_rb_uninit(&ca->output);
if (!ca->dataCallback && (ca->deviceType & kCosmoAudioDeviceTypeCapture))
ma_pcm_rb_uninit(&ca->input);
free(ca);
return COSMOAUDIO_SUCCESS;
}
@ -201,6 +285,18 @@ COSMOAUDIO_ABI int cosmoaudio_close(struct CosmoAudio* ca) {
*/
COSMOAUDIO_ABI int cosmoaudio_write(struct CosmoAudio* ca, const float* data,
int frames) {
if (!ca)
return COSMOAUDIO_EINVAL;
if (frames < 0)
return COSMOAUDIO_EINVAL;
if (ca->dataCallback)
return COSMOAUDIO_EINVAL;
if (!(ca->deviceType & kCosmoAudioDeviceTypePlayback))
return COSMOAUDIO_EINVAL;
if (!frames)
return 0;
if (!data)
return COSMOAUDIO_EINVAL;
return write_ring_buffer(&ca->output, data, frames, ca->channels);
}
@ -222,6 +318,18 @@ COSMOAUDIO_ABI int cosmoaudio_write(struct CosmoAudio* ca, const float* data,
*/
COSMOAUDIO_ABI int cosmoaudio_read(struct CosmoAudio* ca, float* data,
int frames) {
if (!ca)
return COSMOAUDIO_EINVAL;
if (frames < 0)
return COSMOAUDIO_EINVAL;
if (ca->dataCallback)
return COSMOAUDIO_EINVAL;
if (!(ca->deviceType & kCosmoAudioDeviceTypeCapture))
return COSMOAUDIO_EINVAL;
if (!frames)
return 0;
if (!data)
return COSMOAUDIO_EINVAL;
return read_ring_buffer(&ca->input, data, frames, ca->channels);
}

Binary file not shown.

View file

@ -11,14 +11,16 @@
#else
#define COSMOAUDIO_API
#ifdef __x86_64__
#define COSMOAUDIO_ABI __attribute__((__ms_abi__))
#define COSMOAUDIO_ABI __attribute__((__ms_abi__, __visibility__("default")))
#else
#define COSMOAUDIO_ABI
#define COSMOAUDIO_ABI __attribute__((__visibility__("default")))
#endif
#endif
#define COSMOAUDIO_SUCCESS 0
#define COSMOAUDIO_ERROR -1
#define COSMOAUDIO_SUCCESS -0 // no error or nothing written
#define COSMOAUDIO_ERROR -1 // unspecified error
#define COSMOAUDIO_EINVAL -2 // invalid parameters passed to api
#define COSMOAUDIO_ELINK -3 // loading cosmoaudio dso failed
#ifdef __cplusplus
extern "C" {
@ -26,13 +28,78 @@ extern "C" {
struct CosmoAudio;
COSMOAUDIO_API int cosmoaudio_open(struct CosmoAudio **, int,
int) COSMOAUDIO_ABI;
COSMOAUDIO_API int cosmoaudio_close(struct CosmoAudio *) COSMOAUDIO_ABI;
COSMOAUDIO_API int cosmoaudio_write(struct CosmoAudio *, const float *,
int) COSMOAUDIO_ABI;
COSMOAUDIO_API int cosmoaudio_read(struct CosmoAudio *, float *,
int) COSMOAUDIO_ABI;
typedef void cosmoaudio_data_callback_f( //
struct CosmoAudio *ca, //
float *outputSamples, //
const float *inputSamples, //
int frameCount, //
int channels, //
void *argument);
enum CosmoAudioDeviceType {
kCosmoAudioDeviceTypePlayback = 1,
kCosmoAudioDeviceTypeCapture = 2,
kCosmoAudioDeviceTypeDuplex =
kCosmoAudioDeviceTypePlayback | kCosmoAudioDeviceTypeCapture,
};
struct CosmoAudioOpenOptions {
// This field must be set to sizeof(struct CosmoAudioOpenOptions) or
// cosmoaudio_open() will return COSMOAUDIO_EINVAL.
int sizeofThis;
// Whether you want this object to open the speaker or microphone.
// Please note that asking for microphone access may cause some OSes
// like MacOS to show a popup asking the user for permission.
enum CosmoAudioDeviceType deviceType;
// The sample rate can be 44100 for CD quality, 8000 for telephone
// quality, etc. Values below 8000 are currently not supported.
int sampleRate;
// The number of audio channels in each interleaved frame. Should be 1
// for mono or 2 for stereo.
int channels;
// Number of periods in ring buffer. Set to 0 for default. Higher
// numbers (e.g. 20) means more buffering. Lower numbers (e.g. 2)
// means less buffering. This is ignored if callback is specified.
int periods;
// If callback is NULL, then cosmoaudio_write() and cosmoaudio_read()
// should be used, which ring buffer audio to the default internal
// routine. Setting this callback to non-NULL puts CosmoAudio in
// manual mode, where the callback is responsible for copying PCM
// samples each time the device calls this.
cosmoaudio_data_callback_f *dataCallback;
// This is an arbitrary value passed to the callback.
void *argument;
};
COSMOAUDIO_API int cosmoaudio_version(void) COSMOAUDIO_ABI;
COSMOAUDIO_API int cosmoaudio_open( //
struct CosmoAudio **out_ca, //
const struct CosmoAudioOpenOptions *options //
) COSMOAUDIO_ABI;
COSMOAUDIO_API int cosmoaudio_close( //
struct CosmoAudio *ca //
) COSMOAUDIO_ABI;
COSMOAUDIO_API int cosmoaudio_write( //
struct CosmoAudio *ca, //
const float *samples, //
int frameCount //
) COSMOAUDIO_ABI;
COSMOAUDIO_API int cosmoaudio_read( //
struct CosmoAudio *ca, //
float *out_samples, //
int frameCount //
) COSMOAUDIO_ABI;
#ifdef __cplusplus
}

View file

@ -1,5 +1,12 @@
#include <errno.h>
#include <limits.h>
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include <math.h>
#include <stdio.h>
#include <time.h>
@ -9,28 +16,43 @@
#define M_PIf 3.14159265358979323846f
#endif
int g_hz = 44100;
int g_channels = 2;
int g_generation = 0;
int g_freq = 440;
void data_callback(struct CosmoAudio *ca, float *outputSamples,
const float *inputSamples, int frameCount, int channels,
void *argument) {
for (int i = 0; i < frameCount; i++) {
float t = (float)g_generation++ / g_hz;
if (g_generation == g_hz)
g_generation = 0;
float s = sinf(2 * M_PIf * g_freq * t);
for (int j = 0; j < channels; j++)
outputSamples[i * channels + j] = s;
}
(void)inputSamples;
(void)argument;
(void)ca;
}
int main() {
int hz = 44100;
int channels = 2;
struct CosmoAudioOpenOptions cao = {};
cao.sizeofThis = sizeof(struct CosmoAudioOpenOptions);
cao.deviceType = kCosmoAudioDeviceTypePlayback;
cao.sampleRate = g_hz;
cao.channels = g_channels;
cao.dataCallback = data_callback;
struct CosmoAudio *ca;
if (cosmoaudio_open(&ca, hz, channels) != COSMOAUDIO_SUCCESS) {
fprintf(stderr, "%s: failed to open audio\n", argv[0]);
if (cosmoaudio_open(&ca, &cao) != COSMOAUDIO_SUCCESS) {
fprintf(stderr, "failed to open audio\n");
return 1;
}
int n = 1000;
int sample = 0;
float *buf = (float *)malloc(sizeof(float) * channels * n);
for (;;) {
for (int i = 0; i < 128; i++) {
float freq = 440;
float t = (float)sample++ / hz;
if (sample == hz)
sample = 0;
buf[i * channels] = sinf(freq * 2.f * M_PIf * t);
buf[i * channels + 1] = sinf(freq * 2.f * M_PIf * t);
}
cosmoaudio_write(ca, buf, 128);
}
fgetc(stdin);
cosmoaudio_close(ca);
}

113
dsp/audio/describe.c Normal file
View file

@ -0,0 +1,113 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2024 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "dsp/audio/describe.h"
#include "dsp/audio/cosmoaudio/cosmoaudio.h"
#include "libc/intrin/describeflags.h"
#include "libc/intrin/kprintf.h"
#include "libc/macros.h"
#define append(...) o += ksnprintf(buf + o, n - o, __VA_ARGS__)
const char *cosmoaudio_describe_status(char *buf, int n, int status) {
switch (status) {
case COSMOAUDIO_SUCCESS:
return "COSMOAUDIO_SUCCESS";
case COSMOAUDIO_ERROR:
return "COSMOAUDIO_ERROR";
case COSMOAUDIO_EINVAL:
return "COSMOAUDIO_EINVAL";
case COSMOAUDIO_ELINK:
return "COSMOAUDIO_ELINK";
default:
ksnprintf(buf, n, "%d", status);
return buf;
}
}
const char *cosmoaudio_describe_open_options(
char *buf, int n, const struct CosmoAudioOpenOptions *options) {
int o = 0;
char b128[128];
bool gotsome = false;
if (!options)
return "NULL";
if (kisdangerous(options)) {
ksnprintf(buf, n, "%p", options);
return buf;
}
append("{");
if (options->sampleRate) {
if (gotsome)
append(", ");
append(".sampleRate=%d", options->sampleRate);
gotsome = true;
}
if (options->channels) {
if (gotsome)
append(", ");
append(".channels=%d", options->channels);
gotsome = true;
}
if (options->deviceType) {
if (gotsome)
append(", ");
static struct DescribeFlags kDeviceType[] = {
{kCosmoAudioDeviceTypeDuplex, "Duplex"}, //
{kCosmoAudioDeviceTypeCapture, "Capture"}, //
{kCosmoAudioDeviceTypePlayback, "Playback"}, //
};
append(".deviceType=%s",
_DescribeFlags(b128, 128, kDeviceType, ARRAYLEN(kDeviceType),
"kCosmoAudioDeviceType", options->deviceType));
gotsome = true;
}
if (options->dataCallback) {
if (gotsome)
append(", ");
append(".dataCallback=%t", options->dataCallback);
gotsome = true;
if (options->argument) {
if (gotsome)
append(", ");
append(".argument=%p", options->argument);
gotsome = true;
}
} else {
if (options->periods) {
if (gotsome)
append(", ");
append(".periods=%d", options->periods);
gotsome = true;
}
}
if (options->sizeofThis) {
if (gotsome)
append(", ");
append(".sizeofThis=%d", options->sizeofThis);
gotsome = true;
}
append("}");
return buf;
}

11
dsp/audio/describe.h Normal file
View file

@ -0,0 +1,11 @@
#ifndef COSMOPOLITAN_DSP_AUDIO_DESCRIBE_H_
#define COSMOPOLITAN_DSP_AUDIO_DESCRIBE_H_
#include "dsp/audio/cosmoaudio/cosmoaudio.h"
COSMOPOLITAN_C_START_
const char *cosmoaudio_describe_status(char *, int, int);
const char *cosmoaudio_describe_open_options(
char *, int, const struct CosmoAudioOpenOptions *);
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_DSP_AUDIO_DESCRIBE_H_ */