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
7 changes: 7 additions & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -1334,6 +1334,13 @@ area.
closing OBS while its browser engine starts no longer hangs. *Linux*,
2026-10-17. PR [#1333](https://github.com/obs-rust/obs-studio/pull/1333),
dependency [obs-browser#1](https://github.com/obs-rust/obs-browser/pull/1).
- SIGTERM while recording or streaming quits OBS and finishes the
recording, even with "Show confirmation on exit while outputs are
active" on, and SIGTERM while a dialog is open (also during startup)
quits too; before, OBS waited until the sender killed it and the
recording was cut off. *Linux, macOS*, 2026-10-18. Issue
[#1402](https://github.com/obs-rust/obs-studio/issues/1402), upstream
[obsproject/obs-studio#10011](https://github.com/obsproject/obs-studio/issues/10011).

### Security hardening

Expand Down
35 changes: 32 additions & 3 deletions frontend/OBSApp.cpp.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1794,11 +1794,40 @@ void OBSApp::processSigTerm()

sigTermNotifier->setEnabled(true);

if (PlatformSavesBeforeSignalQuit()) {
OBSBasic *main = OBSBasic::Get();
if (main) {
OBSBasic *main = OBSBasic::Get();
if (main) {
if (PlatformSavesBeforeSignalQuit()) {
main->saveAll();
}
/* systemctl stop, logind and kill send SIGTERM; nobody is there to
* answer "outputs are active, exit anyway?", and while that dialog
* waits the recording is cut off when the sender gives up. Quit as
* if it had been answered: closeWindow() stops the outputs and
* waits for the recording to finish. */
main->closeWithoutPrompt();
}

/* A modal dialog that is waiting (for example one the main window opens
* during its startup) runs its own event loop, and quit() does not end
* it; before the main event loop has started, quit() does nothing at
* all. Dismiss the dialogs, then quit once their loops have returned to
* the code that opened them; main() quits after a startup that SIGTERM
* interrupted. */
if (activeModalWidget()) {
quitRequested_ = true;
for (int i = 0; i < 16; i++) {
QWidget *modal = activeModalWidget();
if (!modal) {
break;
}
if (QDialog *dialog = qobject_cast<QDialog *>(modal)) {
dialog->reject();
} else {
modal->close();
}
}
QTimer::singleShot(0, this, &OBSApp::quit);
return;
}
quit();
}
Expand Down
4 changes: 4 additions & 0 deletions frontend/OBSApp.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ class OBSApp : public QApplication {
bool branches_loaded = false;

bool libobs_initialized = false;
bool quitRequested_ = false;

os_inhibit_t *sleepInhibitor = nullptr;
int sleepInhibitRefs = 0;
Expand Down Expand Up @@ -239,6 +240,9 @@ private slots:
static void sigAbrtSignalHandler(int);
static void sigQuitSignalHandler(int);
#endif
/* SIGTERM arrived while a dialog was waiting, possibly before the main
* event loop started: main() quits as soon as that loop runs. */
inline bool quitRequested() const { return quitRequested_; }

void loadAppModules();

Expand Down
3 changes: 3 additions & 0 deletions frontend/obs-main.cpp.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,9 @@ static int run_program(fstream &logFile, int argc, char *argv[])

prof.Stop();

if (program.quitRequested()) {
QTimer::singleShot(0, &program, &OBSApp::quit);
}
ret = program.exec();

} catch (const char *error) {
Expand Down
2 changes: 1 addition & 1 deletion frontend/widgets/OBSBasic.cpp.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1770,7 +1770,7 @@ bool OBSBasic::isReadyToClose()
bool OBSBasic::shouldPromptForClose()
{
bool confirmOnExit = config_get_bool(App()->GetUserConfig(), "General", "ConfirmOnExit");
if (confirmOnExit && outputHandler && outputHandler->Active() && !clearingFailed) {
if (confirmOnExit && !closeWithoutPrompt_ && outputHandler && outputHandler->Active() && !clearingFailed) {
return true;
}

Expand Down
4 changes: 4 additions & 0 deletions frontend/widgets/OBSBasic.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ class OBSBasic : public OBSMainWindow {
bool loaded = false;
bool isClosing_ = false;
bool isClosePromptOpen_ = false;
bool closeWithoutPrompt_ = false;
bool handledShutdown = false;

// TODO: Remove, orphaned variable
Expand Down Expand Up @@ -321,6 +322,9 @@ public slots:

void saveAll();
bool shouldPromptForClose();
/* A quit that nobody can answer a dialog for (SIGTERM): the next close
* goes ahead without the exit confirmation. */
inline void closeWithoutPrompt() { closeWithoutPrompt_ = true; }
inline bool isClosing() { return isClosing_; }
inline bool isClosePromptOpen() { return isClosePromptOpen_; }
void closeWindow();
Expand Down
4 changes: 4 additions & 0 deletions test/websocket-tier4/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ obs-websocket port (Phase 5 item 3).
- Linux, in the same run: exactly one libsrt mapped into the OBS process.
With two builds of libsrt in one process (the SRT output's and FFmpeg's)
OBS aborts on quit after any SRT use.
- SIGTERM while recording, with the exit confirmation left on: OBS quits
and finishes the recording instead of waiting at the "exit anyway?"
dialog. SIGTERM while a startup dialog ("encoder missing") is open: OBS
quits cleanly (`--only shutdown` runs just these).
- Request batches: serial, `haltOnFailure`, no-halt error propagation, and
parallel execution acceptance.
- Error codes for malformed JSON (close 4002), unknown opcode (4006),
Expand Down
148 changes: 143 additions & 5 deletions test/websocket-tier4/run_tier4.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,9 @@ class ObsServer:
"""Launches obs headless under xvfb with an isolated profile/config."""

def __init__(self, obs_bin, port, password=None, keep_home=None,
profile=None, extra_env=None):
profile=None, extra_env=None, confirm_on_exit=False):
self.obs_bin = obs_bin
self.confirm_on_exit = confirm_on_exit
self.extra_env = extra_env or {}
self.port = port
self.password = password
Expand All @@ -135,8 +136,9 @@ def _write_profile(self):
with open(os.path.join(cfg, "global.ini"), "w") as f:
f.write("[General]\nFirstRun=true\n")
with open(os.path.join(cfg, "user.ini"), "w") as f:
f.write("[General]\nFirstRun=true\nConfirmOnExit=false\n"
"WarnBeforeStoppingRecord=false\n"
f.write("[General]\nFirstRun=true\n"
+ ("" if self.confirm_on_exit else "ConfirmOnExit=false\n")
+ "WarnBeforeStoppingRecord=false\n"
"[Basic]\nProfile=Tier4\nProfileDir=Tier4\n"
"SceneCollection=Tier4\nSceneCollectionFile=Tier4\n")
ini = {"General": {"Name": "Tier4"}}
Expand Down Expand Up @@ -1362,6 +1364,134 @@ async def test_stats_rescale_output():
}


async def test_sigterm_while_recording(server, rec_dir):
"""SIGTERM while recording must quit OBS and finish the recording, with
"Show confirmation on exit while outputs are active" left on (the
default). systemd, logind at shutdown and kill send SIGTERM, and nobody
can answer the "exit anyway?" dialog for them: OBS stayed up recording
until it was killed, which cut the file off and made the next start an
unclean one (obs-rust/obs-studio#1402)."""
c, _ = await new_identified_client(subscriptions=SUB_NONE)
for _ in range(120):
r = await c.request("StartRecord")
if resp_status(r).get("code") != 207:
break
await asyncio.sleep(0.5)
check("sigterm:recording starts",
resp_status(r).get("code") == STATUS_SUCCESS, json.dumps(r)[:300])
active = False
deadline = time.time() + 15
while time.time() < deadline and not active:
r = await c.request("GetRecordStatus")
active = r.get("d", {}).get("responseData", {}).get("outputActive")
await asyncio.sleep(0.25)
await asyncio.sleep(3)
await c.close_conn()
pids = obs_pids(server)
check("sigterm:OBS process found", bool(pids), f"no {server.obs_bin} process")
for pid in pids:
os.kill(pid, signal.SIGTERM)
deadline = time.time() + 30
while time.time() < deadline and obs_pids(server):
time.sleep(0.2)
left = obs_pids(server)
check("sigterm:OBS quits on SIGTERM while recording", active and not left,
f"recording active={active}; still running 30 s after SIGTERM "
f"(the exit confirmation dialog is open)" if left else "")
files = [os.path.join(rec_dir, f) for f in os.listdir(rec_dir)]
sizes = {os.path.basename(f): os.path.getsize(f) for f in files}
duration = None
probe = shutil.which("ffprobe")
if probe and len(files) == 1 and not left:
out = subprocess.run([probe, "-v", "error", "-show_entries", "format=duration",
"-of", "csv=p=0", files[0]], capture_output=True, text=True)
try:
duration = float(out.stdout.strip())
except ValueError:
duration = None
check("sigterm:the recording is finished", len(files) == 1 and not left
and (duration is None and probe is None or (duration or 0) >= 2.0),
f"files={sizes} duration={duration}")


def test_sigterm_during_startup_dialog(server):
"""SIGTERM while a dialog that the main window opened during its startup
is waiting (here "encoder missing": the profile names an encoder this
build does not have) must quit OBS cleanly. SIGTERM was ignored there: the
quit it requested ended nothing while the dialog's own event loop ran, and
nothing at all before the main event loop had started."""
pids = obs_pids(server)
check("sigterm-startup:OBS process found", bool(pids), f"no {server.obs_bin} process")
for pid in pids:
os.kill(pid, signal.SIGTERM)
deadline = time.time() + 30
while time.time() < deadline and obs_pids(server):
time.sleep(0.2)
left = obs_pids(server)
time.sleep(1)
with open(server.log, errors="replace") as f:
log = f.read()
crashed = "Segmentation fault" in log or "Aborted" in log
check("sigterm-startup:OBS quits on SIGTERM during the startup dialog",
not left and not crashed and "Number of memory leaks" in log,
"still running 30 s after SIGTERM" if left else
("OBS crashed" if crashed else "no clean shutdown in the log"))


async def run_shutdown_phase(obs_bin):
"""Simple output recording into a fresh folder, exit confirmation on."""
home = tempfile.mkdtemp(prefix="obs-tier4-")
rec_dir = os.path.join(home, "recordings")
os.makedirs(rec_dir)
profile = {
"Video": {"BaseCX": "640", "BaseCY": "360", "OutputCX": "640",
"OutputCY": "360", "FPSType": "0", "FPSCommon": "30"},
"Output": {"Mode": "Simple"},
"SimpleOutput": {"FilePath": rec_dir, "RecFormat2": "mkv",
"RecQuality": "Small", "RecEncoder": "x264"},
}
server = ObsServer(obs_bin, PORT, password=None, keep_home=home,
profile=profile, confirm_on_exit=True)
server.start()
try:
print("== SIGTERM while recording ==", flush=True)
await test_sigterm_while_recording(server, rec_dir)
except BaseException:
server.report_failure()
raise
finally:
server.stop()

wait_for_port_closed(PORT)
server = ObsServer(obs_bin, PORT, password=None, profile={
"Output": {"Mode": "Advanced"},
"AdvOut": {"Encoder": "tier4_missing_encoder", "RecEncoder": "obs_x264",
"RecType": "Standard", "RecFilePath": rec_dir},
})
server.start()
try:
print("== SIGTERM during a startup dialog ==", flush=True)
# The server listens before the main window finishes loading; the
# "encoder missing" dialog opens a moment later.
time.sleep(5)
test_sigterm_during_startup_dialog(server)
except BaseException:
server.report_failure()
raise
finally:
server.stop()


async def run_shutdown_only(obs_bin):
await run_shutdown_phase(obs_bin)
failed = [n for n, ok, _ in RESULTS if not ok]
print("=" * 60)
print(f"checks: {len(RESULTS) - len(failed)}/{len(RESULTS)} passed")
for n, _, detail in (r for r in RESULTS if not r[1]):
print(f" - {n}: {detail}")
return 1 if failed else 0


async def run_gpu_phase(obs_bin):
"""OBS forced onto llvmpipe: GetStats.gpuAcceleration and the startup
warning (obs-rust/obs-studio#846, #940); and one libsrt in the
Expand Down Expand Up @@ -1461,6 +1591,10 @@ async def run_all(obs_bin, skip_obs, skip_auth_phase):
wait_for_port_closed(PORT)
await run_gpu_phase(obs_bin)

if not skip_obs:
wait_for_port_closed(PORT)
await run_shutdown_phase(obs_bin)

total = len(RESULTS)
passed = sum(1 for _, ok, _ in RESULTS if ok)
failed = [n for n, ok, _ in RESULTS if not ok]
Expand Down Expand Up @@ -1491,12 +1625,16 @@ def main():
"mainly for debugging)")
ap.add_argument("--skip-auth-phase", action="store_true",
help="with --no-spawn only: skip the auth-required phase")
ap.add_argument("--only", choices=["gpu"],
ap.add_argument("--only", choices=["gpu", "shutdown"],
help="run one group: gpu = GetStats.gpuAcceleration and the "
"startup warning with OpenGL forced onto llvmpipe")
"startup warning with OpenGL forced onto llvmpipe; "
"shutdown = SIGTERM while recording and during a "
"startup dialog")
args = ap.parse_args()
if args.only == "gpu":
sys.exit(asyncio.run(run_gpu_only(args.obs)))
if args.only == "shutdown":
sys.exit(asyncio.run(run_shutdown_only(args.obs)))
sys.exit(asyncio.run(
run_all(args.obs, args.no_spawn, args.skip_auth_phase)))

Expand Down
Loading