1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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);
}
|