From e291eb3af484e0d66fab0a923b6087b2f103b7ac Mon Sep 17 00:00:00 2001
From: vicrodh <103399283+vicrodh@users.noreply.github.com>
Date: Sun, 13 Sep 2026 02:57:21 -0600
Subject: [PATCH] fix: stabilize playback memory, local library sync and Qt
settings
Add shared playback memory profiles, bounded disk-backed playback and storage
selection for desktop and daemon. Preserve gapless during streaming-only playback
and provide explicit cache eviction with playback confirmation.
Stop watcher read events and unchanged scans from rebuilding the local catalog.
Restore playlist/sidebar updates, folder availability feedback and player layout.
Add appearance presets and a radio-based cache settings panel with translated
trade-offs, plus consistent clipboard menus across visible Qt text editors.
Validate with Rust regressions, QML interaction tests, isolated release startup
and idle-library checks; extend the shared local and CI gates.
cx
---
.github/workflows/test-crates.yml | 25 +
README.md | 45 ++
crates/Cargo.lock | 4 +
crates/qbz-app/src/playback_driver.rs | 48 +-
crates/qbz-app/src/settings/bundle.rs | 5 +
crates/qbz-app/src/shell.rs | 6 +
crates/qbz-audio/src/settings.rs | 40 +-
crates/qbz-cache/Cargo.toml | 5 +
crates/qbz-cache/src/audio_cache.rs | 512 +++++++++++++---
crates/qbz-cache/src/lib.rs | 3 +-
crates/qbz-cache/src/memory.rs | 138 +++++
crates/qbz-cache/src/playback_cache.rs | 184 ++++--
.../translations/de/LC_MESSAGES/qbz-ui.po | 238 ++++++++
.../translations/en/LC_MESSAGES/qbz-ui.po | 264 +++++++++
.../translations/es/LC_MESSAGES/qbz-ui.po | 238 ++++++++
.../translations/fr/LC_MESSAGES/qbz-ui.po | 238 ++++++++
.../translations/ja/LC_MESSAGES/qbz-ui.po | 238 ++++++++
.../translations/nl/LC_MESSAGES/qbz-ui.po | 238 ++++++++
.../translations/pt/LC_MESSAGES/qbz-ui.po | 238 ++++++++
.../translations/ru/LC_MESSAGES/qbz-ui.po | 238 ++++++++
crates/qbz-library/src/lib.rs | 1 +
crates/qbz-library/src/scan_changes.rs | 81 +++
crates/qbz-library/src/service.rs | 207 ++++++-
crates/qbz-library/src/watcher.rs | 138 ++++-
crates/qbz-models/src/lib.rs | 1 +
crates/qbz-models/src/playback_cache.rs | 264 +++++++++
crates/qbz-player/Cargo.toml | 3 +
crates/qbz-player/src/player/disk_playback.rs | 215 +++++++
crates/qbz-player/src/player/mod.rs | 392 +++++++------
.../qbz-player/src/player/streaming_source.rs | 549 ++++++++++++++++--
crates/qbz-qt/build.rs | 2 +
.../qbz-qt/qml/assets/icons/accent/server.svg | 16 +
.../qbz-qt/qml/assets/icons/black/server.svg | 16 +
.../qml/assets/icons/favorite/server.svg | 16 +
.../qbz-qt/qml/assets/icons/muted/server.svg | 16 +
.../qml/assets/icons/primary/server.svg | 16 +
.../qml/assets/icons/secondary/server.svg | 16 +
.../qml/assets/icons/warning/server.svg | 16 +
.../qbz-qt/qml/controls/AddToMixtapeModal.qml | 4 +
crates/qbz-qt/qml/controls/DiscMetaModal.qml | 2 +
.../qbz-qt/qml/controls/GenreFilterPopup.qml | 1 +
.../qml/controls/LocalMediaInfoModal.qml | 2 +
.../qml/controls/PlaylistImportModal.qml | 6 +
.../qml/controls/PlaylistPickerModal.qml | 3 +
.../qbz-qt/qml/controls/QbzCompactSeekBar.qml | 103 ++++
crates/qbz-qt/qml/controls/QbzLineEdit.qml | 1 +
crates/qbz-qt/qml/controls/QbzRadioOption.qml | 51 +-
crates/qbz-qt/qml/controls/QbzSelect.qml | 1 +
crates/qbz-qt/qml/controls/QbzTextArea.qml | 2 +
.../qbz-qt/qml/controls/QbzTextEditMenu.qml | 66 +++
crates/qbz-qt/qml/controls/SettingRow.qml | 4 +-
.../qml/controls/TagEditorWorkspace.qml | 1 +
.../qml/controls/TrackReplacementModal.qml | 2 +
crates/qbz-qt/qml/kiosk/KioskMyQBZ.qml | 1 +
.../qbz-qt/qml/kiosk/KioskMyQBZDetailLite.qml | 1 +
crates/qbz-qt/qml/rows/TrackRow.qml | 2 +-
.../qml/settings/AppearanceSettings.qml | 11 +
crates/qbz-qt/qml/settings/DacWizardModal.qml | 2 +
.../qml/settings/LibraryFolderTable.qml | 139 +++--
.../qbz-qt/qml/settings/PlaybackSettings.qml | 277 ++++++++-
crates/qbz-qt/qml/settings/SettingsView.qml | 1 +
crates/qbz-qt/qml/shell/AppShell.qml | 4 +
crates/qbz-qt/qml/shell/HeaderBar.qml | 79 +--
crates/qbz-qt/qml/shell/LogViewerModal.qml | 2 +
.../qbz-qt/qml/shell/NowPlayingBarSmall.qml | 105 +---
crates/qbz-qt/qml/shell/QconnectDevModal.qml | 2 +
crates/qbz-qt/qml/shell/QueuePanel.qml | 3 +-
crates/qbz-qt/qml/shell/Sidebar.qml | 2 +
.../qml/shell/SidebarNowPlayingDock.qml | 2 +-
crates/qbz-qt/qml/views/AlbumListRow.qml | 5 +-
crates/qbz-qt/qml/views/AlbumView.qml | 1 +
crates/qbz-qt/qml/views/LibraryView.qml | 14 +-
crates/qbz-qt/qml/views/LocalAlbumView.qml | 1 +
crates/qbz-qt/qml/views/PlayHistoryView.qml | 1 +
crates/qbz-qt/qml/views/PlaylistView.qml | 1 +
crates/qbz-qt/qml/views/QueueView.qml | 1 +
.../qbz-qt/qml/views/library/FeedGridCell.qml | 13 +
.../qml/views/myqbz/DiscoBuilderView.qml | 1 +
.../qml/views/scene/SceneGenreFilter.qml | 2 +
crates/qbz-qt/src/icon_tint_qt.rs | 1 +
crates/qbz-qt/src/library_bulk.rs | 25 +-
crates/qbz-qt/src/library_qt.rs | 133 ++++-
crates/qbz-qt/src/local_playback.rs | 5 +-
.../qbz-qt/src/local_scan_maintenance_qt.rs | 68 ++-
crates/qbz-qt/src/main.rs | 16 +
crates/qbz-qt/src/playback_qt.rs | 290 +++++++--
crates/qbz-qt/src/playlist_create_qt.rs | 23 +-
crates/qbz-qt/src/playlist_manager_qt.rs | 26 +-
crates/qbz-qt/src/playlist_picker_qt.rs | 9 +
crates/qbz-qt/src/playlist_qt.rs | 66 ++-
crates/qbz-qt/src/playlist_snapshot_qt.rs | 10 +-
crates/qbz-qt/src/qconnect_delegation_qt.rs | 16 +
crates/qbz-qt/src/qconnect_qt.rs | 8 +-
crates/qbz-qt/src/settings_qt.rs | 100 +++-
.../src/settings_qt/appearance_profile.rs | 87 +++
crates/qbz-qt/src/settings_qt/library.rs | 182 +++---
.../src/settings_qt/playback_storage.rs | 124 ++++
crates/qbz-qt/src/sidebar_qt.rs | 118 +++-
crates/qbzd/src/api/status.rs | 4 +-
crates/qbzd/src/cli/settings.rs | 77 ++-
crates/qbzd/src/tui/screens/audio.rs | 15 +-
crates/qbzd/src/tui/screens/playback.rs | 12 +-
crates/qbzd/src/tui/strings.rs | 1 -
packaging/linux/qbzd-standalone-README.md | 64 +-
scripts/cargo-test.sh | 28 +-
.../imports/com/blitzfc/qbz/QbzBridge.qml | 7 +-
.../imports/com/blitzfc/qbz/QbzPlayer.qml | 7 +-
scripts/qml-tests/tst_compact_seek.qml | 82 +++
scripts/qml-tests/tst_library_folders.qml | 61 ++
scripts/qml-tests/tst_playback_cache.qml | 231 ++++++++
scripts/qml-tests/tst_text_edit_menu.qml | 95 +++
scripts/qt-runtime-gate.sh | 6 +
scripts/test-compact-seek-qml.sh | 17 +
scripts/test-library-folders-qml.sh | 17 +
scripts/test-playback-cache-qml.sh | 17 +
scripts/test-text-edit-menu-qml.sh | 17 +
scripts/test_qt_library.mjs | 65 +++
scripts/test_qt_purchases_navigation.mjs | 49 ++
118 files changed, 7128 insertions(+), 883 deletions(-)
create mode 100644 crates/qbz-cache/src/memory.rs
create mode 100644 crates/qbz-library/src/scan_changes.rs
create mode 100644 crates/qbz-models/src/playback_cache.rs
create mode 100644 crates/qbz-player/src/player/disk_playback.rs
create mode 100644 crates/qbz-qt/qml/assets/icons/accent/server.svg
create mode 100644 crates/qbz-qt/qml/assets/icons/black/server.svg
create mode 100644 crates/qbz-qt/qml/assets/icons/favorite/server.svg
create mode 100644 crates/qbz-qt/qml/assets/icons/muted/server.svg
create mode 100644 crates/qbz-qt/qml/assets/icons/primary/server.svg
create mode 100644 crates/qbz-qt/qml/assets/icons/secondary/server.svg
create mode 100644 crates/qbz-qt/qml/assets/icons/warning/server.svg
create mode 100644 crates/qbz-qt/qml/controls/QbzCompactSeekBar.qml
create mode 100644 crates/qbz-qt/qml/controls/QbzTextEditMenu.qml
create mode 100644 crates/qbz-qt/src/settings_qt/appearance_profile.rs
create mode 100644 crates/qbz-qt/src/settings_qt/playback_storage.rs
create mode 100644 scripts/qml-tests/tst_compact_seek.qml
create mode 100644 scripts/qml-tests/tst_library_folders.qml
create mode 100644 scripts/qml-tests/tst_playback_cache.qml
create mode 100644 scripts/qml-tests/tst_text_edit_menu.qml
create mode 100644 scripts/test-compact-seek-qml.sh
create mode 100644 scripts/test-library-folders-qml.sh
create mode 100644 scripts/test-playback-cache-qml.sh
create mode 100755 scripts/test-text-edit-menu-qml.sh
create mode 100644 scripts/test_qt_library.mjs
create mode 100644 scripts/test_qt_purchases_navigation.mjs
diff --git a/.github/workflows/test-crates.yml b/.github/workflows/test-crates.yml
index 74128272e..c5280b4d1 100644
--- a/.github/workflows/test-crates.yml
+++ b/.github/workflows/test-crates.yml
@@ -1,5 +1,7 @@
# CI for the crates/ workspace on the integration branch.
#
+# Playback memory presets: shared persistence/migration, live budgets and growth;
+# Qt profile descriptions/selection are covered by the shared QML runtime gate.
# Three jobs, three economies:
# test — validate all eight gettext catalogs, then `cargo test` on
# every crate that needs no Qt (scripts/cargo-test.sh:
@@ -38,8 +40,19 @@
# and preference preservation; qt-runtime-gate.sh covers the update UI.
# Shared cargo-test.sh also gates Orbit HTTP host isolation, library profiles
# and the SSE public-identity projection. No separate test command to drift.
+# Qt runtime gate includes Library source/count regressions and the Rust
+# playlist-deletion/creation/offline-gapless and maintenance retry regressions.
+# The shared library service gate preserves manual scan feedback while keeping
+# background completions silent, including coalesced work and unavailable roots.
+# Watcher read-feedback and no-op content invalidation are in cargo-test.sh;
+# Library folders status/action layout and tooltips are in qt-runtime-gate.sh.
name: test-crates
+# Shared playback-cache gate covers #774 sealed buffers, Hi-Res decode continuity,
+# memory policy admission/pressure, persistence and qbzd settings round trips.
+# Purchases navigation placement matrix; missing-root watcher retry/recovery.
+# Disk-backed streaming, 24/192 seek, cache reader leases and cancelled prefetch.
+
on:
pull_request:
# pre-release is the real base; main is listed so a PR opened against main
@@ -50,6 +63,8 @@ on:
- "scripts/cargo-test.sh"
- "scripts/install.sh"
- "scripts/test-installer.py"
+ - "scripts/test_qt_library.mjs"
+ - "scripts/test_qt_purchases_navigation.mjs"
- "scripts/qt-*.py"
- "scripts/qt-*.sh"
- "scripts/test_qt_build_gates.py"
@@ -62,6 +77,10 @@ on:
- "scripts/test-search-local-qml.sh"
- "scripts/test-orbit-qml.sh"
- "scripts/test-updates-qml.sh"
+ - "scripts/test-playback-cache-qml.sh"
+ - "scripts/test-text-edit-menu-qml.sh"
+ - "scripts/test-compact-seek-qml.sh"
+ - "scripts/test-library-folders-qml.sh"
- "scripts/test-orbit-daemon.py"
- ".github/workflows/test-crates.yml"
push:
@@ -72,6 +91,8 @@ on:
- "scripts/cargo-test.sh"
- "scripts/install.sh"
- "scripts/test-installer.py"
+ - "scripts/test_qt_library.mjs"
+ - "scripts/test_qt_purchases_navigation.mjs"
- "scripts/qt-*.py"
- "scripts/qt-*.sh"
- "scripts/test_qt_build_gates.py"
@@ -84,6 +105,10 @@ on:
- "scripts/test-search-local-qml.sh"
- "scripts/test-orbit-qml.sh"
- "scripts/test-updates-qml.sh"
+ - "scripts/test-playback-cache-qml.sh"
+ - "scripts/test-text-edit-menu-qml.sh"
+ - "scripts/test-compact-seek-qml.sh"
+ - "scripts/test-library-folders-qml.sh"
- "scripts/test-orbit-daemon.py"
- ".github/workflows/test-crates.yml"
workflow_dispatch:
diff --git a/README.md b/README.md
index 8ed4d4546..98afc7b09 100644
--- a/README.md
+++ b/README.md
@@ -493,6 +493,51 @@ Multi-device playback control using Qobuz's real-time streaming protocol. Full
- **Offline mode** usable without ever logging into Qobuz, with fully offline
playlists and automatic reconnection
+### Playback memory cache
+
+In **Settings → Playback → Playback cache**, choose a playback memory profile:
+
+| Profile | Cache and prefetch behavior |
+| --- | --- |
+| **Auto — recommended** | Fixed 400 MiB on normal-memory hosts or 50 MiB below 2 GiB RAM. |
+| **High — dynamic** | Starts at 400 MiB and can grow to 1600 MiB when RAM is available. |
+| **Desktop** | Fixed 400 MiB with normal prefetch. |
+| **Low — Pi style** | Fixed 50 MiB, smaller initial buffers and reduced prefetch; skips speculative Hi-Res warm-up. |
+| **Custom** | Manual base/maximum and dynamic growth; prefetch follows the detected host class. |
+
+Editing a preset's limits or growth toggle switches to Custom. Existing manual
+cache settings are preserved as Custom. Restore defaults returns to Auto.
+Profiles are shared by qbz and qbzd and preserve the requested audio quality.
+
+Dynamic growth requires measured memory headroom. The cache shrinks after two
+minutes without new demand and can fall below its base under memory pressure.
+These budgets cover cached audio, not reserved RAM or the whole application's
+memory. New buffers follow the selected profile; an existing track continues
+with its current storage. Changing the profile does not restart the DAC.
+
+L2 disk cache remains enabled unless **Streaming only** is selected. Tracks
+outside the memory budget stream through temporary files; L2 playback and
+catalog gapless read files without loading entire tracks into RAM. Keep the
+cache directory on real storage when saving RAM: tmpfs consumes RAM too.
+Offline downloads retain their separate settings. Streaming only keeps gapless
+available, uses less memory and skips cache-based protection against network
+interruptions and instant replay.
+
+```bash
+qbzd settings set audio.playback_memory_profile high
+qbzd status --json
+qbzd settings set audio.playback_memory_profile low
+qbzd settings set audio.playback_memory_profile auto
+```
+
+The CLI also accepts `desktop` and `custom`. Advanced keys remain
+`audio.playback_cache_dynamic`, `audio.playback_cache_min_mib` and
+`audio.playback_cache_max_mib`; editing them selects Custom. Use `none` for an
+automatic limit. Custom dynamic mode defaults to a ceiling four times the base,
+capped at 16384 MiB. `status.playback_cache` reports the active profile, usage,
+and effective/base/maximum budgets in bytes.
+
+
## Headless daemon (qbzd)
diff --git a/crates/Cargo.lock b/crates/Cargo.lock
index b757ba3a1..8c136e0e7 100644
--- a/crates/Cargo.lock
+++ b/crates/Cargo.lock
@@ -3997,8 +3997,11 @@ dependencies = [
"filetime",
"log",
"md-5",
+ "qbz-models",
"rusqlite",
"serde",
+ "tempfile",
+ "windows 0.61.3",
]
[[package]]
@@ -4359,6 +4362,7 @@ dependencies = [
"rodio",
"serde",
"symphonia",
+ "tempfile",
"thiserror 2.0.20",
"tokio",
"tokio-stream",
diff --git a/crates/qbz-app/src/playback_driver.rs b/crates/qbz-app/src/playback_driver.rs
index aef8da422..8aa481149 100644
--- a/crates/qbz-app/src/playback_driver.rs
+++ b/crates/qbz-app/src/playback_driver.rs
@@ -803,7 +803,6 @@ pub async fn run_driver(
log::info!(
"[qbzd] driver: fetching gapless track {successor_id} after {predecessor_id}"
);
- let cached = player.is_track_cached(successor_id);
gapless_fetches.spawn(async move {
let Some(_permit) = task_readmit_owner_action(&task_owner_token) else {
return (
@@ -817,37 +816,21 @@ pub async fn run_driver(
);
};
let core = task_runtime.core();
- // COLD successor: append its initial CMAF buffer as an
- // incremental source (the desktop's streaming
- // hand-off) instead of materializing the whole file —
- // a Hi-Res track cannot reliably download inside the
- // 10 s window on a Pi, and the whole-file `Vec` is
- // exactly what a 1 GB box cannot afford. Cached
- // successors keep the byte path (no network at all).
- if !cached {
+ // L2 successors keep their open file; cold successors
+ // use bounded disk spools when they exceed the RAM budget.
+ // A failed setup must not fall back to a full-file Vec.
+ if task_owner_actions_allowed() {
match core.queue_gapless_streaming(successor_id, quality).await {
- Ok(()) => {
- return (
- task_owner_token,
- GaplessFetchResult {
- predecessor_id,
- successor_id,
- bytes: None,
- streamed: true,
- },
- )
- }
+ Ok(()) => return (
+ task_owner_token,
+ GaplessFetchResult { predecessor_id, successor_id, bytes: None, streamed: true },
+ ),
Err(error) => log::warn!(
- "[qbzd] driver: gapless stream setup for {successor_id} failed: {error}; trying byte fallback"
+ "[qbzd] driver: gapless setup for {successor_id} failed: {error}; normal advance remains available"
),
}
}
- let bytes = if task_owner_actions_allowed() {
- core.fetch_for_gapless_resolved(successor_id, quality, None, None)
- .await
- } else {
- None
- };
+ let bytes = None;
(
task_owner_token,
GaplessFetchResult {
@@ -1037,15 +1020,15 @@ async fn prefetch_successors(
log::debug!("[qbzd] driver: prefetch skipped — memory-pressure halt active");
return;
}
- let profile = qbz_core::system_capabilities::memory_profile();
let core = runtime.core();
+ let profile = core.player().playback_prefetch_policy();
// Depth honors the profile's prefetch_count cap. The daemon's
// historical depth is 1 successor per advance, which is within BOTH
// classes' caps (LowMemory 1, Normal 5), so this changes nothing today
// and clamps automatically if the depth ever grows. There is no
// concurrency loop here — the single prefetch below is awaited — so
// max_concurrent_prefetch (>= 1 in both classes) is trivially honored.
- let depth = 1usize.min(profile.prefetch_count);
+ let depth = 1usize.min(profile.lookahead);
let upcoming = core.peek_upcoming(depth).await;
let Some(next) = upcoming.into_iter().next() else {
return;
@@ -1070,8 +1053,13 @@ async fn prefetch_successors(
// HiRes prefetch on low-pressure ticks. This caps only the warm-ahead
// copy — playback of the user's selected quality is unaffected.
let allow_hires =
- profile.allow_hires_prefetch && !crate::memory_watchdog::hires_prefetch_paused();
+ profile.allow_hires && !crate::memory_watchdog::hires_prefetch_paused();
let prefetch_quality = cap_prefetch_quality(quality, allow_hires);
+ if prefetch_quality != quality {
+ // Do not warm a CD copy that will be rejected at a Hi-Res transition.
+ // The on-demand gapless spool retains the requested format.
+ return;
+ }
if !owner_actions_allowed() {
return;
}
diff --git a/crates/qbz-app/src/settings/bundle.rs b/crates/qbz-app/src/settings/bundle.rs
index faf6c4f7d..d82bb236c 100644
--- a/crates/qbz-app/src/settings/bundle.rs
+++ b/crates/qbz-app/src/settings/bundle.rs
@@ -678,6 +678,7 @@ const AUDIO_PORTABLE: &[&str] = &[
"stream_first_track",
"stream_buffer_seconds",
"streaming_only",
+ "playback_cache",
"normalization_enabled",
"normalization_target_lufs",
"gapless_enabled",
@@ -1195,6 +1196,10 @@ fn apply_audio_writes(data_root: &Path, writes: &[(&str, &Value)]) -> Result<(),
"stream_buffer_seconds" => {
store.set_stream_buffer_seconds(value.as_u64().unwrap_or(2) as u8)?
}
+ "playback_cache" => {
+ let policy = serde_json::from_value((*value).clone()).map_err(|e| format!("playback_cache: {e}"))?;
+ store.set_playback_cache(&policy)?;
+ }
"streaming_only" => store.set_streaming_only(as_bool(value))?,
"limit_quality_to_device" => store.set_limit_quality_to_device(as_bool(value))?,
"preferred_sample_rate" => {
diff --git a/crates/qbz-app/src/shell.rs b/crates/qbz-app/src/shell.rs
index 6ed3fcc07..9e9e30370 100644
--- a/crates/qbz-app/src/shell.rs
+++ b/crates/qbz-app/src/shell.rs
@@ -76,6 +76,12 @@ impl AppRuntime {
audio_settings: AudioSettings,
visualizer_tap: Option,
) -> Self {
+ let host = qbz_core::system_capabilities::memory_profile();
+ qbz_player::player::apply_memory_tuning(
+ host.class == qbz_core::system_capabilities::MemoryClass::LowMemory,
+ host.audio_cache_l1_max_bytes,
+ host.max_initial_buffer_bytes,
+ );
let diagnostic = AudioDiagnostic::new();
let player = Player::new(device_name, audio_settings, visualizer_tap, diagnostic);
let core = QbzCore::new(adapter, player);
diff --git a/crates/qbz-audio/src/settings.rs b/crates/qbz-audio/src/settings.rs
index 7d9b8bf0d..d948fa5e2 100644
--- a/crates/qbz-audio/src/settings.rs
+++ b/crates/qbz-audio/src/settings.rs
@@ -32,6 +32,8 @@ pub struct AudioSettings {
pub stream_buffer_seconds: u8,
/// When true, skip L1+L2 cache writes (streaming-only mode). Offline cache still works.
pub streaming_only: bool,
+ #[serde(default)]
+ pub playback_cache: qbz_models::playback_cache::PlaybackCacheSettings,
/// When true, cap the REQUESTED streaming quality tier at the local output
/// device's detected ceiling (#638 fix 3; consumed by the desktop's
/// request-time resolution, never by the audio backends). Applies to local
@@ -128,6 +130,7 @@ impl Default for AudioSettings {
alsa_hardware_volume_controls: HashMap::new(),
stream_first_track: true, // On by default (opt-out)
stream_buffer_seconds: 2, // 2 seconds initial buffer
+ playback_cache: Default::default(),
streaming_only: false, // Disabled by default (cache tracks for instant replay)
limit_quality_to_device: false, // Opt-in. Off since 1.1.9 (#45); wired to the read-only probe in #638 fix 3
device_max_sample_rate: None, // Set when device is selected
@@ -201,6 +204,7 @@ impl AudioSettingsStore {
"ALTER TABLE audio_settings ADD COLUMN stream_buffer_seconds INTEGER DEFAULT 2",
[],
);
+ let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN playback_cache TEXT NOT NULL DEFAULT '{}'", []);
let _ = conn.execute(
"ALTER TABLE audio_settings ADD COLUMN streaming_only INTEGER DEFAULT 0",
[],
@@ -322,7 +326,7 @@ impl AudioSettingsStore {
pub fn get_settings(&self) -> Result {
self.conn
.query_row(
- "SELECT output_device, exclusive_mode, dac_passthrough, preferred_sample_rate, backend_type, alsa_plugin, alsa_hardware_volume, stream_first_track, stream_buffer_seconds, streaming_only, limit_quality_to_device, device_max_sample_rate, normalization_enabled, normalization_target_lufs, gapless_enabled, device_sample_rate_limits, pw_force_bitperfect, sync_audio_on_startup, quality_fallback_behavior, skip_sink_switch, allow_quality_fallback, reserve_dac_while_running, dsd_mode, alsa_hardware_volume_controls FROM audio_settings WHERE id = 1",
+ "SELECT output_device, exclusive_mode, dac_passthrough, preferred_sample_rate, backend_type, alsa_plugin, alsa_hardware_volume, stream_first_track, stream_buffer_seconds, streaming_only, limit_quality_to_device, device_max_sample_rate, normalization_enabled, normalization_target_lufs, gapless_enabled, device_sample_rate_limits, pw_force_bitperfect, sync_audio_on_startup, quality_fallback_behavior, skip_sink_switch, allow_quality_fallback, reserve_dac_while_running, dsd_mode, alsa_hardware_volume_controls, playback_cache FROM audio_settings WHERE id = 1",
[],
|row| {
// Parse backend_type from JSON string
@@ -360,6 +364,7 @@ impl AudioSettingsStore {
alsa_hardware_volume_controls,
stream_first_track: row.get::<_, Option>(7)?.unwrap_or(0) != 0,
stream_buffer_seconds: row.get::<_, Option>(8)?.unwrap_or(3) as u8,
+ playback_cache: row.get::<_, Option>(24)?.and_then(|s| serde_json::from_str::(&s).ok()).filter(|p| p.validate().is_ok()).unwrap_or_default(),
streaming_only: row.get::<_, Option>(9)?.unwrap_or(0) != 0,
limit_quality_to_device: row.get::<_, Option>(10)?.unwrap_or(0) != 0,
device_max_sample_rate: row.get::<_, Option>(11)?.map(|r| r as u32),
@@ -586,6 +591,14 @@ impl AudioSettingsStore {
Ok(())
}
+ pub fn set_playback_cache(&self, policy: &qbz_models::playback_cache::PlaybackCacheSettings) -> Result<(), String> {
+ policy.validate()?;
+ let json = serde_json::to_string(policy).map_err(|e| e.to_string())?;
+ self.conn.execute("UPDATE audio_settings SET playback_cache = ?1 WHERE id = 1", params![json])
+ .map_err(|e| format!("Failed to save playback cache settings: {e}"))?;
+ Ok(())
+ }
+
pub fn set_streaming_only(&self, enabled: bool) -> Result<(), String> {
self.conn
.execute(
@@ -839,7 +852,8 @@ impl AudioSettingsStore {
skip_sink_switch = ?19,
allow_quality_fallback = ?20,
reserve_dac_while_running = ?21,
- alsa_hardware_volume_controls = ?22
+ alsa_hardware_volume_controls = ?22,
+ playback_cache = '{}'
WHERE id = 1",
params![
defaults.output_device,
@@ -949,6 +963,28 @@ mod tests {
(dir, store)
}
+ #[test]
+ fn playback_cache_persists_validates_and_resets_without_losing_other_settings() {
+ use qbz_models::playback_cache::PlaybackCacheSettings;
+ let (dir, store) = fresh_store("playback-cache");
+ let policy = PlaybackCacheSettings { dynamic: true, min_mib: Some(400), max_mib: Some(1600), ..Default::default() };
+ store.set_playback_cache(&policy).unwrap();
+ store.set_gapless_enabled(true).unwrap();
+ drop(store);
+ let store = AudioSettingsStore::new_at(&dir).unwrap();
+ assert_eq!(store.get_settings().unwrap().playback_cache, policy);
+ let invalid = PlaybackCacheSettings { max_mib: Some(100), ..policy.clone() };
+ assert!(store.set_playback_cache(&invalid).is_err());
+ assert_eq!(store.get_settings().unwrap().playback_cache, policy);
+ store.set_quality_fallback_behavior("always_skip").unwrap();
+ store.reset_all().unwrap();
+ let fresh = store.get_settings().unwrap();
+ assert_eq!(fresh.playback_cache, PlaybackCacheSettings::default());
+ assert_eq!(fresh.quality_fallback_behavior, "always_skip");
+ drop(store);
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
#[test]
fn audio_settings_default_values_are_stable() {
let settings = AudioSettings::default();
diff --git a/crates/qbz-cache/Cargo.toml b/crates/qbz-cache/Cargo.toml
index df8584d09..cf80d51d7 100644
--- a/crates/qbz-cache/Cargo.toml
+++ b/crates/qbz-cache/Cargo.toml
@@ -6,6 +6,7 @@ description = "Audio caching system for QBZ - L1 memory + L2 disk caches"
authors = ["blitzkriegfc"]
[dependencies]
+qbz-models = { path = "../qbz-models" }
# Logging
log = "0.4"
@@ -15,7 +16,11 @@ serde = { version = "1", features = ["derive"] }
# File system utilities
dirs = "6"
filetime = "0.2"
+tempfile = "3"
# Image cache index + URL hashing
rusqlite = { version = "0.40", features = ["bundled"] }
md-5 = "0.10"
+
+[target.'cfg(target_os = "windows")'.dependencies]
+windows = { version = "0.61", features = ["Win32_System_SystemInformation"] }
diff --git a/crates/qbz-cache/src/audio_cache.rs b/crates/qbz-cache/src/audio_cache.rs
index cf03b8520..11e06d7f5 100644
--- a/crates/qbz-cache/src/audio_cache.rs
+++ b/crates/qbz-cache/src/audio_cache.rs
@@ -4,10 +4,11 @@
//! Evicted tracks can optionally spill to L2 disk cache.
use std::collections::{HashMap, HashSet};
-use std::sync::{Arc, Mutex};
+use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
-use crate::PlaybackCache;
+use crate::{memory::MemoryHeadroom, PlaybackCache};
+use qbz_models::playback_cache::PlaybackCacheSettings;
/// Cached audio data for a track
#[derive(Clone)]
@@ -17,10 +18,31 @@ pub struct CachedTrack {
pub size_bytes: usize,
}
+#[derive(Clone)]
+struct SharedTrack {
+ track_id: u64,
+ data: Arc>,
+ size_bytes: usize,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CacheAdmission {
+ Memory,
+ Disk,
+ Skipped,
+}
+
/// Internal cache state - all in one struct to avoid deadlocks
struct CacheState {
/// Cached tracks keyed by track ID
- tracks: HashMap,
+ tracks: HashMap,
+ policy: PlaybackCacheSettings,
+ base: usize,
+ ceiling: usize,
+ effective: usize,
+ headroom: Option<(MemoryHeadroom, Instant)>,
+ growth_since_sample: usize,
+ last_demand: Instant,
/// Order of access for LRU eviction (most recent at back)
access_order: Vec,
/// Current cache size in bytes
@@ -41,6 +63,7 @@ struct CacheState {
/// cache (if configured) for later retrieval.
pub struct AudioCache {
state: Mutex,
+ maintenance_thread: OnceLock,
/// Maximum cache size in bytes
max_size_bytes: usize,
/// Optional disk-based L2 cache for evicted tracks
@@ -57,8 +80,16 @@ impl AudioCache {
/// Create a new cache with specified max size in bytes
pub fn new(max_size_bytes: usize) -> Self {
Self {
+ maintenance_thread: OnceLock::new(),
state: Mutex::new(CacheState {
tracks: HashMap::new(),
+ policy: PlaybackCacheSettings::default(),
+ base: max_size_bytes,
+ ceiling: max_size_bytes,
+ effective: max_size_bytes,
+ headroom: None,
+ growth_since_sample: 0,
+ last_demand: Instant::now(),
access_order: Vec::new(),
current_size: 0,
fetching: HashSet::new(),
@@ -72,8 +103,16 @@ impl AudioCache {
/// Create cache with disk spillover enabled
pub fn with_playback_cache(max_size_bytes: usize, playback_cache: Arc) -> Self {
Self {
+ maintenance_thread: OnceLock::new(),
state: Mutex::new(CacheState {
tracks: HashMap::new(),
+ policy: PlaybackCacheSettings::default(),
+ base: max_size_bytes,
+ ceiling: max_size_bytes,
+ effective: max_size_bytes,
+ headroom: None,
+ growth_since_sample: 0,
+ last_demand: Instant::now(),
access_order: Vec::new(),
current_size: 0,
fetching: HashSet::new(),
@@ -109,7 +148,13 @@ impl AudioCache {
log::debug!("Cache miss for track {}", track_id);
}
- track
+ drop(state);
+ // Legacy Vec consumers copy after releasing the cache lock.
+ track.map(|t| CachedTrack {
+ track_id: t.track_id,
+ data: (*t.data).clone(),
+ size_bytes: t.size_bytes,
+ })
}
/// Check if a track is in cache without updating access order
@@ -161,77 +206,195 @@ impl AudioCache {
self.state.lock().unwrap().failed.remove(&track_id);
}
- /// Insert a track into cache, evicting old entries to disk if needed
- pub fn insert(&self, track_id: u64, data: Vec) {
- let size = data.len();
-
- // Don't cache if track is larger than max cache size
- if size > self.max_size_bytes {
- log::warn!(
- "Track {} ({} bytes) too large for cache (max {} bytes)",
- track_id,
- size,
- self.max_size_bytes
- );
- return;
- }
-
- // Collect tracks to evict (to avoid holding lock while writing to disk)
- let mut tracks_to_spill: Vec = Vec::new();
-
- {
+ /// Apply a validated persisted policy without restarting the audio device.
+ pub fn configure(&self, policy: PlaybackCacheSettings) -> Result<(), String> {
+ policy.validate()?;
+ let retired = {
let mut state = self.state.lock().unwrap();
+ if state.policy == policy {
+ return Ok(());
+ }
+ let (base, ceiling) = policy.budgets(self.max_size_bytes);
+ state.policy = policy;
+ state.base = base;
+ state.ceiling = ceiling;
+ state.effective = base;
+ state.last_demand = Instant::now();
+ Self::trim(&mut state)
+ };
+ if let Some(worker) = self.maintenance_thread.get() {
+ worker.unpark();
+ }
+ drop(retired); // Destruction of large buffers never holds the cache mutex.
+ Ok(())
+ }
- // Evict old entries to make room
- while state.current_size + size > self.max_size_bytes && !state.access_order.is_empty()
- {
- let oldest_id = state.access_order.remove(0);
- if let Some(track) = state.tracks.remove(&oldest_id) {
- state.current_size = state.current_size.saturating_sub(track.size_bytes);
- log::debug!(
- "Evicting track {} ({} bytes) from memory cache",
- oldest_id,
- track.size_bytes
- );
- tracks_to_spill.push(track);
+ /// Weak ownership: maintenance cannot keep a player/cache alive after shutdown.
+ pub fn start_maintenance(cache: &Arc) {
+ let weak = Arc::downgrade(cache);
+ let worker = std::thread::spawn(move || loop {
+ let Some(cache) = weak.upgrade() else { break };
+ let headroom = if cache.stats().dynamic {
+ crate::memory::read()
+ } else {
+ None
+ };
+ cache.maintain(headroom, Instant::now());
+ drop(cache);
+ std::thread::park_timeout(Duration::from_secs(15));
+ });
+ let _ = cache.maintenance_thread.set(worker.thread().clone());
+ }
+
+ fn reserve(memory: MemoryHeadroom) -> u64 {
+ (256 * 1024 * 1024).max(memory.total / 4)
+ }
+
+ fn critical(memory: MemoryHeadroom) -> bool {
+ memory.available < (128 * 1024 * 1024).max(memory.total / 100)
+ }
+
+ fn maintain(&self, headroom: Option, now: Instant) {
+ let retired = {
+ let mut state = self.state.lock().unwrap();
+ state.headroom = headroom.map(|m| (m, now));
+ state.growth_since_sample = 0;
+ if state.policy.dynamic {
+ if headroom.is_some_and(|m| m.available < Self::reserve(m)) {
+ // Relinquish growth first; critical pressure also overrides the base.
+ state.effective = if headroom.is_some_and(Self::critical) {
+ 0
+ } else {
+ state.base
+ };
+ } else if now.saturating_duration_since(state.last_demand)
+ >= Duration::from_secs(120)
+ {
+ state.effective = state.base;
+ }
+ }
+ Self::trim(&mut state)
+ };
+ drop(retired);
+ }
+
+ fn trim(state: &mut CacheState) -> Vec {
+ let mut retired = Vec::new();
+ while state.current_size > state.effective && !state.access_order.is_empty() {
+ let oldest = state.access_order.remove(0);
+ if let Some(track) = state.tracks.remove(&oldest) {
+ state.current_size = state.current_size.saturating_sub(track.size_bytes);
+ retired.push(track);
+ }
+ }
+ retired
+ }
+
+ pub fn insert(&self, track_id: u64, data: Vec) -> CacheAdmission {
+ self.insert_shared(track_id, Arc::new(data))
+ }
+
+ /// Admit a sealed streaming buffer without allocating a second track-sized copy.
+ /// Reservation, eviction and insertion are atomic with respect to other writers.
+ pub fn insert_shared(&self, track_id: u64, data: Arc>) -> CacheAdmission {
+ self.admit(track_id, data, true)
+ }
+
+ /// L2 reads may warm L1, but an oversized hit must not rewrite the same file.
+ pub fn promote_from_disk(&self, track_id: u64, data: Vec) -> CacheAdmission {
+ self.admit(track_id, Arc::new(data), false)
+ }
+
+ /// Decide storage before a download allocates its payload. Dynamic growth
+ /// uses the same fresh-headroom allowance as L1 admission, not just max MiB.
+ pub fn can_buffer_in_memory(&self, size: usize) -> bool {
+ let mut state = self.state.lock().unwrap();
+ Self::budget_for_incoming(&mut state, size);
+ let fits = size <= state.effective;
+ let retired = Self::trim(&mut state);
+ drop(state);
+ drop(retired);
+ fits
+ }
+
+ fn budget_for_incoming(state: &mut CacheState, size: usize) {
+ let now = Instant::now();
+ state.last_demand = now;
+ if state.policy.dynamic {
+ if let Some((memory, _sampled)) = state.headroom.filter(|(_, sampled)| {
+ now.saturating_duration_since(*sampled) <= Duration::from_secs(30)
+ }) {
+ let reserve = Self::reserve(memory);
+ if memory.available >= reserve {
+ let desired = state.current_size.saturating_add(size).min(state.ceiling);
+ let spare = memory
+ .available
+ .saturating_sub(reserve)
+ .min(usize::MAX as u64) as usize;
+ // Spend at most half the current headroom; decoding/prefetch need room too.
+ let permitted = state
+ .effective
+ .saturating_add((spare / 2).saturating_sub(state.growth_since_sample));
+ let next = state.effective.max(desired.min(permitted));
+ state.growth_since_sample += next.saturating_sub(state.effective);
+ state.effective = next;
+ } else {
+ state.effective = if Self::critical(memory) {
+ 0
+ } else {
+ state.base
+ };
}
}
}
+ }
- // Spill evicted tracks to disk cache (outside of lock)
- if let Some(playback_cache) = &self.playback_cache {
- for track in tracks_to_spill {
- playback_cache.insert(track.track_id, &track.data);
+ fn admit(&self, track_id: u64, data: Arc>, spill_rejected: bool) -> CacheAdmission {
+ let size = data.len();
+ let mut retired = Vec::new();
+ let admitted = {
+ let mut state = self.state.lock().unwrap();
+ Self::budget_for_incoming(&mut state, size);
+ if size > state.effective {
+ retired.extend(Self::trim(&mut state));
+ false
+ } else {
+ if let Some(old) = state.tracks.remove(&track_id) {
+ state.current_size = state.current_size.saturating_sub(old.size_bytes);
+ retired.push(old);
+ }
+ state.access_order.retain(|&id| id != track_id);
+ state.current_size = state.current_size.saturating_add(size);
+ retired.extend(Self::trim(&mut state));
+ state.tracks.insert(
+ track_id,
+ SharedTrack {
+ track_id,
+ data: data.clone(),
+ size_bytes: size,
+ },
+ );
+ state.access_order.push(track_id);
+ true
+ }
+ };
+ if let Some(disk) = &self.playback_cache {
+ for track in retired {
+ disk.insert(track.track_id, &track.data);
}
}
-
- let mut state = self.state.lock().unwrap();
-
- // If track already exists, update size tracking
- if let Some(existing) = state.tracks.get(&track_id) {
- state.current_size = state.current_size.saturating_sub(existing.size_bytes);
+ if admitted {
+ CacheAdmission::Memory
+ } else if spill_rejected
+ && self
+ .playback_cache
+ .as_ref()
+ .is_some_and(|disk| disk.insert(track_id, &data))
+ {
+ CacheAdmission::Disk
+ } else {
+ CacheAdmission::Skipped
}
-
- let cached = CachedTrack {
- track_id,
- data,
- size_bytes: size,
- };
-
- state.tracks.insert(track_id, cached);
- state.current_size += size;
-
- // Update access order
- state.access_order.retain(|&id| id != track_id);
- state.access_order.push(track_id);
-
- log::info!(
- "Cached track {} ({} bytes). Cache size: {}/{} bytes",
- track_id,
- size,
- state.current_size,
- self.max_size_bytes
- );
}
/// Clear all cached data (both L1 memory and L2 disk caches)
@@ -268,9 +431,14 @@ impl AudioCache {
pub fn stats(&self) -> CacheStats {
let state = self.state.lock().unwrap();
CacheStats {
+ profile: state.policy.selected_profile().as_str().into(),
cached_tracks: state.tracks.len(),
current_size_bytes: state.current_size,
- max_size_bytes: self.max_size_bytes,
+ max_size_bytes: state.effective,
+ base_size_bytes: state.base,
+ ceiling_size_bytes: state.ceiling,
+ recommended_size_bytes: self.max_size_bytes,
+ dynamic: state.policy.dynamic,
fetching_count: state.fetching.len(),
}
}
@@ -279,8 +447,218 @@ impl AudioCache {
/// Cache statistics
#[derive(Debug, Clone, serde::Serialize)]
pub struct CacheStats {
+ pub profile: String,
pub cached_tracks: usize,
pub current_size_bytes: usize,
pub max_size_bytes: usize,
pub fetching_count: usize,
+ pub base_size_bytes: usize,
+ pub ceiling_size_bytes: usize,
+ pub recommended_size_bytes: usize,
+ pub dynamic: bool,
+}
+
+#[cfg(test)]
+mod playback_policy_tests {
+ use super::*;
+ const MIB: usize = 1024 * 1024;
+ fn dynamic() -> PlaybackCacheSettings {
+ PlaybackCacheSettings {
+ dynamic: true,
+ min_mib: Some(16),
+ max_mib: Some(64),
+ ..Default::default()
+ }
+ }
+ fn roomy() -> MemoryHeadroom {
+ MemoryHeadroom {
+ total: 4 << 30,
+ available: 3 << 30,
+ }
+ }
+
+ #[test]
+ fn defaults_and_unknown_headroom_do_not_grow() {
+ let cache = AudioCache::new(16 * MIB);
+ cache.configure(dynamic()).unwrap();
+ assert_eq!(cache.insert(1, vec![0; 20 * MIB]), CacheAdmission::Skipped);
+ assert_eq!(cache.stats().max_size_bytes, 16 * MIB);
+ cache.configure(PlaybackCacheSettings::default()).unwrap();
+ cache.maintain(Some(roomy()), Instant::now());
+ assert_eq!(cache.insert(1, vec![0; 20 * MIB]), CacheAdmission::Skipped);
+ }
+
+ #[test]
+ fn on_demand_growth_shares_bytes_obeys_ceiling_and_shrinks_with_hysteresis() {
+ let cache = AudioCache::new(16 * MIB);
+ cache.configure(dynamic()).unwrap();
+ let now = Instant::now();
+ cache.maintain(Some(roomy()), now);
+ let bytes = Arc::new(vec![7; 24 * MIB]);
+ assert_eq!(
+ cache.insert_shared(1, bytes.clone()),
+ CacheAdmission::Memory
+ );
+ assert!(Arc::ptr_eq(
+ &bytes,
+ &cache.state.lock().unwrap().tracks[&1].data
+ ));
+ assert_eq!(cache.stats().max_size_bytes, 24 * MIB);
+ cache.maintain(Some(roomy()), now + Duration::from_secs(60));
+ assert_eq!(cache.stats().cached_tracks, 1);
+ cache.maintain(Some(roomy()), now + Duration::from_secs(121));
+ assert_eq!(cache.stats().max_size_bytes, 16 * MIB);
+ assert!(!cache.contains(1));
+ assert_eq!(bytes[0], 7); // eviction cannot truncate the active source
+ cache.maintain(Some(roomy()), Instant::now());
+ assert_eq!(cache.insert(2, vec![0; 65 * MIB]), CacheAdmission::Skipped);
+ assert!(cache.stats().max_size_bytes <= 64 * MIB);
+ }
+
+ #[test]
+ fn pressure_overrides_base_and_stale_metrics_cannot_grant_growth() {
+ let cache = AudioCache::new(16 * MIB);
+ cache.configure(dynamic()).unwrap();
+ cache.maintain(Some(roomy()), Instant::now() - Duration::from_secs(31));
+ assert_eq!(cache.insert(1, vec![0; 24 * MIB]), CacheAdmission::Skipped);
+ cache.maintain(Some(roomy()), Instant::now());
+ cache.insert(1, vec![0; 24 * MIB]);
+ cache.maintain(
+ Some(MemoryHeadroom {
+ total: 4 << 30,
+ available: 64 * MIB as u64,
+ }),
+ Instant::now(),
+ );
+ assert_eq!(cache.stats().max_size_bytes, 0);
+ assert_eq!(cache.stats().current_size_bytes, 0);
+ assert_eq!(cache.insert(2, vec![0; 8]), CacheAdmission::Skipped);
+ }
+
+ #[test]
+ fn limited_headroom_releases_growth_but_keeps_the_base() {
+ let cache = AudioCache::new(16 * MIB);
+ cache.configure(dynamic()).unwrap();
+ cache.maintain(Some(roomy()), Instant::now());
+ cache.insert(1, vec![0; 24 * MIB]);
+ cache.maintain(
+ Some(MemoryHeadroom {
+ total: 4 << 30,
+ available: 512 << 20,
+ }),
+ Instant::now(),
+ );
+ assert_eq!(cache.stats().max_size_bytes, 16 * MIB);
+ assert_eq!(cache.insert(2, vec![1; 8 * MIB]), CacheAdmission::Memory);
+ }
+
+ #[test]
+ fn disk_promotion_does_not_write_rejected_bytes_back_to_disk() {
+ let path =
+ std::env::temp_dir().join(format!("qbz-774-promote-disk-{}", std::process::id()));
+ let disk = Arc::new(PlaybackCache::with_path(path.clone(), 1024).unwrap());
+ let cache = AudioCache::with_playback_cache(16, disk.clone());
+ assert_eq!(
+ cache.promote_from_disk(1, vec![7; 32]),
+ CacheAdmission::Skipped
+ );
+ assert!(!disk.contains(1));
+ assert_eq!(
+ cache.promote_from_disk(2, vec![7; 8]),
+ CacheAdmission::Memory
+ );
+ drop(cache);
+ drop(disk);
+ std::fs::remove_dir_all(path).unwrap();
+ }
+
+ #[test]
+ fn concurrent_oversized_streams_respect_the_disk_budget() {
+ let path =
+ std::env::temp_dir().join(format!("qbz-774-parallel-disk-{}", std::process::id()));
+ let disk = Arc::new(PlaybackCache::with_path(path.clone(), 1024).unwrap());
+ let cache = Arc::new(AudioCache::with_playback_cache(16, disk.clone()));
+ let handles: Vec<_> = (0..8)
+ .map(|id| {
+ let cache = cache.clone();
+ std::thread::spawn(move || {
+ assert_eq!(cache.insert(id, vec![id as u8; 600]), CacheAdmission::Disk);
+ })
+ })
+ .collect();
+ for handle in handles {
+ handle.join().unwrap();
+ }
+ assert!(disk.stats().current_size_bytes <= 1024);
+ let data = (0..8).find_map(|id| disk.get(id)).unwrap();
+ assert_eq!(data.len(), 600);
+ assert!(data.iter().all(|b| *b == data[0]));
+ drop(cache);
+ drop(disk);
+ std::fs::remove_dir_all(path).unwrap();
+ }
+
+ #[test]
+ fn concurrent_writers_and_replacement_never_exceed_budget() {
+ let cache = Arc::new(AudioCache::new(128));
+ let handles: Vec<_> = (0..8)
+ .map(|id| {
+ let cache = cache.clone();
+ std::thread::spawn(move || {
+ for _ in 0..50 {
+ cache.insert(id, vec![id as u8; 32]);
+ let stats = cache.stats();
+ assert!(stats.current_size_bytes <= stats.max_size_bytes);
+ }
+ })
+ })
+ .collect();
+ for handle in handles {
+ handle.join().unwrap();
+ }
+ let state = cache.state.lock().unwrap();
+ assert_eq!(
+ state.current_size,
+ state.tracks.values().map(|t| t.size_bytes).sum::()
+ );
+ assert_eq!(state.access_order.len(), state.tracks.len());
+ }
+
+ #[test]
+ fn oversized_l1_falls_back_to_disk_and_reports_rejection_truthfully() {
+ let path = std::env::temp_dir().join(format!("qbz-774-disk-{}", std::process::id()));
+ let disk = Arc::new(PlaybackCache::with_path(path.clone(), 1024).unwrap());
+ let cache = AudioCache::with_playback_cache(16, disk.clone());
+ assert_eq!(cache.insert(1, vec![7; 32]), CacheAdmission::Disk);
+ assert_eq!(disk.get(1).unwrap(), vec![7; 32]);
+ assert!(!cache.contains(1));
+ assert_eq!(cache.insert(2, vec![8; 2048]), CacheAdmission::Skipped);
+ assert!(!disk.contains(2));
+ drop(cache);
+ drop(disk);
+ std::fs::remove_dir_all(path).unwrap();
+ }
+}
+
+#[cfg(test)]
+mod memory_profile_tests {
+ use super::*;
+ use qbz_models::playback_cache::PlaybackMemoryProfile;
+ #[test]
+ fn memory_profile_switches_live_budget_and_high_growth_requires_headroom() {
+ let cache=AudioCache::new(400<<20);
+ let mut policy=PlaybackCacheSettings::default();policy.select_profile(PlaybackMemoryProfile::High);
+ cache.configure(policy.clone()).unwrap();
+ assert!(!cache.can_buffer_in_memory(681736251));
+ cache.maintain(Some(MemoryHeadroom { total:4<<30, available:3<<30 }),Instant::now());
+ assert!(cache.can_buffer_in_memory(681736251));
+ assert_eq!(cache.stats().ceiling_size_bytes,1600<<20);
+ assert!(cache.stats().max_size_bytes>400<<20);
+ policy.select_profile(PlaybackMemoryProfile::Low);cache.configure(policy.clone()).unwrap();
+ assert_eq!(cache.stats().max_size_bytes,50<<20);
+ assert!(!cache.can_buffer_in_memory(681736251));
+ assert_eq!(cache.stats().profile,"low");
+ policy.dynamic=true;assert!(cache.configure(policy).is_err());
+ assert_eq!(cache.stats().profile,"low");
+ }
}
diff --git a/crates/qbz-cache/src/lib.rs b/crates/qbz-cache/src/lib.rs
index 882d5aad0..da326a674 100644
--- a/crates/qbz-cache/src/lib.rs
+++ b/crates/qbz-cache/src/lib.rs
@@ -56,9 +56,10 @@
//! ```
mod audio_cache;
+mod memory;
mod image_cache;
mod playback_cache;
-pub use audio_cache::{AudioCache, CacheStats, CachedTrack};
+pub use audio_cache::{AudioCache, CacheStats, CachedTrack, CacheAdmission};
pub use image_cache::{ImageCacheService, ImageCacheStats};
pub use playback_cache::{PlaybackCache, PlaybackCacheStats};
diff --git a/crates/qbz-cache/src/memory.rs b/crates/qbz-cache/src/memory.rs
new file mode 100644
index 000000000..704fc237a
--- /dev/null
+++ b/crates/qbz-cache/src/memory.rs
@@ -0,0 +1,138 @@
+//! Memory headroom sampled by the cache worker, never by an audio callback.
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct MemoryHeadroom {
+ pub total: u64,
+ pub available: u64,
+}
+
+#[cfg(target_os = "linux")]
+pub(crate) fn read() -> Option {
+ let text = std::fs::read_to_string("/proc/meminfo").ok()?;
+ let kib = |key: &str| -> Option {
+ text.lines()
+ .find_map(|line| line.strip_prefix(key))?
+ .split_whitespace()
+ .next()?
+ .parse::()
+ .ok()?
+ .checked_mul(1024)
+ };
+ let mut memory = MemoryHeadroom {
+ total: kib("MemTotal:")?,
+ available: kib("MemAvailable:")?,
+ };
+ // Respect all enclosing cgroup-v2 limits, including a container's parent.
+ if let Ok(groups) = std::fs::read_to_string("/proc/self/cgroup") {
+ if let Some(group) = groups.lines().find_map(|line| line.strip_prefix("0::")) {
+ let root = std::path::Path::new("/sys/fs/cgroup");
+ let mut path = root.join(group.trim_start_matches('/'));
+ while path.starts_with(root) {
+ let read_number = |name| {
+ std::fs::read_to_string(path.join(name))
+ .ok()?
+ .trim()
+ .parse::()
+ .ok()
+ };
+ if let (Some(limit), Some(used)) =
+ (read_number("memory.max"), read_number("memory.current"))
+ {
+ memory.total = memory.total.min(limit);
+ memory.available = memory.available.min(limit.saturating_sub(used));
+ }
+ if !path.pop() {
+ break;
+ }
+ }
+ }
+ }
+ Some(memory)
+}
+
+#[cfg(target_os = "macos")]
+pub(crate) fn read() -> Option {
+ let total = std::process::Command::new("/usr/sbin/sysctl")
+ .args(["-n", "hw.memsize", "kern.memorystatus_vm_pressure_level"])
+ .output()
+ .ok()?;
+ let pages = std::process::Command::new("/usr/bin/vm_stat")
+ .output()
+ .ok()?;
+ if !total.status.success() || !pages.status.success() {
+ return None;
+ }
+ let info = std::str::from_utf8(&total.stdout).ok()?;
+ let mut info = info.lines();
+ parse_macos(
+ info.next()?.trim().parse().ok()?,
+ std::str::from_utf8(&pages.stdout).ok()?,
+ info.next()?.trim().parse().ok()?,
+ )
+}
+
+#[cfg(any(target_os = "macos", test))]
+fn parse_macos(total: u64, text: &str, pressure: u32) -> Option {
+ let page_size = text
+ .lines()
+ .next()?
+ .split("page size of ")
+ .nth(1)?
+ .split_whitespace()
+ .next()?
+ .parse::()
+ .ok()?;
+ let pages = |key| {
+ text.lines()
+ .find_map(|line| line.strip_prefix(key))?
+ .trim()
+ .trim_end_matches('.')
+ .parse::()
+ .ok()
+ };
+ // sysctl exports dispatch flags, not XNU's internal 0..4 enum:
+ // 1 = normal, 2 = warning, 4 = critical. Unknown/missing metrics grant nothing.
+ // File-backed pages are reclaimable; do not count anonymous inactive pages
+ // or compressed memory. Counting only free pages misclassifies healthy Macs.
+ let available = match pressure {
+ 1 => pages("Pages free:")?
+ .checked_add(pages("File-backed pages:")?)?
+ .checked_mul(page_size)?
+ .min(total),
+ 2 | 4 => 0,
+ _ => return None,
+ };
+ Some(MemoryHeadroom { total, available })
+}
+
+#[cfg(target_os = "windows")]
+pub(crate) fn read() -> Option {
+ use windows::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
+ let mut status = MEMORYSTATUSEX {
+ dwLength: std::mem::size_of::() as u32,
+ ..Default::default()
+ };
+ unsafe { GlobalMemoryStatusEx(&mut status) }.ok()?;
+ Some(MemoryHeadroom {
+ total: status.ullTotalPhys,
+ available: status.ullAvailPhys,
+ })
+}
+
+#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
+pub(crate) fn read() -> Option {
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn macos_counts_reclaimable_files_but_honors_real_pressure() {
+ let text = "Mach Virtual Memory Statistics: (page size of 16384 bytes)\nPages free: 4058.\nPages inactive: 161060.\nFile-backed pages: 119431.\nPages occupied by compressor: 97493.\n";
+ let m = super::parse_macos(8 << 30, text, 1).unwrap();
+ assert_eq!(m.available, (4058 + 119431) * 16384);
+ assert_eq!(super::parse_macos(8 << 30, text, 2).unwrap().available, 0);
+ assert_eq!(super::parse_macos(8 << 30, text, 4).unwrap().available, 0);
+ assert!(super::parse_macos(8 << 30, text, 0).is_none());
+ assert!(super::parse_macos(8 << 30, "unavailable", 1).is_none());
+ }
+}
diff --git a/crates/qbz-cache/src/playback_cache.rs b/crates/qbz-cache/src/playback_cache.rs
index 00a4149ab..990910b0c 100644
--- a/crates/qbz-cache/src/playback_cache.rs
+++ b/crates/qbz-cache/src/playback_cache.rs
@@ -33,6 +33,8 @@ struct PlaybackCacheState {
/// Files are named `{track_id}.audio` in the cache directory.
pub struct PlaybackCache {
state: Mutex,
+ // Serialize admission with eviction so parallel oversized streams respect L2.
+ writes: Mutex<()>,
/// Cache directory path
cache_dir: PathBuf,
/// Maximum cache size in bytes
@@ -59,6 +61,7 @@ impl PlaybackCache {
.map_err(|e| format!("Failed to create playback cache directory: {}", e))?;
let cache = Self {
+ writes: Mutex::new(()),
state: Mutex::new(PlaybackCacheState {
entries: HashMap::new(),
current_size: 0,
@@ -131,6 +134,23 @@ impl PlaybackCache {
self.state.lock().unwrap().entries.contains_key(&track_id)
}
+ /// Open an immutable cache entry without allocating its contents. Cache
+ /// replacement is atomic so active decoder handles keep the original file.
+ pub fn open(&self, track_id: u64) -> Option {
+ let file = fs::File::open(self.track_path(track_id)).ok()?;
+ let mut state = self.state.lock().ok()?;
+ if let Some(entry) = state.entries.get_mut(&track_id) {
+ entry.last_accessed = SystemTime::now();
+ }
+ Some(file)
+ }
+
+ /// Temporary playback spools live on the cache disk, never the system /tmp
+ /// (commonly tmpfs on streamers). They disappear with their last file handle.
+ pub fn create_spool(&self) -> std::io::Result {
+ tempfile::tempfile_in(&self.cache_dir)
+ }
+
/// Get a track from the cache
pub fn get(&self, track_id: u64) -> Option> {
let path = self.track_path(track_id);
@@ -181,7 +201,8 @@ impl PlaybackCache {
}
/// Insert a track into the cache (called when evicting from memory cache)
- pub fn insert(&self, track_id: u64, data: &[u8]) {
+ pub fn insert(&self, track_id: u64, data: &[u8]) -> bool {
+ let _write = self.writes.lock().unwrap();
let size = data.len() as u64;
// Don't cache if larger than max size
@@ -192,18 +213,27 @@ impl PlaybackCache {
size / (1024 * 1024),
self.max_size_bytes / (1024 * 1024)
);
- return;
+ return false;
}
// Evict old entries if needed
self.evict_if_needed(size);
let path = self.track_path(track_id);
+ let pending = path.with_extension(format!("audio.{}.tmp", std::process::id()));
// Write file
- match fs::File::create(&path) {
+ match fs::File::create(&pending) {
Ok(mut file) => {
if file.write_all(data).is_ok() {
+ drop(file);
+ if let Err(error) = fs::rename(&pending, &path) {
+ log::warn!(
+ "Failed to publish playback cache file for track {track_id}: {error}"
+ );
+ let _ = fs::remove_file(&pending);
+ return false;
+ }
let mut state = self.state.lock().unwrap();
// Remove old entry if exists
@@ -229,9 +259,10 @@ impl PlaybackCache {
state.current_size / (1024 * 1024),
self.max_size_bytes / (1024 * 1024)
);
+ return true;
} else {
log::warn!("Failed to write playback cache file for track {}", track_id);
- let _ = fs::remove_file(&path);
+ let _ = fs::remove_file(&pending);
}
}
Err(e) => {
@@ -242,6 +273,7 @@ impl PlaybackCache {
);
}
}
+ false
}
/// Insert a track whose bytes are streamed in by `fill` rather than
@@ -253,70 +285,54 @@ impl PlaybackCache {
/// `size_hint` is the expected byte count: it drives the too-large
/// rejection and pre-write eviction; the entry records the actual bytes
/// written.
- pub fn insert_from(&self, track_id: u64, size_hint: u64, fill: F)
+ pub fn insert_from(&self, track_id: u64, size_hint: u64, fill: F) -> bool
where
F: FnOnce(&mut fs::File) -> std::io::Result,
{
- // Don't cache if larger than max size
+ let _write = self.writes.lock().unwrap();
if size_hint > self.max_size_bytes {
- log::debug!(
- "Track {} too large for playback cache ({} MB > {} MB)",
- track_id,
- size_hint / (1024 * 1024),
- self.max_size_bytes / (1024 * 1024)
- );
- return;
+ return false;
}
-
- // Evict old entries if needed
- self.evict_if_needed(size_hint);
-
- let path = self.track_path(track_id);
-
- match fs::File::create(&path) {
- Ok(mut file) => match fill(&mut file) {
- Ok(written) => {
- let size = written as u64;
- let mut state = self.state.lock().unwrap();
-
- // Remove old entry if exists
- if let Some(old) = state.entries.remove(&track_id) {
- state.current_size = state.current_size.saturating_sub(old.size_bytes);
- }
-
- state.entries.insert(
- track_id,
- CacheEntry {
- track_id,
- size_bytes: size,
- last_accessed: SystemTime::now(),
- },
- );
- state.current_size += size;
-
- log::info!(
- "Saved track {} to playback cache ({} KB). Total: {} MB / {} MB",
- track_id,
- size / 1024,
- state.current_size / (1024 * 1024),
- self.max_size_bytes / (1024 * 1024)
- );
+ // Build a separate inode. Replacing a cached id must not truncate the
+ // open file of an active decoder, and failed writes must not publish.
+ let pending = self
+ .cache_dir
+ .join(format!("{track_id}.stream.{}.tmp", std::process::id()));
+ let result = (|| -> std::io::Result {
+ let mut file = fs::File::create(&pending)?;
+ let written = fill(&mut file)? as u64;
+ if written > self.max_size_bytes || file.metadata()?.len() != written {
+ return Err(std::io::Error::other(
+ "invalid playback cache streamed size",
+ ));
+ }
+ drop(file);
+ self.evict_if_needed(written);
+ fs::rename(&pending, self.track_path(track_id))?;
+ Ok(written)
+ })();
+ match result {
+ Ok(size) => {
+ let mut state = self.state.lock().unwrap();
+ if let Some(old) = state.entries.remove(&track_id) {
+ state.current_size = state.current_size.saturating_sub(old.size_bytes);
}
- Err(e) => {
- log::warn!(
- "Failed to stream playback cache file for track {}: {}",
- track_id,
- e
- );
- let _ = fs::remove_file(&path);
- }
- },
- Err(e) => {
- log::warn!(
- "Failed to create playback cache file for track {}: {}",
+ state.entries.insert(
track_id,
- e
+ CacheEntry {
+ track_id,
+ size_bytes: size,
+ last_accessed: SystemTime::now(),
+ },
);
+ state.current_size += size;
+ log::info!("Saved track {track_id} to playback disk cache ({size} bytes)");
+ true
+ }
+ Err(error) => {
+ let _ = fs::remove_file(&pending);
+ log::warn!("Failed to stream playback cache track {track_id}: {error}");
+ false
}
}
}
@@ -357,6 +373,7 @@ impl PlaybackCache {
/// Clear the entire cache
pub fn clear(&self) {
+ let _write = self.writes.lock().unwrap();
let mut state = self.state.lock().unwrap();
for track_id in state.entries.keys() {
@@ -393,3 +410,50 @@ pub struct PlaybackCacheStats {
pub current_size_bytes: u64,
pub max_size_bytes: u64,
}
+
+#[cfg(test)]
+mod disk_reader_tests {
+ use super::*;
+
+ #[test]
+ fn open_reader_survives_replacement_and_eviction() {
+ let temp = tempfile::tempdir().unwrap();
+ let cache = PlaybackCache::with_path(temp.path().into(), 1024).unwrap();
+ assert!(cache.insert(1, b"original bytes"));
+ let mut original = cache.open(1).unwrap();
+ assert!(cache.insert_from(1, 11, |file| {
+ file.write_all(b"replacement")?;
+ Ok(11)
+ }));
+ assert_eq!(cache.get(1).unwrap(), b"replacement");
+ cache.clear();
+ let mut bytes = Vec::new();
+ original.read_to_end(&mut bytes).unwrap();
+ assert_eq!(bytes, b"original bytes");
+ }
+
+ #[test]
+ fn failed_stream_write_does_not_publish_or_damage_existing_track() {
+ let temp = tempfile::tempdir().unwrap();
+ let cache = PlaybackCache::with_path(temp.path().into(), 1024).unwrap();
+ assert!(cache.insert(1, b"original"));
+ assert!(!cache.insert_from(1, 10, |file| {
+ file.write_all(b"partial")?;
+ Err(std::io::Error::other("fixture disk failure"))
+ }));
+ assert_eq!(cache.get(1).unwrap(), b"original");
+ assert_eq!(fs::read_dir(temp.path()).unwrap().count(), 1);
+ }
+
+ #[test]
+ fn understated_stream_size_cannot_exceed_disk_budget() {
+ let temp = tempfile::tempdir().unwrap();
+ let cache = PlaybackCache::with_path(temp.path().into(), 8).unwrap();
+ assert!(!cache.insert_from(1, 1, |file| {
+ file.write_all(&[0; 9])?;
+ Ok(9)
+ }));
+ assert!(cache.open(1).is_none());
+ assert_eq!(fs::read_dir(temp.path()).unwrap().count(), 0);
+ }
+}
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 73a24fad9..f49479b72 100644
--- a/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po
+++ b/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po
@@ -7249,3 +7249,241 @@ msgstr "System / manuell"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Update bereit. Schließe QBZ, um die Installation abzuschließen. QBZ wird automatisch wieder geöffnet."
+
+#. Playback memory cache policy (#774).
+msgid "PLAYBACK CACHE"
+msgstr "WIEDERGABECACHE"
+
+#. Playback memory cache policy (#774).
+msgid "Grow cache when memory is available"
+msgstr "Cache bei verfügbarem Speicher vergrößern"
+
+#. Playback memory cache policy (#774).
+msgid "Optional; recommended for long Hi-Res tracks. The fixed budget remains the recommended default."
+msgstr "Optional; für lange Hi-Res-Titel empfohlen. Das feste Budget bleibt die empfohlene Standardeinstellung."
+
+#. Playback memory cache policy (#774).
+msgid "Minimum cache budget (MiB)"
+msgstr "Minimales Cache-Budget (MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Base budget, not reserved RAM. Memory pressure can reduce it. Leave blank for the recommended value."
+msgstr "Basisbudget ohne RAM-Reservierung. Bei Speicherdruck kann es sinken. Leer lassen für den empfohlenen Wert."
+
+#. Playback memory cache policy (#774).
+msgid "Maximum cache budget (MiB)"
+msgstr "Maximales Cache-Budget (MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Growth ceiling; available memory may impose a lower limit. Leave blank for automatic."
+msgstr "Wachstumsgrenze; verfügbarer Speicher kann sie weiter begrenzen. Leer lassen für Automatik."
+
+#. Playback memory cache policy (#774).
+msgid "Memory cache usage"
+msgstr "Speichercache-Nutzung"
+
+#. Playback memory cache policy (#774).
+msgid "Used / current budget: %1 / %2 MiB. This excludes decoder memory and offline downloads."
+msgstr "Belegt / aktuelles Budget: %1 / %2 MiB. Ohne Decoder-Speicher und Offline-Downloads."
+
+#. Playback memory cache policy (#774).
+msgid "Recommended cache defaults"
+msgstr "Empfohlene Cache-Standardwerte"
+
+#. Playback memory cache policy (#774).
+msgid "Restore defaults"
+msgstr "Standardwerte wiederherstellen"
+
+#. Playback memory cache policy (#774).
+msgid "Playback cache limits must be between 16 and 16384 MiB"
+msgstr "Die Wiedergabecache-Limits müssen zwischen 16 und 16384 MiB liegen"
+
+#. Playback memory cache policy (#774).
+msgid "Minimum playback cache budget must not exceed its maximum"
+msgstr "Das minimale Wiedergabecache-Budget darf das Maximum nicht überschreiten"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory profile"
+msgstr "Speicherprofil für die Wiedergabe"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto — recommended"
+msgstr "Auto — empfohlen"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High — dynamic"
+msgstr "High — dynamisch"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop"
+msgstr "Desktop"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low — Pi style"
+msgstr "Low — Pi-Stil"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto selects Desktop or Low from the computer's RAM. Fixed cache budget; dynamic growth is off. Recommended default."
+msgstr "Auto wählt Desktop oder Low anhand des Arbeitsspeichers. Festes Cache-Budget ohne dynamisches Wachstum. Empfohlene Standardeinstellung."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High starts with a 400 MiB cache budget and grows up to 1600 MiB when memory is available. It shrinks after inactivity or memory pressure. For long Hi-Res tracks and computers with spare RAM."
+msgstr "High beginnt mit einem Cache-Budget von 400 MiB und wächst bei verfügbarem Speicher auf bis zu 1600 MiB. Bei Inaktivität oder Speicherdruck wird es reduziert. Für lange Hi-Res-Titel und Rechner mit freiem RAM."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop uses a fixed 400 MiB cache budget and normal prefetch. Larger tracks use disk-backed buffers."
+msgstr "Desktop verwendet ein festes Cache-Budget von 400 MiB und normales Vorladen. Größere Titel verwenden dateigestützte Puffer."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low uses a 50 MiB cache budget, smaller startup buffers and reduced prefetch. Large tracks use disk; speculative Hi-Res prefetch is skipped. Useful on Raspberry Pi or when saving RAM."
+msgstr "Low verwendet ein Cache-Budget von 50 MiB, kleinere Startpuffer und weniger Vorladen. Große Titel nutzen die Festplatte; vorausschauendes Hi-Res-Vorladen entfällt. Für Raspberry Pi oder zum Sparen von RAM."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Custom uses your cache limits and growth preference below. Prefetch follows the computer's detected memory class. Editing a preset switches to Custom."
+msgstr "Benutzerdefiniert verwendet die unten eingestellten Cache-Grenzen und Wachstumsoptionen. Das Vorladen folgt der erkannten Speicherklasse. Änderungen an einer Vorgabe wechseln zu Benutzerdefiniert."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Same audio quality in every profile"
+msgstr "Gleiche Audioqualität in jedem Profil"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Profiles control playback memory, not audio quality or the whole app's RAM. Disk cache stays enabled unless Streaming only is on. Changes apply to new buffers; the current track continues."
+msgstr "Profile steuern den Wiedergabespeicher, nicht die Audioqualität oder den gesamten RAM der App. Der Festplatten-Cache bleibt außer bei Nur Streaming aktiv. Änderungen gelten für neue Puffer; der aktuelle Titel läuft weiter."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Allow the cache to grow within your maximum when RAM is available. High enables this automatically. Editing this option switches to Custom."
+msgstr "Der Cache darf bei freiem RAM bis zum festgelegten Maximum wachsen. High aktiviert dies automatisch. Änderungen wechseln zu Benutzerdefiniert."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Unknown playback memory profile"
+msgstr "Unbekanntes Wiedergabespeicherprofil"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory preset conflicts with custom cache limits"
+msgstr "Das Wiedergabespeicherprofil widerspricht den benutzerdefinierten Cache-Grenzen"
+
+msgid "Apply playback memory profile?"
+msgstr "Wiedergabe-Speicherprofil anwenden?"
+
+msgid "Playback buffers will be released. If playing, the current track will stop and restart from the beginning. If paused, it will stay stopped at 0:00. Your queue and disk cache will be kept."
+msgstr "Die Wiedergabepuffer werden freigegeben. Bei laufender Wiedergabe wird der aktuelle Titel gestoppt und von Anfang an neu gestartet. Bei pausierter Wiedergabe bleibt er bei 0:00 gestoppt. Warteschlange und Festplatten-Cache bleiben erhalten."
+
+msgid "Apply & free memory"
+msgstr "Anwenden & Speicher freigeben"
+
+msgid "Rebuild playback buffers"
+msgstr "Wiedergabepuffer neu aufbauen"
+
+msgid "The profile already applies to new buffers. Apply now to release existing playback buffers and the memory cache. Memory use can grow again as playback continues."
+msgstr "Das Profil gilt bereits für neue Puffer. Jetzt anwenden, um bestehende Wiedergabepuffer und den Speicher-Cache freizugeben. Während der weiteren Wiedergabe kann die Speichernutzung wieder steigen."
+
+msgid "Playback memory can only be applied to local playback."
+msgstr "Das Speicherprofil kann nur auf die Wiedergabe auf diesem Gerät angewendet werden."
+
+msgid "Playback is not ready yet."
+msgstr "Die Wiedergabe ist noch nicht bereit."
+
+msgid "Playback is busy. Try applying the memory profile again."
+msgstr "Die Wiedergabe ist beschäftigt. Versuche erneut, das Speicherprofil anzuwenden."
+
+msgid "Playback changed. Apply again to confirm the current track."
+msgstr "Die Wiedergabe hat sich geändert. Erneut anwenden, um den aktuellen Titel zu bestätigen."
+
+msgid "Visual resource profile"
+msgstr "Profil für Grafikressourcen"
+
+msgid "Low uses the Small player, compact headers, no dynamic background, header gradient, spectrum, animated play indicator, sidebar collages or optional track artwork. Default restores these visual defaults. Editing a managed option selects Custom. Audio quality and playback memory are independent."
+msgstr "Low nutzt den kleinen Player und kompakte Kopfbereiche; dynamischer Hintergrund, Kopfverlauf, Spektrum, animierte Wiedergabeanzeige, Collagen und optionale Titelbilder sind aus. Default stellt diese Standardwerte wieder her. Änderungen wählen Custom. Audioqualität und Wiedergabespeicher sind unabhängig."
+
+msgid "Compare memory profiles"
+msgstr "Speicherprofile vergleichen"
+
+msgid "Auto: fixed 400 MiB or 50 MiB according to the computer's RAM; disk handles larger tracks."
+msgstr "Auto: feste 400 MiB oder 50 MiB je nach RAM; größere Titel nutzen die Festplatte."
+
+msgid "High: dynamic 400–1600 MiB; more room in RAM for large tracks, with less need for disk-backed buffers."
+msgstr "High: dynamische 400–1600 MiB; mehr RAM für große Titel, weniger Bedarf an dateibasierten Puffern."
+
+msgid "Desktop: fixed 400 MiB; balances RAM use with disk-backed playback for larger tracks."
+msgstr "Desktop: feste 400 MiB; gleicht RAM-Nutzung und dateibasierte Wiedergabe größerer Titel aus."
+
+msgid "Low: fixed 50 MiB and reduced prefetch; lower RAM use, with more disk reads and writes for large tracks."
+msgstr "Low: feste 50 MiB und weniger Vorladen; weniger RAM, dafür mehr Festplattenzugriffe bei großen Titeln."
+
+msgid "Custom: your RAM limits and growth preference determine when playback needs disk storage."
+msgstr "Custom: deine RAM-Grenzen und Wachstumseinstellung bestimmen, wann Festplattenspeicher benötigt wird."
+
+msgid "RAM and storage trade-off"
+msgstr "RAM und Speicher abwägen"
+
+msgid "All profiles preserve audio quality and can use disk cache. Lower memory budgets rely more on storage speed and writes; more RAM can reduce that work. Cached disk tracks are read from disk even in High. Choose storage appropriate for your listening workload."
+msgstr "Alle Profile behalten die Audioqualität und können den Festplatten-Cache nutzen. Weniger RAM bedeutet mehr Abhängigkeit von Speichergeschwindigkeit und Schreibzugriffen; mehr RAM kann diese verringern. Bereits auf Festplatte gespeicherte Titel werden auch in High von dort gelesen. Wähle einen passenden Datenträger."
+
+msgid "Playback storage folder"
+msgstr "Ordner für Wiedergabespeicher"
+
+msgid "Choose an existing folder on the drive you want to use. QBZ stores its playback cache and temporary track buffers in a qbz-playback subfolder. Offline downloads are separate. Leave blank for the default location."
+msgstr "Wähle einen vorhandenen Ordner auf dem gewünschten Laufwerk. QBZ speichert Wiedergabe-Cache und temporäre Titelpuffer im Unterordner qbz-playback. Offline-Downloads sind getrennt. Leer lassen für den Standardpfad."
+
+msgid "Current playback storage"
+msgstr "Aktueller Wiedergabespeicher"
+
+msgid "Changing the folder takes effect after restarting QBZ. Existing cache files stay in the old location; they are not moved or deleted automatically."
+msgstr "Der neue Ordner wird nach einem Neustart von QBZ verwendet. Vorhandene Cache-Dateien bleiben am alten Ort; sie werden nicht automatisch verschoben oder gelöscht."
+
+msgid "Could not use this playback storage folder:"
+msgstr "Dieser Wiedergabeordner konnte nicht verwendet werden:"
+
+msgid "Folder access"
+msgstr "Ordnerzugriff"
+
+msgid "If the sandbox blocks this folder, run the command below in a host terminal, restart QBZ, then select the folder again. Only grant access to a folder you intend to use."
+msgstr "Falls die Sandbox den Ordner blockiert, führe den folgenden Befehl in einem Terminal des Hostsystems aus, starte QBZ neu und wähle den Ordner erneut. Erlaube nur Zugriff auf den gewünschten Ordner."
+
+msgid "Snap can access supported home folders and removable storage under /mnt, /media or /run/media. For removable storage, connect the interface below and retry. Snap cannot grant arbitrary folder access with a Flatpak-style override."
+msgstr "Snap kann auf unterstützte persönliche Ordner und Wechselmedien unter /mnt, /media oder /run/media zugreifen. Verbinde dafür die unten angegebene Schnittstelle und versuche es erneut. Beliebige Ordner lassen sich nicht wie bei Flatpak per Override freigeben."
+
+msgid "Choose an absolute folder path for playback storage."
+msgstr "Wähle einen absoluten Ordnerpfad für den Wiedergabespeicher."
+
+msgid "The folder is accessible and visible in the library."
+msgstr "Der Ordner ist zugänglich und in der Bibliothek sichtbar."
+
+msgid "The folder is accessible but hidden by your preference."
+msgstr "Der Ordner ist zugänglich, wurde aber von dir ausgeblendet."
+
+msgid "The folder path no longer exists. Reconnect it, change its path or remove it from the library."
+msgstr "Der Ordnerpfad existiert nicht mehr. Verbinde ihn erneut, ändere den Pfad oder entferne ihn aus der Bibliothek."
+
+msgid "A connection failure prevents access to this storage."
+msgstr "Ein Verbindungsfehler verhindert den Zugriff auf diesen Speicher."
+
+msgid "QBZ does not have permission to access this folder."
+msgstr "QBZ hat keine Berechtigung, auf diesen Ordner zuzugreifen."
+
+msgid "The folder could not be accessed. The check timed out or returned another access error."
+msgstr "Auf den Ordner konnte nicht zugegriffen werden. Die Prüfung dauerte zu lange oder meldete einen anderen Zugriffsfehler."
+
+msgid "Folder access is being checked or has not been checked yet."
+msgstr "Der Ordnerzugriff wird geprüft oder wurde noch nicht geprüft."
+
+msgid "Local folder"
+msgstr "Lokaler Ordner"
+
+msgid "Access denied"
+msgstr "Zugriff verweigert"
+
+msgid "Missing"
+msgstr "Fehlend"
+
+msgid "Actions"
+msgstr "Aktionen"
+
+msgid "Low"
+msgstr "Niedrig"
+
+msgid "These options do not apply while Streaming only is enabled. Turn it off to choose a playback memory profile and apply changes."
+msgstr "Diese Optionen gelten nicht, solange Nur Streaming aktiviert ist. Deaktiviere es, um ein Wiedergabespeicherprofil auszuwählen und Änderungen anzuwenden."
+
+msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay."
+msgstr "Entspricht dem Streaming-Verhalten der offiziellen Clients bei geringerem Speicherbedarf. Umgeht den Wiedergabe-Cache und seinen Schutz vor Netzwerkunterbrechungen: Der QBZ-Cache hält kommende Audiodaten für zuverlässigere Wiedergabe und sofortiges erneutes Abspielen bereit."
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 17ffe71f0..8acd13af6 100644
--- a/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po
+++ b/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po
@@ -2849,3 +2849,267 @@ msgstr "System / manual"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Update ready. Close QBZ to finish installation. It will reopen automatically."
+
+#. Playback memory cache policy (#774).
+msgid "PLAYBACK CACHE"
+msgstr "PLAYBACK CACHE"
+
+#. Playback memory cache policy (#774).
+msgid "Grow cache when memory is available"
+msgstr "Grow cache when memory is available"
+
+#. Playback memory cache policy (#774).
+msgid "Optional; recommended for long Hi-Res tracks. The fixed budget remains the recommended default."
+msgstr "Optional; recommended for long Hi-Res tracks. The fixed budget remains the recommended default."
+
+#. Playback memory cache policy (#774).
+msgid "Minimum cache budget (MiB)"
+msgstr "Minimum cache budget (MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Base budget, not reserved RAM. Memory pressure can reduce it. Leave blank for the recommended value."
+msgstr "Base budget, not reserved RAM. Memory pressure can reduce it. Leave blank for the recommended value."
+
+#. Playback memory cache policy (#774).
+msgid "Maximum cache budget (MiB)"
+msgstr "Maximum cache budget (MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Growth ceiling; available memory may impose a lower limit. Leave blank for automatic."
+msgstr "Growth ceiling; available memory may impose a lower limit. Leave blank for automatic."
+
+#. Playback memory cache policy (#774).
+msgid "Memory cache usage"
+msgstr "Memory cache usage"
+
+#. Playback memory cache policy (#774).
+msgid "Used / current budget: %1 / %2 MiB. This excludes decoder memory and offline downloads."
+msgstr "Used / current budget: %1 / %2 MiB. This excludes decoder memory and offline downloads."
+
+#. Playback memory cache policy (#774).
+msgid "Recommended cache defaults"
+msgstr "Recommended cache defaults"
+
+#. Playback memory cache policy (#774).
+msgid "Restore defaults"
+msgstr "Restore defaults"
+
+#. Playback memory cache policy (#774).
+msgid "Refresh"
+msgstr "Refresh"
+
+#. Playback memory cache policy (#774).
+msgid "Playback cache limits must be between 16 and 16384 MiB"
+msgstr "Playback cache limits must be between 16 and 16384 MiB"
+
+#. Playback memory cache policy (#774).
+msgid "Minimum playback cache budget must not exceed its maximum"
+msgstr "Minimum playback cache budget must not exceed its maximum"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory profile"
+msgstr "Playback memory profile"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto — recommended"
+msgstr "Auto — recommended"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High — dynamic"
+msgstr "High — dynamic"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop"
+msgstr "Desktop"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low — Pi style"
+msgstr "Low — Pi style"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Custom"
+msgstr "Custom"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto selects Desktop or Low from the computer's RAM. Fixed cache budget; dynamic growth is off. Recommended default."
+msgstr "Auto selects Desktop or Low from the computer's RAM. Fixed cache budget; dynamic growth is off. Recommended default."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High starts with a 400 MiB cache budget and grows up to 1600 MiB when memory is available. It shrinks after inactivity or memory pressure. For long Hi-Res tracks and computers with spare RAM."
+msgstr "High starts with a 400 MiB cache budget and grows up to 1600 MiB when memory is available. It shrinks after inactivity or memory pressure. For long Hi-Res tracks and computers with spare RAM."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop uses a fixed 400 MiB cache budget and normal prefetch. Larger tracks use disk-backed buffers."
+msgstr "Desktop uses a fixed 400 MiB cache budget and normal prefetch. Larger tracks use disk-backed buffers."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low uses a 50 MiB cache budget, smaller startup buffers and reduced prefetch. Large tracks use disk; speculative Hi-Res prefetch is skipped. Useful on Raspberry Pi or when saving RAM."
+msgstr "Low uses a 50 MiB cache budget, smaller startup buffers and reduced prefetch. Large tracks use disk; speculative Hi-Res prefetch is skipped. Useful on Raspberry Pi or when saving RAM."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Custom uses your cache limits and growth preference below. Prefetch follows the computer's detected memory class. Editing a preset switches to Custom."
+msgstr "Custom uses your cache limits and growth preference below. Prefetch follows the computer's detected memory class. Editing a preset switches to Custom."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Same audio quality in every profile"
+msgstr "Same audio quality in every profile"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Profiles control playback memory, not audio quality or the whole app's RAM. Disk cache stays enabled unless Streaming only is on. Changes apply to new buffers; the current track continues."
+msgstr "Profiles control playback memory, not audio quality or the whole app's RAM. Disk cache stays enabled unless Streaming only is on. Changes apply to new buffers; the current track continues."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Allow the cache to grow within your maximum when RAM is available. High enables this automatically. Editing this option switches to Custom."
+msgstr "Allow the cache to grow within your maximum when RAM is available. High enables this automatically. Editing this option switches to Custom."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Unknown playback memory profile"
+msgstr "Unknown playback memory profile"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory preset conflicts with custom cache limits"
+msgstr "Playback memory preset conflicts with custom cache limits"
+
+msgid "Apply playback memory profile?"
+msgstr "Apply playback memory profile?"
+
+msgid "Playback buffers will be released. If playing, the current track will stop and restart from the beginning. If paused, it will stay stopped at 0:00. Your queue and disk cache will be kept."
+msgstr "Playback buffers will be released. If playing, the current track will stop and restart from the beginning. If paused, it will stay stopped at 0:00. Your queue and disk cache will be kept."
+
+msgid "Apply & free memory"
+msgstr "Apply & free memory"
+
+msgid "Rebuild playback buffers"
+msgstr "Rebuild playback buffers"
+
+msgid "The profile already applies to new buffers. Apply now to release existing playback buffers and the memory cache. Memory use can grow again as playback continues."
+msgstr "The profile already applies to new buffers. Apply now to release existing playback buffers and the memory cache. Memory use can grow again as playback continues."
+
+msgid "Playback memory can only be applied to local playback."
+msgstr "Playback memory can only be applied to local playback."
+
+msgid "Playback is not ready yet."
+msgstr "Playback is not ready yet."
+
+msgid "Playback is busy. Try applying the memory profile again."
+msgstr "Playback is busy. Try applying the memory profile again."
+
+msgid "Playback changed. Apply again to confirm the current track."
+msgstr "Playback changed. Apply again to confirm the current track."
+
+msgid "Visual resource profile"
+msgstr "Visual resource profile"
+
+msgid "Low uses the Small player, compact headers, no dynamic background, header gradient, spectrum, animated play indicator, sidebar collages or optional track artwork. Default restores these visual defaults. Editing a managed option selects Custom. Audio quality and playback memory are independent."
+msgstr "Low uses the Small player, compact headers, no dynamic background, header gradient, spectrum, animated play indicator, sidebar collages or optional track artwork. Default restores these visual defaults. Editing a managed option selects Custom. Audio quality and playback memory are independent."
+
+msgid "Compare memory profiles"
+msgstr "Compare memory profiles"
+
+msgid "Auto: fixed 400 MiB or 50 MiB according to the computer's RAM; disk handles larger tracks."
+msgstr "Auto: fixed 400 MiB or 50 MiB according to the computer's RAM; disk handles larger tracks."
+
+msgid "High: dynamic 400–1600 MiB; more room in RAM for large tracks, with less need for disk-backed buffers."
+msgstr "High: dynamic 400–1600 MiB; more room in RAM for large tracks, with less need for disk-backed buffers."
+
+msgid "Desktop: fixed 400 MiB; balances RAM use with disk-backed playback for larger tracks."
+msgstr "Desktop: fixed 400 MiB; balances RAM use with disk-backed playback for larger tracks."
+
+msgid "Low: fixed 50 MiB and reduced prefetch; lower RAM use, with more disk reads and writes for large tracks."
+msgstr "Low: fixed 50 MiB and reduced prefetch; lower RAM use, with more disk reads and writes for large tracks."
+
+msgid "Custom: your RAM limits and growth preference determine when playback needs disk storage."
+msgstr "Custom: your RAM limits and growth preference determine when playback needs disk storage."
+
+msgid "RAM and storage trade-off"
+msgstr "RAM and storage trade-off"
+
+msgid "All profiles preserve audio quality and can use disk cache. Lower memory budgets rely more on storage speed and writes; more RAM can reduce that work. Cached disk tracks are read from disk even in High. Choose storage appropriate for your listening workload."
+msgstr "All profiles preserve audio quality and can use disk cache. Lower memory budgets rely more on storage speed and writes; more RAM can reduce that work. Cached disk tracks are read from disk even in High. Choose storage appropriate for your listening workload."
+
+msgid "Playback storage folder"
+msgstr "Playback storage folder"
+
+msgid "Choose an existing folder on the drive you want to use. QBZ stores its playback cache and temporary track buffers in a qbz-playback subfolder. Offline downloads are separate. Leave blank for the default location."
+msgstr "Choose an existing folder on the drive you want to use. QBZ stores its playback cache and temporary track buffers in a qbz-playback subfolder. Offline downloads are separate. Leave blank for the default location."
+
+msgid "Current playback storage"
+msgstr "Current playback storage"
+
+msgid "Changing the folder takes effect after restarting QBZ. Existing cache files stay in the old location; they are not moved or deleted automatically."
+msgstr "Changing the folder takes effect after restarting QBZ. Existing cache files stay in the old location; they are not moved or deleted automatically."
+
+msgid "Could not use this playback storage folder:"
+msgstr "Could not use this playback storage folder:"
+
+msgid "Folder access"
+msgstr "Folder access"
+
+msgid "If the sandbox blocks this folder, run the command below in a host terminal, restart QBZ, then select the folder again. Only grant access to a folder you intend to use."
+msgstr "If the sandbox blocks this folder, run the command below in a host terminal, restart QBZ, then select the folder again. Only grant access to a folder you intend to use."
+
+msgid "Snap can access supported home folders and removable storage under /mnt, /media or /run/media. For removable storage, connect the interface below and retry. Snap cannot grant arbitrary folder access with a Flatpak-style override."
+msgstr "Snap can access supported home folders and removable storage under /mnt, /media or /run/media. For removable storage, connect the interface below and retry. Snap cannot grant arbitrary folder access with a Flatpak-style override."
+
+msgid "Choose an absolute folder path for playback storage."
+msgstr "Choose an absolute folder path for playback storage."
+
+msgid "The folder is accessible and visible in the library."
+msgstr "The folder is accessible and visible in the library."
+
+msgid "The folder is accessible but hidden by your preference."
+msgstr "The folder is accessible but hidden by your preference."
+
+msgid "The folder path no longer exists. Reconnect it, change its path or remove it from the library."
+msgstr "The folder path no longer exists. Reconnect it, change its path or remove it from the library."
+
+msgid "A connection failure prevents access to this storage."
+msgstr "A connection failure prevents access to this storage."
+
+msgid "QBZ does not have permission to access this folder."
+msgstr "QBZ does not have permission to access this folder."
+
+msgid "The folder could not be accessed. The check timed out or returned another access error."
+msgstr "The folder could not be accessed. The check timed out or returned another access error."
+
+msgid "Folder access is being checked or has not been checked yet."
+msgstr "Folder access is being checked or has not been checked yet."
+
+msgid "Local folder"
+msgstr "Local folder"
+
+msgid "Network folder"
+msgstr "Network folder"
+
+msgid "Access denied"
+msgstr "Access denied"
+
+msgid "Missing"
+msgstr "Missing"
+
+msgid "Disconnected"
+msgstr "Disconnected"
+
+msgid "Hidden"
+msgstr "Hidden"
+
+msgid "Active"
+msgstr "Active"
+
+msgid "Unavailable"
+msgstr "Unavailable"
+
+msgid "Checking..."
+msgstr "Checking..."
+
+msgid "Actions"
+msgstr "Actions"
+
+msgid "Low"
+msgstr "Low"
+
+msgid "These options do not apply while Streaming only is enabled. Turn it off to choose a playback memory profile and apply changes."
+msgstr "These options do not apply while Streaming only is enabled. Turn it off to choose a playback memory profile and apply changes."
+
+msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay."
+msgstr "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay."
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 917b8c3e7..e7429a328 100644
--- a/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po
+++ b/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po
@@ -7255,3 +7255,241 @@ msgstr "Sistema / manual"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Actualización lista. Cierra QBZ para terminar la instalación. Se abrirá de nuevo automáticamente."
+
+#. Playback memory cache policy (#774).
+msgid "PLAYBACK CACHE"
+msgstr "CACHÉ DE REPRODUCCIÓN"
+
+#. Playback memory cache policy (#774).
+msgid "Grow cache when memory is available"
+msgstr "Ampliar la caché cuando haya memoria disponible"
+
+#. Playback memory cache policy (#774).
+msgid "Optional; recommended for long Hi-Res tracks. The fixed budget remains the recommended default."
+msgstr "Opcional; recomendado para pistas largas en Hi-Res. El presupuesto fijo sigue siendo el valor predeterminado recomendado."
+
+#. Playback memory cache policy (#774).
+msgid "Minimum cache budget (MiB)"
+msgstr "Presupuesto mínimo de caché (MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Base budget, not reserved RAM. Memory pressure can reduce it. Leave blank for the recommended value."
+msgstr "Presupuesto base, sin reservar RAM. Puede reducirse si falta memoria. Deja vacío para usar el valor recomendado."
+
+#. Playback memory cache policy (#774).
+msgid "Maximum cache budget (MiB)"
+msgstr "Presupuesto máximo de caché (MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Growth ceiling; available memory may impose a lower limit. Leave blank for automatic."
+msgstr "Tope de crecimiento; la memoria disponible puede imponer un límite menor. Deja vacío para usar el valor automático."
+
+#. Playback memory cache policy (#774).
+msgid "Memory cache usage"
+msgstr "Uso de caché en memoria"
+
+#. Playback memory cache policy (#774).
+msgid "Used / current budget: %1 / %2 MiB. This excludes decoder memory and offline downloads."
+msgstr "Uso / presupuesto actual: %1 / %2 MiB. Excluye la memoria del decodificador y las descargas offline."
+
+#. Playback memory cache policy (#774).
+msgid "Recommended cache defaults"
+msgstr "Valores recomendados de caché"
+
+#. Playback memory cache policy (#774).
+msgid "Restore defaults"
+msgstr "Restaurar valores predeterminados"
+
+#. Playback memory cache policy (#774).
+msgid "Playback cache limits must be between 16 and 16384 MiB"
+msgstr "Los límites de caché de reproducción deben estar entre 16 y 16384 MiB"
+
+#. Playback memory cache policy (#774).
+msgid "Minimum playback cache budget must not exceed its maximum"
+msgstr "El presupuesto mínimo de caché de reproducción no puede superar el máximo"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory profile"
+msgstr "Perfil de memoria de reproducción"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto — recommended"
+msgstr "Auto — recomendado"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High — dynamic"
+msgstr "High — dinámico"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop"
+msgstr "Desktop"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low — Pi style"
+msgstr "Low — estilo Pi"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto selects Desktop or Low from the computer's RAM. Fixed cache budget; dynamic growth is off. Recommended default."
+msgstr "Auto selecciona Desktop o Low según la RAM del equipo. El límite de caché es fijo y el crecimiento dinámico está desactivado. Es la opción predeterminada recomendada."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High starts with a 400 MiB cache budget and grows up to 1600 MiB when memory is available. It shrinks after inactivity or memory pressure. For long Hi-Res tracks and computers with spare RAM."
+msgstr "High parte de un límite de caché de 400 MiB y puede crecer hasta 1600 MiB cuando hay memoria disponible. Se reduce tras inactividad o presión de memoria. Para pistas Hi-Res largas y equipos con RAM de sobra."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop uses a fixed 400 MiB cache budget and normal prefetch. Larger tracks use disk-backed buffers."
+msgstr "Desktop usa un límite fijo de caché de 400 MiB y precarga normal. Las pistas más grandes usan buffers respaldados en disco."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low uses a 50 MiB cache budget, smaller startup buffers and reduced prefetch. Large tracks use disk; speculative Hi-Res prefetch is skipped. Useful on Raspberry Pi or when saving RAM."
+msgstr "Low usa un límite de caché de 50 MiB, buffers iniciales más pequeños y menos precarga. Las pistas grandes usan disco; se omite la precarga especulativa Hi-Res. Útil en Raspberry Pi o para ahorrar RAM."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Custom uses your cache limits and growth preference below. Prefetch follows the computer's detected memory class. Editing a preset switches to Custom."
+msgstr "Personalizado usa los límites de caché y la preferencia de crecimiento indicados abajo. La precarga sigue la memoria detectada del equipo. Editar un perfil cambia a Personalizado."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Same audio quality in every profile"
+msgstr "La misma calidad de audio en todos los perfiles"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Profiles control playback memory, not audio quality or the whole app's RAM. Disk cache stays enabled unless Streaming only is on. Changes apply to new buffers; the current track continues."
+msgstr "Los perfiles controlan la memoria de reproducción, no la calidad de audio ni toda la RAM de la aplicación. La caché de disco permanece activa salvo en Solo streaming. Los cambios se aplican a buffers nuevos; la pista actual continúa."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Allow the cache to grow within your maximum when RAM is available. High enables this automatically. Editing this option switches to Custom."
+msgstr "Permite que la caché crezca hasta tu máximo cuando hay RAM disponible. High lo activa automáticamente. Editar esta opción cambia a Personalizado."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Unknown playback memory profile"
+msgstr "Perfil de memoria de reproducción desconocido"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory preset conflicts with custom cache limits"
+msgstr "El perfil de memoria de reproducción entra en conflicto con los límites de caché personalizados"
+
+msgid "Apply playback memory profile?"
+msgstr "¿Aplicar el perfil de memoria de reproducción?"
+
+msgid "Playback buffers will be released. If playing, the current track will stop and restart from the beginning. If paused, it will stay stopped at 0:00. Your queue and disk cache will be kept."
+msgstr "Se liberarán los buffers de reproducción. Si hay reproducción activa, el track actual se detendrá y comenzará desde el principio. Si está pausado, quedará detenido en 0:00. Se conservarán la cola y la caché en disco."
+
+msgid "Apply & free memory"
+msgstr "Aplicar y liberar memoria"
+
+msgid "Rebuild playback buffers"
+msgstr "Reconstruir buffers de reproducción"
+
+msgid "The profile already applies to new buffers. Apply now to release existing playback buffers and the memory cache. Memory use can grow again as playback continues."
+msgstr "El perfil ya se aplica a los buffers nuevos. Aplica ahora para liberar los buffers existentes y la caché en memoria. El uso de memoria puede volver a crecer al continuar la reproducción."
+
+msgid "Playback memory can only be applied to local playback."
+msgstr "El perfil de memoria solo se puede aplicar a la reproducción en este equipo."
+
+msgid "Playback is not ready yet."
+msgstr "La reproducción aún no está lista."
+
+msgid "Playback is busy. Try applying the memory profile again."
+msgstr "La reproducción está ocupada. Intenta aplicar el perfil de memoria de nuevo."
+
+msgid "Playback changed. Apply again to confirm the current track."
+msgstr "La reproducción cambió. Vuelve a aplicar para confirmar el track actual."
+
+msgid "Visual resource profile"
+msgstr "Perfil de recursos visuales"
+
+msgid "Low uses the Small player, compact headers, no dynamic background, header gradient, spectrum, animated play indicator, sidebar collages or optional track artwork. Default restores these visual defaults. Editing a managed option selects Custom. Audio quality and playback memory are independent."
+msgstr "Low usa NPB Small y encabezados compactos; desactiva fondo dinámico, gradiente, espectro, indicador animado, collages y carátulas opcionales por track. Default restaura estos valores visuales. Editarlos cambia a Custom. La calidad de audio y la memoria de reproducción son independientes."
+
+msgid "Compare memory profiles"
+msgstr "Comparar perfiles de memoria"
+
+msgid "Auto: fixed 400 MiB or 50 MiB according to the computer's RAM; disk handles larger tracks."
+msgstr "Auto: 400 MiB o 50 MiB fijos según la RAM del equipo; las pistas mayores usan disco."
+
+msgid "High: dynamic 400–1600 MiB; more room in RAM for large tracks, with less need for disk-backed buffers."
+msgstr "High: 400–1600 MiB dinámicos; más espacio en RAM para pistas grandes y menor necesidad de buffers en disco."
+
+msgid "Desktop: fixed 400 MiB; balances RAM use with disk-backed playback for larger tracks."
+msgstr "Desktop: 400 MiB fijos; equilibra el uso de RAM con reproducción desde disco para pistas mayores."
+
+msgid "Low: fixed 50 MiB and reduced prefetch; lower RAM use, with more disk reads and writes for large tracks."
+msgstr "Low: 50 MiB fijos y menos precarga; menor uso de RAM, con más lecturas y escrituras en disco para pistas grandes."
+
+msgid "Custom: your RAM limits and growth preference determine when playback needs disk storage."
+msgstr "Custom: tus límites de RAM y el crecimiento elegido determinan cuándo se necesita almacenamiento en disco."
+
+msgid "RAM and storage trade-off"
+msgstr "Equilibrio entre RAM y almacenamiento"
+
+msgid "All profiles preserve audio quality and can use disk cache. Lower memory budgets rely more on storage speed and writes; more RAM can reduce that work. Cached disk tracks are read from disk even in High. Choose storage appropriate for your listening workload."
+msgstr "Todos los perfiles conservan la calidad y pueden usar caché en disco. Menos RAM implica mayor dependencia de la velocidad y las escrituras del almacenamiento; más RAM puede reducir ese trabajo. Las pistas ya cacheadas en disco se leen desde ahí incluso en High. Elige una unidad adecuada para tu uso."
+
+msgid "Playback storage folder"
+msgstr "Carpeta de almacenamiento de reproducción"
+
+msgid "Choose an existing folder on the drive you want to use. QBZ stores its playback cache and temporary track buffers in a qbz-playback subfolder. Offline downloads are separate. Leave blank for the default location."
+msgstr "Elige una carpeta existente en la unidad que quieras usar. QBZ guardará la caché de reproducción y los buffers temporales en la subcarpeta qbz-playback. Las descargas offline son independientes. Déjalo vacío para usar la ubicación predeterminada."
+
+msgid "Current playback storage"
+msgstr "Almacenamiento de reproducción actual"
+
+msgid "Changing the folder takes effect after restarting QBZ. Existing cache files stay in the old location; they are not moved or deleted automatically."
+msgstr "La nueva carpeta se usará después de reiniciar QBZ. Los archivos de caché existentes permanecerán en la ubicación anterior; no se moverán ni eliminarán automáticamente."
+
+msgid "Could not use this playback storage folder:"
+msgstr "No se pudo usar esta carpeta de reproducción:"
+
+msgid "Folder access"
+msgstr "Acceso a la carpeta"
+
+msgid "If the sandbox blocks this folder, run the command below in a host terminal, restart QBZ, then select the folder again. Only grant access to a folder you intend to use."
+msgstr "Si el sandbox bloquea la carpeta, ejecuta el comando de abajo en una terminal del sistema, reinicia QBZ y vuelve a seleccionarla. Da acceso solo a la carpeta que quieras usar."
+
+msgid "Snap can access supported home folders and removable storage under /mnt, /media or /run/media. For removable storage, connect the interface below and retry. Snap cannot grant arbitrary folder access with a Flatpak-style override."
+msgstr "Snap puede acceder a carpetas compatibles del directorio personal y unidades bajo /mnt, /media o /run/media. Para estas unidades, conecta la interfaz indicada y reintenta. Snap no permite dar acceso a cualquier carpeta mediante un override como Flatpak."
+
+msgid "Choose an absolute folder path for playback storage."
+msgstr "Elige una ruta absoluta para el almacenamiento de reproducción."
+
+msgid "The folder is accessible and visible in the library."
+msgstr "La carpeta es accesible y visible en la biblioteca."
+
+msgid "The folder is accessible but hidden by your preference."
+msgstr "La carpeta es accesible, pero está oculta por tu configuración."
+
+msgid "The folder path no longer exists. Reconnect it, change its path or remove it from the library."
+msgstr "La ruta ya no existe. Reconecta la carpeta, cambia su ruta o elimínala de la biblioteca."
+
+msgid "A connection failure prevents access to this storage."
+msgstr "Un fallo de conexión impide acceder a este almacenamiento."
+
+msgid "QBZ does not have permission to access this folder."
+msgstr "QBZ no tiene permisos para acceder a esta carpeta."
+
+msgid "The folder could not be accessed. The check timed out or returned another access error."
+msgstr "No se pudo acceder a la carpeta. La comprobación agotó el tiempo o devolvió otro error de acceso."
+
+msgid "Folder access is being checked or has not been checked yet."
+msgstr "Se está comprobando el acceso o la comprobación aún está pendiente."
+
+msgid "Local folder"
+msgstr "Carpeta local"
+
+msgid "Access denied"
+msgstr "Acceso denegado"
+
+msgid "Missing"
+msgstr "Ausente"
+
+msgid "Actions"
+msgstr "Acciones"
+
+msgid "Low"
+msgstr "Bajo"
+
+msgid "These options do not apply while Streaming only is enabled. Turn it off to choose a playback memory profile and apply changes."
+msgstr "Estas opciones no se aplican mientras Solo streaming esté activado. Desactívalo para elegir un perfil de memoria de reproducción y aplicar los cambios."
+
+msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay."
+msgstr "Imita el comportamiento de streaming de los clientes oficiales y usa menos memoria. Omite la caché de reproducción y su protección ante interrupciones de red: la caché de QBZ prepara el audio siguiente para una reproducción más fiable y permite volver a escuchar al instante."
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 ac8b79d6f..250571998 100644
--- a/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po
+++ b/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po
@@ -7247,3 +7247,241 @@ msgstr "Système / manuelle"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Mise à jour prête. Fermez QBZ pour terminer l’installation. Il se rouvrira automatiquement."
+
+#. Playback memory cache policy (#774).
+msgid "PLAYBACK CACHE"
+msgstr "CACHE DE LECTURE"
+
+#. Playback memory cache policy (#774).
+msgid "Grow cache when memory is available"
+msgstr "Agrandir le cache si la mémoire le permet"
+
+#. Playback memory cache policy (#774).
+msgid "Optional; recommended for long Hi-Res tracks. The fixed budget remains the recommended default."
+msgstr "Facultatif ; recommandé pour les longs titres Hi-Res. Le budget fixe reste le réglage par défaut recommandé."
+
+#. Playback memory cache policy (#774).
+msgid "Minimum cache budget (MiB)"
+msgstr "Budget minimal du cache (MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Base budget, not reserved RAM. Memory pressure can reduce it. Leave blank for the recommended value."
+msgstr "Budget de base, sans réservation de RAM. Il peut diminuer si la mémoire manque. Laisser vide pour la valeur recommandée."
+
+#. Playback memory cache policy (#774).
+msgid "Maximum cache budget (MiB)"
+msgstr "Budget maximal du cache (MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Growth ceiling; available memory may impose a lower limit. Leave blank for automatic."
+msgstr "Plafond de croissance ; la mémoire disponible peut imposer une limite inférieure. Laisser vide pour le mode automatique."
+
+#. Playback memory cache policy (#774).
+msgid "Memory cache usage"
+msgstr "Utilisation du cache mémoire"
+
+#. Playback memory cache policy (#774).
+msgid "Used / current budget: %1 / %2 MiB. This excludes decoder memory and offline downloads."
+msgstr "Utilisé / budget actuel : %1 / %2 MiB. Hors mémoire du décodeur et téléchargements hors ligne."
+
+#. Playback memory cache policy (#774).
+msgid "Recommended cache defaults"
+msgstr "Valeurs par défaut recommandées du cache"
+
+#. Playback memory cache policy (#774).
+msgid "Restore defaults"
+msgstr "Rétablir les valeurs par défaut"
+
+#. Playback memory cache policy (#774).
+msgid "Playback cache limits must be between 16 and 16384 MiB"
+msgstr "Les limites du cache de lecture doivent être comprises entre 16 et 16384 MiB"
+
+#. Playback memory cache policy (#774).
+msgid "Minimum playback cache budget must not exceed its maximum"
+msgstr "Le budget minimal du cache de lecture ne doit pas dépasser le maximum"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory profile"
+msgstr "Profil mémoire de lecture"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto — recommended"
+msgstr "Auto — recommandé"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High — dynamic"
+msgstr "High — dynamique"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop"
+msgstr "Desktop"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low — Pi style"
+msgstr "Low — style Pi"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto selects Desktop or Low from the computer's RAM. Fixed cache budget; dynamic growth is off. Recommended default."
+msgstr "Auto choisit Desktop ou Low selon la RAM de l’ordinateur. Budget de cache fixe, sans croissance dynamique. Réglage par défaut recommandé."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High starts with a 400 MiB cache budget and grows up to 1600 MiB when memory is available. It shrinks after inactivity or memory pressure. For long Hi-Res tracks and computers with spare RAM."
+msgstr "High démarre avec un budget de cache de 400 MiB et peut atteindre 1600 MiB si la mémoire est disponible. Il diminue après une période d’inactivité ou sous pression mémoire. Pour les longs morceaux Hi-Res et les ordinateurs disposant de RAM libre."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop uses a fixed 400 MiB cache budget and normal prefetch. Larger tracks use disk-backed buffers."
+msgstr "Desktop utilise un budget de cache fixe de 400 MiB et un préchargement normal. Les morceaux plus volumineux utilisent des tampons sur disque."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low uses a 50 MiB cache budget, smaller startup buffers and reduced prefetch. Large tracks use disk; speculative Hi-Res prefetch is skipped. Useful on Raspberry Pi or when saving RAM."
+msgstr "Low utilise un budget de cache de 50 MiB, des tampons de démarrage plus petits et un préchargement réduit. Les gros morceaux utilisent le disque ; le préchargement spéculatif Hi-Res est désactivé. Utile sur Raspberry Pi ou pour économiser la RAM."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Custom uses your cache limits and growth preference below. Prefetch follows the computer's detected memory class. Editing a preset switches to Custom."
+msgstr "Personnalisé utilise les limites et la préférence de croissance ci-dessous. Le préchargement suit la classe mémoire détectée. Modifier un préréglage sélectionne Personnalisé."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Same audio quality in every profile"
+msgstr "Même qualité audio dans tous les profils"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Profiles control playback memory, not audio quality or the whole app's RAM. Disk cache stays enabled unless Streaming only is on. Changes apply to new buffers; the current track continues."
+msgstr "Les profils contrôlent la mémoire de lecture, pas la qualité audio ni toute la RAM de l’application. Le cache disque reste actif sauf en mode Streaming uniquement. Les changements concernent les nouveaux tampons ; le morceau actuel continue."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Allow the cache to grow within your maximum when RAM is available. High enables this automatically. Editing this option switches to Custom."
+msgstr "Autorise la croissance du cache jusqu’au maximum choisi lorsque de la RAM est disponible. High l’active automatiquement. Modifier cette option sélectionne Personnalisé."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Unknown playback memory profile"
+msgstr "Profil mémoire de lecture inconnu"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory preset conflicts with custom cache limits"
+msgstr "Le profil mémoire de lecture entre en conflit avec les limites de cache personnalisées"
+
+msgid "Apply playback memory profile?"
+msgstr "Appliquer le profil mémoire de lecture ?"
+
+msgid "Playback buffers will be released. If playing, the current track will stop and restart from the beginning. If paused, it will stay stopped at 0:00. Your queue and disk cache will be kept."
+msgstr "Les tampons de lecture seront libérés. Si la lecture est en cours, le titre sera arrêté puis relancé depuis le début. En pause, il restera arrêté à 0:00. La file et le cache disque seront conservés."
+
+msgid "Apply & free memory"
+msgstr "Appliquer et libérer la mémoire"
+
+msgid "Rebuild playback buffers"
+msgstr "Reconstruire les tampons de lecture"
+
+msgid "The profile already applies to new buffers. Apply now to release existing playback buffers and the memory cache. Memory use can grow again as playback continues."
+msgstr "Le profil s’applique déjà aux nouveaux tampons. Appliquez-le maintenant pour libérer les tampons existants et le cache mémoire. L’utilisation de mémoire peut augmenter à nouveau pendant la lecture."
+
+msgid "Playback memory can only be applied to local playback."
+msgstr "Le profil mémoire ne peut être appliqué qu’à la lecture sur cet appareil."
+
+msgid "Playback is not ready yet."
+msgstr "La lecture n’est pas encore prête."
+
+msgid "Playback is busy. Try applying the memory profile again."
+msgstr "La lecture est occupée. Réessayez d’appliquer le profil mémoire."
+
+msgid "Playback changed. Apply again to confirm the current track."
+msgstr "La lecture a changé. Appliquez à nouveau pour confirmer le titre actuel."
+
+msgid "Visual resource profile"
+msgstr "Profil de ressources visuelles"
+
+msgid "Low uses the Small player, compact headers, no dynamic background, header gradient, spectrum, animated play indicator, sidebar collages or optional track artwork. Default restores these visual defaults. Editing a managed option selects Custom. Audio quality and playback memory are independent."
+msgstr "Low utilise le petit lecteur et des en-têtes compacts, sans fond dynamique, dégradé, spectre, indicateur animé, collages ni pochettes facultatives des titres. Default rétablit ces réglages visuels. Les modifier active Custom. Qualité audio et mémoire de lecture restent indépendantes."
+
+msgid "Compare memory profiles"
+msgstr "Comparer les profils mémoire"
+
+msgid "Auto: fixed 400 MiB or 50 MiB according to the computer's RAM; disk handles larger tracks."
+msgstr "Auto : 400 MiB ou 50 MiB fixes selon la RAM ; les titres plus volumineux utilisent le disque."
+
+msgid "High: dynamic 400–1600 MiB; more room in RAM for large tracks, with less need for disk-backed buffers."
+msgstr "High : 400–1600 MiB dynamiques ; plus de RAM pour les gros titres, moins de recours aux tampons sur disque."
+
+msgid "Desktop: fixed 400 MiB; balances RAM use with disk-backed playback for larger tracks."
+msgstr "Desktop : 400 MiB fixes ; équilibre RAM et lecture sur disque des titres plus volumineux."
+
+msgid "Low: fixed 50 MiB and reduced prefetch; lower RAM use, with more disk reads and writes for large tracks."
+msgstr "Low : 50 MiB fixes et préchargement réduit ; moins de RAM, davantage de lectures et écritures disque pour les gros titres."
+
+msgid "Custom: your RAM limits and growth preference determine when playback needs disk storage."
+msgstr "Custom : vos limites de RAM et de croissance déterminent quand la lecture utilise le disque."
+
+msgid "RAM and storage trade-off"
+msgstr "Équilibre entre RAM et stockage"
+
+msgid "All profiles preserve audio quality and can use disk cache. Lower memory budgets rely more on storage speed and writes; more RAM can reduce that work. Cached disk tracks are read from disk even in High. Choose storage appropriate for your listening workload."
+msgstr "Tous les profils préservent la qualité audio et peuvent utiliser le cache disque. Moins de RAM implique davantage de dépendance à la vitesse et aux écritures du stockage ; plus de RAM peut les réduire. Les titres déjà sur disque y sont lus même en High. Choisissez un stockage adapté à votre usage."
+
+msgid "Playback storage folder"
+msgstr "Dossier de stockage de lecture"
+
+msgid "Choose an existing folder on the drive you want to use. QBZ stores its playback cache and temporary track buffers in a qbz-playback subfolder. Offline downloads are separate. Leave blank for the default location."
+msgstr "Choisissez un dossier existant sur le disque souhaité. QBZ stocke le cache de lecture et les tampons temporaires dans le sous-dossier qbz-playback. Les téléchargements hors ligne sont séparés. Laissez vide pour le dossier par défaut."
+
+msgid "Current playback storage"
+msgstr "Stockage de lecture actuel"
+
+msgid "Changing the folder takes effect after restarting QBZ. Existing cache files stay in the old location; they are not moved or deleted automatically."
+msgstr "Le nouveau dossier sera utilisé après le redémarrage de QBZ. Les fichiers du cache restent à leur ancien emplacement ; ils ne sont ni déplacés ni supprimés automatiquement."
+
+msgid "Could not use this playback storage folder:"
+msgstr "Impossible d’utiliser ce dossier de lecture :"
+
+msgid "Folder access"
+msgstr "Accès au dossier"
+
+msgid "If the sandbox blocks this folder, run the command below in a host terminal, restart QBZ, then select the folder again. Only grant access to a folder you intend to use."
+msgstr "Si le bac à sable bloque ce dossier, exécutez la commande ci-dessous dans un terminal du système hôte, redémarrez QBZ et sélectionnez-le à nouveau. N’autorisez que le dossier souhaité."
+
+msgid "Snap can access supported home folders and removable storage under /mnt, /media or /run/media. For removable storage, connect the interface below and retry. Snap cannot grant arbitrary folder access with a Flatpak-style override."
+msgstr "Snap peut accéder aux dossiers personnels pris en charge et aux supports sous /mnt, /media ou /run/media. Connectez l’interface indiquée puis réessayez. Snap ne permet pas d’autoriser n’importe quel dossier avec un override comme Flatpak."
+
+msgid "Choose an absolute folder path for playback storage."
+msgstr "Choisissez un chemin de dossier absolu pour le stockage de lecture."
+
+msgid "The folder is accessible and visible in the library."
+msgstr "Le dossier est accessible et visible dans la bibliothèque."
+
+msgid "The folder is accessible but hidden by your preference."
+msgstr "Le dossier est accessible, mais masqué selon votre préférence."
+
+msgid "The folder path no longer exists. Reconnect it, change its path or remove it from the library."
+msgstr "Le chemin n’existe plus. Reconnectez le dossier, changez son chemin ou retirez-le de la bibliothèque."
+
+msgid "A connection failure prevents access to this storage."
+msgstr "Un échec de connexion empêche l’accès à ce stockage."
+
+msgid "QBZ does not have permission to access this folder."
+msgstr "QBZ n’a pas l’autorisation d’accéder à ce dossier."
+
+msgid "The folder could not be accessed. The check timed out or returned another access error."
+msgstr "Le dossier est inaccessible. La vérification a expiré ou a renvoyé une autre erreur d’accès."
+
+msgid "Folder access is being checked or has not been checked yet."
+msgstr "L’accès est en cours de vérification ou n’a pas encore été vérifié."
+
+msgid "Local folder"
+msgstr "Dossier local"
+
+msgid "Access denied"
+msgstr "Accès refusé"
+
+msgid "Missing"
+msgstr "Absent"
+
+msgid "Actions"
+msgstr "Actions"
+
+msgid "Low"
+msgstr "Faible"
+
+msgid "These options do not apply while Streaming only is enabled. Turn it off to choose a playback memory profile and apply changes."
+msgstr "Ces options ne s’appliquent pas lorsque Streaming uniquement est activé. Désactivez cette option pour choisir un profil mémoire de lecture et appliquer les modifications."
+
+msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay."
+msgstr "Reproduit le comportement de streaming des clients officiels en utilisant moins de mémoire. Désactive le cache de lecture et sa protection contre les interruptions réseau : le cache de QBZ prépare les prochains contenus audio pour une lecture plus fiable et une réécoute immédiate."
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 3466fdd41..b66323267 100644
--- a/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po
+++ b/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po
@@ -7230,3 +7230,241 @@ msgstr "システム / 手動"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "更新の準備ができました。QBZ を終了するとインストールが完了し、自動的に再起動します。"
+
+#. Playback memory cache policy (#774).
+msgid "PLAYBACK CACHE"
+msgstr "再生キャッシュ"
+
+#. Playback memory cache policy (#774).
+msgid "Grow cache when memory is available"
+msgstr "メモリに余裕がある場合にキャッシュを拡張"
+
+#. Playback memory cache policy (#774).
+msgid "Optional; recommended for long Hi-Res tracks. The fixed budget remains the recommended default."
+msgstr "任意設定です。長いハイレゾ曲におすすめします。通常は既定の固定容量を推奨します。"
+
+#. Playback memory cache policy (#774).
+msgid "Minimum cache budget (MiB)"
+msgstr "キャッシュの最小容量(MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Base budget, not reserved RAM. Memory pressure can reduce it. Leave blank for the recommended value."
+msgstr "RAMを予約する設定ではありません。メモリ不足時は縮小されます。空欄で推奨値を使用します。"
+
+#. Playback memory cache policy (#774).
+msgid "Maximum cache budget (MiB)"
+msgstr "キャッシュの最大容量(MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Growth ceiling; available memory may impose a lower limit. Leave blank for automatic."
+msgstr "拡張の上限です。空きメモリによってさらに制限される場合があります。空欄で自動設定になります。"
+
+#. Playback memory cache policy (#774).
+msgid "Memory cache usage"
+msgstr "メモリキャッシュの使用量"
+
+#. Playback memory cache policy (#774).
+msgid "Used / current budget: %1 / %2 MiB. This excludes decoder memory and offline downloads."
+msgstr "使用量 / 現在の容量:%1 / %2 MiB。デコーダーのメモリとオフラインダウンロードは含みません。"
+
+#. Playback memory cache policy (#774).
+msgid "Recommended cache defaults"
+msgstr "キャッシュの推奨設定"
+
+#. Playback memory cache policy (#774).
+msgid "Restore defaults"
+msgstr "既定値に戻す"
+
+#. Playback memory cache policy (#774).
+msgid "Playback cache limits must be between 16 and 16384 MiB"
+msgstr "再生キャッシュの容量は16〜16384 MiBで指定してください"
+
+#. Playback memory cache policy (#774).
+msgid "Minimum playback cache budget must not exceed its maximum"
+msgstr "再生キャッシュの最小容量は最大容量以下にしてください"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory profile"
+msgstr "再生メモリプロファイル"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto — recommended"
+msgstr "Auto — 推奨"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High — dynamic"
+msgstr "High — 動的"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop"
+msgstr "Desktop"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low — Pi style"
+msgstr "Low — Pi向け"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto selects Desktop or Low from the computer's RAM. Fixed cache budget; dynamic growth is off. Recommended default."
+msgstr "AutoはコンピューターのRAMに応じてDesktopまたはLowを選択します。キャッシュ容量は固定で、動的拡張は無効です。推奨の初期設定です。"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High starts with a 400 MiB cache budget and grows up to 1600 MiB when memory is available. It shrinks after inactivity or memory pressure. For long Hi-Res tracks and computers with spare RAM."
+msgstr "Highは400 MiBのキャッシュ容量から開始し、空きメモリがある場合に最大1600 MiBまで拡張します。非アクティブ時やメモリ不足時には縮小します。長いHi-Res曲やRAMに余裕のあるコンピューター向けです。"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop uses a fixed 400 MiB cache budget and normal prefetch. Larger tracks use disk-backed buffers."
+msgstr "Desktopは400 MiBの固定キャッシュ容量と通常の先読みを使用します。大きな曲にはディスク上のバッファを使用します。"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low uses a 50 MiB cache budget, smaller startup buffers and reduced prefetch. Large tracks use disk; speculative Hi-Res prefetch is skipped. Useful on Raspberry Pi or when saving RAM."
+msgstr "Lowは50 MiBのキャッシュ容量、小さな開始バッファ、少ない先読みを使用します。大きな曲にはディスクを使用し、Hi-Resの事前読み込みは省略します。Raspberry PiやRAMの節約に適しています。"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Custom uses your cache limits and growth preference below. Prefetch follows the computer's detected memory class. Editing a preset switches to Custom."
+msgstr "カスタムは以下のキャッシュ上限と拡張設定を使用します。先読みは検出されたメモリクラスに従います。プリセットを編集するとカスタムに切り替わります。"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Same audio quality in every profile"
+msgstr "すべてのプロファイルで同じ音質"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Profiles control playback memory, not audio quality or the whole app's RAM. Disk cache stays enabled unless Streaming only is on. Changes apply to new buffers; the current track continues."
+msgstr "プロファイルは再生メモリを制御し、音質やアプリ全体のRAMは変更しません。ストリーミングのみのモードを除き、ディスクキャッシュは有効です。変更は新しいバッファに適用され、現在の曲は再生を続けます。"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Allow the cache to grow within your maximum when RAM is available. High enables this automatically. Editing this option switches to Custom."
+msgstr "RAMに余裕がある場合、指定した上限までキャッシュを拡張します。Highでは自動的に有効になります。この設定を編集するとカスタムに切り替わります。"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Unknown playback memory profile"
+msgstr "不明な再生メモリプロファイルです"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory preset conflicts with custom cache limits"
+msgstr "再生メモリプリセットとカスタムキャッシュ上限が矛盾しています"
+
+msgid "Apply playback memory profile?"
+msgstr "再生メモリプロファイルを適用しますか?"
+
+msgid "Playback buffers will be released. If playing, the current track will stop and restart from the beginning. If paused, it will stay stopped at 0:00. Your queue and disk cache will be kept."
+msgstr "再生バッファを解放します。再生中の曲は停止し、最初から再生し直します。一時停止中の場合は、0:00で停止したままになります。キューとディスクキャッシュは保持されます。"
+
+msgid "Apply & free memory"
+msgstr "適用してメモリを解放"
+
+msgid "Rebuild playback buffers"
+msgstr "再生バッファを再構築"
+
+msgid "The profile already applies to new buffers. Apply now to release existing playback buffers and the memory cache. Memory use can grow again as playback continues."
+msgstr "プロファイルはすでに新しいバッファに適用されています。今すぐ適用すると、既存の再生バッファとメモリキャッシュを解放します。再生を続けると、メモリ使用量が再び増えることがあります。"
+
+msgid "Playback memory can only be applied to local playback."
+msgstr "メモリプロファイルは、このデバイスでの再生にのみ適用できます。"
+
+msgid "Playback is not ready yet."
+msgstr "再生の準備がまだできていません。"
+
+msgid "Playback is busy. Try applying the memory profile again."
+msgstr "再生処理が進行中です。メモリプロファイルの適用をもう一度お試しください。"
+
+msgid "Playback changed. Apply again to confirm the current track."
+msgstr "再生内容が変わりました。現在の曲を確認して、もう一度適用してください。"
+
+msgid "Visual resource profile"
+msgstr "表示リソースプロファイル"
+
+msgid "Low uses the Small player, compact headers, no dynamic background, header gradient, spectrum, animated play indicator, sidebar collages or optional track artwork. Default restores these visual defaults. Editing a managed option selects Custom. Audio quality and playback memory are independent."
+msgstr "Lowは小型プレーヤーとコンパクトなヘッダーを使い、動的背景、グラデーション、スペクトラム、再生アニメーション、コラージュ、任意の曲の画像を無効にします。Defaultで標準値に戻り、対象設定を変更するとCustomになります。音質と再生メモリは独立しています。"
+
+msgid "Compare memory profiles"
+msgstr "メモリプロファイルを比較"
+
+msgid "Auto: fixed 400 MiB or 50 MiB according to the computer's RAM; disk handles larger tracks."
+msgstr "Auto:RAM容量に応じて400 MiBまたは50 MiBに固定。大きな曲はディスクを使用します。"
+
+msgid "High: dynamic 400–1600 MiB; more room in RAM for large tracks, with less need for disk-backed buffers."
+msgstr "High:400~1600 MiBで可変。大きな曲をRAMに保持しやすくなり、ディスクバッファの必要性が減ります。"
+
+msgid "Desktop: fixed 400 MiB; balances RAM use with disk-backed playback for larger tracks."
+msgstr "Desktop:400 MiB固定。RAMを使い、大きな曲はディスクで再生します。"
+
+msgid "Low: fixed 50 MiB and reduced prefetch; lower RAM use, with more disk reads and writes for large tracks."
+msgstr "Low:50 MiB固定で先読みを抑制。RAM使用量は減りますが、大きな曲ではディスクの読み書きが増えます。"
+
+msgid "Custom: your RAM limits and growth preference determine when playback needs disk storage."
+msgstr "Custom:RAMの上限と拡張設定に応じてディスクを使用します。"
+
+msgid "RAM and storage trade-off"
+msgstr "RAMとストレージのバランス"
+
+msgid "All profiles preserve audio quality and can use disk cache. Lower memory budgets rely more on storage speed and writes; more RAM can reduce that work. Cached disk tracks are read from disk even in High. Choose storage appropriate for your listening workload."
+msgstr "どのプロファイルも音質を維持し、ディスクキャッシュを使用できます。RAMが少ないほどストレージ速度や書き込みへの依存が増え、RAMを増やすと負荷を減らせます。ディスクにキャッシュ済みの曲はHighでもディスクから読みます。用途に合うストレージを選んでください。"
+
+msgid "Playback storage folder"
+msgstr "再生ストレージのフォルダー"
+
+msgid "Choose an existing folder on the drive you want to use. QBZ stores its playback cache and temporary track buffers in a qbz-playback subfolder. Offline downloads are separate. Leave blank for the default location."
+msgstr "使用するドライブの既存フォルダーを選びます。QBZはqbz-playbackサブフォルダーに再生キャッシュと一時バッファを保存します。オフラインダウンロードは別です。空欄なら標準の場所を使います。"
+
+msgid "Current playback storage"
+msgstr "現在の再生ストレージ"
+
+msgid "Changing the folder takes effect after restarting QBZ. Existing cache files stay in the old location; they are not moved or deleted automatically."
+msgstr "フォルダーの変更はQBZの再起動後に反映されます。既存のキャッシュは元の場所に残り、自動で移動や削除はされません。"
+
+msgid "Could not use this playback storage folder:"
+msgstr "この再生ストレージフォルダーを使用できませんでした:"
+
+msgid "Folder access"
+msgstr "フォルダーへのアクセス"
+
+msgid "If the sandbox blocks this folder, run the command below in a host terminal, restart QBZ, then select the folder again. Only grant access to a folder you intend to use."
+msgstr "サンドボックスがフォルダーをブロックする場合、ホストの端末で下のコマンドを実行し、QBZを再起動して再度選んでください。使用するフォルダーだけにアクセスを許可してください。"
+
+msgid "Snap can access supported home folders and removable storage under /mnt, /media or /run/media. For removable storage, connect the interface below and retry. Snap cannot grant arbitrary folder access with a Flatpak-style override."
+msgstr "Snapは対応するホームフォルダーと/mnt、/media、/run/media配下の外部ストレージにアクセスできます。外部ストレージでは下のインターフェースを接続して再試行してください。Flatpakのようなoverrideで任意のフォルダーを許可することはできません。"
+
+msgid "Choose an absolute folder path for playback storage."
+msgstr "再生ストレージの絶対パスを指定してください。"
+
+msgid "The folder is accessible and visible in the library."
+msgstr "フォルダーにアクセスでき、ライブラリに表示されます。"
+
+msgid "The folder is accessible but hidden by your preference."
+msgstr "フォルダーにアクセスできますが、設定により非表示です。"
+
+msgid "The folder path no longer exists. Reconnect it, change its path or remove it from the library."
+msgstr "フォルダーのパスが存在しません。再接続するか、パスを変更するか、ライブラリから削除してください。"
+
+msgid "A connection failure prevents access to this storage."
+msgstr "接続エラーにより、このストレージにアクセスできません。"
+
+msgid "QBZ does not have permission to access this folder."
+msgstr "QBZにはこのフォルダーへのアクセス権がありません。"
+
+msgid "The folder could not be accessed. The check timed out or returned another access error."
+msgstr "フォルダーにアクセスできませんでした。確認がタイムアウトしたか、別のアクセスエラーが発生しました。"
+
+msgid "Folder access is being checked or has not been checked yet."
+msgstr "フォルダーへのアクセスを確認中、またはまだ未確認です。"
+
+msgid "Local folder"
+msgstr "ローカルフォルダー"
+
+msgid "Access denied"
+msgstr "アクセス拒否"
+
+msgid "Missing"
+msgstr "見つかりません"
+
+msgid "Actions"
+msgstr "操作"
+
+msgid "Low"
+msgstr "低"
+
+msgid "These options do not apply while Streaming only is enabled. Turn it off to choose a playback memory profile and apply changes."
+msgstr "「ストリーミングのみ」が有効な間、これらの設定は適用されません。無効にすると、再生メモリプロファイルを選択して変更を適用できます。"
+
+msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay."
+msgstr "公式クライアントと同様のストリーミング動作でメモリ使用量を抑えます。再生キャッシュとそのネットワーク中断への保護を無効にします。QBZのキャッシュは次の音声を事前に用意し、より安定した再生と即座のリプレイを可能にします。"
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 8cf72cf6f..d0a80f4ef 100644
--- a/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po
+++ b/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po
@@ -7237,3 +7237,241 @@ msgstr "Systeem / handmatig"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Update gereed. Sluit QBZ om de installatie te voltooien. Het wordt automatisch opnieuw geopend."
+
+#. Playback memory cache policy (#774).
+msgid "PLAYBACK CACHE"
+msgstr "AFSPEELCACHE"
+
+#. Playback memory cache policy (#774).
+msgid "Grow cache when memory is available"
+msgstr "Cache vergroten bij beschikbaar geheugen"
+
+#. Playback memory cache policy (#774).
+msgid "Optional; recommended for long Hi-Res tracks. The fixed budget remains the recommended default."
+msgstr "Optioneel; aanbevolen voor lange Hi-Res-nummers. Het vaste budget blijft de aanbevolen standaard."
+
+#. Playback memory cache policy (#774).
+msgid "Minimum cache budget (MiB)"
+msgstr "Minimaal cachebudget (MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Base budget, not reserved RAM. Memory pressure can reduce it. Leave blank for the recommended value."
+msgstr "Basisbudget zonder RAM te reserveren. Kan dalen bij geheugendruk. Laat leeg voor de aanbevolen waarde."
+
+#. Playback memory cache policy (#774).
+msgid "Maximum cache budget (MiB)"
+msgstr "Maximaal cachebudget (MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Growth ceiling; available memory may impose a lower limit. Leave blank for automatic."
+msgstr "Groeiplimiet; beschikbaar geheugen kan een lagere grens opleggen. Laat leeg voor automatisch."
+
+#. Playback memory cache policy (#774).
+msgid "Memory cache usage"
+msgstr "Gebruik van geheugencache"
+
+#. Playback memory cache policy (#774).
+msgid "Used / current budget: %1 / %2 MiB. This excludes decoder memory and offline downloads."
+msgstr "Gebruikt / huidig budget: %1 / %2 MiB. Exclusief decodergeheugen en offline downloads."
+
+#. Playback memory cache policy (#774).
+msgid "Recommended cache defaults"
+msgstr "Aanbevolen cachestandaarden"
+
+#. Playback memory cache policy (#774).
+msgid "Restore defaults"
+msgstr "Standaardwaarden herstellen"
+
+#. Playback memory cache policy (#774).
+msgid "Playback cache limits must be between 16 and 16384 MiB"
+msgstr "De afspeelcachelimieten moeten tussen 16 en 16384 MiB liggen"
+
+#. Playback memory cache policy (#774).
+msgid "Minimum playback cache budget must not exceed its maximum"
+msgstr "Het minimale afspeelcachebudget mag het maximum niet overschrijden"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory profile"
+msgstr "Geheugenprofiel voor afspelen"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto — recommended"
+msgstr "Auto — aanbevolen"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High — dynamic"
+msgstr "High — dynamisch"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop"
+msgstr "Desktop"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low — Pi style"
+msgstr "Low — Pi-stijl"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto selects Desktop or Low from the computer's RAM. Fixed cache budget; dynamic growth is off. Recommended default."
+msgstr "Auto kiest Desktop of Low op basis van het RAM. Vast cachebudget zonder dynamische groei. Aanbevolen standaardinstelling."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High starts with a 400 MiB cache budget and grows up to 1600 MiB when memory is available. It shrinks after inactivity or memory pressure. For long Hi-Res tracks and computers with spare RAM."
+msgstr "High begint met een cachebudget van 400 MiB en groeit tot 1600 MiB als geheugen beschikbaar is. Het krimpt na inactiviteit of bij geheugendruk. Voor lange Hi-Res-nummers en computers met vrij RAM."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop uses a fixed 400 MiB cache budget and normal prefetch. Larger tracks use disk-backed buffers."
+msgstr "Desktop gebruikt een vast cachebudget van 400 MiB en normaal vooraf laden. Grotere nummers gebruiken buffers op schijf."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low uses a 50 MiB cache budget, smaller startup buffers and reduced prefetch. Large tracks use disk; speculative Hi-Res prefetch is skipped. Useful on Raspberry Pi or when saving RAM."
+msgstr "Low gebruikt een cachebudget van 50 MiB, kleinere startbuffers en minder vooraf laden. Grote nummers gebruiken de schijf; speculatief vooraf laden van Hi-Res wordt overgeslagen. Handig op Raspberry Pi of om RAM te besparen."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Custom uses your cache limits and growth preference below. Prefetch follows the computer's detected memory class. Editing a preset switches to Custom."
+msgstr "Aangepast gebruikt de onderstaande cachegrenzen en groeivoorkeur. Vooraf laden volgt de gedetecteerde geheugenklasse. Een voorinstelling bewerken schakelt naar Aangepast."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Same audio quality in every profile"
+msgstr "Dezelfde audiokwaliteit in elk profiel"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Profiles control playback memory, not audio quality or the whole app's RAM. Disk cache stays enabled unless Streaming only is on. Changes apply to new buffers; the current track continues."
+msgstr "Profielen regelen het afspeelgeheugen, niet de audiokwaliteit of het totale RAM van de app. De schijfcache blijft actief behalve bij Alleen streamen. Wijzigingen gelden voor nieuwe buffers; het huidige nummer speelt door."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Allow the cache to grow within your maximum when RAM is available. High enables this automatically. Editing this option switches to Custom."
+msgstr "Laat de cache tot het ingestelde maximum groeien wanneer RAM beschikbaar is. High schakelt dit automatisch in. Deze optie bewerken schakelt naar Aangepast."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Unknown playback memory profile"
+msgstr "Onbekend afspeelgeheugenprofiel"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory preset conflicts with custom cache limits"
+msgstr "Het afspeelgeheugenprofiel conflicteert met aangepaste cachegrenzen"
+
+msgid "Apply playback memory profile?"
+msgstr "Geheugenprofiel voor afspelen toepassen?"
+
+msgid "Playback buffers will be released. If playing, the current track will stop and restart from the beginning. If paused, it will stay stopped at 0:00. Your queue and disk cache will be kept."
+msgstr "De afspeelbuffers worden vrijgegeven. Tijdens het afspelen stopt het huidige nummer en begint het opnieuw vanaf het begin. Bij pauze blijft het gestopt op 0:00. Je wachtrij en schijfcache blijven behouden."
+
+msgid "Apply & free memory"
+msgstr "Toepassen en geheugen vrijmaken"
+
+msgid "Rebuild playback buffers"
+msgstr "Afspeelbuffers opnieuw opbouwen"
+
+msgid "The profile already applies to new buffers. Apply now to release existing playback buffers and the memory cache. Memory use can grow again as playback continues."
+msgstr "Het profiel geldt al voor nieuwe buffers. Pas het nu toe om bestaande afspeelbuffers en de geheugencache vrij te geven. Het geheugengebruik kan weer toenemen tijdens het afspelen."
+
+msgid "Playback memory can only be applied to local playback."
+msgstr "Het geheugenprofiel kan alleen worden toegepast op afspelen op dit apparaat."
+
+msgid "Playback is not ready yet."
+msgstr "Afspelen is nog niet gereed."
+
+msgid "Playback is busy. Try applying the memory profile again."
+msgstr "Afspelen is bezig. Probeer het geheugenprofiel opnieuw toe te passen."
+
+msgid "Playback changed. Apply again to confirm the current track."
+msgstr "Het afspelen is gewijzigd. Pas opnieuw toe om het huidige nummer te bevestigen."
+
+msgid "Visual resource profile"
+msgstr "Profiel voor visuele bronnen"
+
+msgid "Low uses the Small player, compact headers, no dynamic background, header gradient, spectrum, animated play indicator, sidebar collages or optional track artwork. Default restores these visual defaults. Editing a managed option selects Custom. Audio quality and playback memory are independent."
+msgstr "Low gebruikt de kleine speler en compacte koppen, zonder dynamische achtergrond, kleurverloop, spectrum, bewegende afspeelindicator, collages of optionele hoesjes per nummer. Default herstelt deze standaardwaarden. Wijzigingen kiezen Custom. Audiokwaliteit en afspeelgeheugen staan hier los van."
+
+msgid "Compare memory profiles"
+msgstr "Geheugenprofielen vergelijken"
+
+msgid "Auto: fixed 400 MiB or 50 MiB according to the computer's RAM; disk handles larger tracks."
+msgstr "Auto: vast 400 MiB of 50 MiB afhankelijk van het RAM; grotere nummers gebruiken schijfopslag."
+
+msgid "High: dynamic 400–1600 MiB; more room in RAM for large tracks, with less need for disk-backed buffers."
+msgstr "High: dynamisch 400–1600 MiB; meer RAM voor grote nummers en minder behoefte aan schijfgebufferde weergave."
+
+msgid "Desktop: fixed 400 MiB; balances RAM use with disk-backed playback for larger tracks."
+msgstr "Desktop: vast 400 MiB; verdeelt het gebruik tussen RAM en schijf voor grotere nummers."
+
+msgid "Low: fixed 50 MiB and reduced prefetch; lower RAM use, with more disk reads and writes for large tracks."
+msgstr "Low: vast 50 MiB en minder vooraf laden; minder RAM, meer lezen en schrijven op schijf bij grote nummers."
+
+msgid "Custom: your RAM limits and growth preference determine when playback needs disk storage."
+msgstr "Custom: je RAM-limieten en groei-instelling bepalen wanneer schijfopslag nodig is."
+
+msgid "RAM and storage trade-off"
+msgstr "Afweging tussen RAM en opslag"
+
+msgid "All profiles preserve audio quality and can use disk cache. Lower memory budgets rely more on storage speed and writes; more RAM can reduce that work. Cached disk tracks are read from disk even in High. Choose storage appropriate for your listening workload."
+msgstr "Alle profielen behouden de audiokwaliteit en kunnen schijfcache gebruiken. Minder RAM vraagt meer van opslagsnelheid en schrijfwerk; meer RAM kan dit verminderen. Nummers in de schijfcache worden ook bij High van schijf gelezen. Kies opslag die bij je gebruik past."
+
+msgid "Playback storage folder"
+msgstr "Opslagmap voor afspelen"
+
+msgid "Choose an existing folder on the drive you want to use. QBZ stores its playback cache and temporary track buffers in a qbz-playback subfolder. Offline downloads are separate. Leave blank for the default location."
+msgstr "Kies een bestaande map op het gewenste station. QBZ bewaart afspeelcache en tijdelijke buffers in de submap qbz-playback. Offline downloads staan hier los van. Laat leeg voor de standaardlocatie."
+
+msgid "Current playback storage"
+msgstr "Huidige afspeelopslag"
+
+msgid "Changing the folder takes effect after restarting QBZ. Existing cache files stay in the old location; they are not moved or deleted automatically."
+msgstr "De nieuwe map wordt na een herstart van QBZ gebruikt. Bestaande cachebestanden blijven op de oude locatie; ze worden niet automatisch verplaatst of verwijderd."
+
+msgid "Could not use this playback storage folder:"
+msgstr "Deze afspeelopslagmap kon niet worden gebruikt:"
+
+msgid "Folder access"
+msgstr "Maptoegang"
+
+msgid "If the sandbox blocks this folder, run the command below in a host terminal, restart QBZ, then select the folder again. Only grant access to a folder you intend to use."
+msgstr "Als de sandbox deze map blokkeert, voer je de onderstaande opdracht uit in een hostterminal, herstart je QBZ en kies je de map opnieuw. Verleen alleen toegang tot de gewenste map."
+
+msgid "Snap can access supported home folders and removable storage under /mnt, /media or /run/media. For removable storage, connect the interface below and retry. Snap cannot grant arbitrary folder access with a Flatpak-style override."
+msgstr "Snap heeft toegang tot ondersteunde persoonlijke mappen en verwisselbare opslag onder /mnt, /media of /run/media. Verbind hiervoor de onderstaande interface en probeer opnieuw. Snap kan willekeurige mappen niet via een Flatpak-achtige override toestaan."
+
+msgid "Choose an absolute folder path for playback storage."
+msgstr "Kies een absoluut mappad voor afspeelopslag."
+
+msgid "The folder is accessible and visible in the library."
+msgstr "De map is toegankelijk en zichtbaar in de bibliotheek."
+
+msgid "The folder is accessible but hidden by your preference."
+msgstr "De map is toegankelijk, maar door je instelling verborgen."
+
+msgid "The folder path no longer exists. Reconnect it, change its path or remove it from the library."
+msgstr "Het pad bestaat niet meer. Verbind de map opnieuw, wijzig het pad of verwijder de map uit de bibliotheek."
+
+msgid "A connection failure prevents access to this storage."
+msgstr "Een verbindingsfout verhindert toegang tot deze opslag."
+
+msgid "QBZ does not have permission to access this folder."
+msgstr "QBZ heeft geen toestemming om deze map te openen."
+
+msgid "The folder could not be accessed. The check timed out or returned another access error."
+msgstr "De map kon niet worden geopend. De controle duurde te lang of gaf een andere toegangsfout."
+
+msgid "Folder access is being checked or has not been checked yet."
+msgstr "De toegang wordt gecontroleerd of is nog niet gecontroleerd."
+
+msgid "Local folder"
+msgstr "Lokale map"
+
+msgid "Access denied"
+msgstr "Toegang geweigerd"
+
+msgid "Missing"
+msgstr "Ontbreekt"
+
+msgid "Actions"
+msgstr "Acties"
+
+msgid "Low"
+msgstr "Laag"
+
+msgid "These options do not apply while Streaming only is enabled. Turn it off to choose a playback memory profile and apply changes."
+msgstr "Deze opties zijn niet van toepassing zolang Alleen streamen is ingeschakeld. Schakel dit uit om een geheugenprofiel voor afspelen te kiezen en wijzigingen toe te passen."
+
+msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay."
+msgstr "Bootst het streaminggedrag van de officiële clients na met minder geheugengebruik. Slaat de afspeelcache en de bescherming tegen netwerkonderbrekingen over: de cache van QBZ houdt komende audio gereed voor betrouwbaarder afspelen en direct opnieuw afspelen."
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 ce161eb2b..010891937 100644
--- a/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po
+++ b/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po
@@ -7247,3 +7247,241 @@ msgstr "Sistema / manual"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Atualização pronta. Feche o QBZ para concluir a instalação. Ele será reaberto automaticamente."
+
+#. Playback memory cache policy (#774).
+msgid "PLAYBACK CACHE"
+msgstr "CACHE DE REPRODUÇÃO"
+
+#. Playback memory cache policy (#774).
+msgid "Grow cache when memory is available"
+msgstr "Expandir o cache quando houver memória disponível"
+
+#. Playback memory cache policy (#774).
+msgid "Optional; recommended for long Hi-Res tracks. The fixed budget remains the recommended default."
+msgstr "Opcional; recomendado para faixas longas em Hi-Res. O limite fixo continua sendo o padrão recomendado."
+
+#. Playback memory cache policy (#774).
+msgid "Minimum cache budget (MiB)"
+msgstr "Limite mínimo do cache (MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Base budget, not reserved RAM. Memory pressure can reduce it. Leave blank for the recommended value."
+msgstr "Limite base, sem reservar RAM. Pode diminuir se faltar memória. Deixe em branco para usar o valor recomendado."
+
+#. Playback memory cache policy (#774).
+msgid "Maximum cache budget (MiB)"
+msgstr "Limite máximo do cache (MiB)"
+
+#. Playback memory cache policy (#774).
+msgid "Growth ceiling; available memory may impose a lower limit. Leave blank for automatic."
+msgstr "Teto de expansão; a memória disponível pode impor um limite menor. Deixe em branco para automático."
+
+#. Playback memory cache policy (#774).
+msgid "Memory cache usage"
+msgstr "Uso do cache em memória"
+
+#. Playback memory cache policy (#774).
+msgid "Used / current budget: %1 / %2 MiB. This excludes decoder memory and offline downloads."
+msgstr "Uso / limite atual: %1 / %2 MiB. Exclui a memória do decodificador e os downloads offline."
+
+#. Playback memory cache policy (#774).
+msgid "Recommended cache defaults"
+msgstr "Valores padrão recomendados do cache"
+
+#. Playback memory cache policy (#774).
+msgid "Restore defaults"
+msgstr "Restaurar padrões"
+
+#. Playback memory cache policy (#774).
+msgid "Playback cache limits must be between 16 and 16384 MiB"
+msgstr "Os limites do cache de reprodução devem estar entre 16 e 16384 MiB"
+
+#. Playback memory cache policy (#774).
+msgid "Minimum playback cache budget must not exceed its maximum"
+msgstr "O limite mínimo do cache de reprodução não pode exceder o máximo"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory profile"
+msgstr "Perfil de memória de reprodução"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto — recommended"
+msgstr "Auto — recomendado"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High — dynamic"
+msgstr "High — dinâmico"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop"
+msgstr "Desktop"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low — Pi style"
+msgstr "Low — estilo Pi"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto selects Desktop or Low from the computer's RAM. Fixed cache budget; dynamic growth is off. Recommended default."
+msgstr "Auto seleciona Desktop ou Low conforme a RAM do computador. Limite de cache fixo, sem crescimento dinâmico. Padrão recomendado."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High starts with a 400 MiB cache budget and grows up to 1600 MiB when memory is available. It shrinks after inactivity or memory pressure. For long Hi-Res tracks and computers with spare RAM."
+msgstr "High começa com um limite de cache de 400 MiB e cresce até 1600 MiB quando há memória disponível. Diminui após inatividade ou pressão de memória. Para faixas Hi-Res longas e computadores com RAM livre."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop uses a fixed 400 MiB cache budget and normal prefetch. Larger tracks use disk-backed buffers."
+msgstr "Desktop usa um limite fixo de cache de 400 MiB e pré-carregamento normal. Faixas maiores usam buffers em disco."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low uses a 50 MiB cache budget, smaller startup buffers and reduced prefetch. Large tracks use disk; speculative Hi-Res prefetch is skipped. Useful on Raspberry Pi or when saving RAM."
+msgstr "Low usa um limite de cache de 50 MiB, buffers iniciais menores e menos pré-carregamento. Faixas grandes usam disco; o pré-carregamento especulativo Hi-Res é ignorado. Útil no Raspberry Pi ou para economizar RAM."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Custom uses your cache limits and growth preference below. Prefetch follows the computer's detected memory class. Editing a preset switches to Custom."
+msgstr "Personalizado usa os limites de cache e a preferência de crescimento abaixo. O pré-carregamento segue a classe de memória detectada. Editar um perfil muda para Personalizado."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Same audio quality in every profile"
+msgstr "A mesma qualidade de áudio em todos os perfis"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Profiles control playback memory, not audio quality or the whole app's RAM. Disk cache stays enabled unless Streaming only is on. Changes apply to new buffers; the current track continues."
+msgstr "Os perfis controlam a memória de reprodução, não a qualidade de áudio nem toda a RAM do aplicativo. O cache em disco continua ativo, exceto em Somente streaming. As alterações se aplicam a novos buffers; a faixa atual continua."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Allow the cache to grow within your maximum when RAM is available. High enables this automatically. Editing this option switches to Custom."
+msgstr "Permite que o cache cresça até o máximo definido quando há RAM disponível. High ativa isso automaticamente. Editar esta opção muda para Personalizado."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Unknown playback memory profile"
+msgstr "Perfil de memória de reprodução desconhecido"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory preset conflicts with custom cache limits"
+msgstr "O perfil de memória de reprodução conflita com os limites de cache personalizados"
+
+msgid "Apply playback memory profile?"
+msgstr "Aplicar o perfil de memória de reprodução?"
+
+msgid "Playback buffers will be released. If playing, the current track will stop and restart from the beginning. If paused, it will stay stopped at 0:00. Your queue and disk cache will be kept."
+msgstr "Os buffers de reprodução serão liberados. Se estiver tocando, a faixa atual será interrompida e reiniciada do começo. Se estiver pausada, ficará parada em 0:00. A fila e o cache em disco serão mantidos."
+
+msgid "Apply & free memory"
+msgstr "Aplicar e liberar memória"
+
+msgid "Rebuild playback buffers"
+msgstr "Reconstruir buffers de reprodução"
+
+msgid "The profile already applies to new buffers. Apply now to release existing playback buffers and the memory cache. Memory use can grow again as playback continues."
+msgstr "O perfil já se aplica aos novos buffers. Aplique agora para liberar os buffers existentes e o cache em memória. O uso de memória pode voltar a crescer conforme a reprodução continua."
+
+msgid "Playback memory can only be applied to local playback."
+msgstr "O perfil de memória só pode ser aplicado à reprodução neste dispositivo."
+
+msgid "Playback is not ready yet."
+msgstr "A reprodução ainda não está pronta."
+
+msgid "Playback is busy. Try applying the memory profile again."
+msgstr "A reprodução está ocupada. Tente aplicar o perfil de memória novamente."
+
+msgid "Playback changed. Apply again to confirm the current track."
+msgstr "A reprodução mudou. Aplique novamente para confirmar a faixa atual."
+
+msgid "Visual resource profile"
+msgstr "Perfil de recursos visuais"
+
+msgid "Low uses the Small player, compact headers, no dynamic background, header gradient, spectrum, animated play indicator, sidebar collages or optional track artwork. Default restores these visual defaults. Editing a managed option selects Custom. Audio quality and playback memory are independent."
+msgstr "Low usa o player Small e cabeçalhos compactos, sem fundo dinâmico, gradiente, espectro, indicador animado, colagens ou capas opcionais nas faixas. Default restaura esses padrões visuais. Alterações ativam Custom. Qualidade de áudio e memória de reprodução são independentes."
+
+msgid "Compare memory profiles"
+msgstr "Comparar perfis de memória"
+
+msgid "Auto: fixed 400 MiB or 50 MiB according to the computer's RAM; disk handles larger tracks."
+msgstr "Auto: 400 MiB ou 50 MiB fixos conforme a RAM; faixas maiores usam o disco."
+
+msgid "High: dynamic 400–1600 MiB; more room in RAM for large tracks, with less need for disk-backed buffers."
+msgstr "High: 400–1600 MiB dinâmicos; mais RAM para faixas grandes e menor necessidade de buffers em disco."
+
+msgid "Desktop: fixed 400 MiB; balances RAM use with disk-backed playback for larger tracks."
+msgstr "Desktop: 400 MiB fixos; equilibra RAM e reprodução em disco para faixas maiores."
+
+msgid "Low: fixed 50 MiB and reduced prefetch; lower RAM use, with more disk reads and writes for large tracks."
+msgstr "Low: 50 MiB fixos e menos pré-carregamento; menos RAM, com mais leituras e gravações em disco para faixas grandes."
+
+msgid "Custom: your RAM limits and growth preference determine when playback needs disk storage."
+msgstr "Custom: seus limites de RAM e preferência de crescimento determinam quando a reprodução usa o disco."
+
+msgid "RAM and storage trade-off"
+msgstr "Equilíbrio entre RAM e armazenamento"
+
+msgid "All profiles preserve audio quality and can use disk cache. Lower memory budgets rely more on storage speed and writes; more RAM can reduce that work. Cached disk tracks are read from disk even in High. Choose storage appropriate for your listening workload."
+msgstr "Todos os perfis preservam a qualidade e podem usar cache em disco. Menos RAM implica maior dependência da velocidade e das gravações no armazenamento; mais RAM pode reduzir esse trabalho. Faixas já no cache em disco são lidas dele mesmo em High. Escolha uma unidade adequada ao seu uso."
+
+msgid "Playback storage folder"
+msgstr "Pasta de armazenamento de reprodução"
+
+msgid "Choose an existing folder on the drive you want to use. QBZ stores its playback cache and temporary track buffers in a qbz-playback subfolder. Offline downloads are separate. Leave blank for the default location."
+msgstr "Escolha uma pasta existente na unidade desejada. QBZ armazena o cache de reprodução e buffers temporários na subpasta qbz-playback. Downloads offline são separados. Deixe vazio para usar o local padrão."
+
+msgid "Current playback storage"
+msgstr "Armazenamento atual de reprodução"
+
+msgid "Changing the folder takes effect after restarting QBZ. Existing cache files stay in the old location; they are not moved or deleted automatically."
+msgstr "A nova pasta será usada após reiniciar QBZ. Arquivos de cache existentes ficam no local anterior; não são movidos nem excluídos automaticamente."
+
+msgid "Could not use this playback storage folder:"
+msgstr "Não foi possível usar esta pasta de reprodução:"
+
+msgid "Folder access"
+msgstr "Acesso à pasta"
+
+msgid "If the sandbox blocks this folder, run the command below in a host terminal, restart QBZ, then select the folder again. Only grant access to a folder you intend to use."
+msgstr "Se o sandbox bloquear a pasta, execute o comando abaixo em um terminal do sistema, reinicie QBZ e selecione a pasta novamente. Dê acesso apenas à pasta desejada."
+
+msgid "Snap can access supported home folders and removable storage under /mnt, /media or /run/media. For removable storage, connect the interface below and retry. Snap cannot grant arbitrary folder access with a Flatpak-style override."
+msgstr "Snap acessa pastas pessoais compatíveis e mídias em /mnt, /media ou /run/media. Para essas mídias, conecte a interface abaixo e tente novamente. Snap não libera pastas arbitrárias com override como Flatpak."
+
+msgid "Choose an absolute folder path for playback storage."
+msgstr "Escolha um caminho absoluto para o armazenamento de reprodução."
+
+msgid "The folder is accessible and visible in the library."
+msgstr "A pasta está acessível e visível na biblioteca."
+
+msgid "The folder is accessible but hidden by your preference."
+msgstr "A pasta está acessível, mas oculta pela sua preferência."
+
+msgid "The folder path no longer exists. Reconnect it, change its path or remove it from the library."
+msgstr "O caminho não existe mais. Reconecte a pasta, altere o caminho ou remova-a da biblioteca."
+
+msgid "A connection failure prevents access to this storage."
+msgstr "Uma falha de conexão impede o acesso a este armazenamento."
+
+msgid "QBZ does not have permission to access this folder."
+msgstr "QBZ não tem permissão para acessar esta pasta."
+
+msgid "The folder could not be accessed. The check timed out or returned another access error."
+msgstr "Não foi possível acessar a pasta. A verificação expirou ou retornou outro erro de acesso."
+
+msgid "Folder access is being checked or has not been checked yet."
+msgstr "O acesso está sendo verificado ou ainda está pendente."
+
+msgid "Local folder"
+msgstr "Pasta local"
+
+msgid "Access denied"
+msgstr "Acesso negado"
+
+msgid "Missing"
+msgstr "Ausente"
+
+msgid "Actions"
+msgstr "Ações"
+
+msgid "Low"
+msgstr "Baixo"
+
+msgid "These options do not apply while Streaming only is enabled. Turn it off to choose a playback memory profile and apply changes."
+msgstr "Estas opções não se aplicam enquanto Apenas streaming estiver ativado. Desative-o para escolher um perfil de memória de reprodução e aplicar as alterações."
+
+msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay."
+msgstr "Reproduz o comportamento de streaming dos clientes oficiais com menor uso de memória. Ignora o cache de reprodução e sua proteção contra interrupções de rede: o cache do QBZ prepara o próximo áudio para uma reprodução mais confiável e repetição imediata."
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 1b0c608a8..db37399a1 100644
--- a/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po
+++ b/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po
@@ -7268,3 +7268,241 @@ msgstr "Системная / ручная"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Обновление готово. Закройте QBZ для завершения установки. Приложение откроется автоматически."
+
+#. Playback memory cache policy (#774).
+msgid "PLAYBACK CACHE"
+msgstr "КЭШ ВОСПРОИЗВЕДЕНИЯ"
+
+#. Playback memory cache policy (#774).
+msgid "Grow cache when memory is available"
+msgstr "Увеличивать кэш при наличии свободной памяти"
+
+#. Playback memory cache policy (#774).
+msgid "Optional; recommended for long Hi-Res tracks. The fixed budget remains the recommended default."
+msgstr "Необязательно; рекомендуется для длинных треков Hi-Res. Фиксированный лимит остаётся рекомендуемым значением по умолчанию."
+
+#. Playback memory cache policy (#774).
+msgid "Minimum cache budget (MiB)"
+msgstr "Минимальный лимит кэша (МиБ)"
+
+#. Playback memory cache policy (#774).
+msgid "Base budget, not reserved RAM. Memory pressure can reduce it. Leave blank for the recommended value."
+msgstr "Базовый лимит без резервирования ОЗУ. Может снижаться при нехватке памяти. Оставьте пустым для рекомендуемого значения."
+
+#. Playback memory cache policy (#774).
+msgid "Maximum cache budget (MiB)"
+msgstr "Максимальный лимит кэша (МиБ)"
+
+#. Playback memory cache policy (#774).
+msgid "Growth ceiling; available memory may impose a lower limit. Leave blank for automatic."
+msgstr "Предел роста; доступная память может ограничить его сильнее. Оставьте пустым для автоматического выбора."
+
+#. Playback memory cache policy (#774).
+msgid "Memory cache usage"
+msgstr "Использование кэша в памяти"
+
+#. Playback memory cache policy (#774).
+msgid "Used / current budget: %1 / %2 MiB. This excludes decoder memory and offline downloads."
+msgstr "Использовано / текущий лимит: %1 / %2 МиБ. Без памяти декодера и офлайн-загрузок."
+
+#. Playback memory cache policy (#774).
+msgid "Recommended cache defaults"
+msgstr "Рекомендуемые настройки кэша"
+
+#. Playback memory cache policy (#774).
+msgid "Restore defaults"
+msgstr "Восстановить значения по умолчанию"
+
+#. Playback memory cache policy (#774).
+msgid "Playback cache limits must be between 16 and 16384 MiB"
+msgstr "Лимиты кэша воспроизведения должны быть от 16 до 16384 МиБ"
+
+#. Playback memory cache policy (#774).
+msgid "Minimum playback cache budget must not exceed its maximum"
+msgstr "Минимальный лимит кэша воспроизведения не может превышать максимальный"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory profile"
+msgstr "Профиль памяти воспроизведения"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto — recommended"
+msgstr "Auto — рекомендуется"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High — dynamic"
+msgstr "High — динамический"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop"
+msgstr "Desktop"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low — Pi style"
+msgstr "Low — режим Pi"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Auto selects Desktop or Low from the computer's RAM. Fixed cache budget; dynamic growth is off. Recommended default."
+msgstr "Auto выбирает Desktop или Low по объёму ОЗУ компьютера. Фиксированный бюджет кэша без динамического роста. Рекомендуемая настройка по умолчанию."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "High starts with a 400 MiB cache budget and grows up to 1600 MiB when memory is available. It shrinks after inactivity or memory pressure. For long Hi-Res tracks and computers with spare RAM."
+msgstr "High начинает с бюджета кэша 400 МиБ и увеличивает его до 1600 МиБ при наличии свободной памяти. После простоя или при нехватке памяти бюджет уменьшается. Для длинных треков Hi-Res и компьютеров со свободной ОЗУ."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Desktop uses a fixed 400 MiB cache budget and normal prefetch. Larger tracks use disk-backed buffers."
+msgstr "Desktop использует фиксированный бюджет кэша 400 МиБ и обычную предзагрузку. Более крупные треки используют дисковые буферы."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Low uses a 50 MiB cache budget, smaller startup buffers and reduced prefetch. Large tracks use disk; speculative Hi-Res prefetch is skipped. Useful on Raspberry Pi or when saving RAM."
+msgstr "Low использует бюджет кэша 50 МиБ, меньшие стартовые буферы и сокращённую предзагрузку. Большие треки используют диск; упреждающая загрузка Hi-Res пропускается. Полезно на Raspberry Pi или для экономии ОЗУ."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Custom uses your cache limits and growth preference below. Prefetch follows the computer's detected memory class. Editing a preset switches to Custom."
+msgstr "Свой профиль использует указанные ниже лимиты кэша и настройку роста. Предзагрузка зависит от определённого класса памяти компьютера. Изменение готового профиля включает свой профиль."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Same audio quality in every profile"
+msgstr "Одинаковое качество звука во всех профилях"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Profiles control playback memory, not audio quality or the whole app's RAM. Disk cache stays enabled unless Streaming only is on. Changes apply to new buffers; the current track continues."
+msgstr "Профили управляют памятью воспроизведения, а не качеством звука или всей ОЗУ приложения. Дисковый кэш работает, кроме режима Только потоковая передача. Изменения действуют на новые буферы; текущий трек продолжает играть."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Allow the cache to grow within your maximum when RAM is available. High enables this automatically. Editing this option switches to Custom."
+msgstr "Разрешить рост кэша до заданного максимума при наличии свободной ОЗУ. High включает это автоматически. Изменение этой настройки включает свой профиль."
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Unknown playback memory profile"
+msgstr "Неизвестный профиль памяти воспроизведения"
+
+#: qbz-qt/qml/settings/PlaybackSettings.qml
+msgid "Playback memory preset conflicts with custom cache limits"
+msgstr "Профиль памяти воспроизведения несовместим с заданными лимитами кэша"
+
+msgid "Apply playback memory profile?"
+msgstr "Применить профиль памяти воспроизведения?"
+
+msgid "Playback buffers will be released. If playing, the current track will stop and restart from the beginning. If paused, it will stay stopped at 0:00. Your queue and disk cache will be kept."
+msgstr "Буферы воспроизведения будут освобождены. Если трек воспроизводится, он остановится и начнётся сначала. Если он на паузе, он останется остановленным на 0:00. Очередь и дисковый кэш сохранятся."
+
+msgid "Apply & free memory"
+msgstr "Применить и освободить память"
+
+msgid "Rebuild playback buffers"
+msgstr "Пересоздать буферы воспроизведения"
+
+msgid "The profile already applies to new buffers. Apply now to release existing playback buffers and the memory cache. Memory use can grow again as playback continues."
+msgstr "Профиль уже применяется к новым буферам. Примените его сейчас, чтобы освободить существующие буферы и кэш в памяти. При продолжении воспроизведения расход памяти может снова вырасти."
+
+msgid "Playback memory can only be applied to local playback."
+msgstr "Профиль памяти можно применить только к воспроизведению на этом устройстве."
+
+msgid "Playback is not ready yet."
+msgstr "Воспроизведение ещё не готово."
+
+msgid "Playback is busy. Try applying the memory profile again."
+msgstr "Воспроизведение занято. Попробуйте применить профиль памяти ещё раз."
+
+msgid "Playback changed. Apply again to confirm the current track."
+msgstr "Воспроизведение изменилось. Примените снова, чтобы подтвердить текущий трек."
+
+msgid "Visual resource profile"
+msgstr "Профиль визуальных ресурсов"
+
+msgid "Low uses the Small player, compact headers, no dynamic background, header gradient, spectrum, animated play indicator, sidebar collages or optional track artwork. Default restores these visual defaults. Editing a managed option selects Custom. Audio quality and playback memory are independent."
+msgstr "Low использует маленький плеер и компактные заголовки, отключает динамический фон, градиент, спектр, анимацию воспроизведения, коллажи и дополнительные обложки треков. Default восстанавливает эти настройки. Их изменение выбирает Custom. Качество звука и память воспроизведения независимы."
+
+msgid "Compare memory profiles"
+msgstr "Сравнение профилей памяти"
+
+msgid "Auto: fixed 400 MiB or 50 MiB according to the computer's RAM; disk handles larger tracks."
+msgstr "Auto: фиксированные 400 MiB или 50 MiB в зависимости от ОЗУ; крупные треки используют диск."
+
+msgid "High: dynamic 400–1600 MiB; more room in RAM for large tracks, with less need for disk-backed buffers."
+msgstr "High: динамические 400–1600 MiB; больше ОЗУ для крупных треков, меньше потребность в дисковых буферах."
+
+msgid "Desktop: fixed 400 MiB; balances RAM use with disk-backed playback for larger tracks."
+msgstr "Desktop: фиксированные 400 MiB; баланс ОЗУ и дискового воспроизведения крупных треков."
+
+msgid "Low: fixed 50 MiB and reduced prefetch; lower RAM use, with more disk reads and writes for large tracks."
+msgstr "Low: фиксированные 50 MiB и сокращённая предзагрузка; меньше ОЗУ, больше чтения и записи на диск для крупных треков."
+
+msgid "Custom: your RAM limits and growth preference determine when playback needs disk storage."
+msgstr "Custom: ваши пределы ОЗУ и настройки роста определяют, когда нужен диск."
+
+msgid "RAM and storage trade-off"
+msgstr "Баланс ОЗУ и накопителя"
+
+msgid "All profiles preserve audio quality and can use disk cache. Lower memory budgets rely more on storage speed and writes; more RAM can reduce that work. Cached disk tracks are read from disk even in High. Choose storage appropriate for your listening workload."
+msgstr "Все профили сохраняют качество звука и могут использовать дисковый кэш. Меньше ОЗУ означает большую зависимость от скорости накопителя и больше записей; дополнительная ОЗУ может снизить эту нагрузку. Треки в дисковом кэше читаются с диска даже в High. Выбирайте накопитель с учётом своего использования."
+
+msgid "Playback storage folder"
+msgstr "Папка хранения воспроизведения"
+
+msgid "Choose an existing folder on the drive you want to use. QBZ stores its playback cache and temporary track buffers in a qbz-playback subfolder. Offline downloads are separate. Leave blank for the default location."
+msgstr "Выберите существующую папку на нужном диске. QBZ хранит кэш и временные буферы в подпапке qbz-playback. Офлайн-загрузки хранятся отдельно. Оставьте поле пустым для стандартного пути."
+
+msgid "Current playback storage"
+msgstr "Текущее хранилище воспроизведения"
+
+msgid "Changing the folder takes effect after restarting QBZ. Existing cache files stay in the old location; they are not moved or deleted automatically."
+msgstr "Новая папка будет использоваться после перезапуска QBZ. Старые файлы кэша останутся на прежнем месте; они не перемещаются и не удаляются автоматически."
+
+msgid "Could not use this playback storage folder:"
+msgstr "Не удалось использовать эту папку воспроизведения:"
+
+msgid "Folder access"
+msgstr "Доступ к папке"
+
+msgid "If the sandbox blocks this folder, run the command below in a host terminal, restart QBZ, then select the folder again. Only grant access to a folder you intend to use."
+msgstr "Если песочница блокирует папку, выполните команду ниже в терминале основной системы, перезапустите QBZ и выберите папку снова. Разрешайте доступ только к нужной папке."
+
+msgid "Snap can access supported home folders and removable storage under /mnt, /media or /run/media. For removable storage, connect the interface below and retry. Snap cannot grant arbitrary folder access with a Flatpak-style override."
+msgstr "Snap может обращаться к поддерживаемым домашним папкам и накопителям в /mnt, /media или /run/media. Для накопителей подключите указанный интерфейс и повторите попытку. Snap не разрешает произвольные папки через override, как Flatpak."
+
+msgid "Choose an absolute folder path for playback storage."
+msgstr "Укажите абсолютный путь к папке воспроизведения."
+
+msgid "The folder is accessible and visible in the library."
+msgstr "Папка доступна и видна в библиотеке."
+
+msgid "The folder is accessible but hidden by your preference."
+msgstr "Папка доступна, но скрыта по вашей настройке."
+
+msgid "The folder path no longer exists. Reconnect it, change its path or remove it from the library."
+msgstr "Путь больше не существует. Подключите папку, измените путь или удалите её из библиотеки."
+
+msgid "A connection failure prevents access to this storage."
+msgstr "Ошибка соединения препятствует доступу к накопителю."
+
+msgid "QBZ does not have permission to access this folder."
+msgstr "У QBZ нет разрешения на доступ к этой папке."
+
+msgid "The folder could not be accessed. The check timed out or returned another access error."
+msgstr "Не удалось обратиться к папке. Проверка превысила время ожидания или вернула другую ошибку доступа."
+
+msgid "Folder access is being checked or has not been checked yet."
+msgstr "Доступ проверяется или ещё не был проверен."
+
+msgid "Local folder"
+msgstr "Локальная папка"
+
+msgid "Access denied"
+msgstr "Доступ запрещён"
+
+msgid "Missing"
+msgstr "Отсутствует"
+
+msgid "Actions"
+msgstr "Действия"
+
+msgid "Low"
+msgstr "Низкий"
+
+msgid "These options do not apply while Streaming only is enabled. Turn it off to choose a playback memory profile and apply changes."
+msgstr "Эти параметры не применяются, пока включён режим «Только потоковое воспроизведение». Отключите его, чтобы выбрать профиль памяти воспроизведения и применить изменения."
+
+msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay."
+msgstr "Повторяет поведение потокового воспроизведения официальных клиентов, используя меньше памяти. Отключает кэш воспроизведения и его защиту от перебоев сети: кэш QBZ заранее подготавливает аудио для более надёжного воспроизведения и мгновенного повтора."
diff --git a/crates/qbz-library/src/lib.rs b/crates/qbz-library/src/lib.rs
index e89cfbbc5..6f086ce8c 100644
--- a/crates/qbz-library/src/lib.rs
+++ b/crates/qbz-library/src/lib.rs
@@ -46,6 +46,7 @@ mod remote_tag_sidecar;
mod sacd;
pub mod sacd_scan;
mod scan;
+mod scan_changes;
mod scanner;
pub mod search;
pub mod service;
diff --git a/crates/qbz-library/src/scan_changes.rs b/crates/qbz-library/src/scan_changes.rs
new file mode 100644
index 000000000..1b47cf617
--- /dev/null
+++ b/crates/qbz-library/src/scan_changes.rs
@@ -0,0 +1,81 @@
+//! Connection-local change tracking for a scan. Scan checkpoints, generations
+//! and last-scan timestamps are not changes to the browsable catalog.
+//!
+//! TEMP triggers observe committed track writes, including CUE/SACD imports and
+//! partial scans. The flag rolls back with a failed batch. No persistent schema
+//! changes, full-library copies or hashes are needed for an unchanged scan.
+
+use rusqlite::Connection;
+
+pub(crate) fn begin(connection: &Connection) -> rusqlite::Result<()> {
+ let mut columns = connection.prepare("PRAGMA main.table_info(local_tracks)")?;
+ let changed_columns = columns
+ .query_map([], |row| row.get::<_, String>(1))?
+ .map(|column| {
+ column.map(|name| {
+ let quoted = name.replace('"', "\"\"");
+ format!("OLD.\"{quoted}\" IS NOT NEW.\"{quoted}\"")
+ })
+ })
+ .collect::>>()?
+ .join(" OR ");
+ connection.execute_batch(&format!(
+ "CREATE TEMP TABLE qbz_scan_changes (changed INTEGER NOT NULL);
+ INSERT INTO qbz_scan_changes VALUES (0);
+ CREATE TEMP TRIGGER qbz_scan_insert AFTER INSERT ON main.local_tracks
+ BEGIN UPDATE qbz_scan_changes SET changed=1 WHERE changed=0; END;
+ CREATE TEMP TRIGGER qbz_scan_delete AFTER DELETE ON main.local_tracks
+ BEGIN UPDATE qbz_scan_changes SET changed=1 WHERE changed=0; END;
+ CREATE TEMP TRIGGER qbz_scan_update AFTER UPDATE ON main.local_tracks
+ WHEN {changed_columns}
+ BEGIN UPDATE qbz_scan_changes SET changed=1 WHERE changed=0; END;"
+ ))
+}
+
+pub(crate) fn changed(connection: &Connection) -> rusqlite::Result {
+ connection.query_row("SELECT changed FROM temp.qbz_scan_changes", [], |row| row.get(0))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn bookkeeping_and_rolled_back_batches_do_not_invalidate_content() {
+ let conn = Connection::open_in_memory().unwrap();
+ conn.execute_batch(
+ "CREATE TABLE local_tracks(id INTEGER PRIMARY KEY, title TEXT, artwork_path TEXT);
+ CREATE TABLE local_scan_roots(generation INTEGER);
+ INSERT INTO local_tracks VALUES(1,'Dogs',NULL);"
+ ).unwrap();
+ begin(&conn).unwrap();
+ conn.execute_batch(
+ "INSERT INTO local_scan_roots VALUES(104);
+ UPDATE local_scan_roots SET generation=105;
+ UPDATE local_tracks SET title=title, artwork_path=NULL;
+ BEGIN; DELETE FROM local_tracks; ROLLBACK;"
+ ).unwrap();
+ assert!(!changed(&conn).unwrap());
+ conn.execute_batch("UPDATE local_tracks SET artwork_path='cover.jpg'").unwrap();
+ assert!(changed(&conn).unwrap());
+ }
+
+ #[test]
+ fn inserts_deletes_and_committed_partial_imports_invalidate_content() {
+ for mutation in [
+ "INSERT INTO local_tracks VALUES(2,'Sheep')",
+ "DELETE FROM local_tracks",
+ "UPDATE local_tracks SET title='Dogs (Remix)'",
+ ] {
+ let conn = Connection::open_in_memory().unwrap();
+ conn.execute_batch(
+ "CREATE TABLE local_tracks(id INTEGER PRIMARY KEY, title TEXT);
+ INSERT INTO local_tracks VALUES(1,'Dogs');"
+ ).unwrap();
+ begin(&conn).unwrap();
+ conn.execute_batch(mutation).unwrap();
+ conn.execute_batch("BEGIN; DELETE FROM local_tracks; ROLLBACK;").unwrap();
+ assert!(changed(&conn).unwrap(), "{mutation}");
+ }
+ }
+}
diff --git a/crates/qbz-library/src/service.rs b/crates/qbz-library/src/service.rs
index da30ee0d2..78e3d8088 100644
--- a/crates/qbz-library/src/service.rs
+++ b/crates/qbz-library/src/service.rs
@@ -6,7 +6,7 @@
//! is cooperative: call `close` immediately, then `shutdown` on a blocking thread
//! to join (filesystem calls on an unavailable mount may take time to return).
-use std::collections::BTreeSet;
+use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
@@ -42,6 +42,7 @@ pub enum ScanOutcome {
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct ScanCompletion {
pub job: u64,
+ pub background: bool,
pub outcome: ScanOutcome,
pub skipped: usize,
}
@@ -50,44 +51,62 @@ pub struct ScanCompletion {
pub struct LibrarySnapshot {
pub progress: ScanProgress,
pub last_scan: Option,
+ /// Keep a manual result available even if background work finishes between UI polls.
+ #[serde(skip_serializing)]
+ pub last_requested_scan: Option,
/// Changes after each scan, even a partial/cancelled one: committed batches
/// remain authoritative. This is an invalidation signal, not a DB cursor.
pub revision: u64,
+ /// Changes only when scans write catalog rows (or a folder is registered).
+ /// Completion/progress still advances for an unchanged or unavailable root.
+ pub content_revision: u64,
pub queued: usize,
pub closed: bool,
}
#[derive(Default)]
struct PendingScans {
- all: bool,
- folders: BTreeSet,
+ all: Option,
+ folders: BTreeMap,
}
impl PendingScans {
fn push(&mut self, id: Option) {
+ self.push_with_background(id, false);
+ }
+
+ fn push_with_background(&mut self, id: Option, background: bool) {
match id {
None => {
- self.all = true;
+ self.all = Some(
+ background
+ && self.all.unwrap_or(true)
+ && self.folders.values().all(|background| *background),
+ );
self.folders.clear();
}
- Some(id) if !self.all => {
- self.folders.insert(id);
+ Some(id) if self.all.is_none() => {
+ self.folders
+ .entry(id)
+ .and_modify(|old| *old &= background)
+ .or_insert(background);
}
- Some(_) => {}
+ Some(_) => *self.all.as_mut().unwrap() &= background,
}
}
- fn pop(&mut self) -> Option