Skip to content

11098 fix assert on device change - #11245

Merged
saintmatthieu merged 11 commits into
audacity:masterfrom
saintmatthieu:11098-fix-assert-on-device-change
Jul 10, 2026
Merged

saintmatthieu merged 11 commits into
audacity:masterfrom
saintmatthieu:11098-fix-assert-on-device-change

Conversation

@saintmatthieu

@saintmatthieu saintmatthieu commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Resolves: #11098 #9443

Some operations cannot technically be done with running IO streams: changing audio host or device, number of input channels, buffer size, etc.

A simple solution is to grey all these out. User-friendlier is to implement a workaround whereby, upon such action, the streams are automatically stopped and, if appropriate, resumed afterwards.

This requires more transport-level logic, and, unfortunately, some refactoring. Existing alike logic lives in PlaybackController, which was initially probably intended to be just an "action controller" (like ProjectActionsController) and now mixes up both. Rather than making it even worse, this PR intends to clean that up first: extract this logic in a new injectable, ITransport.

After the refactoring commits, this PR implements the above-mentioned automations.

Leftovers

Remaining things to clean up:

  • IAudioEngine interface still has references to legacy AudacityProject class
  • Create TranportActionsController and move handling of transport-only actions there
  • TBC
  • I signed CLA
  • The title of the pull request describes an issue it addresses
  • If changes are extensive, then there is a sequence of easily reviewable commits
  • Each commit's message describes its purpose and effects
  • There are no behavior changes unnecessary for the stated purpose of the PR

Recommended:

  • Each commit compiles and runs on my machine without known undesirable changes of behavior

QA

Setup: Use a machine with ≥2 playback devices and ≥2 recording devices (or ≥2 audio hosts/APIs) so you can switch between them.
Don't enable looping: there is currently a bug when enabled (ticket exists) that hides this PR's fixes
Test primarily on Windows + WASAPI (the config reported in #11098)

The device-related actions are

  • change host
  • change device (playback or recording)
  • rescan devices
  • change recording channels

Other audio-related settings such as buffer length, default sample rate, etc., don't need an interrupt - they'll be taken into account on the next playback. (Those precise actions weren't discussed with @teetow, but I guess their impact may be too small to be worth the implementation effort, albeit low.)

  • While playing: playback keeps going from ~the same position. Pressing stop returns the playhead to the initial position (not the position where the device action took place).
  • While paused: the transport goes to stopped — it does not stay paused and does not auto-resume. Pressing Play afterwards starts playback again from the paused position.
  • While recording: recording stops cleanly but doesn't automatically resume. (It could in a new clip, as suggested by @kryksyh , but we can implement this in a follow-up.)
  • For any of the above, if input monitoring is ON before the device action, it is still ON after.

@saintmatthieu

Copy link
Copy Markdown
Contributor Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR introduces a Transport/ITransport abstraction in the playback module that centralizes play/pause/stop/seek, playback-region, loop, and audio-device-change logic, replacing the previous IPlaybackController interface. PlaybackController is narrowed to action dispatch delegating to Transport. IPlayer gains isPlaying/isPaused/isStopped/isPlayingChanged. Dozens of consumers (appshell, context, effects, import/export, projectscene, record, trackedit, preferences QML/models) migrate from IPlaybackController to IPlayer/IPlayback/ITransport. Separately, au3audio adds a test build option, device-change teardown improvements (stop stream when busy), a new engine mock, and provider tests.

Estimated code review effort: 4 (Complex) | ~75 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant PlaybackController
  participant Transport
  participant Au3Player
  User->>PlaybackController: togglePlayAction()
  PlaybackController->>Transport: togglePlay(ignoreSelection)
  Transport->>Au3Player: play() / pause() / stop() / seek()
  Au3Player-->>Transport: isPlayingChanged notification
  Transport-->>PlaybackController: isPlayAllowedChanged notification
Loading
sequenceDiagram
  participant CommonAudioApiConfigurationModel
  participant Transport
  participant AudioDevicesProvider
  participant Au3Player
  CommonAudioApiConfigurationModel->>Transport: setAudioOutputDevice(device)
  Transport->>Au3Player: stop() if playing/paused
  Transport->>AudioDevicesProvider: apply device change
  Transport->>Au3Player: resume/play if previously playing
Loading

Related Issues: None identified from provided data.

Related PRs: None identified from provided data.

Suggested labels: playback, refactor, tests

Suggested reviewers: None identified from provided data.

🐰 A rabbit hops through transport lanes,
Controllers shed their old refrains,
Player states now notify with care,
Devices swap without despair,
Tests confirm the stream restarts fair.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address #11098 by making device changes safe while paused and by covering the device-change cases in tests.
Out of Scope Changes check ✅ Passed The broader playback refactor and transport wiring are directly tied to the device-change fix and its test coverage.
Title check ✅ Passed The title is concise and matches the main change: fixing a device-change assert.
Description check ✅ Passed The description mostly matches the template and includes the issue, summary, checkboxes, and QA notes, with only minor formatting gaps.

Warning

Review ran into problems

🔥 Problems

Linked repositories: Your configuration references 1 linked repositories, but your current plan allows 0. Analyzed ``, skipped musescore/musescore.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: 53c8ecaa-3d20-4298-b3e8-b76813b40452

📥 Commits

Reviewing files that changed from the base of the PR and between d6610f0 and 254ccb5f906987b6c17a48d4517c11009c210351.

📒 Files selected for processing (11)
  • CMakeLists.txt
  • src/au3audio/CMakeLists.txt
  • src/au3audio/internal/au3audiodevicesprovider.cpp
  • src/au3audio/internal/au3audiodevicesprovider.h
  • src/au3audio/tests/CMakeLists.txt
  • src/au3audio/tests/au3audiodevicesprovider_tests.cpp
  • src/au3audio/tests/mocks/audioenginemock.h
  • src/playback/internal/playbackcontroller.cpp
  • src/playback/internal/playbackcontroller.h
  • src/playback/tests/environment.cpp
  • src/playback/tests/playbackcontroller_tests.cpp

@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from 254ccb5 to 8be9d3d Compare June 24, 2026 10:17

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/au3audio/tests/au3audiodevicesprovider_tests.cpp (1)

19-25: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a dedicated null-engine test case.

Au3AudioDevicesProviderTests::SetUp() always sets m_provider->audioEngine, so this suite only exercises engine-present paths. Add one test that leaves audioEngine unset and verifies handleDeviceChange() returns safely without engine calls.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: 0d3e9a06-5e70-4716-a469-f4ddbe3b3bcb

📥 Commits

Reviewing files that changed from the base of the PR and between 254ccb5f906987b6c17a48d4517c11009c210351 and 8be9d3d48cc1cc95e367cf31f7a7c0f71ce9658f.

📒 Files selected for processing (10)
  • CMakeLists.txt
  • src/au3audio/CMakeLists.txt
  • src/au3audio/internal/au3audiodevicesprovider.h
  • src/au3audio/tests/CMakeLists.txt
  • src/au3audio/tests/au3audiodevicesprovider_tests.cpp
  • src/au3audio/tests/mocks/audioenginemock.h
  • src/playback/internal/playbackcontroller.cpp
  • src/playback/internal/playbackcontroller.h
  • src/playback/tests/environment.cpp
  • src/playback/tests/playbackcontroller_tests.cpp
✅ Files skipped from review due to trivial changes (4)
  • src/au3audio/internal/au3audiodevicesprovider.h
  • src/au3audio/CMakeLists.txt
  • CMakeLists.txt
  • src/playback/internal/playbackcontroller.h
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/au3audio/tests/CMakeLists.txt
  • src/playback/tests/environment.cpp
  • src/au3audio/tests/mocks/audioenginemock.h
  • src/playback/tests/playbackcontroller_tests.cpp

@saintmatthieu
saintmatthieu requested a review from luapmartin June 24, 2026 10:34
@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from 8be9d3d to 6873658 Compare June 24, 2026 10:58

@luapmartin luapmartin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

looks ok, should we add a bounds check guard new test for the device id fallback ?

@luapmartin

luapmartin commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

also you might want to adjust those commit message as we don't restore the paused state in practice

@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from 6873658 to 0acc4a4 Compare June 26, 2026 09:00
Comment on lines +71 to +74
EXPECT_CALL(*m_audioEngine, stopMonitoring()).Times(1);
EXPECT_CALL(*m_audioEngine, stopStream()).Times(0);
EXPECT_CALL(*m_audioEngine, handleDeviceChange()).Times(1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

is the monitoring resumed?

Comment on lines +56 to +57
handleDeviceChange();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

after that should we check that the stream and/or monitoring restarted?

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.

It definitely should!

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.

... although ... not at this lower device-provider level. This is something for the playback controller tests. But good catch! Will address it there.

Comment on lines +885 to +894
EXPECT_CALL(*m_recordController, isRecording())
.WillRepeatedly(Return(true));

//! [THEN] The stream is stopped but playback is not resumed
EXPECT_CALL(*m_player, stop()).Times(1);
EXPECT_CALL(*m_player, play()).Times(0);
EXPECT_CALL(*m_player, pause()).Times(0);

//! [WHEN] The device is changed
changeAudioDevice([this]() { m_events.push_back("apply"); });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

here we might also want to test the recordController stops ? not only the player

@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from 0acc4a4 to 608846f Compare June 27, 2026 03:56

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 6


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: 8e8e00d4-ac90-4aeb-9ae2-20f5d2dfdfab

📥 Commits

Reviewing files that changed from the base of the PR and between 0acc4a4449b75eacbb5e7fc16d050d47e53f38f8 and 608846f3a6bd6173c0c715402cc81f3def27fe60.

📒 Files selected for processing (42)
  • CMakeLists.txt
  • src/appshell/internal/startupscenario.h
  • src/au3audio/CMakeLists.txt
  • src/au3audio/internal/au3audiodevicesprovider.cpp
  • src/au3audio/internal/au3audiodevicesprovider.h
  • src/au3audio/tests/CMakeLists.txt
  • src/au3audio/tests/au3audiodevicesprovider_tests.cpp
  • src/au3audio/tests/mocks/audioenginemock.h
  • src/context/internal/uicontextresolver.h
  • src/effects/builtin_collection/dynamics/timeline/dynamicsplaystatemodel.h
  • src/effects/effects_base/internal/effectsactionscontroller.h
  • src/importexport/export/internal/au3/au3exporter.h
  • src/importexport/export/view/exportpreferencesmodel.h
  • src/playback/CMakeLists.txt
  • src/playback/iaudioconfigurationscenario.h
  • src/playback/internal/audioconfigurationscenario.cpp
  • src/playback/internal/audioconfigurationscenario.h
  • src/playback/internal/playbackcontroller.cpp
  • src/playback/internal/playbackcontroller.h
  • src/playback/internal/transportscenario.cpp
  • src/playback/internal/transportscenario.h
  • src/playback/itransportscenario.h
  • src/playback/playbackmodule.cpp
  • src/playback/playbackmodule.h
  • src/playback/tests/environment.cpp
  • src/playback/tests/playbackcontroller_tests.cpp
  • src/playback/view/common/playbackstatemodel.h
  • src/playback/view/panels/playbackmeterpanelmodel.h
  • src/playback/view/toolbars/playbacktoolbarlevelitem.h
  • src/preferences/qml/Audacity/Preferences/commonaudioapiconfigurationmodel.cpp
  • src/preferences/qml/Audacity/Preferences/commonaudioapiconfigurationmodel.h
  • src/preferences/qml/Audacity/Preferences/internal/AudioApiSection.qml
  • src/preferences/qml/Audacity/Preferences/internal/BufferAndLatencySection.qml
  • src/preferences/qml/Audacity/Preferences/internal/SampleRateSection.qml
  • src/projectscene/view/common/trackviewstatemodel.h
  • src/projectscene/view/timeline/playregioncontroller.h
  • src/projectscene/view/timeline/playregionmodel.h
  • src/projectscene/view/timeline/timelinecontext.h
  • src/projectscene/view/toolbars/playbacktoolbarmodel.h
  • src/record/internal/au3/au3audioinput.h
  • src/record/internal/recordcontroller.h
  • src/trackedit/internal/trackeditinteraction.h
💤 Files with no reviewable changes (2)
  • src/preferences/qml/Audacity/Preferences/internal/SampleRateSection.qml
  • src/preferences/qml/Audacity/Preferences/internal/AudioApiSection.qml
✅ Files skipped from review due to trivial changes (3)
  • src/effects/effects_base/internal/effectsactionscontroller.h
  • src/playback/iaudioconfigurationscenario.h
  • src/playback/playbackmodule.h
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/au3audio/internal/au3audiodevicesprovider.h
  • src/au3audio/CMakeLists.txt
  • CMakeLists.txt
  • src/playback/tests/environment.cpp
  • src/au3audio/tests/CMakeLists.txt
  • src/au3audio/internal/au3audiodevicesprovider.cpp
  • src/au3audio/tests/mocks/audioenginemock.h

@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from 608846f to 7c44b33 Compare June 30, 2026 18:23
@saintmatthieu

Copy link
Copy Markdown
Contributor Author

@codereabbit review

@saintmatthieu

Copy link
Copy Markdown
Contributor Author

Partially resolves #9180

@saintmatthieu

Copy link
Copy Markdown
Contributor Author

@CodeRabbit full review

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/playback/internal/au3/au3playback.cpp (1)

8-18: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Rebind the global player when the active project changes

PlaybackContext::onInit() eagerly creates one player, and Au3Playback::player() only calls globalContext()->setPlayer(m_player) on first access. GlobalContext holds a single PlaybackState, so with multiple open projects the app-wide playback state can stay attached to whichever project touched playback first. Re-sync it on project activation, or make the single-project assumption explicit.

src/playback/internal/playbackcontroller.cpp (1)

222-229: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Resolve the input-channel index before applying it.

Line 228 passes input-channels_index directly as the channel count, unlike the API/device handlers that resolve indices to selected values. Selecting the first entry can send 0 channels and misconfigure recording input; resolve and bounds-check against the available channel options before calling transport()->setInputChannels(...).

Proposed fix
 void PlaybackController::setInputChannels(const muse::actions::ActionQuery& q)
 {
     IF_ASSERT_FAILED(q.contains("input-channels_index")) {
         return;
     }
 
-    transport()->setInputChannels(q.param("input-channels_index").toInt());
+    const int index = q.param("input-channels_index").toInt();
+    const auto& options = audioDevicesProvider()->inputChannels();
+    IF_ASSERT_FAILED(index >= 0 && index < static_cast<int>(options.size())) {
+        return;
+    }
+
+    transport()->setInputChannels(options.at(index));
 }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: d2abe8dc-031e-4cf6-ae13-5036ee27c557

📥 Commits

Reviewing files that changed from the base of the PR and between 15de5c5 and 217c257f5feda0a44924c242e3ca97419a20adad.

📒 Files selected for processing (65)
  • CMakeLists.txt
  • src/appshell/internal/startupscenario.cpp
  • src/appshell/internal/startupscenario.h
  • src/au3audio/CMakeLists.txt
  • src/au3audio/internal/au3audiodevicesprovider.cpp
  • src/au3audio/internal/au3audiodevicesprovider.h
  • src/au3audio/tests/CMakeLists.txt
  • src/au3audio/tests/au3audiodevicesprovider_tests.cpp
  • src/au3audio/tests/mocks/audioenginemock.h
  • src/context/internal/uicontextresolver.cpp
  • src/context/internal/uicontextresolver.h
  • src/effects/builtin_collection/dynamics/timeline/dynamicsplaystatemodel.cpp
  • src/effects/builtin_collection/dynamics/timeline/dynamicsplaystatemodel.h
  • src/effects/effects_base/internal/effectsactionscontroller.cpp
  • src/effects/effects_base/internal/effectsactionscontroller.h
  • src/importexport/export/internal/au3/au3exporter.cpp
  • src/importexport/export/internal/au3/au3exporter.h
  • src/importexport/export/view/exportpreferencesmodel.cpp
  • src/importexport/export/view/exportpreferencesmodel.h
  • src/playback/CMakeLists.txt
  • src/playback/internal/au3/au3playback.cpp
  • src/playback/internal/au3/au3playback.h
  • src/playback/internal/au3/au3player.cpp
  • src/playback/internal/au3/au3player.h
  • src/playback/internal/playbackcontroller.cpp
  • src/playback/internal/playbackcontroller.h
  • src/playback/internal/playbackuiactions.cpp
  • src/playback/internal/playbackuiactions.h
  • src/playback/internal/transport.cpp
  • src/playback/internal/transport.h
  • src/playback/iplaybackcontroller.h
  • src/playback/iplayer.h
  • src/playback/itransport.h
  • src/playback/playbackmodule.cpp
  • src/playback/playbackmodule.h
  • src/playback/tests/CMakeLists.txt
  • src/playback/tests/environment.cpp
  • src/playback/tests/mocks/playermock.h
  • src/playback/tests/transport_tests.cpp
  • src/playback/view/common/playbackstatemodel.cpp
  • src/playback/view/common/playbackstatemodel.h
  • src/playback/view/panels/playbackmeterpanelmodel.cpp
  • src/playback/view/panels/playbackmeterpanelmodel.h
  • src/playback/view/toolbars/playbacktoolbarlevelitem.cpp
  • src/playback/view/toolbars/playbacktoolbarlevelitem.h
  • src/preferences/qml/Audacity/Preferences/commonaudioapiconfigurationmodel.cpp
  • src/preferences/qml/Audacity/Preferences/commonaudioapiconfigurationmodel.h
  • src/preferences/qml/Audacity/Preferences/internal/AudioApiSection.qml
  • src/preferences/qml/Audacity/Preferences/internal/BufferAndLatencySection.qml
  • src/preferences/qml/Audacity/Preferences/internal/SampleRateSection.qml
  • src/projectscene/view/common/trackviewstatemodel.cpp
  • src/projectscene/view/common/trackviewstatemodel.h
  • src/projectscene/view/timeline/playregioncontroller.cpp
  • src/projectscene/view/timeline/playregioncontroller.h
  • src/projectscene/view/timeline/playregionmodel.cpp
  • src/projectscene/view/timeline/playregionmodel.h
  • src/projectscene/view/timeline/timelinecontext.cpp
  • src/projectscene/view/timeline/timelinecontext.h
  • src/projectscene/view/toolbars/playbacktoolbarmodel.cpp
  • src/projectscene/view/toolbars/playbacktoolbarmodel.h
  • src/record/internal/au3/au3audioinput.cpp
  • src/record/internal/au3/au3audioinput.h
  • src/record/internal/recordcontroller.cpp
  • src/record/internal/recordcontroller.h
  • src/trackedit/internal/trackeditinteraction.h
💤 Files with no reviewable changes (5)
  • src/playback/iplaybackcontroller.h
  • src/playback/view/toolbars/playbacktoolbarlevelitem.h
  • src/preferences/qml/Audacity/Preferences/internal/SampleRateSection.qml
  • src/playback/view/panels/playbackmeterpanelmodel.h
  • src/preferences/qml/Audacity/Preferences/internal/AudioApiSection.qml

Comment on lines 344 to 361
/**
* @brief Toggle play when already playing with run from start position
* @details User clicked play with Shift modifier
* Playback should run from start position
*/
TEST_F(PlaybackControllerTests, TogglePlay_WhenPlaying_PlayAgain)
TEST_F(TransportTests, TogglePlay_WhenPlaying_PlayAgain)
{
//! [GIVEN] Playback is running
ON_CALL(*m_player, playbackStatus())
.WillByDefault(Return(PlaybackStatus::Running));

//! [GIVEN] Play with Shift modifier
ON_CALL(*m_application, keyboardModifiers())
.WillByDefault(Return(Qt::ShiftModifier));

//! [THEN] Player should stop playing
EXPECT_CALL(*m_player, stop())
.Times(1);

//! [WHEN] Toggle play
togglePlay();
//! [WHEN] Toggle play ignoring selection (Shift+Space)
m_transport->togglePlay(true /* ignoreSelection */);
}

@coderabbitai coderabbitai Bot Jul 1, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Test doesn't verify the "run from start position" behavior it documents.

The docstring claims playback should "run from start position" when toggling play again while playing (ignore-selection), but the test only asserts stop() is called once — there's no EXPECT_CALL on play() or seek(...) to confirm playback actually restarts from the beginning. Since m_player is a NiceMock, an unmocked play() call is silently allowed either way, so this test would pass even if the restart-from-start behavior is missing entirely.

This is particularly relevant since PR comments flag that "the paused state is not actually restored in practice" for this same play/pause/resume flow — this test gap could be masking that exact issue.

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.

Will look closer, but note that this test case is almost a verbatim of TEST_F(PlaybackControllerTests, TogglePlay_WhenPlaying_PlayAgain) currently on master.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
git fetch origin main --depth=50 2>&1 | tail -5 || true
git log --oneline -3 origin/main -- src/playback/tests/ 2>&1 || true
# Find the base commit for this PR branch
git merge-base HEAD origin/main 2>&1 || true
</dev/null

Length of output: 3425


@saintmatthieu, you're right — I traced through the diff again and confirmed this test is a near-1:1 carryover: the only changes are the rename from PlaybackControllerTests to TransportTests and swapping the keyboardModifiers()/togglePlay() plumbing for the direct m_transport->togglePlay(true /* ignoreSelection */) call. No assertions were added or removed around play()/seek() — the gap (missing verification that playback actually restarts from position 0 after stop) already exists on master.

So this isn't a regression introduced by this PR, just a pre-existing test coverage gap that happened to catch my eye during the migration review. Given that, I won't insist on it blocking this PR. If you'd like, I can help draft a small follow-up test addition (e.g., asserting seek(0.0, _) and play() after stop() in this scenario) either here or as a separate issue — your call.


🧬 Code Graph Analysis Results

src/playback/tests/mocks/playermock.h (lines 10-59)

namespace au::playback {
class PlayerMock : public IPlayer
{
public:
    MOCK_METHOD(bool, isBusy, (), (const, override));
    MOCK_METHOD(void, play, (), (override));
    MOCK_METHOD(void, seek, (const muse::secs_t, bool), (override));
    MOCK_METHOD(void, rewind, (), (override));
    MOCK_METHOD(void, stop, (), (override));
    MOCK_METHOD(void, pause, (), (override));
    MOCK_METHOD(void, resume, (), (override));

    MOCK_METHOD(bool, isRunning, (), (const, override));
    MOCK_METHOD(PlaybackStatus, playbackStatus, (), (const, override));
    MOCK_METHOD(muse::async::Channel<PlaybackStatus>, playbackStatusChanged, (), (const, override));
    MOCK_METHOD(muse::ValNt<bool>, reachedEnd, (), (const, override));

    MOCK_METHOD(PlaybackRegion, playbackRegion, (), (const, override));
    MOCK_METHOD(void, setPlaybackRegion, (const PlaybackRegion&), (override));

    MOCK_METHOD(PlaybackRegion, loopRegion, (), (const, override));
    MOCK_METHOD(void, loopEditingBegin, (), (override));
    MOCK_METHOD(void, loopEditingEnd, (), (override));
    MOCK_METHOD(void, setLoopRegion, (const PlaybackRegion&), (override));
    MOCK_METHOD(void, setLoopRegionStart, (const muse::secs_t time), (override));
    MOCK_METHOD(void, setLoopRegionEnd, (const muse::secs_t time), (override));

    MOCK_METHOD(void, clearLoopRegion, (), (override));
    MOCK_METHOD(muse::async::Notification, loopRegionChanged, (), (const, override));

    MOCK_METHOD(bool, isLoopRegionClear, (), (const, override));

    MOCK_METHOD(void, setLoopRegionActive, (const bool), (override));
    MOCK_METHOD(bool, isLoopRegionActive, (), (const, override));

    MOCK_METHOD(muse::secs_t, playbackPosition, (), (const, override));
    MOCK_METHOD(void, updatePlaybackPosition, (), (override));
    MOCK_METHOD(muse::async::Channel<muse::secs_t>, playbackPositionChanged, (), (const, override));

    MOCK_METHOD(muse::Ret, playTracks, (TrackList&, double, double, const PlayTracksOptions&), (override));

    MOCK_METHOD(muse::async::Notification, isPlayingChanged, (), (const, override));

    //! The raw status predicates derive from playbackStatus() so tests can drive
    //! the whole transport state machine by stubbing a single getter.
    bool isPlaying() const override { return playbackStatus() == PlaybackStatus::Running; }
    bool isPaused() const override { return playbackStatus() == PlaybackStatus::Paused; }
    bool isStopped() const override { return playbackStatus() == PlaybackStatus::Stopped; }
};
}

src/playback/tests/mocks/playbackmock.h (lines 10-17)

namespace au::playback {
class PlaybackMock : public IPlayback
{
public:
    MOCK_METHOD(std::shared_ptr<IPlayer>, player, (TrackSequenceId), (const, override));
    MOCK_METHOD(std::shared_ptr<IAudioOutput>, audioOutput, (), (const, override));
};
}

🧠 Learnings used
Learnt from: saintmatthieu
Repo: audacity/audacity PR: 10597
File: src/effects/effects_base/internal/au3/au3audiopluginmetareader.cpp:61-68
Timestamp: 2026-03-31T16:35:57.623Z
Learning: In Audacity’s codebase, `IF_ASSERT_FAILED(condition)` is a failure-only conditional: it executes its body when `condition` is falsy (i.e., the assertion fails). Treat patterns like `IF_ASSERT_FAILED(x) { return ...; }` as correct early-return control flow rather than a control-flow bug, since the body runs exactly on assertion failure (like `if (!condition)`, but with assertion triggering).

Learnt from: DPDmancul
Repo: audacity/audacity PR: 10776
File: src/tracks/ui/TextEditHelper.cpp:99-112
Timestamp: 2026-04-22T21:55:54.795Z
Learning: When handling wxWidgets keyboard modifier flags, treat `wxMOD_CONTROL` (0x0002) as the physical Ctrl key on all platforms. On macOS, the Command key is `wxMOD_META` (0x0008), not `wxMOD_CONTROL`. Use `wxMOD_CMD` as an alias (it maps to `wxMOD_META` on macOS and `wxMOD_CONTROL` on Windows/Linux). Therefore, a mask such as `wxMOD_SHIFT | wxMOD_ALTGR` (0x0007) will not match Command key combinations on macOS because `wxMOD_META` (0x0008) is outside that mask; only flag/mask modifier logic accordingly.

@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from 217c257 to 9df4e97 Compare July 1, 2026 10:32
@saintmatthieu
saintmatthieu requested a review from luapmartin July 1, 2026 10:33
@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from 9df4e97 to ee38692 Compare July 2, 2026 09:04
@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from b3a4cd3 to b67b7c3 Compare July 2, 2026 12:06
@Eism

Eism commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

Is this solving the exact same problem as here?
If so, maybe it would be better to use the same approach?

Comment thread src/playback/transport-vs-tracktion.md Outdated

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

please remove this file

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.

Oops - thanks.

@saintmatthieu

Copy link
Copy Markdown
Contributor Author

Is this solving the exact same problem as here? If so, maybe it would be better to use the same approach?

@Eism what do you mean exactly? Letting Transport become a decorator of existing Player ?

@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from b67b7c3 to 4adc6a5 Compare July 2, 2026 16:43
@Eism

Eism commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator

@saintmatthieu I simply asked whether they solve the same problem. And why did you choose a new approach and If this approach is better, will we replace the old one in trackedit?

@saintmatthieu

Copy link
Copy Markdown
Contributor Author

@Eism in the trackedit case I think the decorator pattern makes sense because it allows to eliminate the dependency of TrackeditOperationController on playback and record. In this case, Transport depends on them anyway.

@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from 4adc6a5 to 9993fc3 Compare July 9, 2026 14:26
@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from 9993fc3 to 70c2335 Compare July 10, 2026 09:02
@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from 70c2335 to e1b952a Compare July 10, 2026 12:37
@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from e1b952a to 46c8e59 Compare July 10, 2026 12:38
saintmatthieu and others added 11 commits July 10, 2026 16:03
…ntroller into Au3Player

Move isPlayAllowed, isPlaying/isPaused/isStopped, totalPlayTime, and
loop-region handling (toggle, set-to-selection, set-region-in-out,
selection-follows-loop) out of PlaybackController and into Au3Player, the
only IPlayer implementation. PlaybackController keeps implementing
IPlaybackController but forwards to the player in place; consumers and
behaviour are unchanged. Also regroups the remaining pass-through methods by
topic (status, loop region, transport) for readability.

No behaviour change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ntroller

Now that PlaybackController only forwarded IPlaybackController to the player,
delete the interface and the forwarding layer and point every consumer at the
player via IPlayback::player(). PlaybackController is left as the thin action
listener it now is, no longer module-exported.

No behaviour change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…anges during playback

Switching the audio host, playback/recording device, or recording-channel
count while a stream was open used to hit an assert or leave the engine
busy. The player now brackets each change with withStreamRestart(): stop,
apply the change, and resume from the same position if the user was
actively playing. Rescanning devices and recording-channel-count changes are
routed through the same mechanism, so they behave like any other device
change.

With this in place, drop the `enabled: !isPlaying` guards on the
host/device/recording-channel/sample-rate/buffer controls in Preferences,
and route their changes through the player too.

Adds a device-change orchestration/teardown test suite for
Au3AudioDevicesProvider (new au3audio test target + audio engine mock).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…yer into a Transport class

Move the higher-level playback/pause/stop/seek/device-change orchestration
that used to live in Au3Player into a new Transport class, sitting between
PlaybackController and the player. This re-opens a seam for mocking the
player, so the former PlaybackController unit tests are reinstated as
TransportTests, driving Transport through a player mock.
A host/device/channel change or rescan unconditionally stopped input
monitoring to perform the low-level switch, but nothing started it back up:
the user silently lost input metering for good. Capture whether monitoring
was on beforehand (recording the owning project before the stop resets it)
and resume it once the switch is done, in IAudioEngine/Au3AudioEngine and the
device provider, with a regression test.
Add regression coverage for three PR audacity#11245 QA checklist behaviors that were
implemented but untested: resuming at the interrupted position, a later Stop
still returning to the original seek anchor rather than the resume position,
and Play after a paused device change resuming from the paused position.
Rename playbackcontroller.h/cpp to transportactionscontroller.h/cpp and the
class itself to match what it now is: the UI action listener that forwards
to Transport, not a playback implementation. Includes follow-up clean-up in
the renamed file.
…state across a device change

Round out device-change handling with the position/selection edge cases:

- setInputChannels() skips the stream teardown when the channel count is
  unchanged.
- withStreamRestart() stops the capture stream via the record machinery
  (record()->stop()) during a device action; Au3Player::stop() early-returns
  while recording, so the previous unconditional player()->stop() was a
  no-op and left the capture stream open, hitting the exact
  AudioIOBase::HandleDeviceChange() assert this branch fixes.
- Reinstate the selection end on resume: player()->seek() collapses the
  player's region as a side effect, so the pre-device-change region bounds
  are captured and reapplied on resume instead of overrunning to the end of
  the project.
- A fresh region change (not just an explicit seek) now clears any pending
  paused-resume position, so a selection made after a device-change-while-
  paused isn't discarded in favour of the stale position.
- Resume at the interrupted position by handing it straight to
  player()->play() as the stream start position, instead of seeking and
  rewriting play-region/session state: no seek, no play-region write, a
  bounded selection keeps its own end, an active loop resumes inside its
  bounds and wraps as usual, and a later stop still returns to the seek
  anchor.
- Loop-playback resume is covered end-to-end: IPlayer::play() takes an
  optional start position, threaded down to au3's
  AudioIOStartStreamOptions::pStartTime, so switching devices mid-loop
  resumes at the interrupted position instead of the loop start.
- m_pausedResumePos is reset on stop, and parameter naming in
  TransportActionsController / AudioSetupContextMenuModel is made
  consistent.
@saintmatthieu
saintmatthieu force-pushed the 11098-fix-assert-on-device-change branch from 46c8e59 to 0d40ce9 Compare July 10, 2026 14:03
@saintmatthieu
saintmatthieu merged commit 77f16e3 into audacity:master Jul 10, 2026
1 check passed
@kryksyh kryksyh mentioned this pull request Jul 10, 2026
10 tasks done
@luapmartin luapmartin mentioned this pull request Jul 15, 2026
5 of 7 tasks
luapmartin added a commit that referenced this pull request Jul 28, 2026
Original PR: #11245

Resolves: #11098 
Resolves: #9443
Resolves: #11102 


- [x] I signed [CLA](https://www.audacityteam.org/cla/)
- [x] The title of the pull request describes an issue it addresses
- [x] If changes are extensive, then there is a sequence of easily
reviewable commits
- [x] Each commit's message describes its purpose and effects
- [x] There are no behavior changes unnecessary for the stated purpose
of the PR

Recommended:
- [ ] Each commit compiles and runs on my machine without known
undesirable changes of behavior

QA:

- [ ] Testflow test cases have been run
@saintmatthieu
saintmatthieu deleted the 11098-fix-assert-on-device-change branch August 28, 2026 11:11
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.

wxWidgets Debug Alert when changing audio devices while playback is paused

3 participants