summaryrefslogtreecommitdiff
path: root/src/load/load-mp3.c
blob: d3e7598e01ce788c4efe3aee9ed979f43691128e (plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
#define MINIMP3_FLOAT_OUTPUT
#define MINIMP3_IMPLEMENTATION
#include <stdio.h>
#include <minimp3_ex.h>
#include <mossrose.h>
#include "load.h"


#define ABORT(...) do { \
	fprintf(stderr, __VA_ARGS__); \
	free(mp3.buffer); \
	return NULL; \
} while(0)


struct mossrose_sound_t * load_mp3(const char *filename)
{
	mp3dec_t mp3d;
	mp3dec_file_info_t mp3;
	if (mp3dec_load(&mp3d, filename, &mp3, NULL, NULL)) {
		fprintf(stderr, "failed to decode mp3 file '%s'\n", filename);
		return NULL;
	}

	if (mp3.channels != 1 && mp3.channels != 2) {
		ABORT("files with %d audio tracks are not supported!\n", mp3.channels);
	}

	struct mossrose_sound_t *sound = malloc(sizeof(struct mossrose_sound_t));
	if (sound == NULL)
		ABORT("failed to allocate sound structure\n");
	
	if (mp3.channels == 1) {
		sound->mono = true;
		sound->left = malloc(mp3.samples * sizeof(float));
		if (sound->left == NULL) {
			free(sound);
			ABORT("failed to allocate mono audio data!\n");
		}
		memcpy(sound->left, mp3.buffer, mp3.samples * sizeof(float));
		sound->right = NULL;
		sound->len = mp3.samples;
	}
	else {
		/* stereo */
		sound->mono = false;
		size_t sz = (mp3.samples/2) * sizeof(float);
		sound->left = malloc(sz);
		if (sound->left == NULL) {
			free(sound);
			ABORT("failed to allocate left audio channel!\n");
		}
		sound->right = malloc(sz);
		if (sound->right == NULL) {
			free(sound->left);
			free(sound);
			ABORT("failed to allocate right audio channel!\n");
		}
		for (int i=0; i<mp3.samples; i++) {
			if (i%2)
				sound->left[i/2] = mp3.buffer[i];
			else
				sound->right[i/2] = mp3.buffer[i];
		}
		sound->len = mp3.samples/2;
	}

	free(mp3.buffer);
	return sound;
}