From a0cab9cebca0e9530a825b5b83d8dd5df446fcb8 Mon Sep 17 00:00:00 2001 From: David Li Date: Tue, 24 May 2022 14:56:43 +0800 Subject: add delay to drain the data in ALSA ringbuffer Bug: 230045556 Test: mm tinyplay Change-Id: I20cbc048dc40c2e770e2c9942ce03add6aee70fb --- tinyplay.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/tinyplay.c b/tinyplay.c index 0354df6..1cd74e7 100644 --- a/tinyplay.c +++ b/tinyplay.c @@ -33,6 +33,7 @@ #include #include #include +#include #define ID_RIFF 0x46464952 #define ID_WAVE 0x45564157 @@ -59,7 +60,7 @@ struct chunk_fmt { uint16_t bits_per_sample; }; -static int close = 0; +static int closing = 0; void play_sample(FILE *file, unsigned int card, unsigned int device, unsigned int channels, unsigned int rate, unsigned int bits, unsigned int period_size, @@ -69,7 +70,7 @@ void stream_close(int sig) { /* allow the stream to be closed gracefully */ signal(sig, SIG_IGN); - close = 1; + closing = 1; } int main(int argc, char **argv) @@ -270,7 +271,15 @@ void play_sample(FILE *file, unsigned int card, unsigned int device, unsigned in } data_sz -= num_read; } - } while (!close && num_read > 0 && data_sz > 0); + } while (!closing && num_read > 0 && data_sz > 0); + + if (!closing) { + // drain the data in the ALSA ring buffer before closing the PCM device + unsigned long sleep_time_in_us = + (unsigned long) pcm_get_buffer_size(pcm) * 1000UL / ((unsigned long) rate / 1000UL); + printf("Draining... Wait %lu us\n", sleep_time_in_us); + usleep(sleep_time_in_us); + } free(buffer); pcm_close(pcm); -- cgit v1.2.3