Read 32 bit float audio PCM samples from stdin

Signed-off-by: David Oberhollenzer <goliath@infraroot.at>
This commit is contained in:
David Oberhollenzer 2022-07-19 22:10:23 +02:00
parent 770deae6cd
commit f3bf686a52
2 changed files with 46 additions and 7 deletions

View file

@ -23,6 +23,39 @@ static GLfloat vertex_buffer[] = {
static GLubyte audio_buffer[AUDIO_SAMPLES * AUDIO_CHANNELS]; static GLubyte audio_buffer[AUDIO_SAMPLES * AUDIO_CHANNELS];
static float audio_sample_data[AUDIO_SAMPLES]; 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, static double diff_timespec(const struct timespec *time1,
const struct timespec *time0) 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) { if (!shader_file) {
fputs(usage_str, stderr); fputs(usage_str, stderr);
fputs("No shader file specified!\n", stderr); fputs("No shader file specified!\n", stderr);
@ -323,15 +365,11 @@ int main(int argc, char **argv)
glClear(GL_COLOR_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT);
if (have_audio) { if (have_audio) {
if (try_fetch_audio())
break;
glBindTexture(GL_TEXTURE_2D, sound_tex); 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, glTexImage2D(GL_TEXTURE_2D, 0, GL_R8,
AUDIO_SAMPLES, AUDIO_CHANNELS, 0, AUDIO_SAMPLES, AUDIO_CHANNELS, 0,
GL_RED, GL_UNSIGNED_BYTE, audio_buffer); GL_RED, GL_UNSIGNED_BYTE, audio_buffer);

View file

@ -23,6 +23,7 @@
#include <unistd.h> #include <unistd.h>
#include <stdio.h> #include <stdio.h>
#include <errno.h> #include <errno.h>
#include <fcntl.h>
#include <poll.h> #include <poll.h>
#include <time.h> #include <time.h>