-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudio8.c
More file actions
503 lines (422 loc) · 14.5 KB
/
audio8.c
File metadata and controls
503 lines (422 loc) · 14.5 KB
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
/*
File audio8.c
API for playing retro 8 bit audio
MIT License
Copyright (c) 2023 Brian Corriveau https://github.com/bcorriveau/audio8
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <SDL.h>
#include "audio8.h"
#define DEBUG 0
#define FREQUENCY (44100 / 2)
#define SAMPLES 512
#define CHANNELS 1
#define VOICES 4
#define MAX_VOLUME 10
typedef enum {FALSE=0, TRUE=1} BOOL;
typedef struct tone_ {
int hz; /* hz of tone being generate */
int wavelen; /* wave length of the tone */
struct {
Effect type;
unsigned int level; /* effect level */
int cur_level; /* current effect level */
int low; /* low for bounce */
int inc; /* bounce inc */
} effect;
int volume;
unsigned int si; /* current sample index for square wave */
} tone_t;
#define SCALENOTES 7 /* All Notes in an Octave minus the last one */
#define ACCIDENTAL_FLAT 0
#define ACCIDENTAL_NATURAL 1
#define ACCIDENTAL_SHARP 2
#define ACCIDENTALS 3
/* All the notes in one octave minus the last one. */
typedef struct octave_s {
int note[ACCIDENTALS][SCALENOTES];
} octave_t;
#define OCTAVE_MIN 0
#define OCTAVE_MAX 3
#define OCTAVES 4
/* Third octave contains middle C = 262Hz
* Notes - A B C D E F G */
octave_t octave[OCTAVES] = {
{{{ 52, 58, 62, 69, 78, 82, 93 }, /* flats */
{ 55, 62, 65, 73, 82, 87, 98 }, /* naturals */
{ 58, 65, 69, 78, 87, 93, 104 }}}, /* sharps */
{{{ 104, 117, 123, 139, 156, 165, 185 }, /* flats */
{ 110, 123, 131, 147, 165, 175, 196 }, /* naturals */
{ 117, 131, 139, 156, 175, 185, 208 }}}, /* sharps */
{{{ 208, 233, 247, 277, 311, 330, 370 }, /* flats */
{ 220, 247, 262, 293, 330, 349, 392 }, /* naturals */
{ 233, 262, 277, 311, 349, 370, 415 }}}, /* sharps */
{{{ 415, 466, 494, 554, 622, 659, 740 }, /* flats */
{ 440, 494, 523, 587, 659, 698, 784 }, /* naturals */
{ 466, 523, 554, 622, 698, 740, 831 }}} /* sharps */
};
/* Audio specification obtained */
static SDL_AudioSpec *obtained;
/* user tone data */
static tone_t user_tone[VOICES];
/* gen_tone_val - generates a value for a tone for a sample index
*
* Params:
* si: sample index
* wavelen: wavelength
* volume: volume
* level: effect level
*
* Return: value to add to sample
*/
int gen_tone_val(int si, int wavelen, int volume, int effect_level)
{
int val;
if ((si % wavelen) < (wavelen / 2) ) {
val = volume;
}
else {
val = 0 - volume;
}
/* check if effect should be applied - if si / level is odd then effect is on */
if (effect_level && (si / effect_level % 2))
/* application of effect puts a hole in the sound wave */
val = 0;
return val;
}
/* gen_noise - generates a noise value using LFSR
*
* Params:
* volume: volume
*
* Return: value to add to sample
*/
int gen_noise(int volume)
{
static struct {
unsigned int reg : 24;
} LFSR = { 0x7FFFF8 }; /* initial state - each call increments */
unsigned int feedback, value, silent, positive;
/* two taps: first used to indicate silence, 2nd used for sign of wave */
silent = LFSR.reg >> 22 & 0x1;
positive = LFSR.reg >> 20 & 0x1;
/* feed back into LFSR */
feedback = (LFSR.reg >> 17 & 0x1) ^ (LFSR.reg >> 22 & 0x1);
LFSR.reg = (LFSR.reg << 1) | feedback;
/* if not silent then add positve or negative value */
if (!silent) {
if (positive)
value = volume;
else
value = 0 - volume;
} else {
value = 0;
}
if (DEBUG && (LFSR.reg == 0x7FFFF8)) printf("wrapped\n");
if (DEBUG) printf("%x %d %d %d\n", LFSR.reg, silent, positive, value);
return value;
}
/* create_tone_sq - creates a tone with a square wave
*
* Params:
* user_tone - tones to create a wave. hz is zero for silence.
* stream - points to where to put samples
* len - length of stream in bytes
*/
void create_tone_sq(tone_t *user_tone, Uint8 *stream, int len )
{
int i, samples;
int v; /* voice */
Uint8 *datap, value;
datap = (Uint8 *) stream;
samples = len / sizeof(value) / CHANNELS;
/* first fill with silence */
memset(datap, obtained->silence, len);
if (DEBUG) {
printf("\n***Filling %d bytes (%d samples) from sample %d for %d hz effect %d wavelen %d\n",
len, samples, user_tone[0].si,
user_tone[0].hz,
user_tone[0].effect.level,
user_tone[0].wavelen);
}
for(i=0; i < samples; i++) {
for (v=0; v < VOICES; v++) {
if ((user_tone[v].hz == 0) && (user_tone[v].effect.type != NOISE))
continue;
/* each voice adds its value to the sample */
if (user_tone[v].effect.type == NOISE) {
*datap += gen_noise(user_tone[v].volume);
} else {
*datap += gen_tone_val(user_tone[v].si,
user_tone[v].wavelen,
user_tone[v].volume,
user_tone[v].effect.cur_level);
}
user_tone[v].si++; /* let si wrap */
/* adjust effect level per effect type */
switch (user_tone[v].effect.type) {
case NONE:
case FIXED:
case NOISE:
break;
case BOUNCE:
if (user_tone[v].si % user_tone[v].wavelen == 0) {
user_tone[v].effect.cur_level += user_tone[v].effect.inc;
if (user_tone[v].effect.cur_level < user_tone[v].effect.low) {
user_tone[v].effect.cur_level += 2;
user_tone[v].effect.inc = 1;
} else if (user_tone[v].effect.cur_level > user_tone[v].effect.level) {
user_tone[v].effect.cur_level -= 2;
user_tone[v].effect.inc = -1;
}
}
break;
case UP:
if (user_tone[v].si % user_tone[v].wavelen == 0) {
user_tone[v].effect.cur_level--;
if (user_tone[v].effect.cur_level <= 1)
user_tone[v].effect.cur_level = user_tone[v].effect.level;
}
break;
case DOWN:
if (user_tone[v].si % user_tone[v].wavelen == 0) {
user_tone[v].effect.cur_level++;
if (user_tone[v].effect.cur_level >= user_tone[v].effect.level)
user_tone[v].effect.cur_level = 1;
}
break;
}
}
if (DEBUG) {
if (i < 64) {
printf("%d ",*datap);
}
if (i == 64) {
printf("%d\n", *datap);
}
}
datap++;
}
}
/* create_tone_cb - calls the selected tone generator
*
* Params:
* user_tone - user tone array, element per voice
* stream - points to where to put samples
* len - length of stream in bytes
*/
void create_tone_cb(void *user_tone, Uint8 *stream, int len )
{
/* get pointer to the user tone to play */
create_tone_sq(user_tone, stream, len);
}
/* play_tone - plays a tone for a duration
*
* Params:
* voice - voice for tone, 0-3
* hz - hertz of the tone (integer)
* duration - duration in ms. 50ms increments, or 0 for continuous
* volume - volume (0-10)
* effect - type of effect
* effect_level - value of effect, higher numbers give higher effect
* effect_low - low value of effect with bounce
*
* Notes:
* Duration in 50ms increments.
* To Stop a continuous tone play 0 hz with 0 volume.
* Noise effect uses effect level 0.
*/
void play_tone(int voice, int hz, int duration, int volume, Effect effect, int effect_level, int effect_low)
{
/* sanity check - return if the argments are invalid */
if (effect > EFFECTS || volume > MAX_VOLUME || volume < 0 || voice < 0 || voice >= VOICES || duration < 0) {
if (DEBUG) printf("no tone to play\n");
return;
}
if (effect == NOISE) {
effect_level = 0;
hz = 0; /* dummy */
}
user_tone[voice].hz = hz;
if (hz == 0)
user_tone[voice].wavelen = 0;
else
user_tone[voice].wavelen = (((FREQUENCY * 10)/ hz) + 5) / 10;
user_tone[voice].effect.type = effect;
if (effect) {
user_tone[voice].effect.level = abs(effect_level) * 8; /* absolute value for safety - x 8 for final effect value */
user_tone[voice].effect.low = abs(effect_low) * 8;
user_tone[voice].effect.inc = 1;
} else {
user_tone[voice].effect.level = 0;
}
user_tone[voice].effect.cur_level = user_tone[voice].effect.level;
/* adjust volume for range with voice */
user_tone[voice].volume = volume * (obtained->silence / VOICES / MAX_VOLUME);
user_tone[voice].si = 0; /* current sample index */
if (DEBUG) printf("playing tone %d time(ms) = %d , volume = %d\n", hz, duration, volume);
/* this manually limits the tone length in increments of 50ms */
SDL_PauseAudio(0);
if (duration) {
while (duration > 0) {
SDL_Delay(50);
duration -= 50;
}
user_tone[voice].hz = 0;
user_tone[voice].effect.type = NONE;
}
}
/* play_notes - plays notes from the given string
*
* Params:
* increment: time in ms (minimum 50ms increments)
* volume: note volume (0-10)
* notes: Notes in the form of a null terminated string.
* Notes are A-G, '-' to hold note, space for silence.
* Notes can be flatted with 'b' or sharped with '#'.
* Octave can be moved up and down with '^' or 'v'.
* Octave can also be set with a number 1-4.
* Notes are played with voice 0.
*
*/
void play_notes(int increment, int volume, char *notes)
{
int i, len, hz;
int a; /* note index */
int acc; /* note accidental */
int oct; /* octave */
int duration;
BOOL adjust;
if (increment < 50)
return;
len = strlen(notes);
i = 0;
oct = 0;
while (i < len)
{
a = SCALENOTES; /* default to max index + 1 */
acc = ACCIDENTAL_NATURAL; /* default to natural notes */
duration = increment;
/* check for octave adjust and perform if needed */
adjust = TRUE;
switch (notes[i]) {
case '^':
oct++;
if (oct > OCTAVE_MAX) {
oct = OCTAVE_MAX;
}
break;
case 'v':
oct--;
if (oct < OCTAVE_MIN) {
oct = OCTAVE_MIN;
}
break;
case '1':
case '2':
case '3':
case '4':
oct = notes[i] - '1';
break;
default:
adjust = FALSE;
break;
}
if (adjust) {
i++;
continue;
}
switch (notes[i]) {
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
a = notes[i] - 'A';
break;
case ' ':
hz = 0; /* silence for a space */
break;
default:
break;
}
i++;
/* adjust for flats or sharps */
switch (notes[i]) {
case 'b':
acc--;
i++;
break;
case '#':
acc++;
i++;
break;
default :
break;
}
/* set hz if not silence */
if (a < SCALENOTES) {
hz = octave[oct].note[acc][a];
}
while (notes[i] == '-') {
duration += increment;
i++;
}
play_tone(0, hz, duration, volume, NONE, 0, 0);
if (DEBUG) printf("play tone %c %d\n", notes[i-1], hz);
}
}
/* audio_init - initialize audio */
void audio_init(void)
{
/* Audio Setup */
SDL_AudioSpec *desired;
desired = (SDL_AudioSpec*)malloc(sizeof(SDL_AudioSpec));
obtained = (SDL_AudioSpec*)malloc(sizeof(SDL_AudioSpec));
desired->freq = FREQUENCY;
desired->format = AUDIO_U8;
desired->channels = CHANNELS;
desired->samples = SAMPLES;
desired->callback = create_tone_cb;
desired->userdata = user_tone;
SDL_Init( SDL_INIT_AUDIO);
/* Open the audio device */
if ( SDL_OpenAudio(desired, obtained) < 0 ){
fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
exit(-1);
}
/* desired spec is no longer needed */
if (desired->format != obtained->format) {
printf("obtained format (%d) different than desired format (%d)\n"
,obtained->format,desired->format);
}
if (DEBUG) printf("freq %d samples %d channels %d size %d silence %d\n",
obtained->freq,
obtained->samples,
obtained->channels,
obtained->size,
obtained->silence);
free(desired);
desired = NULL;
/* clear out user tones */
memset(user_tone, 0, sizeof(user_tone));
}
/* audio_close - Shut down audio */
void audio_close(void)
{
SDL_PauseAudio(1);
SDL_Quit();
free(obtained);
}