Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions obs-studio-server/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,8 @@ SET(osn-server_SOURCES
"${PROJECT_SOURCE_DIR}/source/osn-audio-bitrate.hpp"
"${PROJECT_SOURCE_DIR}/source/osn-output.cpp"
"${PROJECT_SOURCE_DIR}/source/osn-output.hpp"
"${PROJECT_SOURCE_DIR}/source/shutdown-watchdog.cpp"
"${PROJECT_SOURCE_DIR}/source/shutdown-watchdog.hpp"
"${PROJECT_SOURCE_DIR}/source/osn-properties.cpp"
"${PROJECT_SOURCE_DIR}/source/osn-properties.hpp"
"${PROJECT_SOURCE_DIR}/source/osn-scene.cpp"
Expand Down Expand Up @@ -669,6 +671,7 @@ if(BUILD_TESTING)
"tests/test-nodeobs-enhanced-broadcasting-vod.cpp"
"tests/test-osn-scene-relative-coordinates.cpp"
"tests/test-osn-video-mix-lifecycle.cpp"
"tests/test-shutdown-watchdog.cpp"
"tests/obs-setup.cpp"
"tests/obs-setup.hpp"
"tests/scoped-helpers.hpp"
Expand Down
6 changes: 6 additions & 0 deletions obs-studio-server/source/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@

#include "util-crashmanager.h"
#include "shared.hpp"
#include "shutdown-watchdog.hpp"

#ifndef OSN_VERSION
#define OSN_VERSION "DEVMODE_VERSION"
Expand Down Expand Up @@ -341,6 +342,7 @@ int main(int argc, char *argv[])
// before going further with shutdown. It needed for usecase where obs64 process stay alive and
// continue streaming till user confirms exit in crash-handler.
OBS_API::WaitCrashHandlerClose(waitBeforeClosing);
osn::ShutdownWatchdog::Instance().Arm("Prepare", osn::shutdown_budget::Prepare);
#endif
osn::Source::finalize_global_signals();

Expand All @@ -349,6 +351,10 @@ int main(int argc, char *argv[])

// Then, shutdown OBS
OBS_API::destroyOBS_API();
#ifdef WIN32
// Skips exit-time work (DLL detach, static destructors) that can hang.
TerminateProcess(GetCurrentProcess(), 0);
#endif
#ifdef __APPLE__
util::CrashManager::DeleteBriefCrashInfoFile();
if (override_std_fd) {
Expand Down
46 changes: 30 additions & 16 deletions obs-studio-server/source/nodeobs_api.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@

//to destroy cpu usage object
#include "osn-global.hpp"
#include "shutdown-watchdog.hpp"

#include <sys/types.h>

Expand Down Expand Up @@ -1098,6 +1099,10 @@ void OBS_API::OBS_API_destroyOBS_API(void *data, const int64_t id, const std::ve
osn::Source::finalize_global_signals();
/* END INJECT osn::Source::Manager */
destroyOBS_API();
#ifdef _WIN32
// The process keeps running after this call.
osn::ShutdownWatchdog::Instance().Disarm();
#endif
rval.push_back(ipc::value((uint64_t)ErrorCode::Ok));
AUTO_DEBUG;
}
Expand Down Expand Up @@ -1425,17 +1430,6 @@ BOOL ConnectToNewClient(HANDLE hPipe, LPOVERLAPPED lpo)
return fPendingIO;
}

VOID DisconnectAndReconnect(void)
{
if (!DisconnectNamedPipe(Pipe.hPipeInst)) {
return;
}

Pipe.fPendingIO = ConnectToNewClient(Pipe.hPipeInst, &(Pipe.oOverlap));

Pipe.dwState = Pipe.fPendingIO ? CONNECTING_STATE : READING_STATE;
}

bool prepareTerminationPipe()
{
LPCTSTR lpszPipename = TEXT("\\\\.\\pipe\\exit-slobs-crash-handler");
Expand Down Expand Up @@ -1479,7 +1473,6 @@ void acknowledgeTerminate()
// We timeout, crash handler failed to send the shutdown acknowledge,
// we move forward with the shutdown procedure
crash_handler_exit = true;
CloseHandle(Pipe.hPipeInst);
break;
}
}
Expand All @@ -1500,7 +1493,6 @@ void acknowledgeTerminate()
case READING_STATE: {
if (!fSuccess || cbRet == 0) {
crash_handler_exit = true;
DisconnectAndReconnect();
break;
}
Pipe.cbRead = cbRet;
Expand Down Expand Up @@ -1530,12 +1522,17 @@ void acknowledgeTerminate()
break;
}
crash_handler_exit = true;
DisconnectAndReconnect();
break;
}
}
}
}

// Single exit: the pipe name is free again for the next session.
CloseHandle(Pipe.hPipeInst);
Pipe.hPipeInst = INVALID_HANDLE_VALUE;
CloseHandle(hEvents);
hEvents = NULL;
}
#else __APPLE__
void acknowledgeTerminate(void)
Expand Down Expand Up @@ -1667,6 +1664,11 @@ void OBS_API::destroyOBS_API(void)
DisableAudioDucking(false);
}
#endif

#ifdef _WIN32
osn::ShutdownWatchdog::Instance().Arm("Outputs", osn::shutdown_budget::OutputStep);
osn::ShutdownWatchdog::Instance().SetCap(osn::shutdown_budget::OutputCap);
Comment on lines +1669 to +1670

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this as is. The legacy stopAllOutputs terminate is intentional and useful as telemetry, and Desktop records and streams only through the osn::Output API; the legacy OBS_service path is used only for the virtual camera.

#endif
OBS_content::OBS_content_shutdownDisplays();

ScreenshotManager::GetInstance().Shutdown();
Expand Down Expand Up @@ -1768,16 +1770,28 @@ void OBS_API::destroyOBS_API(void)

// Release all streaming ouputs
osn::IStreaming::Manager::GetInstance().for_each([](osn::Streaming *streamingOutput) {
if (streamingOutput)
if (streamingOutput) {
#ifdef _WIN32
osn::ShutdownWatchdog::Instance().Kick(osn::shutdown_budget::OutputStep);
#endif
delete streamingOutput;
}
});

// Release all recording ouputs
osn::IFileOutput::Manager::GetInstance().for_each([](osn::FileOutput *fileOutput) {
if (fileOutput)
if (fileOutput) {
#ifdef _WIN32
osn::ShutdownWatchdog::Instance().Kick(osn::shutdown_budget::OutputStep);
#endif
delete fileOutput;
}
});

#ifdef _WIN32
osn::ShutdownWatchdog::Instance().Arm("Teardown", osn::shutdown_budget::Teardown);
#endif

// Stop the cache worker before draining destruction: it can still own the
// last reference to a removed source and enqueue its destruction later.
// Both source-registry walks below connect/disconnect signals while holding
Expand Down
11 changes: 11 additions & 0 deletions obs-studio-server/source/osn-output.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,23 @@ void osn::Output::InitOutput(obs_output_t *output)
}

signal_handler *sh = obs_output_get_signal_handler(output);
signal_handler_connect(sh, "stopping", osn::Output::OnStopping, this);
signal_handler_connect(sh, "stop", osn::Output::OnStopped, this);

ConnectSignals();
}

void osn::Output::OnStopping(void *data, calldata_t *)
{
reinterpret_cast<osn::Output *>(data)->m_finalizeTracker.Begin();
}

void osn::Output::OnStopped(void *data, calldata_t *)
{
osn::Output *context = reinterpret_cast<osn::Output *>(data);

context->m_finalizeTracker.End();

// Before m_mtxOutputStop: DeleteOutput() holds that lock for up to 20s waiting
// on m_cvStop, and nothing should queue behind it.
context->OnOutputStopped();
Expand Down Expand Up @@ -92,8 +100,10 @@ void osn::Output::DeleteOutput()
// into freed CallbackData/this would crash in signal_handler_signal.
DisconnectSignals();

// Release can block until the muxer finishes writing, so it still counts as finalizing.
obs_output_release(m_output);
m_output = nullptr;
m_finalizeTracker.End();
}

void osn::OutputSignalCallback(void *data, calldata_t *params)
Expand Down Expand Up @@ -136,6 +146,7 @@ void osn::Output::DisconnectSignals()

signal_handler *handler = obs_output_get_signal_handler(m_output);
if (handler) {
signal_handler_disconnect(handler, "stopping", osn::Output::OnStopping, this);
signal_handler_disconnect(handler, "stop", osn::Output::OnStopped, this);
for (auto *cd : m_signalCallbackData)
signal_handler_disconnect(handler, cd->signal.c_str(), osn::OutputSignalCallback, cd);
Expand Down
5 changes: 5 additions & 0 deletions obs-studio-server/source/osn-output.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

#include <obs.h>

#include "shutdown-watchdog.hpp"

#include <mutex>
#include <optional>
#include <queue>
Expand Down Expand Up @@ -85,8 +87,11 @@ class Output {
// the CallbackData. Must run while m_output is still valid.
void DisconnectSignals();

static void OnStopping(void *data, calldata_t *params);
static void OnStopped(void *data, calldata_t *params);

osn::FinalizeTracker m_finalizeTracker{osn::ShutdownWatchdog::Instance()};

obs_video_info *m_canvas = nullptr;
obs_output_t *m_output = nullptr;

Expand Down
136 changes: 136 additions & 0 deletions obs-studio-server/source/shutdown-watchdog.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
#include "shutdown-watchdog.hpp"

#include <memory>

#include <util/base.h>

#ifdef _WIN32
#include <Windows.h>
#endif

osn::ShutdownWatchdog::ShutdownWatchdog(NowFn now, ExpiredFn onExpired, std::chrono::milliseconds pollInterval)
: m_now(std::move(now)), m_onExpired(std::move(onExpired)), m_pollInterval(pollInterval)
{
}

osn::ShutdownWatchdog::~ShutdownWatchdog()
{
{
std::lock_guard lock(m_mtx);
m_stop = true;
}
m_cv.notify_all();
if (m_thread.joinable())
m_thread.join();
}

#ifdef _WIN32
namespace {
constexpr UINT WatchdogExitCode = 0x0B5D0001;

void TerminateSelf(const std::string &stage, std::chrono::seconds exceeded)
{
// The hung thread may hold the log mutex, so log from a helper and give up on it after 1 s.
auto logged = std::make_shared<std::atomic<bool>>(false);
std::thread([logged, stage, exceeded] {
blog(LOG_ERROR, "Shutdown watchdog: %s exceeded %lld s, terminating", stage.c_str(), static_cast<long long>(exceeded.count()));
*logged = true;
}).detach();

for (int i = 0; i < 100 && !*logged; i++)
std::this_thread::sleep_for(std::chrono::milliseconds(10));

TerminateProcess(GetCurrentProcess(), WatchdogExitCode);
}
} // namespace

#endif

osn::ShutdownWatchdog &osn::ShutdownWatchdog::Instance()
{
#ifdef _WIN32
static ShutdownWatchdog *instance = new ShutdownWatchdog(&Clock::now, &TerminateSelf);
#else
// Never armed outside Windows.
static ShutdownWatchdog *instance = new ShutdownWatchdog(&Clock::now, [](const std::string &, std::chrono::seconds) {});
#endif
return *instance;
}

void osn::ShutdownWatchdog::Arm(const std::string &stage, std::chrono::seconds budget)
{
{
std::lock_guard lock(m_mtx);
m_armed = true;
m_stage = stage;
m_budget = budget;
m_deadline = m_now() + budget;
m_cap.reset();
if (!m_thread.joinable())
m_thread = std::thread(&ShutdownWatchdog::Run, this);
}
m_cv.notify_all();
}

void osn::ShutdownWatchdog::Kick(std::chrono::seconds budget)
{
std::lock_guard lock(m_mtx);
if (!m_armed)
return;
m_budget = budget;
m_deadline = m_now() + budget;
}

void osn::ShutdownWatchdog::SetCap(std::chrono::seconds cap)
{
std::lock_guard lock(m_mtx);
m_cap = Cap{m_now() + cap, cap};
}

void osn::ShutdownWatchdog::Disarm()
{
std::lock_guard lock(m_mtx);
m_armed = false;
}

void osn::ShutdownWatchdog::AddFinalizing(int delta)
{
std::lock_guard lock(m_mtx);
m_finalizing += delta;
// Each output gets a fresh step once it finishes finalizing.
if (m_finalizing == 0 && delta < 0 && m_armed && m_cap)
m_deadline = m_now() + m_budget;
}

bool osn::ShutdownWatchdog::IsExpired(Clock::time_point now, std::chrono::seconds &exceeded) const
{
if (m_cap && now >= m_cap->at) {
exceeded = m_cap->limit;
return true;
}
if (now < m_deadline)
return false;
if (m_cap && m_finalizing > 0)
return false;
exceeded = m_budget;
return true;
}

void osn::ShutdownWatchdog::Run()
{
std::unique_lock lock(m_mtx);
while (!m_stop) {
m_cv.wait_for(lock, m_pollInterval);
if (m_stop)
break;
std::chrono::seconds exceeded{0};
if (!m_armed || !IsExpired(m_now(), exceeded))
continue;

m_armed = false;
const std::string stage = m_stage;
lock.unlock();
m_onExpired(stage, exceeded);
lock.lock();
}
}
Loading
Loading