cubeb_sink: Protect queue against multithreaded access

This commit is contained in:
MerryMage 2018-08-31 18:42:28 +01:00
parent ac419c8612
commit 7daed185cb

View File

@ -2,6 +2,7 @@
// Licensed under GPLv2 or any later version // Licensed under GPLv2 or any later version
// Refer to the license.txt file included. // Refer to the license.txt file included.
#include <mutex>
#include <vector> #include <vector>
#include <cubeb/cubeb.h> #include <cubeb/cubeb.h>
#include "audio_core/audio_types.h" #include "audio_core/audio_types.h"
@ -17,6 +18,7 @@ struct CubebSink::Impl {
cubeb* ctx = nullptr; cubeb* ctx = nullptr;
cubeb_stream* stream = nullptr; cubeb_stream* stream = nullptr;
std::mutex queue_mutex;
std::vector<s16> queue; std::vector<s16> queue;
static long DataCallback(cubeb_stream* stream, void* user_data, const void* input_buffer, static long DataCallback(cubeb_stream* stream, void* user_data, const void* input_buffer,
@ -97,6 +99,8 @@ void CubebSink::EnqueueSamples(const s16* samples, size_t sample_count) {
if (!impl->ctx) if (!impl->ctx)
return; return;
std::lock_guard lock{impl->queue_mutex};
impl->queue.reserve(impl->queue.size() + sample_count * 2); impl->queue.reserve(impl->queue.size() + sample_count * 2);
std::copy(samples, samples + sample_count * 2, std::back_inserter(impl->queue)); std::copy(samples, samples + sample_count * 2, std::back_inserter(impl->queue));
} }
@ -105,6 +109,7 @@ size_t CubebSink::SamplesInQueue() const {
if (!impl->ctx) if (!impl->ctx)
return 0; return 0;
std::lock_guard lock{impl->queue_mutex};
return impl->queue.size() / 2; return impl->queue.size() / 2;
} }
@ -116,6 +121,8 @@ long CubebSink::Impl::DataCallback(cubeb_stream* stream, void* user_data, const
if (!impl) if (!impl)
return 0; return 0;
std::lock_guard lock{impl->queue_mutex};
size_t frames_to_write = std::min(impl->queue.size() / 2, static_cast<size_t>(num_frames)); size_t frames_to_write = std::min(impl->queue.size() / 2, static_cast<size_t>(num_frames));
memcpy(buffer, impl->queue.data(), frames_to_write * sizeof(s16) * 2); memcpy(buffer, impl->queue.data(), frames_to_write * sizeof(s16) * 2);