From 96342e23bc079e29df7c526e4456d24a9fe73c56 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 30 Aug 2026 09:14:29 -0600 Subject: [PATCH] feat(qt): expose ALSA hardware volume settings Add capability-aware enablement, exact control selection, diagnostics, live volume synchronization, and translated unsupported-state feedback to the Qt settings surface. cx --- .../translations/de/LC_MESSAGES/qbz-ui.po | 33 + .../translations/en/LC_MESSAGES/qbz-ui.po | 33 + .../translations/es/LC_MESSAGES/qbz-ui.po | 33 + .../translations/fr/LC_MESSAGES/qbz-ui.po | 33 + .../translations/ja/LC_MESSAGES/qbz-ui.po | 33 + .../translations/nl/LC_MESSAGES/qbz-ui.po | 33 + .../translations/pt/LC_MESSAGES/qbz-ui.po | 33 + .../translations/ru/LC_MESSAGES/qbz-ui.po | 33 + crates/qbz-qt/qml/controls/QbzSelect.qml | 49 +- crates/qbz-qt/qml/settings/AudioSettings.qml | 67 ++ crates/qbz-qt/src/diagnostics_qt.rs | 23 + crates/qbz-qt/src/playback_qt.rs | 14 + crates/qbz-qt/src/settings_qt.rs | 780 +++++++++++++++++- 13 files changed, 1156 insertions(+), 41 deletions(-) diff --git a/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po index 6b3845a91..afbe1c424 100644 --- a/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po @@ -6215,3 +6215,36 @@ msgstr "Hörverlauf gelöscht." msgid "Couldn't clear listening history." msgstr "Hörverlauf konnte nicht gelöscht werden." + +msgid "Checking ALSA mixer controls…" +msgstr "ALSA-Mixerregler werden geprüft…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "Dieses Gerät stellt mehrere Wiedergaberegler bereit. Wählen Sie aus, welchen QBZ verwenden soll." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "Der gespeicherte Mixerregler ist nicht mehr verfügbar. Wählen Sie einen anderen Regler." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "QBZ hat keine Berechtigung, den ALSA-Mixer dieses Geräts zu lesen." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "Der ALSA-Mixer ist belegt. Schließen Sie die verwendende Anwendung und versuchen Sie es erneut." + +msgid "The selected ALSA device is no longer available." +msgstr "Das ausgewählte ALSA-Gerät ist nicht mehr verfügbar." + +msgid "This ALSA device does not expose a mixer." +msgstr "Dieses ALSA-Gerät stellt keinen Mixer bereit." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "QBZ konnte den ausgewählten ALSA-Mixerregler nicht schreiben. Die direkte Wiedergabe bleibt auf 100 % eingestellt." + +msgid "Selected mixer control" +msgstr "Ausgewählter Mixerregler" + +msgid "Choose mixer control" +msgstr "Mixerregler auswählen" + +msgid "Change mixer control" +msgstr "Mixerregler ändern" diff --git a/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po index dece75e89..2ca40e693 100644 --- a/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po @@ -1835,3 +1835,36 @@ msgstr "Listening history cleared." msgid "Couldn't clear listening history." msgstr "Couldn't clear listening history." + +msgid "Checking ALSA mixer controls…" +msgstr "Checking ALSA mixer controls…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "This device exposes multiple playback controls. Choose which one QBZ should use." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "The saved mixer control is no longer available. Choose another control." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "QBZ does not have permission to read this device's ALSA mixer." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "The ALSA mixer is busy. Close the app using it and try again." + +msgid "The selected ALSA device is no longer available." +msgstr "The selected ALSA device is no longer available." + +msgid "This ALSA device does not expose a mixer." +msgstr "This ALSA device does not expose a mixer." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." + +msgid "Selected mixer control" +msgstr "Selected mixer control" + +msgid "Choose mixer control" +msgstr "Choose mixer control" + +msgid "Change mixer control" +msgstr "Change mixer control" diff --git a/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po index 7293fd7ba..db59f27a7 100644 --- a/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po @@ -6221,3 +6221,36 @@ msgstr "Historial de escucha borrado." msgid "Couldn't clear listening history." msgstr "No se pudo borrar el historial de escucha." + +msgid "Checking ALSA mixer controls…" +msgstr "Comprobando los controles del mezclador ALSA…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "Este dispositivo expone varios controles de reproducción. Elige cuál debe usar QBZ." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "El control del mezclador guardado ya no está disponible. Elige otro control." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "QBZ no tiene permiso para leer el mezclador ALSA de este dispositivo." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "El mezclador ALSA está ocupado. Cierra la aplicación que lo está usando e inténtalo de nuevo." + +msgid "The selected ALSA device is no longer available." +msgstr "El dispositivo ALSA seleccionado ya no está disponible." + +msgid "This ALSA device does not expose a mixer." +msgstr "Este dispositivo ALSA no expone un mezclador." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "QBZ no pudo escribir en el control del mezclador ALSA seleccionado. La reproducción directa permanece fija al 100 %." + +msgid "Selected mixer control" +msgstr "Control de mezclador seleccionado" + +msgid "Choose mixer control" +msgstr "Elegir control de mezclador" + +msgid "Change mixer control" +msgstr "Cambiar control de mezclador" diff --git a/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po index d77a0dc4d..3ee1a8ccd 100644 --- a/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po @@ -6213,3 +6213,36 @@ msgstr "Historique d’écoute effacé." msgid "Couldn't clear listening history." msgstr "Impossible d’effacer l’historique d’écoute." + +msgid "Checking ALSA mixer controls…" +msgstr "Vérification des commandes du mixeur ALSA…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "Ce périphérique expose plusieurs commandes de lecture. Choisissez celle que QBZ doit utiliser." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "La commande de mixage enregistrée n’est plus disponible. Choisissez-en une autre." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "QBZ n’est pas autorisé à lire le mixeur ALSA de ce périphérique." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "Le mixeur ALSA est occupé. Fermez l’application qui l’utilise et réessayez." + +msgid "The selected ALSA device is no longer available." +msgstr "Le périphérique ALSA sélectionné n’est plus disponible." + +msgid "This ALSA device does not expose a mixer." +msgstr "Ce périphérique ALSA n’expose aucun mixeur." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "QBZ n’a pas pu modifier la commande du mixeur ALSA sélectionnée. La lecture directe reste fixée à 100 %." + +msgid "Selected mixer control" +msgstr "Commande de mixage sélectionnée" + +msgid "Choose mixer control" +msgstr "Choisir la commande de mixage" + +msgid "Change mixer control" +msgstr "Changer la commande de mixage" diff --git a/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po index 6b4d379cd..757c3e5a6 100644 --- a/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po @@ -6197,3 +6197,36 @@ msgstr "再生履歴を消去しました。" msgid "Couldn't clear listening history." msgstr "再生履歴を消去できませんでした。" + +msgid "Checking ALSA mixer controls…" +msgstr "ALSA ミキサーコントロールを確認しています…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "このデバイスには複数の再生コントロールがあります。QBZ が使用するものを選択してください。" + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "保存されたミキサーコントロールは利用できなくなりました。別のコントロールを選択してください。" + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "QBZ にはこのデバイスの ALSA ミキサーを読み取る権限がありません。" + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "ALSA ミキサーは使用中です。使用しているアプリを閉じて、もう一度お試しください。" + +msgid "The selected ALSA device is no longer available." +msgstr "選択した ALSA デバイスは利用できなくなりました。" + +msgid "This ALSA device does not expose a mixer." +msgstr "この ALSA デバイスにはミキサーがありません。" + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "選択した ALSA ミキサーコントロールに書き込めませんでした。ダイレクト再生は 100% に固定されます。" + +msgid "Selected mixer control" +msgstr "選択中のミキサーコントロール" + +msgid "Choose mixer control" +msgstr "ミキサーコントロールを選択" + +msgid "Change mixer control" +msgstr "ミキサーコントロールを変更" diff --git a/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po index 462a3bbec..32975d377 100644 --- a/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po @@ -6203,3 +6203,36 @@ msgstr "Luistergeschiedenis gewist." msgid "Couldn't clear listening history." msgstr "Kon de luistergeschiedenis niet wissen." + +msgid "Checking ALSA mixer controls…" +msgstr "ALSA-mixerregelaars controleren…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "Dit apparaat biedt meerdere afspeelregelaars. Kies welke QBZ moet gebruiken." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "De opgeslagen mixerregelaar is niet meer beschikbaar. Kies een andere regelaar." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "QBZ heeft geen toestemming om de ALSA-mixer van dit apparaat te lezen." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "De ALSA-mixer is bezet. Sluit de app die deze gebruikt en probeer het opnieuw." + +msgid "The selected ALSA device is no longer available." +msgstr "Het geselecteerde ALSA-apparaat is niet meer beschikbaar." + +msgid "This ALSA device does not expose a mixer." +msgstr "Dit ALSA-apparaat biedt geen mixer." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "QBZ kon de geselecteerde ALSA-mixerregelaar niet schrijven. Direct afspelen blijft vastgezet op 100%." + +msgid "Selected mixer control" +msgstr "Geselecteerde mixerregelaar" + +msgid "Choose mixer control" +msgstr "Mixerregelaar kiezen" + +msgid "Change mixer control" +msgstr "Mixerregelaar wijzigen" diff --git a/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po index 5b7427932..fb2aa0b41 100644 --- a/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po @@ -6213,3 +6213,36 @@ msgstr "Histórico de audição limpo." msgid "Couldn't clear listening history." msgstr "Não foi possível limpar o histórico de audição." + +msgid "Checking ALSA mixer controls…" +msgstr "A verificar os controlos do misturador ALSA…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "Este dispositivo apresenta vários controlos de reprodução. Escolha qual o QBZ deve usar." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "O controlo do misturador guardado já não está disponível. Escolha outro controlo." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "O QBZ não tem permissão para ler o misturador ALSA deste dispositivo." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "O misturador ALSA está ocupado. Feche a aplicação que o está a usar e tente novamente." + +msgid "The selected ALSA device is no longer available." +msgstr "O dispositivo ALSA selecionado já não está disponível." + +msgid "This ALSA device does not expose a mixer." +msgstr "Este dispositivo ALSA não disponibiliza um misturador." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "O QBZ não conseguiu escrever no controlo do misturador ALSA selecionado. A reprodução direta permanece fixa em 100%." + +msgid "Selected mixer control" +msgstr "Controlo do misturador selecionado" + +msgid "Choose mixer control" +msgstr "Escolher controlo do misturador" + +msgid "Change mixer control" +msgstr "Alterar controlo do misturador" diff --git a/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po index 47de7e045..b5c06a510 100644 --- a/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po @@ -6233,3 +6233,36 @@ msgstr "История прослушиваний очищена." msgid "Couldn't clear listening history." msgstr "Не удалось очистить историю прослушиваний." + +msgid "Checking ALSA mixer controls…" +msgstr "Проверка регуляторов микшера ALSA…" + +msgid "This device exposes multiple playback controls. Choose which one QBZ should use." +msgstr "Это устройство предоставляет несколько регуляторов воспроизведения. Выберите, какой из них должен использовать QBZ." + +msgid "The saved mixer control is no longer available. Choose another control." +msgstr "Сохранённый регулятор микшера больше недоступен. Выберите другой регулятор." + +msgid "QBZ does not have permission to read this device's ALSA mixer." +msgstr "У QBZ нет разрешения на чтение микшера ALSA этого устройства." + +msgid "The ALSA mixer is busy. Close the app using it and try again." +msgstr "Микшер ALSA занят. Закройте использующее его приложение и повторите попытку." + +msgid "The selected ALSA device is no longer available." +msgstr "Выбранное устройство ALSA больше недоступно." + +msgid "This ALSA device does not expose a mixer." +msgstr "Это устройство ALSA не предоставляет микшер." + +msgid "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%." +msgstr "QBZ не удалось изменить выбранный регулятор микшера ALSA. Громкость прямого воспроизведения остаётся на уровне 100 %." + +msgid "Selected mixer control" +msgstr "Выбранный регулятор микшера" + +msgid "Choose mixer control" +msgstr "Выбрать регулятор микшера" + +msgid "Change mixer control" +msgstr "Изменить регулятор микшера" diff --git a/crates/qbz-qt/qml/controls/QbzSelect.qml b/crates/qbz-qt/qml/controls/QbzSelect.qml index 7749ff36f..fba0e1f0c 100644 --- a/crates/qbz-qt/qml/controls/QbzSelect.qml +++ b/crates/qbz-qt/qml/controls/QbzSelect.qml @@ -66,6 +66,7 @@ Rectangle { } function optHasBadges() { return options.length > 0 && typeof options[0] !== "string" + && options[0] && options[0].bp !== undefined } function optBp(i) { const o = options[i] @@ -75,6 +76,18 @@ Rectangle { const o = options[i] return (o && o.group !== undefined) ? o.group : "" } + function optDetail(i) { + const o = options[i] + return (o && o.detail !== undefined) ? o.detail : "" + } + function openPopup() { + if (!selectRoot.enabled || selectRoot.options.length === 0) + return + selectRoot.filter = "" + popup.open() + if (selectRoot.searchable) + searchInput.forceActiveFocus() + } Row { anchors.fill: parent @@ -132,8 +145,7 @@ Rectangle { cursorShape: selectRoot.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor onClicked: { if (selectRoot.enabled) { - selectRoot.filter = "" - popup.open() + selectRoot.openPopup() } } } @@ -254,22 +266,39 @@ Rectangle { Rectangle { visible: optRow.shown width: parent.width - height: visible ? selectRoot.rowHeight : 0 + height: visible + ? (selectRoot.optDetail(optRow.index) !== "" ? 50 : selectRoot.rowHeight) + : 0 color: optArea.containsMouse ? theme.surfaceHover : "transparent" Row { anchors.fill: parent anchors.leftMargin: 12 anchors.rightMargin: 12 spacing: 8 - Text { + Column { width: parent.width - rowBadge.width - (rowBadge.visible ? 8 : 0) height: parent.height - text: optRow.label - color: optRow.index === selectRoot.currentIndex - ? theme.accent : theme.textSecondary - font.pixelSize: selectRoot.sm ? 12 : theme.fontBody - verticalAlignment: Text.AlignVCenter - elide: Text.ElideRight + anchors.verticalCenter: parent.verticalCenter + Text { + width: parent.width + height: selectRoot.optDetail(optRow.index) !== "" ? 26 : parent.height + text: optRow.label + color: optRow.index === selectRoot.currentIndex + ? theme.accent : theme.textSecondary + font.pixelSize: selectRoot.sm ? 12 : theme.fontBody + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + } + Text { + visible: selectRoot.optDetail(optRow.index) !== "" + width: parent.width + height: visible ? 18 : 0 + text: selectRoot.optDetail(optRow.index) + color: theme.textMuted + font.pixelSize: theme.fontLegal + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + } } Item { id: rowBadge diff --git a/crates/qbz-qt/qml/settings/AudioSettings.qml b/crates/qbz-qt/qml/settings/AudioSettings.qml index c96ab4a43..d5ed0868a 100644 --- a/crates/qbz-qt/qml/settings/AudioSettings.qml +++ b/crates/qbz-qt/qml/settings/AudioSettings.qml @@ -25,6 +25,24 @@ Column { id: root property var doc: ({}) + property string openedHardwareVolumeChoice: "" + + function maybeOpenHardwareVolumeChoice() { + const status = root.doc.alsaHardwareVolumeStatus || "" + const needsChoice = status === "ambiguous" || status === "stale" + const token = root.doc.alsaHardwareVolumeChoiceToken || "" + if (!needsChoice) { + root.openedHardwareVolumeChoice = "" + return + } + if (token !== "" && token !== root.openedHardwareVolumeChoice) { + root.openedHardwareVolumeChoice = token + Qt.callLater(function () { hardwareVolumeSelect.openPopup() }) + } + } + + onDocChanged: maybeOpenHardwareVolumeChoice() + Component.onCompleted: maybeOpenHardwareVolumeChoice() QbzTheme { id: theme } @@ -149,6 +167,55 @@ Column { onToggled: function (v) { QbzBridge.settingsBool("alsa-hardware-volume", v) } } } + Text { + visible: root.doc.backendIsAlsa === true + && root.doc.alsaDirectSelected === true + && (root.doc.alsaHardwareVolumeMessage || "") !== "" + width: parent.width + text: root.doc.alsaHardwareVolumeMessage || "" + color: (root.doc.alsaHardwareVolumeStatus || "") === "probing" + ? theme.textMuted : theme.warning + font.pixelSize: 12 + wrapMode: Text.WordWrap + } + SettingRow { + visible: root.doc.backendIsAlsa === true + && root.doc.alsaDirectSelected === true + && (root.doc.alsaHardwareVolumeSelected || "") !== "" + label: QbzSession.tr("Selected mixer control", QbzSession.trRev) + Text { + text: root.doc.alsaHardwareVolumeSelected || "" + color: theme.textPrimary + font.pixelSize: theme.fontBody + font.weight: theme.weightMedium + verticalAlignment: Text.AlignVCenter + } + } + SettingRow { + visible: root.doc.backendIsAlsa === true + && root.doc.alsaDirectSelected === true + && ((root.doc.alsaHardwareVolumeStatus || "") === "ambiguous" + || (root.doc.alsaHardwareVolumeStatus || "") === "stale" + || (root.doc.alsaHardwareVolume === true + && root.doc.alsaHardwareVolumeCanChange === true)) + && (root.doc.alsaHardwareVolumeOptions || []).length > 0 + label: ((root.doc.alsaHardwareVolumeStatus || "") === "ambiguous" + || (root.doc.alsaHardwareVolumeStatus || "") === "stale") + ? QbzSession.tr("Choose mixer control", QbzSession.trRev) + : QbzSession.tr("Change mixer control", QbzSession.trRev) + QbzSelect { + id: hardwareVolumeSelect + menuWidth: 260 + popupWidth: 480 + searchable: (root.doc.alsaHardwareVolumeOptions || []).length > 8 + options: root.doc.alsaHardwareVolumeOptions || [] + currentIndex: root.doc.alsaHardwareVolumeIndex !== undefined + ? root.doc.alsaHardwareVolumeIndex : -1 + onSelected: function (i) { + QbzBridge.settingsSelect("alsa-hardware-volume-control", i) + } + } + } SettingRow { // ALSA only. fc0d35e29 opened this to WASAPI expecting plan B Task 6 // (DoP over exclusive mode); the spike then measured this DAC refusing diff --git a/crates/qbz-qt/src/diagnostics_qt.rs b/crates/qbz-qt/src/diagnostics_qt.rs index 2376a3387..3a4d3fc5b 100644 --- a/crates/qbz-qt/src/diagnostics_qt.rs +++ b/crates/qbz-qt/src/diagnostics_qt.rs @@ -706,6 +706,26 @@ fn build_system_rows( fn build_audio_rows(g: &Gathered) -> Vec { let d = &g.diag; + let selected_mixer = d + .audio_alsa_hardware_volume_probe + .as_ref() + .and_then(|probe| probe.route_key.as_ref()) + .and_then(|route| d.audio_alsa_hardware_volume_controls.get(route)) + .map(ToString::to_string) + .unwrap_or_else(|| "—".to_string()); + let mixer_probe = d + .audio_alsa_hardware_volume_probe + .as_ref() + .map(|probe| { + let valid = probe.valid_candidates().count(); + let rejected = probe.candidates.len().saturating_sub(valid); + if let Some(error) = &probe.error { + format!("{:?}: {}", error.kind, error.message) + } else { + format!("{valid} valid · {rejected} rejected") + } + }) + .unwrap_or_else(|| "—".to_string()); let sample_rate = match d.audio_preferred_sample_rate { Some(hz) => format!("{hz} Hz"), None => "Auto".to_string(), @@ -763,6 +783,7 @@ fn build_audio_rows(g: &Gathered) -> Vec { row("Active Format", "—", active_fmt, 0), row("ALSA Plugin", &opt(&d.audio_alsa_plugin), "—", 0), row("ALSA HW Volume", yn(d.audio_alsa_hardware_volume), "—", 0), + row("ALSA HW Control", &selected_mixer, &mixer_probe, 0), row("Normalization", yn(d.audio_normalization_enabled), "—", 0), row( "Normalization Target", @@ -1067,6 +1088,8 @@ fn build_export_json(g: &Gathered) -> Value { "preferredSampleRate": d.audio_preferred_sample_rate, "alsaPlugin": d.audio_alsa_plugin, "alsaHardwareVolume": d.audio_alsa_hardware_volume, + "alsaHardwareVolumeControls": d.audio_alsa_hardware_volume_controls, + "alsaHardwareVolumeProbe": d.audio_alsa_hardware_volume_probe, "normalizationEnabled": d.audio_normalization_enabled, "normalizationTargetLufs": d.audio_normalization_target_lufs, "gaplessEnabled": d.audio_gapless_enabled, diff --git a/crates/qbz-qt/src/playback_qt.rs b/crates/qbz-qt/src/playback_qt.rs index 7916d6d84..af7b84a66 100644 --- a/crates/qbz-qt/src/playback_qt.rs +++ b/crates/qbz-qt/src/playback_qt.rs @@ -3211,6 +3211,10 @@ pub fn start_poll_loop(runtime: Arc>) { // meta refresh just reset the bar's position to 0). Reset to None // whenever another owner (local/cast poll) may have written the bar. let mut last_remote_ui_push: Option<(u64, u64, u64, bool, u32, bool, i32)> = None; + // Physical ALSA knob events update the Player's shared volume atomics. + // Mirror only hardware-volume edges onto QML; ordinary local slider + // writes already publish immediately at their command boundary. + let mut last_hardware_volume: Option<(bool, u32)> = None; let mut ticker = tokio::time::interval(std::time::Duration::from_secs(1)); loop { @@ -3443,6 +3447,15 @@ pub fn start_poll_loop(runtime: Arc>) { let duration = event.duration; let is_playing = event.is_playing; let cache = event.buffer_progress.unwrap_or(0.0); + let hardware_volume = (event.hardware_volume_active, event.volume.to_bits()); + if last_hardware_volume != Some(hardware_volume) { + if event.hardware_volume_active + || last_hardware_volume.is_some_and(|(active, _)| active) + { + crate::now_playing::set_volume(event.volume); + } + last_hardware_volume = Some(hardware_volume); + } // Seek lock (PARITY-DEBT #15, playback.rs:5304): while streaming // (`buffer_progress` is Some) the user can only seek up to what // has downloaded; a fully-available track (None) seeks freely. @@ -3979,6 +3992,7 @@ mod tests { duration: 0, track_id, volume: 1.0, + hardware_volume_active: false, sample_rate: None, bit_depth: None, shuffle: None, diff --git a/crates/qbz-qt/src/settings_qt.rs b/crates/qbz-qt/src/settings_qt.rs index 871883e13..ae261ecac 100644 --- a/crates/qbz-qt/src/settings_qt.rs +++ b/crates/qbz-qt/src/settings_qt.rs @@ -30,6 +30,12 @@ use qbz_app::settings::playback::{ AutoplayMode, PlaybackPreferencesState, PlaybackPreferencesStore, }; use qbz_app::shell::AppRuntime; +use qbz_audio::alsa_hardware_volume::{ + AlsaMixerControlId, HardwareVolumeCandidate, HardwareVolumeChoiceReason, + HardwareVolumeDecision, HardwareVolumeProbe, HardwareVolumeProbeErrorKind, + HardwareVolumeSelection, HardwareVolumeSelectionSource, HardwareVolumeSnapshot, + HardwareVolumeUnsupportedReason, StableAlsaRouteKey, +}; use qbz_audio::backend::{AlsaPlugin, AudioBackendType, BackendManager}; use qbz_audio::settings::{AudioSettingsState, AudioSettingsStore}; use qbz_core::LoggingAdapter; @@ -1687,6 +1693,206 @@ pub struct DeviceOption { pub group: String, } +#[derive(Clone, Default, Serialize)] +pub struct HardwareVolumeOption { + pub label: String, + pub detail: String, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +enum HardwareVolumeUiStatus { + #[default] + Disabled, + Probing, + Selected, + Ambiguous, + Stale, + PermissionDenied, + DeviceBusy, + DeviceUnavailable, + NoMixer, + Unsupported, + WriteFailed, +} + +impl HardwareVolumeUiStatus { + fn key(self) -> &'static str { + match self { + Self::Disabled => "disabled", + Self::Probing => "probing", + Self::Selected => "selected", + Self::Ambiguous => "ambiguous", + Self::Stale => "stale", + Self::PermissionDenied => "permission_denied", + Self::DeviceBusy => "device_busy", + Self::DeviceUnavailable => "device_unavailable", + Self::NoMixer => "no_mixer", + Self::Unsupported => "unsupported", + Self::WriteFailed => "write_failed", + } + } + + fn message(self) -> String { + match self { + Self::Disabled | Self::Selected => String::new(), + Self::Probing => qbz_i18n::t("Checking ALSA mixer controls…"), + Self::Ambiguous => qbz_i18n::t( + "This device exposes multiple playback controls. Choose which one QBZ should use.", + ), + Self::Stale => qbz_i18n::t( + "The saved mixer control is no longer available. Choose another control.", + ), + Self::PermissionDenied => { + qbz_i18n::t("QBZ does not have permission to read this device's ALSA mixer.") + } + Self::DeviceBusy => { + qbz_i18n::t("The ALSA mixer is busy. Close the app using it and try again.") + } + Self::DeviceUnavailable => { + qbz_i18n::t("The selected ALSA device is no longer available.") + } + Self::NoMixer => qbz_i18n::t("This ALSA device does not expose a mixer."), + Self::Unsupported => qbz_i18n::t( + "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%.", + ), + Self::WriteFailed => qbz_i18n::t( + "QBZ could not write the selected ALSA mixer control. Direct playback remains fixed at 100%.", + ), + } + } +} + +#[derive(Clone, Default)] +struct HardwareVolumeUiState { + device_id: Option, + route_key: Option, + candidates: Vec, + selected: Option, + status: HardwareVolumeUiStatus, +} + +#[derive(Default)] +struct HardwareVolumeUiSnapshot { + options: Vec, + selected_index: i32, + selected: String, + status: &'static str, + message: String, + can_change: bool, + choice_token: String, +} + +static HARDWARE_VOLUME_UI: Mutex = Mutex::new(HardwareVolumeUiState { + device_id: None, + route_key: None, + candidates: Vec::new(), + selected: None, + status: HardwareVolumeUiStatus::Disabled, +}); + +fn hardware_volume_candidate_detail(candidate: &HardwareVolumeCandidate) -> String { + let range = if let Some(range) = candidate.db_range { + format!( + "{:.2}–{:.2} dB", + range.min as f64 / 100.0, + range.max as f64 / 100.0 + ) + } else if let Some(range) = candidate.raw_range { + format!("{}–{}", range.min, range.max) + } else { + String::new() + }; + let channels = candidate.channels.join(", "); + match (candidate.recommended, range.is_empty(), channels.is_empty()) { + (true, false, false) => format!("★ {range} · {channels}"), + (true, false, true) => format!("★ {range}"), + (true, true, false) => format!("★ {channels}"), + (true, true, true) => "★".to_string(), + (false, false, false) => format!("{range} · {channels}"), + (false, false, true) => range, + (false, true, false) => channels, + (false, true, true) => String::new(), + } +} + +fn hardware_volume_ui_snapshot( + audio: &qbz_audio::settings::AudioSettings, +) -> HardwareVolumeUiSnapshot { + let Ok(state) = HARDWARE_VOLUME_UI.lock() else { + return HardwareVolumeUiSnapshot::default(); + }; + if state.device_id.as_deref() != audio.output_device.as_deref() { + return HardwareVolumeUiSnapshot { + status: if audio.alsa_hardware_volume { + HardwareVolumeUiStatus::Probing.key() + } else { + HardwareVolumeUiStatus::Disabled.key() + }, + message: if audio.alsa_hardware_volume { + HardwareVolumeUiStatus::Probing.message() + } else { + String::new() + }, + ..Default::default() + }; + } + + let options = state + .candidates + .iter() + .map(|candidate| HardwareVolumeOption { + label: candidate.id.to_string(), + detail: hardware_volume_candidate_detail(candidate), + }) + .collect::>(); + let selected_index = state + .selected + .as_ref() + .and_then(|selected| { + state + .candidates + .iter() + .position(|candidate| candidate.id == *selected) + }) + .map(|index| index as i32) + .unwrap_or(-1); + let choice_token = if matches!( + state.status, + HardwareVolumeUiStatus::Ambiguous | HardwareVolumeUiStatus::Stale + ) { + format!( + "{}|{}", + state + .route_key + .as_ref() + .map(StableAlsaRouteKey::as_str) + .unwrap_or_default(), + state + .candidates + .iter() + .map(|candidate| candidate.id.to_string()) + .collect::>() + .join("|") + ) + } else { + String::new() + }; + + HardwareVolumeUiSnapshot { + selected: state + .selected + .as_ref() + .map(ToString::to_string) + .unwrap_or_default(), + status: state.status.key(), + message: state.status.message(), + can_change: state.candidates.len() > 1 && state.selected.is_some(), + choice_token, + options, + selected_index, + } +} + #[derive(Default, Serialize)] pub struct SettingsDoc { // Audio @@ -1721,6 +1927,20 @@ pub struct SettingsDoc { pub alsa_direct_selected: bool, #[serde(rename = "alsaHardwareVolume")] pub alsa_hardware_volume: bool, + #[serde(rename = "alsaHardwareVolumeOptions")] + pub alsa_hardware_volume_options: Vec, + #[serde(rename = "alsaHardwareVolumeIndex")] + pub alsa_hardware_volume_index: i32, + #[serde(rename = "alsaHardwareVolumeSelected")] + pub alsa_hardware_volume_selected: String, + #[serde(rename = "alsaHardwareVolumeStatus")] + pub alsa_hardware_volume_status: &'static str, + #[serde(rename = "alsaHardwareVolumeMessage")] + pub alsa_hardware_volume_message: String, + #[serde(rename = "alsaHardwareVolumeCanChange")] + pub alsa_hardware_volume_can_change: bool, + #[serde(rename = "alsaHardwareVolumeChoiceToken")] + pub alsa_hardware_volume_choice_token: String, #[serde(rename = "dsdModes")] pub dsd_modes: Vec, #[serde(rename = "dsdModeIndex")] @@ -2202,6 +2422,7 @@ pub async fn publish_snapshot() { .iter() .position(|k| *k == streaming_key) .unwrap_or(STREAMING_QUALITY_KEYS.len() - 1); + let hardware_volume_ui = hardware_volume_ui_snapshot(&audio_settings); let mut maps = MAPS.lock().unwrap(); maps.0 = backend_types.clone(); @@ -2228,6 +2449,13 @@ pub async fn publish_snapshot() { alsa_plugin_is_hw: alsa_plugin == AlsaPlugin::Hw, alsa_direct_selected: qbz_audio::alsa_direct::uses_alsa_direct_route(&audio_settings), alsa_hardware_volume: audio_settings.alsa_hardware_volume, + alsa_hardware_volume_options: hardware_volume_ui.options, + alsa_hardware_volume_index: hardware_volume_ui.selected_index, + alsa_hardware_volume_selected: hardware_volume_ui.selected, + alsa_hardware_volume_status: hardware_volume_ui.status, + alsa_hardware_volume_message: hardware_volume_ui.message, + alsa_hardware_volume_can_change: hardware_volume_ui.can_change, + alsa_hardware_volume_choice_token: hardware_volume_ui.choice_token, dsd_modes: DSD_MODE_LABELS.iter().map(|l| qbz_i18n::t(l)).collect(), dsd_mode_index: DSD_MODE_VALUES .iter() @@ -2465,7 +2693,7 @@ enum Apply { async fn probe_selected_hardware_volume( audio: &qbz_audio::settings::AudioSettings, -) -> Result { +) -> Result<(HardwareVolumeProbe, HardwareVolumeDecision), String> { if !qbz_audio::alsa_direct::uses_alsa_direct_route(audio) { return Err( "hardware volume requires an explicitly selected ALSA Direct device".to_string(), @@ -2475,50 +2703,219 @@ async fn probe_selected_hardware_volume( .output_device .clone() .ok_or_else(|| "ALSA Direct device is missing".to_string())?; - tokio::task::spawn_blocking(move || qbz_audio::alsa_direct::probe_hardware_volume(&device_id)) - .await - .map_err(|error| format!("ALSA hardware-volume probe task failed: {error}"))? + let persisted = audio.alsa_hardware_volume_controls.clone(); + tokio::task::spawn_blocking(move || { + let probe = qbz_audio::alsa_hardware_volume::enumerate_hardware_volume_controls(&device_id); + let decision = qbz_audio::alsa_hardware_volume::decide_hardware_volume(&probe, &persisted); + (probe, decision) + }) + .await + .map_err(|error| format!("ALSA hardware-volume probe task failed: {error}")) } fn seed_hardware_volume( runtime: &Arc>, - info: &qbz_audio::alsa_direct::HardwareVolumeInfo, + control: &AlsaMixerControlId, + volume: f32, ) { // Update SharedState without touching the old output. The new direct // engine reads this after Reinit and writes back the same level the probe // sampled, instead of copying the locked path's synthetic 100% into the // physical mixer (or writing the new device's level through the old one). - runtime.core().player().seed_volume_state(info.volume); - save_pref("volume", serde_json::json!(info.volume)); - crate::now_playing::set_volume(info.volume); + runtime.core().player().seed_volume_state(volume); + save_pref("volume", serde_json::json!(volume)); + crate::now_playing::set_volume(volume); log::info!( "[qbz-qt] ALSA hardware volume: '{}' available at {:.0}%", - info.control_name, - info.volume * 100.0 + control, + volume * 100.0 ); } +fn set_hardware_volume_ui_status(device_id: Option, status: HardwareVolumeUiStatus) { + if let Ok(mut state) = HARDWARE_VOLUME_UI.lock() { + if state.device_id != device_id { + *state = HardwareVolumeUiState { + device_id, + status, + ..Default::default() + }; + } else { + state.status = status; + } + } +} + +fn set_hardware_volume_ui_probe( + device_id: String, + probe: &HardwareVolumeProbe, + selected: Option, + status: HardwareVolumeUiStatus, +) { + if let Ok(mut state) = HARDWARE_VOLUME_UI.lock() { + *state = HardwareVolumeUiState { + device_id: Some(device_id), + route_key: probe.route_key.clone(), + candidates: probe.valid_candidates().cloned().collect(), + selected, + status, + }; + } +} + +fn hardware_volume_unsupported_status( + reason: &HardwareVolumeUnsupportedReason, +) -> HardwareVolumeUiStatus { + match reason { + HardwareVolumeUnsupportedReason::Probe(error) => match error.kind { + HardwareVolumeProbeErrorKind::PermissionDenied => { + HardwareVolumeUiStatus::PermissionDenied + } + HardwareVolumeProbeErrorKind::DeviceBusy => HardwareVolumeUiStatus::DeviceBusy, + HardwareVolumeProbeErrorKind::DeviceUnavailable => { + HardwareVolumeUiStatus::DeviceUnavailable + } + HardwareVolumeProbeErrorKind::NoMixer => HardwareVolumeUiStatus::NoMixer, + HardwareVolumeProbeErrorKind::InvalidDevice + | HardwareVolumeProbeErrorKind::UnsupportedPlatform + | HardwareVolumeProbeErrorKind::Other => HardwareVolumeUiStatus::Unsupported, + }, + // No valid alternative exists in this decision variant. Reserve the + // actionable Stale state for NeedsChoice, where a closed selector can + // actually offer another enumerated control. + HardwareVolumeUnsupportedReason::PersistedSelectionStale(_) => { + HardwareVolumeUiStatus::Unsupported + } + HardwareVolumeUnsupportedReason::NoValidControls => HardwareVolumeUiStatus::Unsupported, + } +} + +fn hardware_volume_choice_status(reason: HardwareVolumeChoiceReason) -> HardwareVolumeUiStatus { + match reason { + HardwareVolumeChoiceReason::PersistedSelectionStale => HardwareVolumeUiStatus::Stale, + HardwareVolumeChoiceReason::Ambiguous | HardwareVolumeChoiceReason::UcmAmbiguous => { + HardwareVolumeUiStatus::Ambiguous + } + } +} + +fn current_hardware_volume_route_is( + expected_device_id: &str, +) -> Result { + let current = with_audio(|store| store.get_settings())?; + if !qbz_audio::alsa_direct::uses_alsa_direct_route(¤t) + || current.output_device.as_deref() != Some(expected_device_id) + { + return Err( + "the selected ALSA route changed while its mixer was being checked".to_string(), + ); + } + Ok(current) +} + +async fn activate_hardware_volume_selection( + device_id: &str, + control: &AlsaMixerControlId, +) -> Result { + let device_id = device_id.to_string(); + let control = control.clone(); + tokio::task::spawn_blocking(move || { + qbz_audio::alsa_hardware_volume::activate_hardware_volume_control(&device_id, &control) + }) + .await + .map_err(|error| format!("ALSA hardware-volume validation task failed: {error}"))? +} + +async fn enable_hardware_volume_selection( + runtime: &Arc>, + device_id: String, + probe: HardwareVolumeProbe, + selection: HardwareVolumeSelection, +) -> Result { + current_hardware_volume_route_is(&device_id)?; + let snapshot = match activate_hardware_volume_selection(&device_id, &selection.control).await { + Ok(snapshot) => snapshot, + Err(error) => { + log::warn!( + "[qbz-qt] ALSA hardware-volume control '{}' failed enable validation: {error}", + selection.control + ); + with_audio(|store| store.set_alsa_hardware_volume(false))?; + set_hardware_volume_ui_probe( + device_id, + &probe, + Some(selection.control), + HardwareVolumeUiStatus::WriteFailed, + ); + return Ok(Apply::Reinit); + } + }; + current_hardware_volume_route_is(&device_id)?; + with_audio(|store| { + store.enable_alsa_hardware_volume(selection.route_key, selection.control.clone()) + })?; + set_hardware_volume_ui_probe( + device_id, + &probe, + Some(selection.control.clone()), + HardwareVolumeUiStatus::Selected, + ); + seed_hardware_volume(runtime, &selection.control, snapshot.volume); + Ok(Apply::Reinit) +} + async fn set_alsa_hardware_volume( runtime: &Arc>, enabled: bool, ) -> Result { if !enabled { - return with_audio(|store| store.set_alsa_hardware_volume(false)).map(|_| Apply::Reinit); + let audio = with_audio(|store| { + store.set_alsa_hardware_volume(false)?; + store.get_settings() + })?; + set_hardware_volume_ui_status(audio.output_device, HardwareVolumeUiStatus::Disabled); + return Ok(Apply::Reinit); } let audio = with_audio(|store| store.get_settings())?; - let info = match probe_selected_hardware_volume(&audio).await { - Ok(info) => info, + let device_id = audio + .output_device + .clone() + .ok_or_else(|| "ALSA Direct device is missing".to_string())?; + set_hardware_volume_ui_status(Some(device_id.clone()), HardwareVolumeUiStatus::Probing); + publish_snapshot().await; + + let (probe, decision) = match probe_selected_hardware_volume(&audio).await { + Ok(result) => result, Err(error) => { - // An old build or an external settings edit may already have left - // this true. Fail closed so the UI cannot advertise an enabled, - // inert slider after the probe rejects the device. let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); - return Err(error); + set_hardware_volume_ui_status(Some(device_id), HardwareVolumeUiStatus::Unsupported); + log::warn!("[qbz-qt] ALSA hardware-volume probe failed: {error}"); + return Ok(Apply::Reinit); } }; - seed_hardware_volume(runtime, &info); - with_audio(|store| store.set_alsa_hardware_volume(true)).map(|_| Apply::Reinit) + current_hardware_volume_route_is(&device_id)?; + match decision { + HardwareVolumeDecision::Selected { selection } => { + enable_hardware_volume_selection(runtime, device_id, probe, selection).await + } + HardwareVolumeDecision::NeedsChoice { reason, .. } => { + with_audio(|store| store.set_alsa_hardware_volume(false))?; + let status = hardware_volume_choice_status(reason); + set_hardware_volume_ui_probe(device_id, &probe, None, status); + log::info!( + "[qbz-qt] ALSA hardware volume needs an explicit control choice ({reason:?}); no mixer write performed" + ); + Ok(Apply::Reinit) + } + HardwareVolumeDecision::Unsupported { reason, .. } => { + with_audio(|store| store.set_alsa_hardware_volume(false))?; + let status = hardware_volume_unsupported_status(&reason); + set_hardware_volume_ui_probe(device_id, &probe, None, status); + log::warn!("[qbz-qt] ALSA hardware volume is unavailable: {reason:?}"); + Ok(Apply::Reinit) + } + } } fn apply_audio(runtime: &Arc>, apply: Apply) { @@ -2618,27 +3015,181 @@ pub(crate) async fn reconcile_alsa_hardware_volume( return None; } }; - if !audio.alsa_hardware_volume || !qbz_audio::alsa_direct::uses_alsa_direct_route(&audio) { + if !qbz_audio::alsa_direct::uses_alsa_direct_route(&audio) { + if audio.alsa_hardware_volume { + if let Err(error) = with_audio(|store| store.set_alsa_hardware_volume(false)) { + log::error!("[qbz-qt] failed to disable hardware volume off ALSA Direct: {error}"); + } + } + set_hardware_volume_ui_status(None, HardwareVolumeUiStatus::Disabled); return None; } - match probe_selected_hardware_volume(&audio).await { - Ok(info) => { - seed_hardware_volume(runtime, &info); - Some(info.volume) + let device_id = audio + .output_device + .clone() + .expect("direct route has a device"); + if !audio.alsa_hardware_volume { + let has_saved_control = qbz_audio::alsa_hardware_volume::stable_alsa_route_key(&device_id) + .ok() + .is_some_and(|route| audio.alsa_hardware_volume_controls.contains_key(&route)); + if !has_saved_control { + set_hardware_volume_ui_status(Some(device_id), HardwareVolumeUiStatus::Disabled); + return None; } + } + + set_hardware_volume_ui_status(Some(device_id.clone()), HardwareVolumeUiStatus::Probing); + let (probe, decision) = match probe_selected_hardware_volume(&audio).await { + Ok(result) => result, Err(error) => { - log::warn!("[qbz-qt] ALSA hardware volume unavailable; disabling the setting: {error}"); - if let Err(persist_error) = with_audio(|store| store.set_alsa_hardware_volume(false)) { - log::error!( - "[qbz-qt] failed to disable unavailable hardware volume: {persist_error}" + log::warn!("[qbz-qt] ALSA hardware-volume reconciliation failed: {error}"); + if audio.alsa_hardware_volume { + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + } + set_hardware_volume_ui_status(Some(device_id), HardwareVolumeUiStatus::Unsupported); + if audio.alsa_hardware_volume { + apply_audio(runtime, Apply::Reinit); + } + return None; + } + }; + + if !audio.alsa_hardware_volume { + match decision { + HardwareVolumeDecision::Selected { selection } + if selection.source == HardwareVolumeSelectionSource::Persisted => + { + set_hardware_volume_ui_probe( + device_id, + &probe, + Some(selection.control), + HardwareVolumeUiStatus::Disabled, ); + } + HardwareVolumeDecision::NeedsChoice { reason, .. } => { + log::warn!( + "[qbz-qt] saved ALSA hardware-volume control needs a new choice ({reason:?})" + ); + set_hardware_volume_ui_probe( + device_id, + &probe, + None, + HardwareVolumeUiStatus::Disabled, + ); + } + HardwareVolumeDecision::Unsupported { reason, .. } => { + log::warn!( + "[qbz-qt] saved ALSA hardware-volume control no longer validates: {reason:?}" + ); + set_hardware_volume_ui_probe( + device_id, + &probe, + None, + HardwareVolumeUiStatus::Disabled, + ); + } + HardwareVolumeDecision::Selected { .. } => { + set_hardware_volume_ui_probe( + device_id, + &probe, + None, + HardwareVolumeUiStatus::Disabled, + ); + } + } + publish_snapshot().await; + return None; + } + + match decision { + HardwareVolumeDecision::Selected { selection } => { + let Some(volume) = selection.candidate.current_volume else { + log::warn!( + "[qbz-qt] selected ALSA control '{}' had no readable level", + selection.control + ); + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + set_hardware_volume_ui_probe( + device_id, + &probe, + Some(selection.control), + HardwareVolumeUiStatus::Unsupported, + ); + apply_audio(runtime, Apply::Reinit); + return None; + }; + let migrated = selection.source != HardwareVolumeSelectionSource::Persisted; + if migrated { + if let Err(error) = with_audio(|store| { + store.set_alsa_hardware_volume_control( + selection.route_key.clone(), + selection.control.clone(), + ) + }) { + log::error!( + "[qbz-qt] failed to migrate ALSA hardware-volume selection: {error}" + ); + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + set_hardware_volume_ui_probe( + device_id, + &probe, + Some(selection.control), + HardwareVolumeUiStatus::Unsupported, + ); + apply_audio(runtime, Apply::Reinit); + return None; + } + } + set_hardware_volume_ui_probe( + device_id, + &probe, + Some(selection.control.clone()), + HardwareVolumeUiStatus::Selected, + ); + seed_hardware_volume(runtime, &selection.control, volume); + if migrated { + // Legacy `alsa_hardware_volume=true` had no exact identity in + // the Player's startup snapshot. Reload the newly migrated map + // without reopening the protected PCM route. + apply_audio(runtime, Apply::Reload); + } else { + publish_snapshot().await; + } + Some(volume) + } + HardwareVolumeDecision::NeedsChoice { reason, .. } => { + log::warn!( + "[qbz-qt] persisted ALSA hardware volume needs an explicit choice ({reason:?}); disabling without writing" + ); + if let Err(error) = with_audio(|store| store.set_alsa_hardware_volume(false)) { + log::error!("[qbz-qt] failed to disable ambiguous hardware volume: {error}"); return None; } + set_hardware_volume_ui_probe( + device_id, + &probe, + None, + hardware_volume_choice_status(reason), + ); + apply_audio(runtime, Apply::Reinit); + None + } + HardwareVolumeDecision::Unsupported { reason, .. } => { + log::warn!( + "[qbz-qt] persisted ALSA hardware volume is unavailable; disabling: {reason:?}" + ); + if let Err(error) = with_audio(|store| store.set_alsa_hardware_volume(false)) { + log::error!("[qbz-qt] failed to disable unavailable hardware volume: {error}"); + return None; + } + set_hardware_volume_ui_probe( + device_id, + &probe, + None, + hardware_volume_unsupported_status(&reason), + ); apply_audio(runtime, Apply::Reinit); - crate::toast_qt::error(qbz_i18n::t( - "This ALSA device has no compatible hardware volume control. Direct playback remains fixed at 100%.", - )); None } } @@ -2997,8 +3548,108 @@ pub async fn settings_bool(runtime: &Arc>, key: &str, } } +async fn select_alsa_hardware_volume_control( + runtime: &Arc>, + index: usize, +) { + let audio = match with_audio(|store| store.get_settings()) { + Ok(audio) => audio, + Err(error) => { + log::error!("[qbz-qt] read audio settings for mixer selection failed: {error}"); + return; + } + }; + if !qbz_audio::alsa_direct::uses_alsa_direct_route(&audio) { + log::warn!("[qbz-qt] ignored mixer selection outside ALSA Direct"); + return; + } + let device_id = audio + .output_device + .clone() + .expect("ALSA Direct route has a device id"); + let requested = HARDWARE_VOLUME_UI.lock().ok().and_then(|state| { + (state.device_id.as_deref() == Some(device_id.as_str())) + .then(|| { + state + .candidates + .get(index) + .map(|candidate| candidate.id.clone()) + }) + .flatten() + }); + let Some(requested) = requested else { + log::warn!("[qbz-qt] ignored stale ALSA mixer option index {index}"); + publish_snapshot().await; + return; + }; + + set_hardware_volume_ui_status(Some(device_id.clone()), HardwareVolumeUiStatus::Probing); + publish_snapshot().await; + + let (probe, _) = match probe_selected_hardware_volume(&audio).await { + Ok(result) => result, + Err(error) => { + log::warn!("[qbz-qt] ALSA mixer revalidation failed: {error}"); + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + set_hardware_volume_ui_status(Some(device_id), HardwareVolumeUiStatus::Unsupported); + apply_audio(runtime, Apply::Reinit); + publish_snapshot().await; + return; + } + }; + if let Err(error) = current_hardware_volume_route_is(&device_id) { + log::warn!("[qbz-qt] discarded stale ALSA mixer selection: {error}"); + publish_snapshot().await; + return; + } + let candidate = probe + .valid_candidates() + .find(|candidate| candidate.id == requested) + .cloned(); + let Some(candidate) = candidate else { + log::warn!( + "[qbz-qt] ALSA mixer control '{}' disappeared before selection; no fallback chosen", + requested + ); + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + set_hardware_volume_ui_probe(device_id, &probe, None, HardwareVolumeUiStatus::Stale); + apply_audio(runtime, Apply::Reinit); + publish_snapshot().await; + return; + }; + let Some(route_key) = probe.route_key.clone() else { + log::warn!("[qbz-qt] ALSA mixer selection has no stable route identity"); + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + set_hardware_volume_ui_probe(device_id, &probe, None, HardwareVolumeUiStatus::Unsupported); + apply_audio(runtime, Apply::Reinit); + publish_snapshot().await; + return; + }; + let selection = HardwareVolumeSelection { + route_key, + control: requested, + candidate, + source: HardwareVolumeSelectionSource::UserChoice, + }; + match enable_hardware_volume_selection(runtime, device_id, probe, selection).await { + Ok(apply) => { + apply_audio(runtime, apply); + maybe_force_bitperfect_volume(runtime).await; + } + Err(error) => { + log::error!("[qbz-qt] persist ALSA mixer selection failed: {error}"); + let _ = with_audio(|store| store.set_alsa_hardware_volume(false)); + apply_audio(runtime, Apply::Reinit); + } + } + publish_snapshot().await; +} + pub async fn settings_select(runtime: &Arc>, key: &str, index: usize) { match key { + "alsa-hardware-volume-control" => { + select_alsa_hardware_volume_control(runtime, index).await; + } "streaming-quality" => { let Some(key) = STREAMING_QUALITY_KEYS.get(index) else { return; @@ -3535,6 +4186,31 @@ pub async fn refresh_devices(runtime: &Arc>) { mod local_tab_order_tests { use super::*; + fn mixer_candidate() -> HardwareVolumeCandidate { + HardwareVolumeCandidate { + id: AlsaMixerControlId { + name: "D50 III".to_string(), + index: 2, + }, + label: "D50 III,2".to_string(), + channels: vec!["front_left".to_string(), "front_right".to_string()], + raw_range: Some(qbz_audio::alsa_hardware_volume::HardwareVolumeRange { + min: 0, + max: 255, + }), + db_range: Some(qbz_audio::alsa_hardware_volume::HardwareVolumeRange { + min: -12_700, + max: 0, + }), + current_values: Vec::new(), + current_volume: Some(0.5), + has_playback_switch: true, + recommended: true, + writability: qbz_audio::alsa_hardware_volume::HardwareVolumeWritability::Verified, + rejection_reason: None, + } + } + #[test] fn absent_or_invalid_order_uses_the_complete_default() { let expected: Vec = LOCAL_TAB_DEFAULT_ORDER @@ -3586,6 +4262,48 @@ mod local_tab_order_tests { assert_eq!(large_spectrum_mode_for_tier(4, true), 4); } + #[test] + fn hardware_volume_statuses_are_typed_and_user_visible() { + let statuses = [ + HardwareVolumeUiStatus::Probing, + HardwareVolumeUiStatus::Ambiguous, + HardwareVolumeUiStatus::Stale, + HardwareVolumeUiStatus::PermissionDenied, + HardwareVolumeUiStatus::DeviceBusy, + HardwareVolumeUiStatus::DeviceUnavailable, + HardwareVolumeUiStatus::NoMixer, + HardwareVolumeUiStatus::Unsupported, + HardwareVolumeUiStatus::WriteFailed, + ]; + let mut keys = std::collections::HashSet::new(); + for status in statuses { + assert!(keys.insert(status.key()), "duplicate status key"); + assert!(!status.message().is_empty(), "missing status message"); + } + } + + #[test] + fn hardware_volume_option_exposes_exact_identity_range_and_channels() { + let candidate = mixer_candidate(); + assert_eq!(candidate.id.to_string(), "D50 III,2"); + let detail = hardware_volume_candidate_detail(&candidate); + assert!(detail.contains("-127.00–0.00 dB"), "{detail}"); + assert!(detail.contains("front_left"), "{detail}"); + assert!(detail.starts_with('★'), "{detail}"); + } + + #[test] + fn qml_uses_the_shared_closed_select_for_mixer_identity() { + let audio_qml = include_str!("../qml/settings/AudioSettings.qml"); + let select_qml = include_str!("../qml/controls/QbzSelect.qml"); + assert!(audio_qml.contains("alsaHardwareVolumeOptions")); + assert!(audio_qml.contains("QbzSelect")); + assert!(!audio_qml.contains("TextInput")); + assert!(select_qml.contains("function openPopup")); + assert!(select_qml.contains("function optDetail")); + assert!(select_qml.contains("selectRoot.optDetail(optRow.index)")); + } + #[test] fn only_alsa_direct_without_a_hardware_mixer_requires_unity_volume() { let mut audio = qbz_audio::settings::AudioSettings::default();