Skip to content

Performance: Prevent UI unresponsiveness when rapidly adjusting output device volume - #103

Merged
G-Stas merged 7 commits into
G-Stas:mainfrom
ElektroStudios:fix/ui-lag-volume-adjustment
Oct 30, 2026
Merged

G-Stas merged 7 commits into
G-Stas:mainfrom
ElektroStudios:fix/ui-lag-volume-adjustment

Conversation

@ElektroStudios

@ElektroStudios ElektroStudios commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR aims to fix a UI lag and stutter issue that happens when rapidly changing the master volume (e.g., holding down a volume hotkey or scrolling the mouse wheel quickly).

It seems that on certain audio hardware setups, the synchronous COM calls to masterVolume.SetVolume can take a moment to return. Since these calls were running on the main UI thread, it caused the application to briefly hang, making the volume trackbar and OSD lag behind the user's actual input.

To give a concrete example: in my personal setup (a Hi-Fi mini system connected to a Sound Blaster Z card), the delay was massive. A fast, long scroll with the mouse wheel caused the UI to choke. The volume trackbar would keep sliding for several seconds after I had already stopped scrolling, or it would just freeze and jump directly to the target position without any smooth path animation.

Technical Details

To work around this, I made the following adjustments:

  • Moved the hardware volume update in MasterSessionModel.SetVolume to a background thread.
  • Added a simple background loop logic: if the user rapidly changes the volume while the background thread is still busy communicating with the COM API, the code simply drops the intermediate values and picks up the latest target volume.
  • The method now immediately returns true to the caller. This frees up the WPF UI (trackbars, text, OSD) to update instantly, keeping the visual experience smooth regardless of the audio driver's response time.

Visual Comparison

Status Preview
❌ Before before
✅ After after

@ElektroStudios ElektroStudios changed the title Performance: Prevent UI unresponsiveness when rapidly adjusting master volume Performance: Prevent UI unresponsiveness when rapidly adjusting output device volume Oct 26, 2026
@G-Stas

G-Stas commented Oct 27, 2026

Copy link
Copy Markdown
Owner

Thanks, but the PR needs a bit of rework:

  1. Stale echoes undo hotkey steps. Hotkey writes use the empty context, so each write comes back as a notification. With writes queued, the echo of an older write arrives while a newer one is pending, and OnVolumeChanged sets _volume back to it. Holding volume up then loses steps and the slider jumps back. I think we should ignore notifications while a write is queued or running.

  2. Mute still blocks the UI. SetMute runs on the UI thread and waits for writeLock, which the worker holds during the slow write. Please move the worker into MasterAudioSessionVolume and send mute through it too, so order is kept.

  3. Failed writes aren't reported. SetVolume now always returns true, so the UI shows a volume the device never got.

  4. Dispose doesn't stop the worker. A queued write can run after the device is released.

  5. Tests. HotkeyMustIncrementVolume and HotkeyMustDecrementVolume now race the background write. Please add a synchronous mode for tests (like InputHookHost's start: false). Also add a test with a fake volume whose SetVolume blocks: press several times, check Volume, release, check the last write is the final value and an old echo doesn't change Volume.

  6. Minor: a nullable (int, Guid)? and a Task? instead of the -1 sentinel, Guid and bool; drop = false; add using System.Threading.Tasks;.

Also, OnNotify reads it on the UI thread for every notification.

@ElektroStudios

ElektroStudios commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks, but the PR needs a bit of rework:

Thanks for the detailed review. Fair warning: this is quite a lot for me, as I have very limited experience with C# and WPF. I therefore delegated the implementation to Claude and focused on reviewing the results, cleaning things up, and requesting changes wherever something looked like—or could potentially be considered—slop code. Hopefully, everything looks good at a glance. I also tried to preserve the existing comments and coding style as much as possible. Here is what changed for each point:

  1. Stale echoes: MasterSessionModel.OnVolumeChanged now returns early while IAudioSessionVolume.HasPendingWrites is true, so the echo of an older write can no longer undo newer steps.

  2. Mute blocking the UI: the worker now lives in MasterAudioSessionVolume. SetVolume and SetMute only enqueue the request (the latest value of each is kept) and return immediately. The worker writes the mute first and then the volume. HasPendingWrites is a volatile bool, so OnNotify on the UI thread never waits for anything.

  3. Failed writes: the worker remembers the exception and, once the queue is empty, raises WriteFailed with the error and the state the device really has. MasterSessionModel logs it and shows that state through the Dispatcher, unless a newer write is already pending.

  4. Dispose: MasterSessionModel.Dispose unsubscribes and disposes MasterAudioSessionVolume, which drops the queued writes and waits (max 2 seconds) for the write in progress. OutputDeviceModel releases the device only after that.

  5. Tests:

    • MasterAudioSessionVolume has an internal constructor that takes the two write delegates and a background flag. With background: false it writes synchronously on the caller's thread.
    • New MasterAudioSessionVolumeTests: synchronous mode, coalescing of queued volumes, mute going through the same queue without blocking the caller, failure reporting, and Dispose.
    • New MasterSessionModelTests: echo ignored while writes are pending, a fake volume whose SetVolume blocks (press several times, check Volume, release, check the last write and that an old echo doesn't change Volume), and a failed write showing the device state.
    • HotkeyMustIncrementVolume and HotkeyMustDecrementVolume are unchanged: they use a mock whose writes are synchronous and which reports no pending writes, so they no longer race.
  6. Minor: (int, Guid)? and (bool, Guid)? replace the -1 sentinel, Task? holds the worker, no = false initializers, and the Tasks using is added.

All Volumey.Tests are passing.

The 2 second limit that MasterAudioSessionVolume.Dispose waits for a write in progress is my own choice, and I'm happy to change it. The same goes for the new names (HasPendingWrites, WriteFailed, and the background parameter of the internal constructor of MasterAudioSessionVolume) if you prefer different ones.

G-Stas
G-Stas previously approved these changes Oct 28, 2026

@G-Stas G-Stas left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few things to fix and it's ready to merge

Comment thread Volumey/Model/MasterSessionModel.cs Resolved
@ElektroStudios

ElektroStudios commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

A few things to fix and it's ready to merge

Hopefully all three points are fixed:

  • Dispose on the UI thread: MasterAudioSessionVolume.Dispose no longer waits. It only drops the queued writes and stops accepting new ones. OutputDeviceModel.ReleaseAsync now awaits Master.WaitForWritesAsync() right before device.Dispose(), so the write in progress finishes before the device is released, without blocking the UI.
  • Outside changes dropped during a write: MasterSessionModel.OnVolumeChanged still ignores notifications while a write is queued or running (the echo of an older write would undo newer steps), but the dropped changes are no longer lost: when the queue empties, the worker reads the device and MasterSessionModel takes that state over if nothing newer is queued. The worker now clears HasPendingWrites before reading the device, so a change made right while it reads is applied by the model instead of being dropped, and the state read can't miss it.
  • Reading the device state: the worker now reads the device every time the queue empties, before going idle, not only after a failure. WriteFailed became WritesCompleted, which always reports the error of the last failed write (or null) and the device state. MasterSessionModel takes that state over if nothing newer is queued, using the same path as OnVolumeChanged (ApplyDeviceState), so a dropped notification (e.g. the keyboard's mute key during a write) is no longer lost.

Tests updated: DisposeMustNotBlockAndMustDropPendingWrites, WritesCompletedMustBeRaisedAfterSuccessfulWritesToo, TheDeviceStateMustNotBeTakenOverWhileNewerWritesArePending and ADeviceChangeMadeWhileWritingMustBeTakenOverWhenTheWritesComplete are new, and the failed-write ones use the renamed event.

Thank you for your patience and reviews.

G-Stas
G-Stas previously approved these changes Oct 29, 2026
/// <param name="volumeWriter">Writes the volume to the device</param>
/// <param name="muteWriter">Writes the mute state to the device</param>
/// <param name="background">False writes synchronously on the caller's thread instead of on the worker (for tests)</param>
internal MasterAudioSessionVolume(Action<int, Guid> volumeWriter, Action<bool, Guid> muteWriter, bool background)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

background: false is only used to test itself; it can go, together with audioVolume = null!.

Comment thread Volumey/Model/MasterSessionModel.cs Outdated
return;
VolumeChangedEventArgs deviceState = state.Value;
//the properties this changes belong to the UI thread
var dispatcher = System.Windows.Application.Current?.Dispatcher;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use the dispatcher helper the other models have (App.Current?.Dispatcher ?? Dispatcher.CurrentDispatcher

Comment thread Volumey/Model/MasterSessionModel.cs Outdated
Comment on lines +394 to +401
private void ShowDeviceState(VolumeChangedEventArgs real)
{
//the device may have changed while we were writing (its notification was dropped) or never got what the UI shows:
//show what it really has, unless a newer write is already on its way
if(disposed || masterVolume.HasPendingWrites)
return;
ApplyDeviceState(real);
}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small race: the worker reads the device (50), then the user presses a volume key (52). OnVolumeChanged applies 52, because busy is already false. Then WritesCompleted with 50 arrives here and sets 50 back. The mixer shows 50 while the device is at 52, until the next change. Please read the device again here instead of using the state from the worker, or skip the state if a notification came in after it was read.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small race: the worker...

Thanks, all three seem done:

  • background: false: removed, together with audioVolume = null!. The internal constructor of MasterAudioSessionVolume now takes the two writers plus the two readers (volume and mute), so the tests use the same worker as production. The two synchronous-mode tests are gone.
  • Dispatcher: MasterSessionModel now uses the same App.Current?.Dispatcher ?? Dispatcher.CurrentDispatcher helper as the other models.
  • Race in ShowDeviceState: the worker no longer reads the device. WritesCompleted now only reports the error (or null) once the worker is idle, and MasterSessionModel.ShowDeviceState reads the device itself on the UI thread, skipping it if a newer write is pending. Since busy is already false by then, a change made after the worker went idle can't be overwritten with an older state. Added ANotificationAfterTheWorkerWentIdleMustNotBeOverwrittenByAnOlderState, and the other WritesCompleted tests read the state from the mock.

@G-Stas
G-Stas merged commit ce45e9e into G-Stas:main Oct 30, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants