summaryrefslogtreecommitdiff
path: root/vendor/codecs.c
diff options
context:
space:
mode:
Diffstat (limited to 'vendor/codecs.c')
-rw-r--r--vendor/codecs.c57
1 files changed, 57 insertions, 0 deletions
diff --git a/vendor/codecs.c b/vendor/codecs.c
new file mode 100644
index 0000000..7d54f34
--- /dev/null
+++ b/vendor/codecs.c
@@ -0,0 +1,57 @@
+#include <stdlib.h>
+#include <string.h>
+#include "codecs.h"
+
+#define DR_WAV_IMPLEMENTATION
+#define DR_WAV_NO_STDIO
+#include "dr_wav.h"
+#define DR_FLAC_IMPLEMENTATION
+#define DR_FLAC_NO_STDIO
+#include "dr_flac.h"
+#define STB_VORBIS_NO_STDIO
+#define STB_VORBIS_NO_PUSHDATA_API
+#include "stb_vorbis.c"
+
+static float *decode_vorbis(const void *data, size_t size, uint32_t *channels, uint32_t *rate, uint64_t *frames) {
+ if (size > INT32_MAX) return NULL;
+ int error = 0;
+ stb_vorbis *v = stb_vorbis_open_memory(data, (int)size, &error, NULL);
+ if (!v) return NULL;
+ stb_vorbis_info info = stb_vorbis_get_info(v);
+ unsigned total = stb_vorbis_stream_length_in_samples(v);
+ float *out = NULL;
+ if (info.channels > 0 && total > 0) out = malloc((size_t)total * info.channels * sizeof(float));
+ if (!out) {
+ stb_vorbis_close(v);
+ return NULL;
+ }
+ size_t got = 0;
+ while (got < total) {
+ int n = stb_vorbis_get_samples_float_interleaved(v, info.channels, out + got * info.channels, (int)((total - got) * info.channels));
+ if (n <= 0) break;
+ got += (size_t)n;
+ }
+ stb_vorbis_close(v);
+ *channels = (uint32_t)info.channels;
+ *rate = info.sample_rate;
+ *frames = got;
+ return out;
+}
+
+float *sketchbook_decode_audio(const void *data, size_t size, uint32_t *channels, uint32_t *rate, uint64_t *frames) {
+ unsigned int ch = 0, sr = 0;
+ drwav_uint64 n = 0;
+ float *out = NULL;
+ if (size < 4) return NULL;
+ if (memcmp(data, "OggS", 4) == 0) return decode_vorbis(data, size, channels, rate, frames);
+ if (memcmp(data, "fLaC", 4) == 0) out = drflac_open_memory_and_read_pcm_frames_f32(data, size, &ch, &sr, &n, NULL);
+ else out = drwav_open_memory_and_read_pcm_frames_f32(data, size, &ch, &sr, &n, NULL);
+ *channels = ch;
+ *rate = sr;
+ *frames = n;
+ return out;
+}
+
+void sketchbook_free_audio(float *samples) {
+ free(samples);
+}