aboutsummaryrefslogtreecommitdiff
path: root/mixer.c
blob: 2145fc331d85107a7fa3cfe8e7fa39b45943b8ac (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
/*
 * standalone sound mixer based on rxi's cmixer.
 */
#include <u.h>
#include <libc.h>
#include <thread.h>
#include "mixer.h"

static Mixer mixer;


static int wav_init(AudioSourceInfo*, int);
static int mp3_init(AudioSourceInfo*, int);

static int
min(int a, int b)
{
	return a < b? a: b;
}

static int
max(int a, int b)
{
	return a > b? a: b;
}

static int
clamp(int n, int min, int max)
{
	return n < min? min: n > max? max: n;
}

static double
fclamp(double n, double min, double max)
{
	return n < min? min: n > max? max: n;
}

static int
float2fixed(double n)
{
	return n*FIXED_UNIT;
}

static int
fixedlerp(int a, int b, int t)
{
	return a + ((b - a)*t >> FIXED_BITS);
}

//static void
//fprintsource(int fd, AudioSource *src)
//{
//	fprint(fd, "src 0x%p:\n"
//		"udata\t0x%p\n"
//		"samplerate\t%d\n"
//		"length\t%d\n"
//		"end\t%d\n"
//		"state\t%d\n"
//		"position\t%lld\n"
//		"gain l/r\t%d/%d\n"
//		"rate\t%d\n"
//		"nextfill\t%d\n"
//		"loop\t%d\n"
//		"rewind\t%d\n"
//		"active\t%d\n"
//		"gain\t%g\n"
//		"pan\t%g\n",
//		src, src->udata, src->samplerate, src->length, src->end, src->state, src->position,
//		src->lgain, src->rgain, src->rate, src->nextfill, src->loop, src->rewind,
//		src->active, src->gain, src->pan);
//
//}

void
audio_init(int samplerate)
{
	mixer.samplerate = samplerate;
	mixer.sources = nil;
	mixer.gain = FIXED_UNIT;
}

void
audio_set_master_gain(double gain)
{
	mixer.gain = float2fixed(gain);
}

static void
rewind_source(AudioSource *src)
{
	AudioEvent e;

	e.type = AUDIO_EVENT_REWIND;
	e.udata = src->udata;
	src->handler(&e);
	src->position = 0;
	src->rewind = 0;
	src->end = src->length;
	src->nextfill = 0;
}

static void
fill_source_buffer(AudioSource *src, int offset, int length)
{
	AudioEvent e;

	e.type = AUDIO_EVENT_SAMPLES;
	e.udata = src->udata;
	e.buffer = src->buffer + offset;
	e.length = length;
	src->handler(&e);
}

static void
process_source(AudioSource *src, int len)
{
	int i, n, a, b, p;
	int frame, count;
	s32int *dst;

	dst = mixer.buffer;

	/* Do rewind if flag is set */
	if(src->rewind)
		rewind_source(src);

	/* Process audio */
	while(len > 0){
		/* Get current position frame */
		frame = src->position >> FIXED_BITS;

		/* Fill buffer if required */
		if(frame + 3 >= src->nextfill){
			fill_source_buffer(src, 2*src->nextfill & MIXBUFMASK, MIXBUFSIZE/2);
			src->nextfill += MIXBUFSIZE/4;
		}

		/* Handle reaching the end of the playthrough */
		if(frame >= src->end){
			/*
			 * As streams continously fill the raw buffer in a loop we simply
			 * increment the end idx by one length and continue reading from it for
			 * another play-through
			 */
			src->end = frame + src->length;
			/* Set state and stop processing if we're not set to loop */
			if(!src->loop){
				src->state = AUDIO_STATE_STOPPED;
				break;
			}
		}

		/* Work out how many frames we should process in the loop */
		n = min(src->nextfill - 2, src->end) - frame;
		count = (n << FIXED_BITS) / src->rate;
		count = max(count, 1);
		count = min(count, len/2);
		len -= count * 2;

		/* Add audio to master buffer */
		if(src->rate == FIXED_UNIT){
			/* Add audio to buffer -- basic */
			n = 2*frame;
			for(i = 0; i < count; i++){
				dst[0] += (src->buffer[n&MIXBUFMASK] * src->lgain) >> FIXED_BITS;
				dst[1] += (src->buffer[(n+1)&MIXBUFMASK] * src->rgain) >> FIXED_BITS;
				n += 2;
				dst += 2;
			}
			src->position += count * FIXED_UNIT;
		}else{
			/* Add audio to buffer -- interpolated */
			for(i = 0; i < count; i++){
				n = (src->position >> FIXED_BITS) * 2;
				p = src->position & FIXED_MASK;

				a = src->buffer[n & MIXBUFMASK];
				b = src->buffer[(n+2) & MIXBUFMASK];
				dst[0] += fixedlerp(a, b, p)*src->lgain >> FIXED_BITS;
				n++;
				a = src->buffer[n & MIXBUFMASK];
				b = src->buffer[(n+2) & MIXBUFMASK];
				dst[1] += fixedlerp(a, b, p)*src->rgain >> FIXED_BITS;

				src->position += src->rate;
				dst += 2;
			}
		}
	}
}

void
audio_process(s16int *dst, int len)
{
	int i, x;
	AudioSource **s;

	/* Process in chunks of MIXBUFSIZE if `len` is larger than MIXBUFSIZE */
	while(len > MIXBUFSIZE){
		audio_process(dst, MIXBUFSIZE);
		dst += MIXBUFSIZE;
		len -= MIXBUFSIZE;
	}

	/* Zeroset internal buffer */
	memset(mixer.buffer, 0, len * sizeof(mixer.buffer[0]));

	/* Process active sources */
	s = &mixer.sources;
	while(*s){
		process_source(*s, len);
		/* Remove source from list if it is no longer playing */
		if((*s)->state != AUDIO_STATE_PLAYING){
			(*s)->active = 0;
			*s = (*s)->next;
		}else
			s = &(*s)->next;
	}

	/* Copy internal buffer to destination and clip */
	for(i = 0; i < len; i++){
		x = (mixer.buffer[i] * mixer.gain) >> FIXED_BITS;
		dst[i] = clamp(x, -32768, 32767);
	}
}

AudioSource *
audio_new_source(AudioSourceInfo *info)
{
	AudioSource *src;

	src = malloc(sizeof *src);
	if(src == nil){
		werrstr("allocation failed");
		return nil;
	}

	memset(src, 0, sizeof *src);
	src->handler = info->handler;
	src->length = info->length;
	src->samplerate = info->samplerate;
	src->udata = info->udata;
	audio_set_gain(src, 1);
	audio_set_pan(src, 0);
	audio_set_pitch(src, 1);
	audio_set_loop(src, 0);
	audio_stop(src);
	return src;
}

AudioSource *
audio_new_source_from_file(char *path)
{
	AudioSourceInfo info;
	uchar buf[12];
	int fd;

	fd = open(path, OREAD);
	if(fd < 0)
		return nil;

	memset(buf, 0, sizeof buf);
	readn(fd, buf, sizeof buf);
	seek(fd, 0, 0);
	if(memcmp(buf, "ID3", 3) == 0 || (buf[0] == 0xFF && buf[1] == 0xFB)){
		if(mp3_init(&info, fd) < 0){
			close(fd);
			return nil;
		}
	}else if(memcmp(buf+8, "WAVE", 4) == 0){
		if(wav_init(&info, fd) < 0){
			close(fd);
			return nil;
		}
	}else{
		werrstr("unsupported file format");
		close(fd);
		return nil;
	}
	close(fd);

	return audio_new_source(&info);
}

void
audio_destroy_source(AudioSource *src)
{
	AudioSource **s;
	AudioEvent e;

	if(src->active){
		s = &mixer.sources;
		while(*s) /* TODO potential spinlock. no bueno */
			if(*s == src){
				*s = src->next;
				break;
			}
	}

	e.type = AUDIO_EVENT_DESTROY;
	e.udata = src->udata;
	src->handler(&e);
	free(src);
}

double
audio_get_length(AudioSource *src)
{
	return src->length / (double)src->samplerate;
}

double
audio_get_position(AudioSource *src)
{
	return ((src->position >> FIXED_BITS) % src->length) / (double)src->samplerate;
}

int
audio_get_state(AudioSource *src)
{
	return src->state;
}

static void
recalc_source_gains(AudioSource *src)
{
	double l, r;
	double pan;

	pan = src->pan;
	l = src->gain * (pan <= 0 ? 1 : 1.0 - pan);
	r = src->gain * (pan >= 0 ? 1 : 1.0 + pan);
	src->lgain = float2fixed(l);
	src->rgain = float2fixed(r);
}

void
audio_set_gain(AudioSource *src, double gain)
{
	src->gain = gain;
	recalc_source_gains(src);
}

void
audio_set_pan(AudioSource *src, double pan)
{
	src->pan = fclamp(pan, -1.0, 1.0);
	recalc_source_gains(src);
}

void
audio_set_pitch(AudioSource *src, double pitch)
{
	double rate;

	if(pitch > 0)
		rate = (double)src->samplerate / mixer.samplerate * pitch;
	else
		rate = 0.001;
	src->rate = float2fixed(rate);
}

void
audio_set_loop(AudioSource *src, int loop)
{
	src->loop = loop;
}

void
audio_play(AudioSource *src)
{
	src->state = AUDIO_STATE_PLAYING;
	if(!src->active){
		src->active = 1;
		src->next = mixer.sources;
		mixer.sources = src;
	}
}

void
audio_pause(AudioSource *src)
{
	src->state = AUDIO_STATE_PAUSED;
}

void
audio_stop(AudioSource *src)
{
	src->state = AUDIO_STATE_STOPPED;
	src->rewind = 1;
}

static void
pcm_handler(AudioEvent *e)
{
	Pcm *pcm;
	s16int *dst;
	int len, i, n;

	pcm = e->udata;

	switch(e->type){
	case AUDIO_EVENT_DESTROY:
		free(pcm->data);
		free(pcm);
		break;
	case AUDIO_EVENT_SAMPLES:
		dst = e->buffer;
		len = e->length/2;
Fillbuf:
		n = min(len, pcm->len - pcm->off);
		len -= n;
		while(n--){
			i = 2*pcm->off;
			dst[0] = ((s16int*)pcm->data)[i];
			dst[1] = ((s16int*)pcm->data)[i+1];
			dst += 2;
			pcm->off++;
		}
		if(len > 0){
			pcm->off = 0;
			goto Fillbuf;
		}
		break;
	case AUDIO_EVENT_REWIND:
		pcm->off = 0;
		break;
	}
}

static void
mp3decproc(void *arg)
{
	int *pfd, fd;

	pfd = arg;
	fd = pfd[2];

	close(pfd[0]);
	dup(fd, 0);
	close(fd);
	dup(pfd[1], 1);
	close(pfd[1]);

	execl("/bin/audio/mp3dec", "mp3dec", nil);
	threadexitsall("execl: %r");
}

static int
mp3_init(AudioSourceInfo *info, int fd)
{
	Pcm *pcm;
	void *data;
	uchar buf[1024];
	int pfd[3], n, len;

	data = nil;
	len = 0;

	if(pipe(pfd) < 0){
		werrstr("pipe: %r");
		return -1;
	}
	pfd[2] = fd;

	procrfork(mp3decproc, pfd, mainstacksize, RFFDG|RFNAMEG|RFNOTEG);
	close(pfd[1]);
	while((n = read(pfd[0], buf, sizeof buf)) > 0){
		data = realloc(data, len+n);
		if(data == nil){
			werrstr("realloc: %r");
			return -1;
		}
		memmove((uchar*)data+len, buf, n);
		len += n;
	}
	close(pfd[0]);

	pcm = malloc(sizeof *pcm);
	if(pcm == nil){
		free(data);
		werrstr("malloc: %r");
		return -1;
	}
	pcm->depth = 16;
	pcm->chans = 2;
	pcm->rate = 44100;
	pcm->data = data;
	pcm->len = len/(pcm->depth/8)/pcm->chans;

	info->udata = pcm;
	info->handler = pcm_handler;
	info->samplerate = pcm->rate;
	info->length = pcm->len;

//	fprint(2, "pcm 0x%p:\ndata 0x%p\nlen %d\ndepth %d\nchans %d\nrate %d\n",
//		pcm, pcm->data, pcm->len, pcm->depth, pcm->chans, pcm->rate);
//	fprint(2, "info 0x%p:\nudata 0x%p\nhandler 0x%p\nsamplerate %d\nlength %d\n",
//		info, info->udata, info->handler, info->samplerate, info->length);

	return 0;
}

/* TODO generalize the *decproc and *_init procedures */
static void
wavdecproc(void *arg)
{
	int *pfd, fd;

	pfd = arg;
	fd = pfd[2];

	close(pfd[0]);
	dup(fd, 0);
	close(fd);
	dup(pfd[1], 1);
	close(pfd[1]);

	execl("/bin/audio/wavdec", "wavdec", nil);
	threadexitsall("execl: %r");
}

static int
wav_init(AudioSourceInfo *info, int fd)
{
	Pcm *pcm;
	void *data;
	uchar buf[1024];
	int pfd[3], n, len;

	data = nil;
	len = 0;

	if(pipe(pfd) < 0){
		werrstr("pipe: %r");
		return -1;
	}
	pfd[2] = fd;

	procrfork(wavdecproc, pfd, mainstacksize, RFFDG|RFNAMEG|RFNOTEG);
	close(pfd[1]);
	while((n = read(pfd[0], buf, sizeof buf)) > 0){
		data = realloc(data, len+n);
		if(data == nil){
			werrstr("realloc: %r");
			return -1;
		}
		memmove((uchar*)data+len, buf, n);
		len += n;
	}
	close(pfd[0]);

	pcm = malloc(sizeof *pcm);
	if(pcm == nil){
		free(data);
		werrstr("malloc: %r");
		return -1;
	}
	pcm->depth = 16;
	pcm->chans = 2;
	pcm->rate = 44100;
	pcm->data = data;
	pcm->len = len/(pcm->depth/8)/pcm->chans;

	info->udata = pcm;
	info->handler = pcm_handler;
	info->samplerate = pcm->rate;
	info->length = pcm->len;

//	fprint(2, "pcm 0x%p:\ndata 0x%p\nlen %d\ndepth %d\nchans %d\nrate %d\n",
//		pcm, pcm->data, pcm->len, pcm->depth, pcm->chans, pcm->rate);
//	fprint(2, "info 0x%p:\nudata 0x%p\nhandler 0x%p\nsamplerate %d\nlength %d\n",
//		info, info->udata, info->handler, info->samplerate, info->length);

	return 0;
}