ampler/ampler.c

108 lines
2.4 KiB
C

// ampler.c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <SDL2/SDL.h>
#define SAMPLE_RATE (44100)
#define CHANNELS (2)
#define FRAME_SAMPLES (SAMPLE_RATE / 60)
typedef uint8_t s8;
typedef uint16_t s16;
typedef struct Ampler_state Ampler_state;
struct Ampler_state {
int size;
SDL_AudioDeviceID playdev;
s8 track_l[SAMPLE_RATE * 120]; // 2 minutes
s8 track_r[SAMPLE_RATE * 120]; // 2 minutes
};
int audio_frame(Ampler_state *state) {
int queued = SDL_GetQueuedAudioSize(state -> playdev);
queued /= sizeof s16; // queued is in bytes
if(queued > FRAME_SAMPLES * CHANNELS * 2) return 0;
// else puts("queued audio.");
s16 silence[FRAME_SAMPLES * CHANNELS] = { 0 };
for (int i = 0; i < FRAME_SAMPLES; i += CHANNELS) {
int vol = 10;
silence[i] = (i/2) * vol - FRAME_SAMPLES / 2;
silence[i + 1] = (i/2) * vol - FRAME_SAMPLES / 2;
}
if(SDL_QueueAudio(state -> playdev, silence, sizeof silence))
puts(SDL_GetError());
return 1; // audio was qued
}
Ampler_state *init() {
Ampler_state *state = malloc(sizeof Ampler_state);
SDL_memset(state, 0, sizeof Ampler_state);
state -> size = sizeof Ampler_state;
SDL_AudioSpec want = { 0 }, have = { 0 };
want.freq = SAMPLE_RATE;
want.format = AUDIO_S16;
want.channels = CHANNELS;
want.samples = 512;
want.callback = NULL; // use que funcs
want.userdata = NULL;
state -> playdev = SDL_OpenAudioDevice(
NULL, // default device
0, // not capture
&want,
&have,
0 // no changes allowed
);
if(!(state -> playdev))
puts(SDL_GetError());
puts("init.");
return state;
}
int ampler_main(SDL_Window *w, SDL_Renderer *r, Ampler_state **u_data) {
if(*u_data == NULL) *u_data = init();
int old_size = (*u_data) -> size, new_size = sizeof Ampler_state;
if(old_size < new_size) {
printf("increasing size. %i to %i\n", old_size, new_size);
Ampler_state *nu = malloc(new_size);
SDL_memset(nu, 0, new_size);
SDL_memcpy(nu, *u_data, old_size);
nu -> size = new_size;
free(*u_data);
*u_data = nu;
}
Ampler_state *state = *u_data;
SDL_PauseAudioDevice(state -> playdev, 0); // unpause audio
while (1) {
SDL_Event e;
while(SDL_PollEvent(&e))
if (e.type == SDL_QUIT)
return 1;
audio_frame(state);
// draw_frame(w, r, state);
SDL_RenderPresent(r);
SDL_Delay(1);
if (!remove("reload-trigger")) {
SDL_PauseAudioDevice(state -> playdev, 1); // pause audio
puts("removed reload-trigger, reloading...");
return 0;
}
}
}