launcher: configure and preview DualSense lightbar color #912

Manually merged
github merged 1 commit from gh-pr/912/head into gh-pr/912/base 2026-11-26 09:36:50 +00:00
Owner

@⁠Pyxellator on GitHub · 2026-09-29 19:11 UTC · original
feature/menu-music-controller-color → main · +255 −8 · 13 files · 1 commits · merged 2026-09-29 20:46 UTC

Adds a DualSense lightbar color picker to launcher settings with immediate preview and a Default action. Saved colors are passed to the emulator through --controller-color #RRGGBB and override game lightbar requests.

The launcher handles controller hotplug events, restores the saved preview when a settings dialog closes, and releases its preview handles when starting a game.

Validation:

  • Linux launcher and emulator builds passed.
  • Five existing controller and CLI tests passed.
  • Eight controller-color CLI cases and twelve virtual RGB gamepad checks passed.
**@⁠Pyxellator** on GitHub · 2026-09-29 19:11 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/912) `feature/menu-music-controller-color` → `main` · +255 −8 · 13 files · 1 commits · merged 2026-09-29 20:46 UTC Adds a DualSense lightbar color picker to launcher settings with immediate preview and a Default action. Saved colors are passed to the emulator through `--controller-color #RRGGBB` and override game lightbar requests. The launcher handles controller hotplug events, restores the saved preview when a settings dialog closes, and releases its preview handles when starting a game. Validation: - Linux launcher and emulator builds passed. - Five existing controller and CLI tests passed. - Eight controller-color CLI cases and twelve virtual RGB gamepad checks passed.
Add an optional lightbar color to launcher settings and pass it to the emulator with --controller-color. Preview changes on RGB gamepads, handle controller hotplug events, and restore the saved color when settings dialogs close. Release launcher preview handles when starting a game.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:36:49 +00:00
github manually merged commit ddfa6b2c44 into gh-pr/912/base 2026-11-26 09:36:50 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-29 19:19 UTC · original · edited 2026-09-29 20:53 UTC

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The launcher adds per-configuration menu music and controller lightbar color settings. It adds menu audio decoding and looping, controller color preview, and emulator color overrides. The launcher updates these services based on the selected configuration and emulator state. A new music-player test target checks playback, looping, and stopping.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Feature

Merge Risk: 🔵 Low · up to bd9b5

Menu music can remain silent for a selected game after a failed start, and the test would not catch a broken loop. These are bounded issues to address or explicitly accept before merging.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to bd9b5

Selected game files now reach a media decoder inside the launcher. File and playback limits provide some protection, but decoding work is not visibly isolated or time-bounded. Controller color preview can also resume while a game is running. No exploit was established.

Retained concerns

  • Medium · security · observed: Selected-game audio is newly decoded inside the launcher without a visible isolation or decode-work budget. Size limits constrain input and accumulated output, but not decoder execution or work already queued by repeated selections.
  • Low · architecture · inferred: The direct settings-preview route can apply a controller color while an emulator process is running, bypassing the launcher's running-state stop rule for its controller handles.
Security review details

Security Blast Radius

  • inferred — A malicious selected-game audio file can reach decoder code running with launcher-process authority. The observed exposure is the local launcher process, not a demonstrated remote or cross-tenant entrypoint.

Security Findings and Attack Paths

  • inferred — Repeated selection of crafted music files can submit further decode jobs before earlier jobs finish. Generation checks prevent stale playback, but the observed path does not cancel submitted decoding; no resource-exhaustion outcome was measured.

Trust Boundaries and Controls

  • observed — The media path limits file input to 64 MiB and accumulated PCM to 128 MiB. The PCM check occurs after frame conversion, and no decode-time limit is visible in the inspected path.
  • observed — Controller preview requires a valid color and applies it only to connected gamepads advertising an RGB LED; its direct settings signal does not check emulator process state.

Resilience and Maintainability Implications

  • observed — On launch, the launcher stops music and lightbar preview; after process completion, it updates selected-state controls. These lifecycle actions do not intercept a separate settings-preview signal during execution.

Hardening Proposals

  • proposed — Consider isolating game-media decoding or enforcing decode-time and concurrent-work budgets before enabling automatic playback for selected games.
  • proposed — Route settings-preview requests through the same running-process gate as normal controller-color updates.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.16% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 49 functions across 15 files. (2 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly describes the launcher’s DualSense lightbar color configuration and preview changes. It does not mention menu music, but it accurately covers a major part of the changeset.
Description check ✅ Passed The description accurately describes the controller-color picker, preview behavior, emulator option, cleanup, and validation. It omits the menu-music changes, but it remains related to the changeset.
Full details: Docstring Coverage

Explanation

Docstring coverage is 8.16% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 49 functions across 15 files. (2 skipped: 2 unsupported.)


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[bot]** on GitHub · 2026-09-29 19:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/912#issuecomment-5897023349) · edited 2026-09-29 20:53 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/912?cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The launcher adds per-configuration menu music and controller lightbar color settings. It adds menu audio decoding and looping, controller color preview, and emulator color overrides. The launcher updates these services based on the selected configuration and emulator state. A new music-player test target checks playback, looping, and stopping. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"bd9b5aacf9ba5d1849f1382b9f163932a47d3163" --> **Change:** Feature <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🔵 Low_ · up to `bd9b5` <!-- final_review_risk_coverage:{"sourceCommitId":"bd9b5aacf9ba5d1849f1382b9f163932a47d3163","coveredCommitId":"bd9b5aacf9ba5d1849f1382b9f163932a47d3163","kind":"reviewed"} --> Menu music can remain silent for a selected game after a failed start, and the test would not catch a broken loop. These are bounded issues to address or explicitly accept before merging. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `bd9b5` Selected game files now reach a media decoder inside the launcher. File and playback limits provide some protection, but decoding work is not visibly isolated or time-bounded. Controller color preview can also resume while a game is running. No exploit was established. **Retained concerns** - **Medium · security · observed:** Selected-game audio is newly decoded inside the launcher without a visible isolation or decode-work budget. Size limits constrain input and accumulated output, but not decoder execution or work already queued by repeated selections. - **Low · architecture · inferred:** The direct settings-preview route can apply a controller color while an emulator process is running, bypassing the launcher's running-state stop rule for its controller handles. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — A malicious selected-game audio file can reach decoder code running with launcher-process authority. The observed exposure is the local launcher process, not a demonstrated remote or cross-tenant entrypoint. **Security Findings and Attack Paths** - _inferred_ — Repeated selection of crafted music files can submit further decode jobs before earlier jobs finish. Generation checks prevent stale playback, but the observed path does not cancel submitted decoding; no resource-exhaustion outcome was measured. **Trust Boundaries and Controls** - _observed_ — The media path limits file input to 64 MiB and accumulated PCM to 128 MiB. The PCM check occurs after frame conversion, and no decode-time limit is visible in the inspected path. - _observed_ — Controller preview requires a valid color and applies it only to connected gamepads advertising an RGB LED; its direct settings signal does not check emulator process state. **Resilience and Maintainability Implications** - _observed_ — On launch, the launcher stops music and lightbar preview; after process completion, it updates selected-state controls. These lifecycle actions do not intercept a separate settings-preview signal during execution. **Hardening Proposals** - _proposed_ — Consider isolating game-media decoding or enforcing decode-time and concurrent-work budgets before enabling automatic playback for selected games. - _proposed_ — Route settings-preview requests through the same running-process gate as normal controller-color updates. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 8.16% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 49 functions across 15 files. (2 skipped: … | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Title check | ✅ Passed | The title clearly describes the launcher’s DualSense lightbar color configuration and preview changes. It does not mention menu music, but it accurately covers a major part of the changeset. | | Description check | ✅ Passed | The description accurately describes the controller-color picker, preview behavior, emulator option, cleanup, and validation. It omits the menu-music changes, but it remains related to the changeset. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 8.16% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 49 functions across 15 files. (2 skipped: 2 unsupported.) </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=912)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-29 19:19 UTC · original
On src/launcher/src/gameMusicPlayer.cpp line 275 (outdated):

@@ -0,0 +1,308 @@
+#include "gameMusicPlayer.h"
+
+#include "gameContent.h"
+
+#include <QDebug>
+#include <QFutureWatcher>
+#include <QtConcurrent>
+
+#include <SDL3/SDL.h>
+#include <algorithm>
+#include <cerrno>
+#include <cstdint>
+#include <cstdio>
+#include <cstring>
+#include <filesystem>
+
+extern "C" {
+#include <libavcodec/avcodec.h>
+#include <libavformat/avformat.h>
+#include <libavutil/channel_layout.h>
+#include <libavutil/samplefmt.h>
+#include <libswresample/swresample.h>
+}
+
+namespace {
+
+constexpr uint64_t  MAX_MUSIC_FILE = uint64_t {64} << 20u;
+constexpr qsizetype MAX_PCM_SIZE   = qsizetype {128} << 20u;
+constexpr int       SAMPLE_RATE    = 48000;
+constexpr int       CHANNELS       = 2;
+
+struct AudioInput {
+	const QByteArray* data;
+	int64_t           offset = 0;
+};
+
+int ReadAudio(void* opaque, uint8_t* destination, int size) {
+	auto*      input     = static_cast<AudioInput*>(opaque);
+	const auto remaining = static_cast<int64_t>(input->data->size()) - input->offset;
+	if (remaining <= 0) {
+		return AVERROR_EOF;
+	}
+	const auto count = static_cast<int>(std::min<int64_t>(remaining, size));
+	std::memcpy(destination, input->data->constData() + input->offset, count);
+	input->offset += count;
+	return count;
+}
+
+int64_t SeekAudio(void* opaque, int64_t offset, int whence) {
+	auto* input = static_cast<AudioInput*>(opaque);
+	if (whence == AVSEEK_SIZE) {
+		return input->data->size();
+	}
+	whence &= ~AVSEEK_FORCE;
+	const auto base = whence == SEEK_SET   ? int64_t {0}
+	                  : whence == SEEK_CUR ? input->offset
+	                  : whence == SEEK_END ? static_cast<int64_t>(input->data->size())
+	                                       : int64_t {-1};
+	if (base < 0 || offset < -base || offset > input->data->size() - base) {
+		return -1;
+	}
+	input->offset = base + offset;
+	return input->offset;
+}
+
+struct Decoder {
+	AVFormatContext* format    = nullptr;
+	AVIOContext*     io        = nullptr;
+	AVCodecContext*  codec     = nullptr;
+	AVPacket*        packet    = nullptr;
+	AVFrame*         frame     = nullptr;
+	AVFrame*         converted = nullptr;
+	SwrContext*      resampler = nullptr;
+
+	~Decoder() {
+		swr_free(&resampler);
+		av_frame_free(&converted);
+		av_frame_free(&frame);
+		av_packet_free(&packet);
+		avcodec_free_context(&codec);
+		avformat_close_input(&format);
+		if (io != nullptr) {
+			av_freep(&io->buffer);
+			avio_context_free(&io);
+		}
+	}
+};
+
+QByteArray DecodeAudio(const QByteArray& data) {
+	if (data.isEmpty()) {
+		return {};
+	}
+
+	AudioInput input {&data};
+	Decoder    decoder;
+	decoder.format  = avformat_alloc_context();
+	auto* io_buffer = static_cast<unsigned char*>(av_malloc(8192));
+	if (decoder.format == nullptr || io_buffer == nullptr) {
+		av_free(io_buffer);
+		return {};
+	}
+	decoder.io = avio_alloc_context(io_buffer, 8192, 0, &input, ReadAudio, nullptr, SeekAudio);
+	if (decoder.io == nullptr) {
+		av_free(io_buffer);
+		return {};
+	}
+	decoder.format->pb    = decoder.io;
+	decoder.format->flags = AVFMT_FLAG_CUSTOM_IO;
+	if (avformat_open_input(&decoder.format, nullptr, nullptr, nullptr) < 0 ||
+	    avformat_find_stream_info(decoder.format, nullptr) < 0) {
+		return {};
+	}
+
+	const auto stream_id =
+	    av_find_best_stream(decoder.format, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0);
+	if (stream_id < 0) {
+		return {};
+	}
+	const auto* stream = decoder.format->streams[stream_id];
+	const auto* codec  = avcodec_find_decoder(stream->codecpar->codec_id);
+	if (codec == nullptr) {
+		return {};
+	}
+	decoder.codec = avcodec_alloc_context3(codec);
+	if (decoder.codec == nullptr ||
+	    avcodec_parameters_to_context(decoder.codec, stream->codecpar) < 0 ||
+	    avcodec_open2(decoder.codec, codec, nullptr) < 0) {
+		return {};
+	}
+	decoder.packet    = av_packet_alloc();
+	decoder.frame     = av_frame_alloc();
+	decoder.converted = av_frame_alloc();
+	if (decoder.packet == nullptr || decoder.frame == nullptr || decoder.converted == nullptr) {
+		return {};
+	}
+
+	QByteArray pcm;
+	const auto append_frame = [&]() -> bool {
+		if (decoder.frame->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC &&
+		    decoder.frame->ch_layout.nb_channels > 0) {
+			const int channels = decoder.frame->ch_layout.nb_channels;
+			av_channel_layout_uninit(&decoder.frame->ch_layout);
+			av_channel_layout_default(&decoder.frame->ch_layout, channels);
+		}
+		if (decoder.resampler == nullptr) {
+			AVChannelLayout output {};
+			AVChannelLayout source {};
+			av_channel_layout_default(&output, CHANNELS);
+			if (decoder.frame->ch_layout.nb_channels > 0) {
+				av_channel_layout_copy(&source, &decoder.frame->ch_layout);
+			} else {
+				av_channel_layout_default(&source, CHANNELS);
+			}
+			const auto source_rate =
+			    decoder.frame->sample_rate > 0 ? decoder.frame->sample_rate : SAMPLE_RATE;
+			const auto result = swr_alloc_set_opts2(
+			    &decoder.resampler, &output, AV_SAMPLE_FMT_S16, SAMPLE_RATE, &source,
+			    static_cast<AVSampleFormat>(decoder.frame->format), source_rate, 0, nullptr);
+			av_channel_layout_uninit(&source);
+			av_channel_layout_uninit(&output);
+			if (result < 0 || swr_init(decoder.resampler) < 0) {
+				return false;
+			}
+		}
+		decoder.converted->format      = AV_SAMPLE_FMT_S16;
+		decoder.converted->sample_rate = SAMPLE_RATE;
+		av_channel_layout_default(&decoder.converted->ch_layout, CHANNELS);
+		if (swr_convert_frame(decoder.resampler, decoder.converted, decoder.frame) < 0) {
+			return false;
+		}
+		const auto bytes = av_samples_get_buffer_size(
+		    nullptr, CHANNELS, decoder.converted->nb_samples, AV_SAMPLE_FMT_S16, 1);
+		if (bytes < 0 || bytes > MAX_PCM_SIZE - pcm.size()) {
+			return false;
+		}
+		if (bytes > 0) {
+			pcm.append(reinterpret_cast<const char*>(decoder.converted->data[0]), bytes);
+		}
+		av_frame_unref(decoder.converted);
+		return true;
+	};
+	const auto drain = [&]() -> bool {
+		int status = 0;
+		while ((status = avcodec_receive_frame(decoder.codec, decoder.frame)) == 0) {
+			const bool ok = append_frame();
+			av_frame_unref(decoder.frame);
+			if (!ok) {
+				return false;
+			}
+		}
+		return status == AVERROR(EAGAIN) || status == AVERROR_EOF;
+	};
+
+	while (av_read_frame(decoder.format, decoder.packet) >= 0) {
+		if (decoder.packet->stream_index == stream_id) {
+			const auto result = avcodec_send_packet(decoder.codec, decoder.packet);
+			if (result < 0 || !drain()) {
+				return {};
+			}
+		}
+		av_packet_unref(decoder.packet);
+	}
+	if (avcodec_send_packet(decoder.codec, nullptr) < 0 || !drain()) {
+		return {};
+	}
+	return pcm;
+}
+
+} // namespace
+
+GameMusicPlayer::GameMusicPlayer(QObject* parent): QObject(parent) {}
+
+GameMusicPlayer::~GameMusicPlayer() {
+	Stop();
+	if (m_audio_initialized) {
+		SDL_QuitSubSystem(SDL_INIT_AUDIO);
+	}
+}
+
+void GameMusicPlayer::Play(const QString& game_base, bool enabled) {
+	if (!enabled) {
+		Stop();
+		return;
+	}
+
+	std::filesystem::path path;
+	for (const auto* name:
+	     {"sce_sys/snd0.at9", "sce_sys/snd0.mp3", "sce_sys/snd0.wav", "sce_sys/snd0.m4a"}) {
+		if (GameContent::FileExists(game_base, QString::fromLatin1(name))) {
+			path = GameContent::Resolve(game_base, QString::fromLatin1(name));
+			break;
+		}
+	}
+	if (path.empty()) {
+		Stop();
+		return;
+	}
+	const auto source = GameContent::FromPath(path);
+	if (source == m_source) {
+		return;
+	}
+	Stop();
+	m_source           = source;
+	const auto current = ++m_generation;
+	auto*      watcher = new QFutureWatcher<QByteArray>(this);
+	connect(watcher, &QFutureWatcher<QByteArray>::finished, this,
+	        [this, watcher, current, source]() {
+		        auto pcm = watcher->result();
+		        watcher->deleteLater();
+		        if (current != m_generation) {
+			        return;
+		        }
+		        if (pcm.isEmpty()) {
+			        qWarning().noquote() << "Cannot decode menu music:" << source;
+			        return;
+		        }
+		        m_pcm = std::move(pcm);
+		        if (!m_audio_initialized) {
+			        m_audio_initialized = SDL_InitSubSystem(SDL_INIT_AUDIO);
+		        }
+		        if (!m_audio_initialized) {
+			        qWarning() << "Cannot initialize menu audio:" << SDL_GetError();
+			        return;
+		        }
+		        const SDL_AudioSpec spec {SDL_AUDIO_S16, CHANNELS, SAMPLE_RATE};
+		        m_stream =
+		            SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec, Feed, this);
+		        if (m_stream != nullptr && !SDL_ResumeAudioStreamDevice(m_stream)) {
+			        SDL_DestroyAudioStream(m_stream);
+			        m_stream = nullptr;
+		        }
+		        if (m_stream == nullptr) {
+			        qWarning() << "Cannot play menu music:" << SDL_GetError();
+		        }
+	        });

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

After a failed start, Play never retries the same game.

Play sets m_source before decoding begins. m_source stays set if any of these steps fails:

  • the decode returns empty PCM,
  • SDL_InitSubSystem(SDL_INIT_AUDIO) fails,
  • SDL_OpenAudioDeviceStream fails.

The early return at Line 239 then skips every later Play call for that game. UpdateMusic calls Play again on each Select and after the emulator exits. Those calls do nothing, so music stays silent until the user picks a different game. For example, a busy audio device at the first attempt keeps music off for that game for the rest of the session.

Fix: clear m_source on each failure path. Another option is to check m_stream in the early-return condition.

Proposed fix
-	if (source == m_source) {
+	if (source == m_source && (m_stream != nullptr || current_decode_pending())) {

A simpler fix is to reset the source in each failure branch of the lambda:

 		        if (pcm.isEmpty()) {
 			        qWarning().noquote() << "Cannot decode menu music:" << source;
+			        m_source.clear();
 			        return;
 		        }
 ...
 		        if (!m_audio_initialized) {
 			        qWarning() << "Cannot initialize menu audio:" << SDL_GetError();
+			        m_source.clear();
 			        return;
 		        }
 ...
 		        if (m_stream == nullptr) {
 			        qWarning() << "Cannot play menu music:" << SDL_GetError();
+			        m_pcm.clear();
+			        m_source.clear();
 		        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	const auto source = GameContent::FromPath(path);
	if (source == m_source) {
		return;
	}
	Stop();
	m_source           = source;
	const auto current = ++m_generation;
	auto*      watcher = new QFutureWatcher<QByteArray>(this);
	connect(watcher, &QFutureWatcher<QByteArray>::finished, this,
	        [this, watcher, current, source]() {
		        auto pcm = watcher->result();
		        watcher->deleteLater();
		        if (current != m_generation) {
			        return;
		        }
		        if (pcm.isEmpty()) {
			        qWarning().noquote() << "Cannot decode menu music:" << source;
			        m_source.clear();
			        return;
		        }
		        m_pcm = std::move(pcm);
		        if (!m_audio_initialized) {
			        m_audio_initialized = SDL_InitSubSystem(SDL_INIT_AUDIO);
		        }
		        if (!m_audio_initialized) {
			        qWarning() << "Cannot initialize menu audio:" << SDL_GetError();
			        m_source.clear();
			        return;
		        }
		        const SDL_AudioSpec spec {SDL_AUDIO_S16, CHANNELS, SAMPLE_RATE};
		        m_stream =
		            SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec, Feed, this);
		        if (m_stream != nullptr && !SDL_ResumeAudioStreamDevice(m_stream)) {
			        SDL_DestroyAudioStream(m_stream);
			        m_stream = nullptr;
		        }
		        if (m_stream == nullptr) {
			        qWarning() << "Cannot play menu music:" << SDL_GetError();
			        m_pcm.clear();
			        m_source.clear();
		        }
	        });
**@⁠coderabbitai[bot]** on GitHub · 2026-09-29 19:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/912#discussion_r4137395741) On `src/launcher/src/gameMusicPlayer.cpp` line 275 (outdated): ```diff @@ -0,0 +1,308 @@ +#include "gameMusicPlayer.h" + +#include "gameContent.h" + +#include <QDebug> +#include <QFutureWatcher> +#include <QtConcurrent> + +#include <SDL3/SDL.h> +#include <algorithm> +#include <cerrno> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <filesystem> + +extern "C" { +#include <libavcodec/avcodec.h> +#include <libavformat/avformat.h> +#include <libavutil/channel_layout.h> +#include <libavutil/samplefmt.h> +#include <libswresample/swresample.h> +} + +namespace { + +constexpr uint64_t MAX_MUSIC_FILE = uint64_t {64} << 20u; +constexpr qsizetype MAX_PCM_SIZE = qsizetype {128} << 20u; +constexpr int SAMPLE_RATE = 48000; +constexpr int CHANNELS = 2; + +struct AudioInput { + const QByteArray* data; + int64_t offset = 0; +}; + +int ReadAudio(void* opaque, uint8_t* destination, int size) { + auto* input = static_cast<AudioInput*>(opaque); + const auto remaining = static_cast<int64_t>(input->data->size()) - input->offset; + if (remaining <= 0) { + return AVERROR_EOF; + } + const auto count = static_cast<int>(std::min<int64_t>(remaining, size)); + std::memcpy(destination, input->data->constData() + input->offset, count); + input->offset += count; + return count; +} + +int64_t SeekAudio(void* opaque, int64_t offset, int whence) { + auto* input = static_cast<AudioInput*>(opaque); + if (whence == AVSEEK_SIZE) { + return input->data->size(); + } + whence &= ~AVSEEK_FORCE; + const auto base = whence == SEEK_SET ? int64_t {0} + : whence == SEEK_CUR ? input->offset + : whence == SEEK_END ? static_cast<int64_t>(input->data->size()) + : int64_t {-1}; + if (base < 0 || offset < -base || offset > input->data->size() - base) { + return -1; + } + input->offset = base + offset; + return input->offset; +} + +struct Decoder { + AVFormatContext* format = nullptr; + AVIOContext* io = nullptr; + AVCodecContext* codec = nullptr; + AVPacket* packet = nullptr; + AVFrame* frame = nullptr; + AVFrame* converted = nullptr; + SwrContext* resampler = nullptr; + + ~Decoder() { + swr_free(&resampler); + av_frame_free(&converted); + av_frame_free(&frame); + av_packet_free(&packet); + avcodec_free_context(&codec); + avformat_close_input(&format); + if (io != nullptr) { + av_freep(&io->buffer); + avio_context_free(&io); + } + } +}; + +QByteArray DecodeAudio(const QByteArray& data) { + if (data.isEmpty()) { + return {}; + } + + AudioInput input {&data}; + Decoder decoder; + decoder.format = avformat_alloc_context(); + auto* io_buffer = static_cast<unsigned char*>(av_malloc(8192)); + if (decoder.format == nullptr || io_buffer == nullptr) { + av_free(io_buffer); + return {}; + } + decoder.io = avio_alloc_context(io_buffer, 8192, 0, &input, ReadAudio, nullptr, SeekAudio); + if (decoder.io == nullptr) { + av_free(io_buffer); + return {}; + } + decoder.format->pb = decoder.io; + decoder.format->flags = AVFMT_FLAG_CUSTOM_IO; + if (avformat_open_input(&decoder.format, nullptr, nullptr, nullptr) < 0 || + avformat_find_stream_info(decoder.format, nullptr) < 0) { + return {}; + } + + const auto stream_id = + av_find_best_stream(decoder.format, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0); + if (stream_id < 0) { + return {}; + } + const auto* stream = decoder.format->streams[stream_id]; + const auto* codec = avcodec_find_decoder(stream->codecpar->codec_id); + if (codec == nullptr) { + return {}; + } + decoder.codec = avcodec_alloc_context3(codec); + if (decoder.codec == nullptr || + avcodec_parameters_to_context(decoder.codec, stream->codecpar) < 0 || + avcodec_open2(decoder.codec, codec, nullptr) < 0) { + return {}; + } + decoder.packet = av_packet_alloc(); + decoder.frame = av_frame_alloc(); + decoder.converted = av_frame_alloc(); + if (decoder.packet == nullptr || decoder.frame == nullptr || decoder.converted == nullptr) { + return {}; + } + + QByteArray pcm; + const auto append_frame = [&]() -> bool { + if (decoder.frame->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC && + decoder.frame->ch_layout.nb_channels > 0) { + const int channels = decoder.frame->ch_layout.nb_channels; + av_channel_layout_uninit(&decoder.frame->ch_layout); + av_channel_layout_default(&decoder.frame->ch_layout, channels); + } + if (decoder.resampler == nullptr) { + AVChannelLayout output {}; + AVChannelLayout source {}; + av_channel_layout_default(&output, CHANNELS); + if (decoder.frame->ch_layout.nb_channels > 0) { + av_channel_layout_copy(&source, &decoder.frame->ch_layout); + } else { + av_channel_layout_default(&source, CHANNELS); + } + const auto source_rate = + decoder.frame->sample_rate > 0 ? decoder.frame->sample_rate : SAMPLE_RATE; + const auto result = swr_alloc_set_opts2( + &decoder.resampler, &output, AV_SAMPLE_FMT_S16, SAMPLE_RATE, &source, + static_cast<AVSampleFormat>(decoder.frame->format), source_rate, 0, nullptr); + av_channel_layout_uninit(&source); + av_channel_layout_uninit(&output); + if (result < 0 || swr_init(decoder.resampler) < 0) { + return false; + } + } + decoder.converted->format = AV_SAMPLE_FMT_S16; + decoder.converted->sample_rate = SAMPLE_RATE; + av_channel_layout_default(&decoder.converted->ch_layout, CHANNELS); + if (swr_convert_frame(decoder.resampler, decoder.converted, decoder.frame) < 0) { + return false; + } + const auto bytes = av_samples_get_buffer_size( + nullptr, CHANNELS, decoder.converted->nb_samples, AV_SAMPLE_FMT_S16, 1); + if (bytes < 0 || bytes > MAX_PCM_SIZE - pcm.size()) { + return false; + } + if (bytes > 0) { + pcm.append(reinterpret_cast<const char*>(decoder.converted->data[0]), bytes); + } + av_frame_unref(decoder.converted); + return true; + }; + const auto drain = [&]() -> bool { + int status = 0; + while ((status = avcodec_receive_frame(decoder.codec, decoder.frame)) == 0) { + const bool ok = append_frame(); + av_frame_unref(decoder.frame); + if (!ok) { + return false; + } + } + return status == AVERROR(EAGAIN) || status == AVERROR_EOF; + }; + + while (av_read_frame(decoder.format, decoder.packet) >= 0) { + if (decoder.packet->stream_index == stream_id) { + const auto result = avcodec_send_packet(decoder.codec, decoder.packet); + if (result < 0 || !drain()) { + return {}; + } + } + av_packet_unref(decoder.packet); + } + if (avcodec_send_packet(decoder.codec, nullptr) < 0 || !drain()) { + return {}; + } + return pcm; +} + +} // namespace + +GameMusicPlayer::GameMusicPlayer(QObject* parent): QObject(parent) {} + +GameMusicPlayer::~GameMusicPlayer() { + Stop(); + if (m_audio_initialized) { + SDL_QuitSubSystem(SDL_INIT_AUDIO); + } +} + +void GameMusicPlayer::Play(const QString& game_base, bool enabled) { + if (!enabled) { + Stop(); + return; + } + + std::filesystem::path path; + for (const auto* name: + {"sce_sys/snd0.at9", "sce_sys/snd0.mp3", "sce_sys/snd0.wav", "sce_sys/snd0.m4a"}) { + if (GameContent::FileExists(game_base, QString::fromLatin1(name))) { + path = GameContent::Resolve(game_base, QString::fromLatin1(name)); + break; + } + } + if (path.empty()) { + Stop(); + return; + } + const auto source = GameContent::FromPath(path); + if (source == m_source) { + return; + } + Stop(); + m_source = source; + const auto current = ++m_generation; + auto* watcher = new QFutureWatcher<QByteArray>(this); + connect(watcher, &QFutureWatcher<QByteArray>::finished, this, + [this, watcher, current, source]() { + auto pcm = watcher->result(); + watcher->deleteLater(); + if (current != m_generation) { + return; + } + if (pcm.isEmpty()) { + qWarning().noquote() << "Cannot decode menu music:" << source; + return; + } + m_pcm = std::move(pcm); + if (!m_audio_initialized) { + m_audio_initialized = SDL_InitSubSystem(SDL_INIT_AUDIO); + } + if (!m_audio_initialized) { + qWarning() << "Cannot initialize menu audio:" << SDL_GetError(); + return; + } + const SDL_AudioSpec spec {SDL_AUDIO_S16, CHANNELS, SAMPLE_RATE}; + m_stream = + SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec, Feed, this); + if (m_stream != nullptr && !SDL_ResumeAudioStreamDevice(m_stream)) { + SDL_DestroyAudioStream(m_stream); + m_stream = nullptr; + } + if (m_stream == nullptr) { + qWarning() << "Cannot play menu music:" << SDL_GetError(); + } + }); ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **After a failed start, `Play` never retries the same game.** `Play` sets `m_source` before decoding begins. `m_source` stays set if any of these steps fails: - the decode returns empty PCM, - `SDL_InitSubSystem(SDL_INIT_AUDIO)` fails, - `SDL_OpenAudioDeviceStream` fails. The early return at Line 239 then skips every later `Play` call for that game. `UpdateMusic` calls `Play` again on each `Select` and after the emulator exits. Those calls do nothing, so music stays silent until the user picks a different game. For example, a busy audio device at the first attempt keeps music off for that game for the rest of the session. Fix: clear `m_source` on each failure path. Another option is to check `m_stream` in the early-return condition. <details> <summary>Proposed fix</summary> ```diff - if (source == m_source) { + if (source == m_source && (m_stream != nullptr || current_decode_pending())) { ``` A simpler fix is to reset the source in each failure branch of the lambda: ```diff if (pcm.isEmpty()) { qWarning().noquote() << "Cannot decode menu music:" << source; + m_source.clear(); return; } ... if (!m_audio_initialized) { qWarning() << "Cannot initialize menu audio:" << SDL_GetError(); + m_source.clear(); return; } ... if (m_stream == nullptr) { qWarning() << "Cannot play menu music:" << SDL_GetError(); + m_pcm.clear(); + m_source.clear(); } ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const auto source = GameContent::FromPath(path); if (source == m_source) { return; } Stop(); m_source = source; const auto current = ++m_generation; auto* watcher = new QFutureWatcher<QByteArray>(this); connect(watcher, &QFutureWatcher<QByteArray>::finished, this, [this, watcher, current, source]() { auto pcm = watcher->result(); watcher->deleteLater(); if (current != m_generation) { return; } if (pcm.isEmpty()) { qWarning().noquote() << "Cannot decode menu music:" << source; m_source.clear(); return; } m_pcm = std::move(pcm); if (!m_audio_initialized) { m_audio_initialized = SDL_InitSubSystem(SDL_INIT_AUDIO); } if (!m_audio_initialized) { qWarning() << "Cannot initialize menu audio:" << SDL_GetError(); m_source.clear(); return; } const SDL_AudioSpec spec {SDL_AUDIO_S16, CHANNELS, SAMPLE_RATE}; m_stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec, Feed, this); if (m_stream != nullptr && !SDL_ResumeAudioStreamDevice(m_stream)) { SDL_DestroyAudioStream(m_stream); m_stream = nullptr; } if (m_stream == nullptr) { qWarning() << "Cannot play menu music:" << SDL_GetError(); m_pcm.clear(); m_source.clear(); } }); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e06a13ac54b12fd744a854d4 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-29 19:19 UTC · original · reviewed

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/launcher/tests/gameMusicPlayerTests.cpp (1)

60-69: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert repeated PCM, not only stream liveness.

WriteTestWave writes only zero-valued samples, and the test checks only IsPlaying(). IsPlaying() returns m_stream != nullptr, so a stream can remain open while Feed stops producing data after the first clip. That regression would pass this test.

Use a non-silent waveform with distinguishable samples. Capture the data from a test-controlled SDL stream, then assert that the waveform appears again after the first 100 ms. The existing controlled-stream pattern in tests/PadHapticsTests.cpp uses SDL_SetAudioStreamGetCallback and SDL_GetAudioStreamData.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: bd7d1be3-d2d4-4a96-a8d6-f6242c6c063f

📥 Commits

Reviewing files that changed from the base of the PR and between 2650478d92 and bd9b5aacf9ba5d1849f1382b9f163932a47d3163.

📒 Files selected for processing (17)
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.h
  • src/launcher/CMakeLists.txt
  • src/launcher/forms/configuration_edit_dialog.ui
  • src/launcher/include/configuration.h
  • src/launcher/include/configurationEditDialog.h
  • src/launcher/include/configurationListWidget.h
  • src/launcher/include/controllerLightbar.h
  • src/launcher/include/gameMusicPlayer.h
  • src/launcher/src/configurationEditDialog.cpp
  • src/launcher/src/configurationListWidget.cpp
  • src/launcher/src/controllerLightbar.cpp
  • src/launcher/src/gameMusicPlayer.cpp
  • src/launcher/src/mainDialog.cpp
  • src/launcher/tests/gameMusicPlayerTests.cpp
  • src/libs/controller.cpp
  • src/main.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-29 19:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/912#pullrequestreview-5357286346) · **reviewed** **Actionable comments posted: 1** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>src/launcher/tests/gameMusicPlayerTests.cpp (1)</summary><blockquote> `60-69`: _🎯 Functional Correctness_ | _🔵 Trivial_ | _⚡ Quick win_ **Assert repeated PCM, not only stream liveness.** `WriteTestWave` writes only zero-valued samples, and the test checks only `IsPlaying()`. `IsPlaying()` returns `m_stream != nullptr`, so a stream can remain open while `Feed` stops producing data after the first clip. That regression would pass this test. Use a non-silent waveform with distinguishable samples. Capture the data from a test-controlled SDL stream, then assert that the waveform appears again after the first 100 ms. The existing controlled-stream pattern in `tests/PadHapticsTests.cpp` uses `SDL_SetAudioStreamGetCallback` and `SDL_GetAudioStreamData`. <!-- cr-comment:v1:1095a669e1645f77adf491f6 --> </blockquote></details> </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `bd7d1be3-d2d4-4a96-a8d6-f6242c6c063f` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 2650478d92c394c092b36ee129962060c623ca16 and bd9b5aacf9ba5d1849f1382b9f163932a47d3163. </details> <details> <summary>📒 Files selected for processing (17)</summary> * `src/common/emulatorConfig.cpp` * `src/common/emulatorConfig.h` * `src/launcher/CMakeLists.txt` * `src/launcher/forms/configuration_edit_dialog.ui` * `src/launcher/include/configuration.h` * `src/launcher/include/configurationEditDialog.h` * `src/launcher/include/configurationListWidget.h` * `src/launcher/include/controllerLightbar.h` * `src/launcher/include/gameMusicPlayer.h` * `src/launcher/src/configurationEditDialog.cpp` * `src/launcher/src/configurationListWidget.cpp` * `src/launcher/src/controllerLightbar.cpp` * `src/launcher/src/gameMusicPlayer.cpp` * `src/launcher/src/mainDialog.cpp` * `src/launcher/tests/gameMusicPlayerTests.cpp` * `src/libs/controller.cpp` * `src/main.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
This discussion has been locked. Commenting is limited to contributors.
No description provided.