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
4 changes: 4 additions & 0 deletions plugin/contents/config/main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@
<label>Mpv Stats</label>
<default>false</default>
</entry>
<entry name="MpvPowerSaving" type="Bool">
<label>Power-saving video playback: cheap scaling, frames at the video's own rate, capped at the Fps setting</label>
<default>false</default>
</entry>
<entry name="MouseInput" type="Bool">
<label>Mouse Input</label>
<default>true</default>
Expand Down
6 changes: 6 additions & 0 deletions plugin/contents/ui/backend/Mpv.qml
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions plugin/contents/ui/config.qml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions plugin/contents/ui/main.qml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions plugin/contents/ui/page/SettingPage.qml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
84 changes: 83 additions & 1 deletion src/backend_mpv/MpvBackend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,85 @@ void MpvObject::setVolume(const int& volume) {
emit volumeChanged();
}

const std::vector<std::pair<const char*, const char*>>& MpvObject::powerSavingOptions() {
static const std::vector<std::pair<const char*, const char*>> 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();
Expand Down Expand Up @@ -504,6 +583,9 @@ void on_mpv_redraw(void* ctx) {
MpvObject::MpvObject(QQuickItem* parent)
: QQuickFramebufferObject(parent), m_shared_mpv(std::make_shared<MpvHandle>(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";
Expand Down Expand Up @@ -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,
Expand Down
37 changes: 37 additions & 0 deletions src/backend_mpv/MpvBackend.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
#include <QtQuick/QQuickFramebufferObject>
#include <QtCore/QLoggingCategory>
#include <QtCore/QMutex>
#include <QtCore/QElapsedTimer>
#include <QtCore/QTimer>
#include <string>
#include <utility>
#include <vector>
#include <atomic>
#include <memory>

Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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<std::pair<const char*, const char*>>& 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();
Expand Down Expand Up @@ -158,6 +181,8 @@ public slots:
void sourceLoadFailed(const QString& reason);
void muteChanged();
void volumeChanged();
void powerSavingChanged();
void maxFpsChanged();
void logfileChanged();

private:
Expand All @@ -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<std::pair<std::string, std::string>> 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<MpvHandle> m_shared_mpv { nullptr };
Expand Down
1 change: 1 addition & 0 deletions tests/qml/Helpers/BackgroundFake.qml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions tests/qml/Helpers/WallpaperFake.qml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ Item {
"NoRandomWhilePaused": false,
"UserPaused": false,
"MpvStats": false,
"MpvPowerSaving": false,
"MouseInput": false,
"AnimatedPreview": false,
"Fps": 30,
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, 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. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 39 additions & 0 deletions tests/qml/tst_backend_mpv.qml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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");
Expand Down
Loading
Loading