Skip to content
Merged
Next Next commit
fix(audio): sort voice-folder candidates before the random pick
Directory order is not stable, and test_folder_scan_filters_non_audio
only checked that a random play succeeded. The candidate list is now
sorted .ogg/.wav files, and the test asserts that list excludes readme.txt.

Co-authored-by: Andrew Brown <lazyxeon@users.noreply.github.com>
  • Loading branch information
cursoragent and lazyxeon committed Oct 16, 2026
commit ca2d8daf85f9ab22ef2ffb67c93e46715d670827
52 changes: 32 additions & 20 deletions astraweave-audio/src/dialogue_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,28 @@ pub struct DialogueAudioMap {
pub map: HashMap<String, HashMap<String, String>>,
}

/// `.ogg` and `.wav` files in `folder`, sorted by path.
///
/// Directory order is not stable across operating systems. The playback
/// pick is still random; the candidate set is not.
pub fn voice_folder_candidates(folder: &Path) -> Vec<std::path::PathBuf> {
let Ok(rd) = fs::read_dir(folder) else {
return Vec::new();
};
let mut pool = Vec::new();
for entry in rd.flatten() {
let path = entry.path();
let Some(ext) = path.extension().and_then(|ext| ext.to_str()) else {
continue;
};
if ext.eq_ignore_ascii_case("ogg") || ext.eq_ignore_ascii_case("wav") {
pool.push(path);
}
}
pool.sort();
pool
}

pub fn load_dialogue_audio_map(path: &str) -> Result<DialogueAudioMap> {
let txt = fs::read_to_string(path)?;
let m: DialogueAudioMap = toml::from_str(&txt)?;
Expand Down Expand Up @@ -68,26 +90,16 @@ impl<'a> DialoguePlayer<'a> {
}
} else {
// or any .ogg/.wav in folder
if let Ok(rd) = fs::read_dir(&vspec.folder) {
let mut pool: Vec<String> = vec![];
for e in rd.flatten() {
if let Some(ext) = e.path().extension() {
if ext == "ogg" || ext == "wav" {
pool.push(e.path().to_string_lossy().to_string());
}
}
}
if !pool.is_empty() {
let mut rng = rand::rng();
// INVARIANT: pool is non-empty (checked above), so choose always returns Some
#[allow(clippy::expect_used)]
let path = pool
.choose(&mut rng)
.expect("BUG: pool should have items after is_empty check")
.clone();
self.audio.play_voice_file(&path, None)?;
return Ok(true);
}
let pool = voice_folder_candidates(Path::new(&vspec.folder));
if !pool.is_empty() {
let mut rng = rand::rng();
// INVARIANT: pool is non-empty (checked above), so choose always returns Some
#[allow(clippy::expect_used)]
let path = pool
.choose(&mut rng)
.expect("BUG: pool should have items after is_empty check");
self.audio.play_voice_file(&path.to_string_lossy(), None)?;
return Ok(true);
}
}

Expand Down
41 changes: 28 additions & 13 deletions astraweave-audio/tests/dialogue_file_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,11 +450,30 @@ fn test_folder_scan_filters_non_audio() -> Result<()> {
let bank = create_test_voice_bank_folder_scan()?;
let mut audio_engine = AudioEngine::new()?;

// Check that readme.txt exists but won't be selected
assert!(Path::new(test_asset_generator::asset_path(
"speakers/charlie/readme.txt"
))
.exists());
// Check that readme.txt exists but is not a voice candidate.
let readme = test_asset_generator::asset_path("speakers/charlie/readme.txt");
assert!(Path::new(readme).exists());
let candidates = astraweave_audio::dialogue_runtime::voice_folder_candidates(Path::new(
test_asset_generator::asset_path("speakers/charlie"),
));
let names: Vec<String> = candidates
.iter()
.map(|path| {
path.file_name()
.and_then(|name| name.to_str())
.unwrap_or("")
.to_string()
})
.collect();
assert_eq!(
names,
vec![
"line_01.wav".to_string(),
"line_02.wav".to_string(),
"line_03.ogg".to_string()
]
);
assert!(!names.iter().any(|name| name == "readme.txt"));

// Should only select .wav/.ogg files, not .txt
let dialogue = Dialogue {
Expand All @@ -481,14 +500,10 @@ fn test_folder_scan_filters_non_audio() -> Result<()> {
subtitle_out: None,
};

// Run multiple times to ensure we never select readme.txt
for _ in 0..5 {
let result = player.speak_current(&dialogue, &state)?;
assert!(result);
thread::sleep(Duration::from_millis(20));
}

// Tick after the loop to avoid borrow issues
// One play. The candidate assertion above is the filter; this checks
// that a listed file actually opens.
let result = player.speak_current(&dialogue, &state)?;
assert!(result);
audio_engine.tick(0.1);

Ok(())
Expand Down
10 changes: 5 additions & 5 deletions docs/architecture/audio.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ domain: gameplay
lifecycle_status: active
integration_status: wired
owns: [astraweave-audio]
doc_version: "1.7"
doc_version: "1.8"
last_verified_commit: 2702a457
---

Expand All @@ -20,10 +20,10 @@ last_verified_commit: 2702a457
|---|---|
| **System name** | Audio |
| **Primary crates** | `astraweave-audio` (sole production crate); `tools/aw_editor` (editor integration via `audio_bridge.rs`); `astraweave-npc` (single direct consumer in runtime) |
| **Document version** | 1.7 |
| **Document version** | 1.8 |
| **Last verified against commit** | `2702a457` |
| **Last verified date** | 2026-10-15 |
| **Revision history** | 1.7 (2026-10-15): Fixture path strings use `/` so a Windows `D:\a\...` root can be embedded in a TOML basic string. Playback is unchanged.<br><br>1.6 (2026-10-15): Test fixtures only. Each nextest process writes WAVs under `target/audio-test-assets/<pid>` so `cleanup_test_assets` cannot delete another process's files. The playback path is unchanged.<br><br>1.2 (2026-05-12): Deep investigation pass. Closed factual portion of Open Question 4 (aspirational docs origin) — git log identifies commit `28bc94f21` "Create comprehensive bespoke wiki with 51-section documentation structure (#34)" authored by GitHub Copilot bot on 2025-09-08; resolution moved to §6. Enriched §11 Open Questions 2 (PanMode), 8 (hardcoded AudioStats), and 9 (veilweaver_demo) with comprehensive git/source evidence. Corrected §9 hot-paths bench-name reference (`listener_movement_*` exercises `tick`, not a separate `audio_tick_per_frame` bench). Added new cognitive trap in §6: `EmitterId` collision silently reuses the existing `SpatialSink` and overwrites its emitter position. Added new §11 Open Question on the `EmitterId` allocator-less design.<br><br>1.1 (2026-05-12): Verification pass. Confirmed rodio→cpal `!Send + !Sync` chain via `cpal-0.15.3/src/platform/mod.rs:73, 736` (`NotSendSyncAcrossAllPlatforms(PhantomData<*mut ()>)` marker). Corrected Sink/SpatialSink Send/Sync claim — only `OutputStream` is the `!Send` blocker, not the sinks themselves. Confirmed `astraweave-audio` is absent from `miri.yml`, `kani.yml`, `mutation-testing.yml`, `coverage.yml` workflows (CI presence only in `ci.yml`). Recovered partial rationale for 5th bus from commit `745c100a8` ("audio ambient" alongside biome materials). Corrected Appendix A `#[non_exhaustive]` claim (irrelevant within same crate). |
| **Last verified date** | 2026-10-16 |
| **Revision history** | 1.8 (2026-10-16): Folder scan builds a sorted `.ogg`/`.wav` candidate list (`voice_folder_candidates`) so the filter does not depend on directory order. The playback pick stays random.<br><br>1.7 (2026-10-15): Fixture path strings use `/` so a Windows `D:\a\...` root can be embedded in a TOML basic string. Playback is unchanged.<br><br>1.6 (2026-10-15): Test fixtures only. Each nextest process writes WAVs under `target/audio-test-assets/<pid>` so `cleanup_test_assets` cannot delete another process's files. The playback path is unchanged.<br><br>1.2 (2026-05-12): Deep investigation pass. Closed factual portion of Open Question 4 (aspirational docs origin) — git log identifies commit `28bc94f21` "Create comprehensive bespoke wiki with 51-section documentation structure (#34)" authored by GitHub Copilot bot on 2025-09-08; resolution moved to §6. Enriched §11 Open Questions 2 (PanMode), 8 (hardcoded AudioStats), and 9 (veilweaver_demo) with comprehensive git/source evidence. Corrected §9 hot-paths bench-name reference (`listener_movement_*` exercises `tick`, not a separate `audio_tick_per_frame` bench). Added new cognitive trap in §6: `EmitterId` collision silently reuses the existing `SpatialSink` and overwrites its emitter position. Added new §11 Open Question on the `EmitterId` allocator-less design.<br><br>1.1 (2026-05-12): Verification pass. Confirmed rodio→cpal `!Send + !Sync` chain via `cpal-0.15.3/src/platform/mod.rs:73, 736` (`NotSendSyncAcrossAllPlatforms(PhantomData<*mut ()>)` marker). Corrected Sink/SpatialSink Send/Sync claim — only `OutputStream` is the `!Send` blocker, not the sinks themselves. Confirmed `astraweave-audio` is absent from `miri.yml`, `kani.yml`, `mutation-testing.yml`, `coverage.yml` workflows (CI presence only in `ci.yml`). Recovered partial rationale for 5th bus from commit `745c100a8` ("audio ambient" alongside biome materials). Corrected Appendix A `#[non_exhaustive]` claim (irrelevant within same crate). |
| **Status** | Active |
| **Owner notes** | Pure facade crate. No ECS plugin, no system stage registration. Forward-designed editor UI exposes features (HRTF, Doppler, distance model, reverb) that the underlying engine does not yet implement. |

Expand Down Expand Up @@ -240,7 +240,7 @@ Dialogue path: DialoguePlayer::speak_current(dlg, st) (dialogue_runtime.rs:33-1
|---|---|---|---|
| `astraweave-audio/src/lib.rs` | Crate facade: 4-line `pub mod` declarations + 5-line `pub use` re-exports | Active | `#![forbid(unsafe_code)]` (line 1). 31 lines total. Docstring says "4-bus mixer" but the engine has 5 buses — stale. |
| `astraweave-audio/src/engine.rs` | `AudioEngine`, `MusicChannel` (private), `ListenerPose`, `PanMode`, `EmitterId`, `MusicTrack`. 1885 lines (most of which are tests inline). | Active | Single file = entire mixer. Lines 1-431 are production code; lines 484-1885 are `#[cfg(test)]`. |
| `astraweave-audio/src/dialogue_runtime.rs` | `DialoguePlayer`, `DialogueAudioMap`, `load_dialogue_audio_map`. The 5-tier voice resolution chain lives here. | Active | 834 lines; ~110 production + extensive tests. |
| `astraweave-audio/src/dialogue_runtime.rs` | `DialoguePlayer`, `DialogueAudioMap`, `load_dialogue_audio_map`, `voice_folder_candidates`. The 5-tier voice resolution chain lives here. | Active | Folder scan sorts candidates, then picks at random. |
| `astraweave-audio/src/voice.rs` | `VoiceBank`, `VoiceSpec`, `TtsAdapter` trait, `SimpleSineTts` (mock_tts only), `load_voice_bank`. | Active | 241 lines. `SimpleSineTts` and its `hound` dep are feature-gated by `mock_tts` (`Cargo.toml:18-23`). |
| `astraweave-audio/src/mutation_tests.rs` | Test-only module for cargo-mutants resistance. | Active (tests) | 2008 lines, all `#[cfg(test)]`. Targets boundary conditions, operator substitutions, return-value mutations. |
| `astraweave-audio/tests/*.rs` (14 files) | Integration test suite: stress, edge cases, behavioral correctness, mutation resistance, dialogue files, error handling, resource cleanup, integration. | Active (tests) | Total integration test LoC: ~7,063. Several use `#[serial]` (via `serial_test` 3.x) because they share the global default audio device. |
Expand Down