From 3965baeadd37e7e16f59d92dd4cf23ff2d84a19a Mon Sep 17 00:00:00 2001 From: makoi66 Date: Wed, 30 Sep 2026 15:17:13 +0300 Subject: [PATCH 1/2] Stop the video-switch freeze: async mpv stop, no sync reads per event Switching away from a video wallpaper froze every plasmashell window for ~200 ms (QSG_RENDER_TIMING). Two synchronous waits on the mpv core: - ~MpvRender runs mpv_render_context_free on the Qt render thread during the scenegraph sync (GUI thread blocked), and that call waits for the core to tear its video output down. - onMpvEvents answered every observed-property event with two mpv_get_property calls ("idle-active", "pause") on the GUI thread, which block while the core is busy, i.e. exactly during a teardown. onMpvEvents now takes both values from the MPV_EVENT_PROPERTY_CHANGE payload (both are observed as MPV_FORMAT_FLAG) and keeps the last seen pair, so an event never calls back into the core. MpvObject::stopAsync() detaches the owner from mpv's wakeup callback (MpvHandle::detachOwner, the first half of beginShutdown) and issues an async "stop". Mpv.qml exposes it as prepareDestroy(), and the handoff's fade-out calls that on the outgoing backend and destroys it 400 ms later: by then mpv has dropped its video output, and mpv_render_context_free no longer waits. Backends without prepareDestroy are destroyed right away, as before. tst_mpvbackend covers stopAsync: it returns without waiting on the core, an observed-property change after it no longer reaches the object (with a control run showing the same change does without it), and repeated / uninitialised calls are safe. Stacked on "Keep the old wallpaper on screen until the new one has drawn" (the fade-out that calls prepareDestroy). --- plugin/contents/ui/backend/Mpv.qml | 6 ++++ plugin/contents/ui/main.qml | 10 ++++++- src/backend_mpv/MpvBackend.cpp | 38 ++++++++++++++++++++---- src/backend_mpv/MpvBackend.hpp | 11 ++++++- tests/tst_mpvbackend.cpp | 46 ++++++++++++++++++++++++++++++ 5 files changed, 103 insertions(+), 8 deletions(-) diff --git a/plugin/contents/ui/backend/Mpv.qml b/plugin/contents/ui/backend/Mpv.qml index eca97bef..c835334c 100644 --- a/plugin/contents/ui/backend/Mpv.qml +++ b/plugin/contents/ui/backend/Mpv.qml @@ -126,6 +126,12 @@ Item{ displayMode = displayMode; videoRate = videoRate; } + // Called by main.qml once this backend has faded out, some time before + // destroying it: mpv drops its video output off the render thread, so + // ~MpvRender no longer waits on the core there. + function prepareDestroy() { + player.stopAsync(); + } function pause(){ volumeFade.stop(); pauseTimer.start(); diff --git a/plugin/contents/ui/main.qml b/plugin/contents/ui/main.qml index 8176f4f6..848ee031 100644 --- a/plugin/contents/ui/main.qml +++ b/plugin/contents/ui/main.qml @@ -574,7 +574,15 @@ Rectangle { to: 0 duration: background.reducedMotion ? 0 : 250 onFinished: { - if (target) target.destroy(); + // Invisible now. A backend that can wind down asynchronously + // (mpv) gets a moment to do so before its render-thread + // teardown, instead of stalling the scenegraph. + if (target && typeof target.prepareDestroy === "function") { + target.prepareDestroy(); + target.destroy(400); + } else if (target) { + target.destroy(); + } target = null; } } diff --git a/src/backend_mpv/MpvBackend.cpp b/src/backend_mpv/MpvBackend.cpp index fa00f95b..3249b1c7 100644 --- a/src/backend_mpv/MpvBackend.cpp +++ b/src/backend_mpv/MpvBackend.cpp @@ -1,5 +1,6 @@ #include "MpvBackend.hpp" +#include #include #include #include @@ -124,6 +125,21 @@ int CreateMpvContex(mpv_handle* mpv, mpv_render_context** mpv_gl) { } // namespace +// Unload the file without waiting on the core. main.qml calls this on an +// outgoing (already faded out) backend some time before destroying it: once +// mpv has dropped its video output, ~MpvRender's mpv_render_context_free on +// the Qt render thread no longer waits on the core — that wait froze every +// plasmashell window for ~200 ms on each switch away from a video. +void MpvObject::stopAsync() { + if (! m_mpv) return; + // Nothing on the GUI thread may touch this player again: the outgoing + // backend's status no longer matters, and event handling is where a + // synchronous call would wait on the busy core. + if (m_shared_mpv) m_shared_mpv->detachOwner(); + const char* cmd[] = { "stop", nullptr }; + mpv_command_async(m_mpv, 0, cmd); +} + bool MpvObject::command(const QVariant& params) { if (! m_mpv) { qWarning() << "MpvObject::command on uninitialized mpv (video backend unavailable)"; @@ -242,7 +258,15 @@ void MpvObject::onMpvEvents() { mpv_event* ev = mpv_wait_event(m_mpv, 0); // non-blocking if (ev->event_id == MPV_EVENT_NONE) break; if (ev->event_id == MPV_EVENT_PROPERTY_CHANGE) { - refreshStatus(getProperty("idle-active").toBool(), getProperty("pause").toBool()); + const auto* prop = static_cast(ev->data); + if (prop && prop->format == MPV_FORMAT_FLAG && prop->data) { + const bool value = *static_cast(prop->data) != 0; + if (std::strcmp(prop->name, "idle-active") == 0) + m_propIdle = value; + else if (std::strcmp(prop->name, "pause") == 0) + m_propPaused = value; + } + refreshStatus(m_propIdle, m_propPaused); } else if (ev->event_id == MPV_EVENT_END_FILE) { // mpv signals demuxer/decoder failures via END_FILE with // reason=ERROR; other reasons (EOF on a non-looping source, @@ -544,7 +568,7 @@ MpvObject::MpvObject(QQuickItem* parent) Q_EMIT initializedChanged(); } -void MpvHandle::beginShutdown() { +void MpvHandle::detachOwner() { // Tell libmpv to stop calling our wakeup (best-effort: doesn't block any // in-flight callback). Then take the wakeup_mutex to serialise against // any callback currently dispatching; clearing owner under that lock @@ -552,10 +576,12 @@ void MpvHandle::beginShutdown() { // The .so is dlopen'd into plasmashell — a dangling postEvent here // would crash the desktop. if (handle) mpv_set_wakeup_callback(handle, nullptr, nullptr); - { - QMutexLocker lock(&wakeup_mutex); - owner = nullptr; - } + QMutexLocker lock(&wakeup_mutex); + owner = nullptr; +} + +void MpvHandle::beginShutdown() { + detachOwner(); // mpv_create() can fail; there is no core to wind down then, and the ctor // has already warned that the video backend is unavailable. if (! handle) return; diff --git a/src/backend_mpv/MpvBackend.hpp b/src/backend_mpv/MpvBackend.hpp index 115959d6..1fe5ca84 100644 --- a/src/backend_mpv/MpvBackend.hpp +++ b/src/backend_mpv/MpvBackend.hpp @@ -36,6 +36,8 @@ struct MpvHandle { // client.h names this as *the* asynchronous-destruction path: run "quit", // then react to MPV_EVENT_SHUTDOWN. void beginShutdown(); + // First half of beginShutdown: stop delivering mpv events to the owner. + void detachOwner(); // Wakeup callback indirection. The callback runs on an arbitrary mpv // player thread; without this hop it would deref a destroyed MpvObject @@ -121,6 +123,8 @@ public slots: void play(); void pause(); void stop(); + // Fire-and-forget `stop` for a backend about to be destroyed; see .cpp. + void stopAsync(); bool command(const QVariant& params); bool setProperty(const QString& name, const QVariant& value); @@ -164,7 +168,12 @@ public slots: // Last status surfaced via statusChanged(); the diff anchor so the signal // fires once per real transition rather than per observed-property event. Status m_lastStatus { Stopped }; - bool m_inited_ok { false }; // set once mpv_initialize() succeeds + // Last observed "idle-active" / "pause" values, taken from the property + // events themselves (a synchronous mpv_get_property on the GUI thread + // blocks while the core is busy, e.g. tearing its video output down). + bool m_propIdle { true }; + bool m_propPaused { false }; + bool m_inited_ok { false }; // set once mpv_initialize() succeeds private: mpv_handle* m_mpv { nullptr }; diff --git a/tests/tst_mpvbackend.cpp b/tests/tst_mpvbackend.cpp index ef7d5764..49987cc0 100644 --- a/tests/tst_mpvbackend.cpp +++ b/tests/tst_mpvbackend.cpp @@ -151,6 +151,8 @@ private slots: // Teardown must not park a thread on the mpv core. void beginShutdown_quitsCoreWithoutWaitingOnIt(); + void stopAsync_detachesEventsAndReturnsImmediately(); + void stopAsync_uninitializedOrRepeated_isSafe(); void beginShutdown_neverInitializedCore_doesNotWarn(); void beginShutdown_healthyCore_doesNotWarn(); void beginShutdown_quitRejectedByChokedCore_warns(); @@ -809,4 +811,48 @@ void TestMpvBackend::beginShutdown_quitRejectedByChokedCore_warns() { } QTEST_MAIN(TestMpvBackend) +// stopAsync() is what main.qml calls on a video backend that has faded out, +// ~400 ms before destroying it. It must not wait on the core (that wait, in +// ~MpvRender on the Qt render thread, froze every plasmashell window for +// ~200 ms per switch away from a video), and nothing on the GUI thread may +// react to that player's events any more. +void TestMpvBackend::stopAsync_detachesEventsAndReturnsImmediately() { + // Control, then the real case: an observed-property event after the + // cache says Playing re-derives the status from the event values (the + // idle player reports idle-active), which is a transition -- so it emits + // exactly when events still reach the object. + for (const bool detach : { false, true }) { + auto obj = makeObject(); + QVERIFY(obj->initialized()); + QTest::qWait(100); // drain the events mpv_observe_property queues up front + QVERIFY(obj->refreshStatus(false, false)); + QCOMPARE(obj->status(), MpvObject::Playing); + QSignalSpy spy(obj.get(), &MpvObject::statusChanged); + + if (detach) { + QElapsedTimer t; + t.start(); + obj->stopAsync(); + QVERIFY2(t.elapsed() < 50, "stopAsync waited on the mpv core"); + } + obj->setProperty(QStringLiteral("pause"), true); + QTest::qWait(150); + + if (detach) { + QCOMPARE(spy.count(), 0); + QCOMPARE(obj->status(), MpvObject::Playing); // nothing re-derived it + } else { + QCOMPARE(spy.count(), 1); + QCOMPARE(obj->status(), MpvObject::Stopped); + } + } +} + +void TestMpvBackend::stopAsync_uninitializedOrRepeated_isSafe() { + auto obj = std::make_unique(); + obj->stopAsync(); + obj->stopAsync(); // idempotent: detach twice, second async stop is a no-op + obj.reset(); // and the normal teardown still runs afterwards +} + #include "tst_mpvbackend.moc" From e8ded7b8f5af73c2e2018191be4c573a851d3797 Mon Sep 17 00:00:00 2001 From: David Goree Date: Mon, 12 Oct 2026 19:40:04 -0500 Subject: [PATCH 2/2] Prepare every mpv backend for teardown, not just the faded-out one The async mpv stop (Mpv.qml prepareDestroy) was only called from outgoingFade.onFinished in main.qml. The other places that destroy a backend still did it synchronously and brought back the render-thread stall on mpv_render_context_free. - main.qml: add backendLoader.retire(backend), which calls prepareDestroy() when the backend has one, then destroys it (delayed 400 ms in that case). outgoingFade.onFinished, Component.onDestruction, a fade cut short by dropOutgoing(), a backend that never drew, and an outgoing backend being replaced all go through it. - tests/qml/_stubs Mpv.qml: add stopAsync() and a stopAsyncCount recorder; prepareDestroy() calls it and would throw on the stub. Mpv row in the stubs README updated. - tst_main_handoff.qml: one test per destroy path, using a backend stand-in that records prepareDestroy() calls. - tst_backend_mpv.qml: prepareDestroy() reaches the player's stopAsync(). --- plugin/contents/ui/main.qml | 29 +++++--- tests/qml/_stubs/README.md | 2 +- .../captsilver/wallpaperEngineKde/Mpv.qml | 2 + tests/qml/tst_backend_mpv.qml | 9 +++ tests/qml/tst_main_handoff.qml | 71 +++++++++++++++++++ 5 files changed, 101 insertions(+), 12 deletions(-) diff --git a/plugin/contents/ui/main.qml b/plugin/contents/ui/main.qml index 0a63ccc9..34eb6892 100644 --- a/plugin/contents/ui/main.qml +++ b/plugin/contents/ui/main.qml @@ -588,12 +588,7 @@ Rectangle { // Invisible now. A backend that can wind down asynchronously // (mpv) gets a moment to do so before its render-thread // teardown, instead of stalling the scenegraph. - if (target && typeof target.prepareDestroy === "function") { - target.prepareDestroy(); - target.destroy(400); - } else if (target) { - target.destroy(); - } + if (target) backendLoader.retire(target); target = null; if (background._accentPending) background.emitAccentColor(); } @@ -606,8 +601,20 @@ Rectangle { } } Component.onDestruction: { - if(this.item) this.item.destroy(); - if(this._outgoing) this._outgoing.destroy(); + if(this.item) this.retire(this.item); + if(this._outgoing) this.retire(this._outgoing); + } + // Every destroy of a backend goes through here. One that can wind + // down asynchronously (mpv) is told to first, so its render-thread + // teardown does not stall the scenegraph; it then gets a moment + // before the destroy. + function retire(backend) { + if (typeof backend.prepareDestroy === "function") { + backend.prepareDestroy(); + backend.destroy(400); + } else { + backend.destroy(); + } } // Fade the outgoing backend out and destroy it. function dropOutgoing() { @@ -617,7 +624,7 @@ Rectangle { if (!old) return; if (outgoingFade.running) { outgoingFade.stop(); - if (outgoingFade.target) outgoingFade.target.destroy(); + if (outgoingFade.target) this.retire(outgoingFade.target); } outgoingFade.target = old; outgoingFade.start(); @@ -631,9 +638,9 @@ Rectangle { if (prev.frameShown === false) { // Never reached the screen (rapid switching): nothing // to keep; whatever is on screen stays the outgoing. - prev.destroy(); + this.retire(prev); } else { - if (this._outgoing) this._outgoing.destroy(); + if (this._outgoing) this.retire(this._outgoing); // Keeps playing until the new one is on screen. this._outgoing = prev; // background.* now follows the next wallpaper; pin diff --git a/tests/qml/_stubs/README.md b/tests/qml/_stubs/README.md index 0e6d3d5a..a0ec25eb 100644 --- a/tests/qml/_stubs/README.md +++ b/tests/qml/_stubs/README.md @@ -16,7 +16,7 @@ known shortcuts. When you add a new test that needs a stub method: | FileHelper | src/FileHelper.hpp + src/FileHelper.cpp | Q_INVOKABLEs: readFile, patchedHtml, qwebChannelSource, getDirSize, requestDirSize, getFolderList, scanVideoFolder, readWallpaperConfig, writeWallpaperConfig, resetWallpaperConfig, readActiveBindings, generateThumbnail, clearCacheDir, addReadRoot, clearReadRoots, videoThumbDir(cacheRoot), pruneOrphanThumbnails(cacheRoot, installedWallpaperDirs, videoFolderPaths), enforceCacheQuota(roots, quotaBytes), enforceCacheQuotaForce(roots, quotaBytes), requestCacheGc(cacheRoot, installedWallpaperDirs, videoFolderPaths, quotaBytes), readWorkshopManifest, allSeenVersions, recordSeenVersion, seenVersion, seedLastSeenVersions(steamLibraryPath). Property: lastGcBytesFreed. Signals: thumbnailReady(videoPath, outPath, ok), dirSizeReady(path, bytes), cacheGcFinished(prunedBytes, evictedBytes). | Method bodies record call counts + last args; thumbnailReady/dirSizeReady fire synchronously via Qt.callLater. clearCacheDir always reports success (real impl gates on cache-root prefix and preserves localstorage*.json). requestCacheGc only records — the real one dispatches onto a QThreadPool and answers via cacheGcFinished. | | MouseGrabber | src/MouseGrabber.hpp + src/MouseGrabber.cpp| Properties: target (QQuickItem*), forceCapture (bool); Q_INVOKABLE: sendEvent(QObject*, QEvent*). | No real mouse capture path — tests assign target directly; sendEvent() is a no-op recorder. | | MprisMonitor | src/MprisMonitor.hpp + src/MprisMonitor.cpp| Signals: playbackStateChanged(int state); propertiesChanged(title, artist, albumTitle, albumArtist, genres, duration); thumbnailChanged(hasThumbnail, colors); timelineChanged(position, duration, state); mediaAvailableChanged(bool available). Q_INVOKABLEs: invokeShortcut(name), engage(). | Machine-checked: `tst_mpriscolors::qmlStubSurfaceMatchesTheRealMonitor` diffs this stub against MprisMonitor's metaobject. The real `mediaAvailable` property is absent — declaring it in QML would auto-generate a second, parameterless `mediaAvailableChanged`. | -| Mpv | src/backend_mpv/ | Properties: source, volume, mute. Functions: play, pause, stop, command(cmd), setProperty(name, val). Signals: firstFrame, sourceLoadFailed(reason). | source setter no-op; no real libmpv decoder. | +| Mpv | src/backend_mpv/ | Properties: source, volume, mute. Functions: play, pause, stop, stopAsync (backend/Mpv.qml's prepareDestroy calls it), command(cmd), setProperty(name, val). Signals: firstFrame, sourceLoadFailed(reason). | source setter no-op; no real libmpv decoder. | | PlaylistManager | src/PlaylistManager.hpp + src/PlaylistManager.cpp | Owns PlaylistsModel + PlaylistItemsModel; Q_INVOKABLE CRUD: createPlaylist, deletePlaylist, renamePlaylist, setMode, setIntervalMin, addItem, removeItem, moveItem, activate, deactivate, skipCurrent, acceptPick, pauseTicks, resumeTicks, setFilteredLibraryIntervalMin, reload, pickShuffle, playlistContains, itemsModel. Signals: tick, requestFilteredPick, activationFailed, persistFailed, persisted. | Models in-memory only; itemsModel returns a fresh empty ListModel each call. playlistContains always false. pickShuffleImpl is a deterministic round-robin (override on stub instance for fixed sequences). `timerActive` is a test-only property (no real Q_PROPERTY counterpart) modelling `m_timer.isActive()` just enough to catch pause/activate ordering bugs: activate() arms it (except the filtered-library sentinel, which defers to acceptPick); pauseTicks()/resumeTicks() mirror the real early-return semantics. skipCurrent/stepBy/acceptPick don't touch it. | | PluginInfo | src/PluginInfo.hpp + src/PluginInfo.cpp | Properties: version, cache_path. | Synthetic test-stub version + empty cache_path by default. | | SafeWallpaperBridge | src/SafeWallpaperBridge.hpp + src/SafeWallpaperBridge.cpp | READ-only properties: generalProperties, userProperties, loaded (mutation only via pushGeneralProperties / pushUserProperties / setLoaded). Signals: sigGeneralProperties, sigUserProperties, sigAudio, sigInit, generalPropertiesChanged, userPropertiesChanged, loadedChanged. | sigInit is one-shot via _initFired guard. Stub mirrors production READ-only QWebChannel posture. | diff --git a/tests/qml/_stubs/com/github/captsilver/wallpaperEngineKde/Mpv.qml b/tests/qml/_stubs/com/github/captsilver/wallpaperEngineKde/Mpv.qml index 08e25948..a71b0835 100644 --- a/tests/qml/_stubs/com/github/captsilver/wallpaperEngineKde/Mpv.qml +++ b/tests/qml/_stubs/com/github/captsilver/wallpaperEngineKde/Mpv.qml @@ -15,6 +15,7 @@ Item { property int playCount: 0 property int pauseCount: 0 property int stopCount: 0 + property int stopAsyncCount: 0 property int commandCount: 0 property var lastCommand: undefined property int setPropertyCount: 0 @@ -23,6 +24,7 @@ Item { function play() { playCount += 1 } function pause() { pauseCount += 1 } function stop() { stopCount += 1 } + function stopAsync() { stopAsyncCount += 1 } function command(cmd) { commandCount += 1; lastCommand = cmd } function setProperty(name, val) { setPropertyCount += 1; lastSetProperty = { name: name, val: val } } diff --git a/tests/qml/tst_backend_mpv.qml b/tests/qml/tst_backend_mpv.qml index 1ebd4e2d..395030e2 100644 --- a/tests/qml/tst_backend_mpv.qml +++ b/tests/qml/tst_backend_mpv.qml @@ -269,4 +269,13 @@ TestCase { compare(p.mute, true, "frozen backend followed the next wallpaper's mute"); item.destroy(); } + + function test_prepareDestroy_stops_the_player_asynchronously() { + const item = freshMpvComp.createObject(mpv.parent); + const p = item.data.find(o => o && typeof o.stopAsync === "function"); + compare(p.stopAsyncCount, 0); + item.prepareDestroy(); + compare(p.stopAsyncCount, 1); + item.destroy(); + } } diff --git a/tests/qml/tst_main_handoff.qml b/tests/qml/tst_main_handoff.qml index b062ca77..89366014 100644 --- a/tests/qml/tst_main_handoff.qml +++ b/tests/qml/tst_main_handoff.qml @@ -201,4 +201,75 @@ TestCase { compare(accentSpy.count, 2); rig.destroy(); } + + // A stand-in for a backend that winds down asynchronously (mpv): records + // every prepareDestroy() call under its tag. + property var prepared: [] + Component { + id: asyncBackendComp + Item { + property string tag: "" + property bool frameShown: true + function prepareDestroy() { tc.prepared.push(tag); } + } + } + function _asyncBackend(loader, tag, shown) { + return asyncBackendComp.createObject(loader, { tag: tag, frameShown: shown }); + } + + function test_destroying_the_loader_prepares_both_backends() { + const rig = _mkRigWithScene("111"); + const loader = _loader(rig); + loader.item = _asyncBackend(loader, "item", true); + loader._outgoing = _asyncBackend(loader, "outgoing", true); + tc.prepared = []; + rig.destroy(); + tryVerify(() => tc.prepared.length === 2, 2000, "teardown destroyed a backend without prepareDestroy"); + verify(tc.prepared.indexOf("item") >= 0 && tc.prepared.indexOf("outgoing") >= 0); + } + + function test_cutting_a_running_fade_short_prepares_that_backend() { + const rig = _mkRigWithScene("111"); + const loader = _loader(rig); + loader._outgoing = _asyncBackend(loader, "fading", true); + tc.prepared = []; + loader.dropOutgoing(); + loader._outgoing = _asyncBackend(loader, "next", true); + loader.dropOutgoing(); + verify(tc.prepared.indexOf("fading") >= 0, "interrupted fade destroyed its backend unprepared"); + rig.destroy(); + } + + function test_a_backend_that_never_drew_is_prepared_before_it_is_dropped() { + const rig = _mkRigWithScene("111"); + const loader = _loader(rig); + loader.item = _asyncBackend(loader, "undrawn", false); + tc.prepared = []; + _switchTo(rig, "222"); + tryVerify(() => tc.prepared.indexOf("undrawn") >= 0, 2000, + "undrawn backend destroyed without prepareDestroy"); + rig.destroy(); + } + + function test_replacing_an_outgoing_backend_prepares_it() { + const rig = _mkRigWithScene("111"); + const loader = _loader(rig); + loader._outgoing = _asyncBackend(loader, "stale", true); + loader.item = _asyncBackend(loader, "shown", true); + tc.prepared = []; + _switchTo(rig, "222"); + tryVerify(() => tc.prepared.indexOf("stale") >= 0, 2000, + "replaced outgoing backend destroyed without prepareDestroy"); + rig.destroy(); + } + + function test_fade_end_prepares_the_outgoing_backend() { + const rig = _mkRigWithScene("111"); + const loader = _loader(rig); + loader._outgoing = _asyncBackend(loader, "done", true); + tc.prepared = []; + loader.dropOutgoing(); + tryVerify(() => tc.prepared.indexOf("done") >= 0, 2000); + rig.destroy(); + } }