From f3bf686a529b4f42bde189b66137103feac817af Mon Sep 17 00:00:00 2001 From: David Oberhollenzer Date: Tue, 19 Jul 2022 22:10:23 +0200 Subject: [PATCH] Read 32 bit float audio PCM samples from stdin Signed-off-by: David Oberhollenzer --- shadermeh.c | 52 +++++++++++++++++++++++++++++++++++++++++++++------- shadermeh.h | 1 + 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/shadermeh.c b/shadermeh.c index c2be88c..cbeaf2c 100644 --- a/shadermeh.c +++ b/shadermeh.c @@ -23,6 +23,39 @@ static GLfloat vertex_buffer[] = { static GLubyte audio_buffer[AUDIO_SAMPLES * AUDIO_CHANNELS]; static float audio_sample_data[AUDIO_SAMPLES]; +static int try_fetch_audio(void) +{ + size_t i, count = 0; + int ret; + + for (;;) { + ret = read(STDIN_FILENO, + (char *)audio_sample_data + count, + sizeof(audio_sample_data) - count); + + if (ret < 0) { + if (errno == EINTR) + continue; + if (errno == EAGAIN) + break; + perror("stdin"); + return -1; + } + + if (ret == 0) + break; + + count += ret; + } + + for (i = 0; i < (count / sizeof(float)); ++i) { + audio_buffer[i + AUDIO_SAMPLES] = audio_sample_data[i] * 127.0f + 127.0f; + audio_buffer[i] = 0.0f; + } + + return 0; +} + static double diff_timespec(const struct timespec *time1, const struct timespec *time0) { @@ -181,6 +214,15 @@ int main(int argc, char **argv) } } + if (have_audio) { + int flags = fcntl(STDIN_FILENO, F_GETFL, 0); + + if (fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK)) { + perror("making stdin non-blocking"); + return EXIT_FAILURE; + } + } + if (!shader_file) { fputs(usage_str, stderr); fputs("No shader file specified!\n", stderr); @@ -323,15 +365,11 @@ int main(int argc, char **argv) glClear(GL_COLOR_BUFFER_BIT); if (have_audio) { + if (try_fetch_audio()) + break; + glBindTexture(GL_TEXTURE_2D, sound_tex); - for (i = 0; i < AUDIO_SAMPLES; ++i) { - audio_buffer[i] = 255.0f * audio_sample_data[i]; - - audio_buffer[AUDIO_SAMPLES + i] = - audio_buffer[i]; - } - glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, AUDIO_SAMPLES, AUDIO_CHANNELS, 0, GL_RED, GL_UNSIGNED_BYTE, audio_buffer); diff --git a/shadermeh.h b/shadermeh.h index df43001..88b0c8a 100644 --- a/shadermeh.h +++ b/shadermeh.h @@ -23,6 +23,7 @@ #include #include #include +#include #include #include