From 1c556a70bce11ffd96a46223703451eee1358d4b Mon Sep 17 00:00:00 2001 From: John Alanbrook Date: Wed, 6 Jul 2022 01:49:51 +0000 Subject: [PATCH] Audio mixer --- source/engine/mix.c | 42 ++++++++++++++++++++++++++++++++++++++++++ source/engine/mix.h | 23 +++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 source/engine/mix.c create mode 100644 source/engine/mix.h diff --git a/source/engine/mix.c b/source/engine/mix.c new file mode 100644 index 0000000..53c8e5e --- /dev/null +++ b/source/engine/mix.c @@ -0,0 +1,42 @@ +#include "mix.h" +#include "stddef.h" + +#include "sound.h" + +static struct bus bus[256]; +short mastermix[BUF_FRAMES*CHANNELS]; + +struct bus *first_free_bus() { + for (int i = 0; i < 256; i++) { + if (!bus[i].on) return &bus[i]; + } + + return NULL; +} + +void bus_fill_buffers() { + for (int i = 0; i < 256; i++) { + if (!bus[i].on) continue; + + short *s = (short*)bus[i].sound->data->data; + + for (int k = 0; k < BUF_FRAMES; k++) { + for (int j = 0; j < CHANNELS; j++) { + bus[i].buf[k*CHANNELS + j] = s[bus[i].sound->frame++]; + if (bus[i].sound->frame == bus[i].sound->data->frames) { + bus[i].sound->frame = 0; + if (!bus[i].sound->loop) bus[i].on = 0; + } + } + } + } + + for (int i = 0; i < BUF_FRAMES*CHANNELS; i++) { + mastermix[i] = 0; + + for (int j = 0; j < 256; j++) { + if (!bus[j].on) continue; + mastermix[i] += bus[j].buf[i]; + } + } +} \ No newline at end of file diff --git a/source/engine/mix.h b/source/engine/mix.h new file mode 100644 index 0000000..d81bb0c --- /dev/null +++ b/source/engine/mix.h @@ -0,0 +1,23 @@ +#ifndef MIX_H +#define MIX_H + +#define BUF_FRAMES 4096 +#define CHANNELS 2 +#define MUSIZE 2 + +struct sound; + + +struct bus { + int on; + struct sound *sound; + short buf[BUF_FRAMES*CHANNELS]; +}; + +extern short mastermix[BUF_FRAMES*CHANNELS]; + +struct bus *first_free_bus(); +void bus_fill_buffers(); + + +#endif \ No newline at end of file