summaryrefslogtreecommitdiff
path: root/src/channel.c
blob: 603a980de826f451ea6fa7a5afcfe161623158b1 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <stdlib.h>
#include <string.h>
#include <plibsys.h>
#include "channel.h"


void channel_init(struct channel_t *chan)
{
	chan->active = false;
	chan->paused = false;
	chan->volume = 255;
	chan->pan = 0;

	chan->sound_mutex = p_mutex_new();
	chan->sound.left = NULL;
	chan->sound.right = NULL;
	chan->pos = 0;
}


void channel_reset(struct channel_t *chan)
{
	p_atomic_int_set(&(chan->paused), false);
	p_atomic_int_set(&(chan->volume), 255);
	p_atomic_int_set(&(chan->pan), 0);
	chan->pos = 0;
	p_atomic_int_set(&(chan->active), false);
}


void channel_pause(struct channel_t *chan)
{
	p_atomic_int_set(&(chan->paused), true);
}


void channel_resume(struct channel_t *chan)
{
	p_atomic_int_set(&(chan->paused), false);
}


void channel_set_volume(struct channel_t *chan, float volume)
{
	if (volume > 1.0f) volume = 1.0f;
	if (volume < 0.0f) volume = 0.0f;

	p_atomic_int_set(&(chan->volume), 255*volume);
}


void channel_set_pan(struct channel_t *chan, float pan)
{
	if (pan > 1.0f) pan = 1.0f;
	if (pan < -1.0f) pan = -1.0f;

	p_atomic_int_set(&(chan->pan), 128*pan);
}


void channel_get_next_sample(float *left, float *right, struct channel_t *chan)
{
	bool active = p_atomic_int_get(&(chan->active));
	bool paused = p_atomic_int_get(&(chan->paused));
	if (!active || paused) {
		/* skip this channel */
		*left = 0;
		*right = 0;
		return;
	}

	if (!p_mutex_trylock(chan->sound_mutex)) {
		/* can't lock mutex, skip */
		*left = 0;
		*right = 0;
		return;
	}

	*left = chan->sound.left[chan->pos];
	*right = chan->sound.right[chan->pos];
	chan->pos += 1;

	if (chan->pos >= chan->sound.len) {
		channel_reset(chan);
	}

	p_mutex_unlock(chan->sound_mutex);
}