diff --git a/plugin/contents/config/main.xml b/plugin/contents/config/main.xml index 2699fff2..65a76e3f 100644 --- a/plugin/contents/config/main.xml +++ b/plugin/contents/config/main.xml @@ -78,6 +78,10 @@ false + + + false + true diff --git a/plugin/contents/ui/backend/Mpv.qml b/plugin/contents/ui/backend/Mpv.qml index 03816002..57460e85 100644 --- a/plugin/contents/ui/backend/Mpv.qml +++ b/plugin/contents/ui/backend/Mpv.qml @@ -66,6 +66,10 @@ Item{ anchors.fill: parent mute: background.mute volume: 0 + // Opt-in power saving: cheap scalers, the video's own frame rate, and + // at most as many redraws per second as scenes get (Fps setting). + powerSaving: background.mpvPowerSaving + maxFps: background.mpvPowerSaving ? background.fps : 0 Connections { ignoreUnknownSignals: true function onFirstFrame() { @@ -126,6 +130,8 @@ Item{ displayMode = displayMode; videoRate = videoRate; player.mute = player.mute; + player.powerSaving = player.powerSaving; + player.maxFps = player.maxFps; volumeFade.freeze(); } // Called by main.qml once this backend has faded out, some time before diff --git a/plugin/contents/ui/config.qml b/plugin/contents/ui/config.qml index bcdfcb9a..33c02bd4 100644 --- a/plugin/contents/ui/config.qml +++ b/plugin/contents/ui/config.qml @@ -43,6 +43,7 @@ ColumnLayout { property alias cfg_Fps: settingPage.cfg_Fps property alias cfg_Volume: settingPage.cfg_Volume property alias cfg_MpvStats: settingPage.cfg_MpvStats + property alias cfg_MpvPowerSaving: settingPage.cfg_MpvPowerSaving property alias cfg_Speed: settingPage.cfg_Speed property alias cfg_MuteAudio: settingPage.cfg_MuteAudio property alias cfg_MouseInput: settingPage.cfg_MouseInput diff --git a/plugin/contents/ui/main.qml b/plugin/contents/ui/main.qml index 34eb6892..2ae940d9 100644 --- a/plugin/contents/ui/main.qml +++ b/plugin/contents/ui/main.qml @@ -31,6 +31,7 @@ Rectangle { property bool mouseInput: wallpaper.configuration.MouseInput property bool animatedPreview: wallpaper.configuration.AnimatedPreview property bool mpvStats: wallpaper.configuration.MpvStats + property bool mpvPowerSaving: wallpaper.configuration.MpvPowerSaving property string videoFolderPath: wallpaper.configuration.VideoFolderPath property int cacheQuotaMB: wallpaper.configuration.CacheQuotaMB diff --git a/plugin/contents/ui/page/SettingPage.qml b/plugin/contents/ui/page/SettingPage.qml index 1148334b..f125a4d3 100644 --- a/plugin/contents/ui/page/SettingPage.qml +++ b/plugin/contents/ui/page/SettingPage.qml @@ -19,6 +19,7 @@ Flickable { property alias cfg_PresentMode: cbPresentMode.currentIndex property alias cfg_Volume: sliderVol.value property alias cfg_MpvStats: ckbox_mpvStats.checked + property alias cfg_MpvPowerSaving: ckbox_mpvPowerSaving.checked property alias cfg_Speed: spin_speed.dValue property alias cfg_MuteAudio: ckbox_muteAudio.checked property alias cfg_MouseInput: ckbox_mouseInput.checked @@ -511,6 +512,18 @@ Flickable { id: ckbox_mpvStats } } + + OptionItem { + text: i18nc("@label settings option", "Power-saving playback") + text_color: Kirigami.Theme.textColor + icon: '../../images/tuning.svg' + visible: cfg_VideoBackend == Common.VideoBackend.Mpv + actor: Switch { + id: ckbox_mpvPowerSaving + ToolTip.visible: hovered + ToolTip.text: i18nc("@info:tooltip", "Cheaper scaling, frames at the video's own rate and at most the scene Fps redraws per second. Uses noticeably less CPU and GPU; loop points may be less smooth.") + } + } } OptionGroup { Layout.fillWidth: true diff --git a/src/backend_mpv/MpvBackend.cpp b/src/backend_mpv/MpvBackend.cpp index 3249b1c7..a9d8d437 100644 --- a/src/backend_mpv/MpvBackend.cpp +++ b/src/backend_mpv/MpvBackend.cpp @@ -323,6 +323,85 @@ void MpvObject::setVolume(const int& volume) { emit volumeChanged(); } +const std::vector>& MpvObject::powerSavingOptions() { + static const std::vector> opts = { + // mpv's built-in `fast` profile, spelled out so it can be undone. + { "scale", "bilinear" }, + { "dscale", "bilinear" }, + { "dither", "no" }, + { "correct-downscaling", "no" }, + { "linear-downscaling", "no" }, + { "sigmoid-upscaling", "no" }, + { "hdr-compute-peak", "no" }, + { "allow-delayed-peak-detect", "yes" }, + // display-resample redraws on every vblank (120/s for a 60 fps file + // on a 120 Hz panel); with no audio track `audio` sync falls back to + // the system clock and presents at the video's own rate. + { "video-sync", "audio" }, + }; + return opts; +} + +// Measured on a 1080p60 wallpaper on a 2520x1680@120 laptop panel (Intel +// Iris Xe), separate mpv instance: CPU 30.4% -> 16.7%, GPU render busy +// 28.4% -> 6.4%. Off by default: the default chain looks better and +// display-resample hides loop-wrap judder. +void MpvObject::setPowerSaving(bool on) { + if (on == m_powerSaving) return; + m_powerSaving = on; + if (m_mpv) { + if (on) { + m_savedOptions.clear(); + for (const auto& [name, value] : powerSavingOptions()) { + char* old = mpv_get_property_string(m_mpv, name); + m_savedOptions.emplace_back(name, old ? old : ""); + mpv_free(old); + mpv_set_property_string(m_mpv, name, value); + } + } else { + for (const auto& [name, value] : m_savedOptions) + if (! value.empty()) mpv_set_property_string(m_mpv, name.c_str(), value.c_str()); + m_savedOptions.clear(); + } + } + emit powerSavingChanged(); +} + +int MpvObject::frameCapDelayMs(int maxFps, qint64 sinceLastMs) { + if (maxFps <= 0) return 0; + const qint64 interval = 1000 / maxFps; + return sinceLastMs >= interval ? 0 : int(interval - sinceLastMs); +} + +void MpvObject::setMaxFps(int fps) { + fps = fps > 0 ? fps : 0; + if (fps == m_maxFps) return; + m_maxFps = fps; + emit maxFpsChanged(); +} + +void MpvObject::redrawNow() { + m_frameClock.restart(); + update(); +} + +// mpv asks for a redraw per decoded frame (60/s for most wallpaper videos). +// Under a cap, a request inside the frame interval is folded into one +// deferred redraw, which then shows mpv's newest frame. +void MpvObject::scheduleUpdate() { + if (m_maxFps <= 0) { + update(); + return; + } + const int delay = + frameCapDelayMs(m_maxFps, m_frameClock.isValid() ? m_frameClock.elapsed() : qint64(1000)); + if (delay == 0) { + redrawNow(); + } else if (! m_frameTimer.isActive()) { + m_frameTimer.start(delay); + } +} + void MpvObject::setLogfile(const QString& logfile) { setProperty("log-file", logfile); emit logfileChanged(); @@ -504,6 +583,9 @@ void on_mpv_redraw(void* ctx) { MpvObject::MpvObject(QQuickItem* parent) : QQuickFramebufferObject(parent), m_shared_mpv(std::make_shared(mpv_create())) { m_mpv = m_shared_mpv.get()->handle; + m_frameTimer.setSingleShot(true); + m_frameTimer.setTimerType(Qt::PreciseTimer); + connect(&m_frameTimer, &QTimer::timeout, this, &MpvObject::redrawNow); if (! m_mpv) { qWarning() << "MpvObject: mpv_create() failed — video backend unavailable"; @@ -624,7 +706,7 @@ QQuickFramebufferObject::Renderer* MpvObject::createRenderer() const { auto* render = new MpvRender(m_shared_mpv, window()); // Use Queued signal to update at gui thread - connect(render, &MpvRender::mpvRedraw, this, &MpvObject::update, Qt::QueuedConnection); + connect(render, &MpvRender::mpvRedraw, this, &MpvObject::scheduleUpdate, Qt::QueuedConnection); connect(render, &MpvRender::inited, this, &MpvObject::initCallback, Qt::QueuedConnection); connect(render, &MpvRender::renderInitFailed, diff --git a/src/backend_mpv/MpvBackend.hpp b/src/backend_mpv/MpvBackend.hpp index 1fe5ca84..c68c1e68 100644 --- a/src/backend_mpv/MpvBackend.hpp +++ b/src/backend_mpv/MpvBackend.hpp @@ -8,6 +8,11 @@ #include #include #include +#include +#include +#include +#include +#include #include #include @@ -74,6 +79,11 @@ class MpvObject : public QQuickFramebufferObject { Q_PROPERTY(QString logfile READ logfile WRITE setLogfile NOTIFY logfileChanged) Q_PROPERTY(int volume READ volume WRITE setVolume NOTIFY volumeChanged) Q_PROPERTY(bool initialized READ initialized NOTIFY initializedChanged) + // Opt-in (MpvPowerSaving): cheap scalers, frames at the video's own rate. + Q_PROPERTY(bool powerSaving READ powerSaving WRITE setPowerSaving NOTIFY powerSavingChanged) + // Upper bound on how often a new video frame is drawn; 0 = every frame + // mpv produces. mpv drops the frames in between, like on a slow display. + Q_PROPERTY(int maxFps READ maxFps WRITE setMaxFps NOTIFY maxFpsChanged) friend class MpvRender; @@ -113,11 +123,24 @@ class MpvObject : public QQuickFramebufferObject { bool mute() const; QString logfile() const; int volume() const; + bool powerSaving() const { return m_powerSaving; } + int maxFps() const { return m_maxFps; } + + // The mpv options powerSaving sets: the built-in `fast` profile (bilinear + // scaling, no dithering / linear or sigmoid scaling / HDR peak detection) + // plus video-sync=audio, i.e. present frames at the video's own rate + // instead of retiming to every display refresh. + static const std::vector>& powerSavingOptions(); + // Frame-rate cap: how long to hold a redraw requested `sinceLastMs` after + // the previous one; 0 = draw now. maxFps <= 0 disables the cap. + static int frameCapDelayMs(int maxFps, qint64 sinceLastMs); void setSource(const QUrl& source); void setMute(const bool& mute); void setLogfile(const QString& logfile); void setVolume(const int& volume); + void setPowerSaving(bool on); + void setMaxFps(int fps); public slots: void play(); @@ -158,6 +181,8 @@ public slots: void sourceLoadFailed(const QString& reason); void muteChanged(); void volumeChanged(); + void powerSavingChanged(); + void maxFpsChanged(); void logfileChanged(); private: @@ -175,6 +200,18 @@ public slots: bool m_propPaused { false }; bool m_inited_ok { false }; // set once mpv_initialize() succeeds + // powerSaving: the values its options had before it was switched on, so + // switching it off restores exactly those (mpv's defaults vary by version). + bool m_powerSaving { false }; + std::vector> m_savedOptions; + // Frame-rate cap (GUI thread): when the last redraw went out, and a + // single-shot timer for a deferred one. + int m_maxFps { 0 }; + QElapsedTimer m_frameClock; + QTimer m_frameTimer; + void scheduleUpdate(); + void redrawNow(); + private: mpv_handle* m_mpv { nullptr }; std::shared_ptr m_shared_mpv { nullptr }; diff --git a/tests/qml/Helpers/BackgroundFake.qml b/tests/qml/Helpers/BackgroundFake.qml index 3a351480..528810ef 100644 --- a/tests/qml/Helpers/BackgroundFake.qml +++ b/tests/qml/Helpers/BackgroundFake.qml @@ -17,6 +17,7 @@ QtObject { property int fps: 30 property int presentMode: 0 // Auto (matches main.xml default) property bool mpvStats: false + property bool mpvPowerSaving: false property bool hdrOutput: false property string postProcessing: "" // empty = wallpaper-default; matches main.qml property bool systemAudioCapture: true // matches main.xml default diff --git a/tests/qml/Helpers/WallpaperFake.qml b/tests/qml/Helpers/WallpaperFake.qml index 5ccdeec1..ba193f54 100644 --- a/tests/qml/Helpers/WallpaperFake.qml +++ b/tests/qml/Helpers/WallpaperFake.qml @@ -41,6 +41,7 @@ Item { "NoRandomWhilePaused": false, "UserPaused": false, "MpvStats": false, + "MpvPowerSaving": false, "MouseInput": false, "AnimatedPreview": false, "Fps": 30, diff --git a/tests/qml/_stubs/README.md b/tests/qml/_stubs/README.md index 5fce3a88..06f248e2 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, 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, 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. | +| Mpv | src/backend_mpv/ | Properties: source, volume, mute, powerSaving, maxFps. 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 a71b0835..2748f91d 100644 --- a/tests/qml/_stubs/com/github/captsilver/wallpaperEngineKde/Mpv.qml +++ b/tests/qml/_stubs/com/github/captsilver/wallpaperEngineKde/Mpv.qml @@ -10,6 +10,8 @@ Item { property string source: "" property real volume: 50 property bool mute: false + property bool powerSaving: false + property int maxFps: 0 // ── test recorders (test-only stub) ────────────────────────────────── property int playCount: 0 diff --git a/tests/qml/tst_backend_mpv.qml b/tests/qml/tst_backend_mpv.qml index 395030e2..b00459f1 100644 --- a/tests/qml/tst_backend_mpv.qml +++ b/tests/qml/tst_backend_mpv.qml @@ -106,6 +106,27 @@ TestCase { compare(p.lastCommand[1], "stats/display-stats-toggle"); } + // MpvPowerSaving is opt-in: off, the player keeps mpv's quality chain and + // draws every frame; on, it also caps redraws at the scene Fps setting. + function test_powerSavingOffByDefault_noFrameCap() { + const p = _findMpvPlayer(); + background.mpvPowerSaving = false; + compare(p.powerSaving, false); + compare(p.maxFps, 0); + } + + function test_powerSavingOn_capsAtSceneFps() { + const p = _findMpvPlayer(); + background.fps = 24; + background.mpvPowerSaving = true; + compare(p.powerSaving, true); + compare(p.maxFps, 24); + background.fps = 30; // follows the Fps setting live + compare(p.maxFps, 30); + background.mpvPowerSaving = false; // and lets go of it when switched off + compare(p.maxFps, 0); + } + function test_videoRateChangedSetsSpeedProperty() { // onVideoRateChanged forwards to player.setProperty('speed', videoRate) // (Mpv.qml:49). videoRate is bound to background.speed, so the @@ -270,6 +291,24 @@ TestCase { item.destroy(); } + // Power saving is per-plugin, not per-wallpaper, but toggling it during + // a handoff must not reach a player that is already being stopped. + function test_freezeOptions_keeps_power_saving() { + background.fps = 24; + background.mpvPowerSaving = true; + const item = freshMpvComp.createObject(mpv.parent); + const p = item.data.find(o => o && typeof o.setProperty === "function" + && typeof o.command === "function"); + compare(p.powerSaving, true); + compare(p.maxFps, 24); + item.freezeOptions(); + background.mpvPowerSaving = false; + background.fps = 30; + compare(p.powerSaving, true, "frozen backend followed the power-saving switch"); + compare(p.maxFps, 24, "frozen backend followed the Fps setting"); + 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"); diff --git a/tests/tst_mpvbackend.cpp b/tests/tst_mpvbackend.cpp index 49987cc0..cbc2ebeb 100644 --- a/tests/tst_mpvbackend.cpp +++ b/tests/tst_mpvbackend.cpp @@ -153,6 +153,10 @@ private slots: void beginShutdown_quitsCoreWithoutWaitingOnIt(); void stopAsync_detachesEventsAndReturnsImmediately(); void stopAsync_uninitializedOrRepeated_isSafe(); + void powerSaving_setsFastOptions_andRestoresPrevious(); + void powerSaving_defaultOff_leavesOptionsAlone(); + void frameCapDelayMs_table(); + void maxFps_negativeClampsToUncapped(); void beginShutdown_neverInitializedCore_doesNotWarn(); void beginShutdown_healthyCore_doesNotWarn(); void beginShutdown_quitRejectedByChokedCore_warns(); @@ -855,4 +859,60 @@ void TestMpvBackend::stopAsync_uninitializedOrRepeated_isSafe() { obj.reset(); // and the normal teardown still runs afterwards } +// MpvPowerSaving flips a fixed set of mpv options (the built-in `fast` +// profile plus video-sync=audio) and must put back exactly what was there, +// since mpv's own defaults for them differ between versions. +void TestMpvBackend::powerSaving_setsFastOptions_andRestoresPrevious() { + auto obj = makeObject(); + QVERIFY(obj->initialized()); + QMap before; + for (const auto& [name, value] : MpvObject::powerSavingOptions()) + before[name] = obj->getProperty(QString::fromLatin1(name)).toString(); + + QSignalSpy spy(obj.get(), &MpvObject::powerSavingChanged); + obj->setPowerSaving(true); + QCOMPARE(spy.count(), 1); + QVERIFY(obj->powerSaving()); + QCOMPARE(obj->getProperty("video-sync").toString(), QStringLiteral("audio")); + QCOMPARE(obj->getProperty("scale").toString(), QStringLiteral("bilinear")); + QCOMPARE(obj->getProperty("dscale").toString(), QStringLiteral("bilinear")); + + obj->setPowerSaving(true); // no-op, no second signal + QCOMPARE(spy.count(), 1); + + obj->setPowerSaving(false); + QCOMPARE(spy.count(), 2); + for (const auto& [name, value] : MpvObject::powerSavingOptions()) + QCOMPARE(obj->getProperty(QString::fromLatin1(name)).toString(), before[name]); + // The constructor's own choice survives a round trip. + QCOMPARE(obj->getProperty("video-sync").toString(), QStringLiteral("display-resample")); +} + +void TestMpvBackend::powerSaving_defaultOff_leavesOptionsAlone() { + auto obj = makeObject(); + QVERIFY(! obj->powerSaving()); + QCOMPARE(obj->maxFps(), 0); + QCOMPARE(obj->getProperty("video-sync").toString(), QStringLiteral("display-resample")); +} + +void TestMpvBackend::frameCapDelayMs_table() { + QCOMPARE(MpvObject::frameCapDelayMs(0, 0), 0); // uncapped: always now + QCOMPARE(MpvObject::frameCapDelayMs(-5, 3), 0); + QCOMPARE(MpvObject::frameCapDelayMs(30, 0), 33); // right after a draw: hold + QCOMPARE(MpvObject::frameCapDelayMs(30, 20), 13); + QCOMPARE(MpvObject::frameCapDelayMs(30, 33), 0); // interval elapsed: draw + QCOMPARE(MpvObject::frameCapDelayMs(30, 500), 0); + QCOMPARE(MpvObject::frameCapDelayMs(24, 10), 31); +} + +void TestMpvBackend::maxFps_negativeClampsToUncapped() { + auto obj = makeObject(); + QSignalSpy spy(obj.get(), &MpvObject::maxFpsChanged); + obj->setMaxFps(30); + QCOMPARE(obj->maxFps(), 30); + obj->setMaxFps(-1); + QCOMPARE(obj->maxFps(), 0); + QCOMPARE(spy.count(), 2); +} + #include "tst_mpvbackend.moc"