mdeutils/mauplay/audio.c

78 lines
1.7 KiB
C
Raw Normal View History

2025-11-23 21:12:09 +09:00
#include "mauplay.h"
#include <samplerate.h>
#include <stb_ds.h>
2025-11-24 19:49:20 +09:00
static MDEAudio audio;
2025-11-25 11:16:05 +09:00
MDEMutex audio_mutex;
2025-11-24 16:21:56 +09:00
queue_t* queue = NULL;
int queue_seek = -1;
int paused = 0;
2025-11-25 04:27:27 +09:00
int repeated = 0;
2025-11-23 21:12:09 +09:00
2025-11-24 19:49:20 +09:00
static void handler(MDEAudio handle, void* user, void* data, int frames) {
2025-11-23 21:12:09 +09:00
memset(data, 0, frames * 2 * 2);
2025-11-25 11:16:05 +09:00
MDEMutexLock(audio_mutex);
2025-11-24 16:21:56 +09:00
if(queue_seek != -1 && !paused) {
2025-11-24 19:49:20 +09:00
int from_frames = frames * queue[queue_seek].sound->context->sample_rate / MDEAudioRate;
2025-11-23 21:12:09 +09:00
float* from = malloc(from_frames * sizeof(*from) * 2);
float* to = malloc(frames * sizeof(*to) * 2);
SRC_DATA d;
int f;
d.data_in = from;
d.data_out = to;
d.input_frames = from_frames;
d.output_frames = frames;
2025-11-24 19:49:20 +09:00
d.src_ratio = (double)MDEAudioRate / queue[queue_seek].sound->context->sample_rate;
2025-11-23 21:12:09 +09:00
2025-11-24 19:49:20 +09:00
f = MDESoundReadFloat(queue[queue_seek].sound, from, from_frames);
2025-11-23 21:12:09 +09:00
src_simple(&d, SRC_SINC_BEST_QUALITY, 2);
src_float_to_short_array(to, data, frames * 2);
2025-11-24 16:21:56 +09:00
queue[queue_seek].frames += f;
2025-11-23 21:12:09 +09:00
free(from);
free(to);
if(f < from_frames) {
2025-11-25 04:27:27 +09:00
if(repeated) {
queue[queue_seek].frames = 0;
MDESoundSeek(queue[queue_seek].sound, 0);
} else {
queue_seek++;
if(queue_seek >= arrlen(queue)) {
queue_seek = -1;
}
2025-11-24 16:21:56 +09:00
}
2025-11-23 21:12:09 +09:00
}
}
2025-11-25 11:16:05 +09:00
MDEMutexUnlock(audio_mutex);
2025-11-23 21:12:09 +09:00
}
void audio_init(void) {
audio = MDEAudioOpen(handler, NULL);
2025-11-25 11:16:05 +09:00
audio_mutex = MDEMutexCreate();
2025-11-23 21:12:09 +09:00
MDEAudioStart(audio);
}
void audio_queue(const char* path) {
queue_t q;
q.path = MDEFileAbsolutePath(path);
2025-11-24 19:49:20 +09:00
q.sound = MDESoundOpen(q.path);
2025-11-23 21:12:09 +09:00
q.frames = 0;
2025-11-27 04:50:35 +09:00
if(q.sound == NULL) {
free(q.path);
return;
}
2025-11-25 11:16:05 +09:00
MDEMutexLock(audio_mutex);
2025-11-23 21:12:09 +09:00
arrput(queue, q);
2025-11-24 16:21:56 +09:00
if(queue_seek == -1) queue_seek = arrlen(queue) - 1;
ui_set_play_queue(arrlen(queue));
2025-11-25 11:16:05 +09:00
MDEMutexUnlock(audio_mutex);
2025-11-23 21:12:09 +09:00
}