From d044231bfcb246ff3f1edc4cdd73e0f8e4c42a6d Mon Sep 17 00:00:00 2001 From: Norihiro Kamae Date: Tue, 3 May 2022 23:06:23 +0900 Subject: [PATCH] libobs/media-io: Sleep to next audio time accurately Prior to this change, the audio thread roughly waits the time of `AUDIO_OUTPUT_FRAMES`, and consecutively processes twice or more if the latency is accumulated. This behavior causes fluctuation of timing to output audio packets. This change introduces `os_sleepto_ns_fast` so that the audio packets will be periodically output. --- libobs/media-io/audio-io.c | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/libobs/media-io/audio-io.c b/libobs/media-io/audio-io.c index dc93bfeaf..df88a4c24 100644 --- a/libobs/media-io/audio-io.c +++ b/libobs/media-io/audio-io.c @@ -213,10 +213,6 @@ static void *audio_thread(void *param) uint64_t samples = 0; uint64_t start_time = os_gettime_ns(); uint64_t prev_time = start_time; - uint64_t audio_time = prev_time; - uint32_t audio_wait_time = - (uint32_t)(audio_frames_to_ns(rate, AUDIO_OUTPUT_FRAMES) / - 1000000); os_set_thread_name("audio-io: audio thread"); @@ -225,21 +221,16 @@ static void *audio_thread(void *param) "audio_thread(%s)", audio->info.name); while (os_event_try(audio->stop_event) == EAGAIN) { - uint64_t cur_time; + samples += AUDIO_OUTPUT_FRAMES; + uint64_t audio_time = + start_time + audio_frames_to_ns(rate, samples); - os_sleep_ms(audio_wait_time); + os_sleepto_ns_fast(audio_time); profile_start(audio_thread_name); - cur_time = os_gettime_ns(); - while (audio_time <= cur_time) { - samples += AUDIO_OUTPUT_FRAMES; - audio_time = - start_time + audio_frames_to_ns(rate, samples); - - input_and_output(audio, audio_time, prev_time); - prev_time = audio_time; - } + input_and_output(audio, audio_time, prev_time); + prev_time = audio_time; profile_end(audio_thread_name);