From 9838f292135551544cb5450fbead64a1b6ffb869 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sun, 18 Oct 2026 03:33:01 -0400 Subject: [PATCH 1/2] test: Tier 4 checks that SIGTERM while recording quits OBS A new Tier 4 phase (run_tier4.py --only shutdown, also part of the full run) checks two stop requests: - SIGTERM while a Simple output recording runs, with "Show confirmation on exit while outputs are active" left on, the default. OBS must quit within 30 s and leave a finished recording (one file, ffprobe duration at least 2 s). - SIGTERM while the "encoder missing" dialog that the main window opens during its startup is waiting (the profile names an encoder the build does not have). OBS must quit within 30 s with a clean shutdown in its log and no crash. systemctl stop, logind at shutdown and kill send SIGTERM. Nobody can answer a dialog for them, so OBS stays up until the service manager kills it: a recording is cut off and the next start is an unclean one (obsproject/obs-studio#10011). The other Tier 4 phases turn the exit confirmation off, so they never saw this. Fails on master, 3 of 6: "OBS quits on SIGTERM while recording: recording active=True; still running 30 s after SIGTERM", the MKV is 0 bytes, and "OBS quits on SIGTERM during the startup dialog: still running 30 s after SIGTERM". Refs #1402. --- test/websocket-tier4/README.md | 4 + test/websocket-tier4/run_tier4.py | 148 +++++++++++++++++++++++++++++- 2 files changed, 147 insertions(+), 5 deletions(-) diff --git a/test/websocket-tier4/README.md b/test/websocket-tier4/README.md index efa68f318c..46c535ba04 100644 --- a/test/websocket-tier4/README.md +++ b/test/websocket-tier4/README.md @@ -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), diff --git a/test/websocket-tier4/run_tier4.py b/test/websocket-tier4/run_tier4.py index 91f5b2a32e..ad5d5f7498 100644 --- a/test/websocket-tier4/run_tier4.py +++ b/test/websocket-tier4/run_tier4.py @@ -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 @@ -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"}} @@ -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 @@ -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] @@ -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))) From 64a5e3379959bd0165f512ef6bfe7dd9d5ce8513 Mon Sep 17 00:00:00 2001 From: Ryan Doupe Date: Sun, 18 Oct 2026 03:33:24 -0400 Subject: [PATCH 2/2] frontend: Quit on SIGTERM while outputs run or a dialog waits SIGTERM ran OBSApp::quit(), which closes the main window. Two cases ignored it, and systemctl stop, logind at shutdown and kill send SIGTERM with nobody there to answer a dialog, so OBS stayed up until the sender killed it (obsproject/obs-studio#10011): - With an output active and "Show confirmation on exit while outputs are active" on (the default), OBSBasic::closeEvent() ignored the close and opened the "exit anyway?" dialog. The recording was cut off when OBS was killed (0 bytes, or no duration) and the next start was an unclean one. - While a modal dialog waited, for example the "encoder missing" one the main window opens during its startup, the quit ended nothing: the dialog runs its own event loop, and before the main event loop has started quit() does nothing at all. processSigTerm() now marks the main window to close without the exit confirmation, so closeWindow() runs as when it is answered with Yes: it stops the outputs and waits for the recording to finish. If a modal dialog is open, it dismisses the dialogs and quits once their loops have returned; main() quits after a startup that SIGTERM interrupted, as soon as the main event loop runs. Closing the window, Exit in the menus and SIGINT are unchanged. run_tier4.py --only shutdown: 6 of 6, three runs. With a recording running, SIGTERM quits in about 1 s and leaves a complete MKV (ffprobe duration 4.97 s). Fixes #1402. --- docs/features.md | 7 +++++++ frontend/OBSApp.cpp.hpp | 35 ++++++++++++++++++++++++++++--- frontend/OBSApp.hpp | 4 ++++ frontend/obs-main.cpp.hpp | 3 +++ frontend/widgets/OBSBasic.cpp.hpp | 2 +- frontend/widgets/OBSBasic.hpp | 4 ++++ 6 files changed, 51 insertions(+), 4 deletions(-) diff --git a/docs/features.md b/docs/features.md index 37ac0fe597..709ab910e7 100644 --- a/docs/features.md +++ b/docs/features.md @@ -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 diff --git a/frontend/OBSApp.cpp.hpp b/frontend/OBSApp.cpp.hpp index 1f195c075c..3c79f62f90 100644 --- a/frontend/OBSApp.cpp.hpp +++ b/frontend/OBSApp.cpp.hpp @@ -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(modal)) { + dialog->reject(); + } else { + modal->close(); + } + } + QTimer::singleShot(0, this, &OBSApp::quit); + return; } quit(); } diff --git a/frontend/OBSApp.hpp b/frontend/OBSApp.hpp index b37eb43c27..c57b297b1b 100644 --- a/frontend/OBSApp.hpp +++ b/frontend/OBSApp.hpp @@ -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; @@ -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(); diff --git a/frontend/obs-main.cpp.hpp b/frontend/obs-main.cpp.hpp index bcf5d15862..89d83e34f2 100644 --- a/frontend/obs-main.cpp.hpp +++ b/frontend/obs-main.cpp.hpp @@ -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) { diff --git a/frontend/widgets/OBSBasic.cpp.hpp b/frontend/widgets/OBSBasic.cpp.hpp index 9b665b6123..2f30e1dc49 100644 --- a/frontend/widgets/OBSBasic.cpp.hpp +++ b/frontend/widgets/OBSBasic.cpp.hpp @@ -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; } diff --git a/frontend/widgets/OBSBasic.hpp b/frontend/widgets/OBSBasic.hpp index bd402cdf7a..e540c5fb2e 100644 --- a/frontend/widgets/OBSBasic.hpp +++ b/frontend/widgets/OBSBasic.hpp @@ -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 @@ -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();