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
6 changes: 6 additions & 0 deletions plugin/contents/ui/backend/Mpv.qml
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,12 @@ Item{
player.mute = player.mute;
volumeFade.freeze();
}
// 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();
Expand Down
27 changes: 21 additions & 6 deletions plugin/contents/ui/main.qml
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,10 @@ 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) backendLoader.retire(target);
target = null;
if (background._accentPending) background.emitAccentColor();
}
Expand All @@ -598,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() {
Expand All @@ -609,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();
Expand All @@ -623,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
Expand Down
38 changes: 32 additions & 6 deletions src/backend_mpv/MpvBackend.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include "MpvBackend.hpp"

#include <cstring>
#include <QtGlobal>
#include <QtCore/QObject>
#include <QtCore/QDir>
Expand Down Expand Up @@ -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)";
Expand Down Expand Up @@ -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<const mpv_event_property*>(ev->data);
if (prop && prop->format == MPV_FORMAT_FLAG && prop->data) {
const bool value = *static_cast<const int*>(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,
Expand Down Expand Up @@ -544,18 +568,20 @@ 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
// means no FUTURE wakeup can ever dispatch into the destroyed MpvObject.
// 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;
Expand Down
11 changes: 10 additions & 1 deletion src/backend_mpv/MpvBackend.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 };
Expand Down
2 changes: 1 addition & 1 deletion tests/qml/_stubs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, image); 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. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 } }

Expand Down
9 changes: 9 additions & 0 deletions tests/qml/tst_backend_mpv.qml
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
71 changes: 71 additions & 0 deletions tests/qml/tst_main_handoff.qml
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
46 changes: 46 additions & 0 deletions tests/tst_mpvbackend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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<MpvObject>();
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"
Loading