Skip to content

Commit 1c4acf6

Browse files
fix: use condition variable for audio buffer synchronization
Introduces a std::condition_variable to WebRTCService for improved synchronization of the audio buffer. The audio thread now waits on the condition variable instead of busy-waiting, and the data channel handler notifies the thread when new audio data arrives. This change reduces CPU usage and improves efficiency.
1 parent 4ea539f commit 1c4acf6

3 files changed

Lines changed: 5 additions & 1 deletion

File tree

src/client/main.cc

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -671,8 +671,9 @@ void ClientContext::init_webrtc_service() {
671671
if (!audio_thread) {
672672
audio_thread.emplace([&]() {
673673
while (true) {
674-
std::this_thread::yield();
675674
std::unique_lock<std::mutex> lock(webrtc_service->audioBufferMutex_);
675+
webrtc_service->audioBufferCv_.wait(
676+
lock, [&]() { return !webrtc_service->audioBuffer_.empty(); });
676677
while (webrtc_service->audioBuffer_.size() >= 960) {
677678
std::vector<uint8_t> buffer(webrtc_service->audioBuffer_.begin(),
678679
webrtc_service->audioBuffer_.begin() +

src/client/webrtc_service.cc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ void WebRTCService::setup_data_channel() {
109109
}
110110
std::lock_guard<std::mutex> lock(audioBufferMutex_);
111111
audioBuffer_.insert(audioBuffer_.end(), data.begin(), data.end());
112+
audioBufferCv_.notify_one();
112113
}
113114
});
114115
}

src/client/webrtc_service.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
#include "httplib.h"
55
#include "rtc/configuration.hpp"
6+
#include <condition_variable>
67
#include <deque>
78
#include <functional>
89
#include <memory>
@@ -39,6 +40,7 @@ struct WebRTCService {
3940
std::shared_ptr<rtc::PeerConnection> pc_;
4041
std::shared_ptr<rtc::DataChannel> dc_;
4142
std::deque<uint8_t> audioBuffer_;
43+
std::condition_variable audioBufferCv_;
4244
std::mutex audioBufferMutex_;
4345
StatusCallback status_callback_;
4446
std::string session_id_;

0 commit comments

Comments
 (0)