dolphin/Source/Core/AudioCommon/CubebStream.cpp
Dentomologist 3b97a7bded CubebStream: Use WorkQueueThread::PushBlocking instead of sync_event
Push and wait on WorkQueueThread items using PushBlocking. Previously we
created a Common::Event sync_event on the caller's stack, called Wait on
it, then had the WorkQueueThread call Set on the sync_event once the
thread was done.

In addition to being simpler the new way avoids a use-after-free that
could happen in convoluted and unlikely yet possible thread scheduling
sequences.

One such case can be triggered as follows:

* Set your audio backend to Cubeb
* In CubebStream::SetVolume set a breakpoint at the call to Wait and at
  the call to cubeb_stream_set_volume.
* Start a game.
* Continue until the Cubeb Worker thread hits the
  cubeb_stream_set_volume breakpoint and Emuthread hits the Wait
  breakpoint, freezing each thread when it hits its breakpoint.
* Unfreeze Cubeb Worker.
* In Event::Set set a breakpoint at the end of the scope containing the
  lock_guard such that the guard has been constructed but not destructed
  when the breakpoint is hit.
* Continue until that breakpoint is hit by Cubeb Worker. If other
  threads hit it first keep going.
* Freeze Cubeb Worker.
* For convenience remove the breakpoint in Event::Set so other threads
  don't trigger it.
* In CubebStream::SetRunning set a breakpoint at the call to Wait.
* Unfreeze Emuthread and continue until the breakpoint is hit.
* In Cubeb Worker go to Event::Set and examine the values of m_mutex's
  member variables. In Visual Studio Debug these are locking_thread_id
  == 0xcccccc01 and ownership_levels == 0xcccccccc. This is the result
  of Visual Studio overwriting the memory used on the stack by
  sync_event in CubebStream::SetVolume with cc bytes to represent
  uninitialized memory on the stack (since that function already
  returned), and then allocating enough memory on the stack when calling
  AudioCommon::SetSoundStreamRunning and then CubebStream::SetRunning
  that it overwrote one byte of the memory formerly occupied by
  locking_thread_id.
* If you unfreeze Cubeb Worker at this point it will trigger the lock
  guard's destructor which will then try to unlock m_mutex. Since
  m_mutex is no longer in scope this is a use-after-free, and in VS
  debug triggers a debug assert due to locking_thread_id not matching
  the current thread id.
2025-11-07 13:19:18 -08:00

151 lines
3.5 KiB
C++

// Copyright 2017 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "AudioCommon/CubebStream.h"
#include <cubeb/cubeb.h>
#include "AudioCommon/CubebUtils.h"
#include "Common/CommonTypes.h"
#include "Common/Event.h"
#include "Common/Logging/Log.h"
#include "Common/ScopeGuard.h"
#include "Core/Config/MainSettings.h"
#ifdef _WIN32
#include <Objbase.h>
#endif
// ~10 ms - needs to be at least 240 for surround
constexpr u32 BUFFER_SAMPLES = 512;
long CubebStream::DataCallback(cubeb_stream* stream, void* user_data, const void* /*input_buffer*/,
void* output_buffer, long num_frames)
{
const auto* const self = static_cast<CubebStream*>(user_data);
if (self->m_stereo)
self->m_mixer->Mix(static_cast<short*>(output_buffer), num_frames);
else
self->m_mixer->MixSurround(static_cast<float*>(output_buffer), num_frames);
return num_frames;
}
void CubebStream::StateCallback(cubeb_stream* stream, void* user_data, cubeb_state state)
{
}
CubebStream::CubebStream()
#ifdef _WIN32
: m_work_queue("Cubeb Worker")
{
m_work_queue.PushBlocking([this] {
auto const result = CoInitializeEx(nullptr, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE);
m_coinit_success = result == S_OK;
m_should_couninit = result == S_OK || result == S_FALSE;
});
}
#else
= default;
#endif
bool CubebStream::Init()
{
bool return_value = false;
#ifdef _WIN32
if (!m_coinit_success)
return false;
m_work_queue.PushBlocking([this, &return_value] {
#endif
m_ctx = CubebUtils::GetContext();
if (m_ctx)
{
m_stereo = !Config::ShouldUseDPL2Decoder();
cubeb_stream_params params{};
params.rate = m_mixer->GetSampleRate();
if (m_stereo)
{
params.channels = 2;
params.format = CUBEB_SAMPLE_S16NE;
params.layout = CUBEB_LAYOUT_STEREO;
}
else
{
params.channels = 6;
params.format = CUBEB_SAMPLE_FLOAT32NE;
params.layout = CUBEB_LAYOUT_3F2_LFE;
}
u32 minimum_latency = 0;
if (cubeb_get_min_latency(m_ctx.get(), &params, &minimum_latency) != CUBEB_OK)
ERROR_LOG_FMT(AUDIO, "Error getting minimum latency");
INFO_LOG_FMT(AUDIO, "Minimum latency: {} frames", minimum_latency);
return_value =
cubeb_stream_init(m_ctx.get(), &m_stream, "Dolphin Audio Output", nullptr, nullptr,
nullptr, &params, std::max(BUFFER_SAMPLES, minimum_latency),
DataCallback, StateCallback, this) == CUBEB_OK;
}
#ifdef _WIN32
});
#endif
return return_value;
}
bool CubebStream::SetRunning(bool running)
{
bool return_value = false;
#ifdef _WIN32
if (!m_coinit_success)
return false;
m_work_queue.PushBlocking([this, running, &return_value] {
#endif
if (running)
return_value = cubeb_stream_start(m_stream) == CUBEB_OK;
else
return_value = cubeb_stream_stop(m_stream) == CUBEB_OK;
#ifdef _WIN32
});
#endif
return return_value;
}
CubebStream::~CubebStream()
{
#ifdef _WIN32
m_work_queue.PushBlocking([this] {
#endif
cubeb_stream_stop(m_stream);
cubeb_stream_destroy(m_stream);
#ifdef _WIN32
if (m_should_couninit)
{
m_should_couninit = false;
CoUninitialize();
}
m_coinit_success = false;
});
#endif
m_ctx.reset();
}
void CubebStream::SetVolume(int volume)
{
#ifdef _WIN32
if (!m_coinit_success)
return;
m_work_queue.PushBlocking([this, volume] {
#endif
cubeb_stream_set_volume(m_stream, volume / 100.0f);
#ifdef _WIN32
});
#endif
}