From d68efbabfc8b911919a04a776024f0c349514301 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:33:17 +0200 Subject: [PATCH] Compare the sound engine bookkeeping with the real vanilla SoundEngine The oracle runs vanilla SoundManager/SoundEngine on OpenAL Soft null device (inline executor, silent buffers) and replays scripts of plays, stops, category gains, option volumes, channel ends, pauses, queued, delayed and looping sounds and tickable ambient instances, printing every AL source parameter, isActive, subtitle notification and pool count per step. Co-Authored-By: Claude Opus 5.5 --- .../examples/sound_engine_fixture.rs | 273 ++++++++++++++++++ .../parity/VanillaSoundEngineOracle.java | 112 +++++++ .../horizonlab/parity/VanillaSoundRig.java | 204 +++++++++++++ tools/audio_harness.py | 7 +- tools/test_sound_engine_parity.py | 247 ++++++++++++++++ 5 files changed, 841 insertions(+), 2 deletions(-) create mode 100644 crates/horizon-client/examples/sound_engine_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundEngineOracle.java create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java create mode 100644 tools/test_sound_engine_parity.py diff --git a/crates/horizon-client/examples/sound_engine_fixture.rs b/crates/horizon-client/examples/sound_engine_fixture.rs new file mode 100644 index 000000000..a9dfbbb02 --- /dev/null +++ b/crates/horizon-client/examples/sound_engine_fixture.rs @@ -0,0 +1,273 @@ +//! Replays `tools/test_sound_engine_parity.py` scripts through Horizon's +//! `SoundEngine` with a backend recording what an OpenAL source would hold: +//! `sound_engine_fixture ROOT INPUT OUTPUT`. +use horizon_client::sound_engine::{ + Attenuation, Backend, ChannelId, InstanceId, SoundEngine, SoundInstance, TickContext, +}; +use horizon_client::sound_events::{Sound, SoundRegistry}; +use horizon_core::random::LegacyRandom; +use std::collections::{BTreeMap, HashMap}; +use std::io::Write; + +const INITIAL: u32 = 0x1011; +const PLAYING: u32 = 0x1012; +const PAUSED: u32 = 0x1013; +const STOPPED: u32 = 0x1014; + +/// An OpenAL source's state as `alGetSource*` reports it. +#[derive(Clone)] +pub struct Source { + pub state: u32, + pub gain: f32, + pub pitch: f32, + pub position: [f32; 3], + pub relative: bool, + pub looping: bool, + pub model: u32, + pub max: f32, + pub rolloff: f32, + pub reference: f32, +} +impl Default for Source { + fn default() -> Self { + Self { + state: INITIAL, + gain: 1.0, + pitch: 1.0, + position: [0.0; 3], + relative: false, + looping: false, + model: 0xD002, + max: f32::MAX, + rolloff: 1.0, + reference: 1.0, + } + } +} +/// Buffers and streams are ready at once (silence in the oracle); stopping an +/// initial source leaves it initial, as in OpenAL Soft. +#[derive(Default)] +pub struct Fake { + pub sources: HashMap, + next: ChannelId, +} +impl Backend for Fake { + fn create(&mut self, _streaming: bool) -> Option { + self.next += 1; + self.sources.insert(self.next, Source::default()); + Some(self.next) + } + fn destroy(&mut self, channel: ChannelId) { + self.sources.remove(&channel); + } + fn set_pitch(&mut self, c: ChannelId, pitch: f32) { + self.sources.get_mut(&c).expect("source").pitch = pitch; + } + fn set_volume(&mut self, c: ChannelId, volume: f32) { + self.sources.get_mut(&c).expect("source").gain = volume; + } + fn set_attenuation(&mut self, c: ChannelId, linear: Option) { + let s = self.sources.get_mut(&c).expect("source"); + match linear { + Some(max) => { + s.model = 0xD003; + s.max = max; + s.rolloff = 1.0; + s.reference = 0.0; + } + None => s.model = 0, + } + } + fn set_looping(&mut self, c: ChannelId, looping: bool) { + self.sources.get_mut(&c).expect("source").looping = looping; + } + fn set_position(&mut self, c: ChannelId, p: [f64; 3]) { + self.sources.get_mut(&c).expect("source").position = + [p[0] as f32, p[1] as f32, p[2] as f32]; + } + fn set_relative(&mut self, c: ChannelId, relative: bool) { + self.sources.get_mut(&c).expect("source").relative = relative; + } + fn start(&mut self, c: ChannelId, _sound: &Sound, _looping: bool) { + self.sources.get_mut(&c).expect("source").state = PLAYING; + } + fn stop(&mut self, c: ChannelId) { + if let Some(s) = self.sources.get_mut(&c) + && s.state != INITIAL + { + s.state = STOPPED; + } + } + fn pause(&mut self, c: ChannelId) { + let s = self.sources.get_mut(&c).expect("source"); + if s.state == PLAYING { + s.state = PAUSED; + } + } + fn unpause(&mut self, c: ChannelId) { + let s = self.sources.get_mut(&c).expect("source"); + if s.state == PAUSED { + s.state = PLAYING; + } + } + fn stopped(&mut self, c: ChannelId) -> bool { + self.sources.get(&c).is_none_or(|s| s.state == STOPPED) + } +} +fn bits(v: f32) -> String { + format!("{:08x}", v.to_bits()) +} +fn f(hex: &str) -> f32 { + f32::from_bits(u32::from_str_radix(hex, 16).expect("float")) +} +fn d(hex: &str) -> f64 { + f64::from_bits(u64::from_str_radix(hex, 16).expect("double")) +} +/// The shared per-step dump (instances, notifications, pool counts). +pub fn describe(engine: &SoundEngine, backend: &Fake, name: &str, id: InstanceId) -> String { + let mut s = format!(" {name} active={}", engine.is_active(id)); + match engine.channel(id).and_then(|c| backend.sources.get(&c)) { + None => s.push_str(" channel=-"), + Some(src) => s.push_str(&format!( + " state={:x} gain={} pitch={} pos={},{},{} rel={} loop={} model={:x} max={} rolloff={} ref={}", + src.state, + bits(src.gain), + bits(src.pitch), + bits(src.position[0]), + bits(src.position[1]), + bits(src.position[2]), + u8::from(src.relative), + u8::from(src.looping), + src.model, + bits(src.max), + bits(src.rolloff), + bits(src.reference) + )), + } + s +} +pub fn flush(engine: &mut SoundEngine, out: &mut impl Write) { + for n in std::mem::take(&mut engine.notifications) { + writeln!( + out, + "notify {} {} {} {} {:016x} {:016x} {:016x}", + n.identifier, + n.subtitle.as_deref().unwrap_or("-"), + bits(n.range), + n.looping, + n.position[0].to_bits(), + n.position[1].to_bits(), + n.position[2].to_bits() + ) + .expect("write"); + } + let [used, streaming] = engine.used_channels(); + writeln!( + out, + " Sounds: {used}/{} + {streaming}/{}", + engine.limits[0], engine.limits[1] + ) + .expect("write"); +} + +fn main() { + let args: Vec = std::env::args().collect(); + let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); + engine.listening = true; + let mut backend = Fake::default(); + let mut ctx = TickContext::default(); + let mut instances: BTreeMap = BTreeMap::new(); + let input = std::fs::read_to_string(&args[2]).expect("input"); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); + for line in input.lines() { + writeln!(out, "{line}").expect("write"); + let a: Vec<&str> = line.split(' ').collect(); + let source = |i: usize| a[i].parse::().expect("source"); + match a[0] { + "play" => { + let event = horizon_client::sound_events::normalize(a[3]); + let random = LegacyRandom::new(a[14].parse().expect("seed")); + let instance = match a[2] { + "simple" => SoundInstance::new( + &event, + source(4), + f(a[5]), + f(a[6]), + random, + a[10] == "1", + a[11].parse().expect("delay"), + if a[12] == "linear" { + Attenuation::Linear + } else { + Attenuation::None + }, + [d(a[7]), d(a[8]), d(a[9])], + a[13] == "1", + ), + "loop" => SoundInstance::biome_loop(&event, random), + "uloop" => SoundInstance::under_liquid_loop(&event, random), + "usub" => SoundInstance::under_liquid_sub(&event, random), + _ => panic!("{line}"), + }; + if let Some(old) = instances.remove(a[1]) { + engine.release(old); + } + let (id, result) = engine.play_new(instance, true, &mut backend); + instances.insert(a[1].to_owned(), id); + writeln!(out, " result {}", result_name(result)).expect("write"); + } + "replay" => { + let result = engine.play(instances[a[1]], &mut backend); + writeln!(out, " result {}", result_name(result)).expect("write"); + } + "queue" => engine.queue_ticking(instances[a[1]]), + "delayed" => engine.play_delayed(instances[a[1]], a[2].parse().expect("delay")), + "fade" => { + let i = engine.instance_mut(instances[a[1]]).expect("instance"); + if a[2] == "in" { + i.fade_in(); + } else { + i.fade_out(); + } + } + "stop" => engine.stop(instances[a[1]], &mut backend), + "stopmatch" => { + let sound = (a[1] != "-").then(|| horizon_client::sound_events::normalize(a[1])); + let src = (a[2] != "-").then(|| source(2)); + engine.stop_matching(sound.as_deref(), src, &mut backend); + } + "finish" => { + if let Some(c) = engine.channel(instances[a[1]]) { + backend.stop(c); + } + } + "gain" => engine.update_category_volume(source(1), f(a[2]), &mut backend), + "volume" => engine.source_volumes[source(1)] = f(a[2]), + "refresh" => engine.refresh_category_volume(source(1), &mut backend), + "pause" => engine.pause_all_except(&[1, 10], &mut backend), + "resume" => engine.resume(&mut backend), + "player" => { + ctx.player_underwater = a[1] == "1"; + ctx.player_removed = a[2] == "1"; + } + "tick" => engine.tick(a[1] == "1", &ctx, &mut backend), + "forget" => { + if let Some(id) = instances.remove(a[1]) { + engine.release(id); + } + } + _ => panic!("{line}"), + } + for (name, id) in &instances { + writeln!(out, "{}", describe(&engine, &backend, name, *id)).expect("write"); + } + flush(&mut engine, &mut out); + } +} +fn result_name(r: horizon_client::sound_engine::PlayResult) -> &'static str { + match r { + horizon_client::sound_engine::PlayResult::Started => "STARTED", + horizon_client::sound_engine::PlayResult::StartedSilently => "STARTED_SILENTLY", + horizon_client::sound_engine::PlayResult::NotStarted => "NOT_STARTED", + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundEngineOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundEngineOracle.java new file mode 100644 index 000000000..317dc177b --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundEngineOracle.java @@ -0,0 +1,112 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.lang.reflect.Constructor; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.resources.sounds.*; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.Entity; + +/** + * Drives the real SoundEngine (see VanillaSoundRig) with a script of plays, + * stops, category gains, option volumes, channel ends, pauses and ticks, and + * prints after every step each instance's activity and AL source parameters, + * the subtitle notifications and the channel pool counts. + */ +public final class VanillaSoundEngineOracle { + /** The local player the underwater instances look at. */ + public static final class Actor extends LocalPlayer { + boolean underwater; + + Actor() { + super(null, null, null, null, null, null, false, null, null); + } + + @Override + public boolean isUnderWater() { + return underwater; + } + } + + static float f(String hex) { + return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16)); + } + + static double d(String hex) { + return Double.longBitsToDouble(Long.parseUnsignedLong(hex, 16)); + } + + static void seed(SoundInstance instance, long seed) throws Exception { + VanillaSoundRig.set(instance, AbstractSoundInstance.class, "random", RandomSource.create(seed)); + } + + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var rig = new VanillaSoundRig(Path.of(args[0])); + var actor = VanillaSoundRig.make(Actor.class); + Constructor sub = UnderLiquidSubSound.class.getDeclaredConstructor(LocalPlayer.class, SoundEvent.class); + sub.setAccessible(true); + var instances = new TreeMap(); + var manager = rig.manager; + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) { + for (String line : Files.readAllLines(Path.of(args[1]))) { + out.println(line); + String[] a = line.split(" "); + switch (a[0]) { + case "play" -> { + // play name kind event source volume pitch x y z looping delay attenuation relative seed + Identifier id = Identifier.parse(a[3]); + SoundEvent event = SoundEvent.createVariableRangeEvent(id); + long seed = Long.parseLong(a[14]); + SoundInstance instance = switch (a[2]) { + case "simple" -> new SimpleSoundInstance(id, SoundSource.values()[Integer.parseInt(a[4])], f(a[5]), f(a[6]), + RandomSource.create(seed), a[10].equals("1"), Integer.parseInt(a[11]), + a[12].equals("linear") ? SoundInstance.Attenuation.LINEAR : SoundInstance.Attenuation.NONE, d(a[7]), d(a[8]), d(a[9]), + a[13].equals("1")); + case "loop" -> new BiomeAmbientSoundsHandler.LoopSoundInstance(event); + case "uloop" -> new UnderLiquidAmbientSoundInstance(event, actor, LocalPlayer::isUnderWater); + case "usub" -> sub.newInstance(actor, event); + default -> throw new IllegalArgumentException(line); + }; + if (!a[2].equals("simple")) seed(instance, seed); + instances.put(a[1], instance); + out.println(" result " + manager.play(instance)); + } + case "replay" -> out.println(" result " + manager.play(instances.get(a[1]))); + case "queue" -> manager.queueTickingSound((TickableSoundInstance) instances.get(a[1])); + case "delayed" -> manager.playDelayed(instances.get(a[1]), Integer.parseInt(a[2])); + case "fade" -> { + if (instances.get(a[1]) instanceof BiomeAmbientSoundsHandler.LoopSoundInstance loop) { + if (a[2].equals("in")) loop.fadeIn(); else loop.fadeOut(); + } + } + case "stop" -> manager.stop(instances.get(a[1])); + case "stopmatch" -> manager.stop(a[1].equals("-") ? null : Identifier.parse(a[1]), + a[2].equals("-") ? null : SoundSource.values()[Integer.parseInt(a[2])]); + case "finish" -> rig.finish(instances.get(a[1])); + case "gain" -> manager.updateCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2])); + case "volume" -> rig.volume(SoundSource.values()[Integer.parseInt(a[1])], f(a[2])); + case "refresh" -> manager.refreshCategoryVolume(SoundSource.values()[Integer.parseInt(a[1])]); + case "pause" -> manager.pauseAllExcept(SoundSource.MUSIC, SoundSource.UI); + case "resume" -> manager.resume(); + case "player" -> { + actor.underwater = a[1].equals("1"); + VanillaSoundRig.set(actor, Entity.class, "removalReason", a[2].equals("1") ? Entity.RemovalReason.DISCARDED : null); + } + case "tick" -> manager.tick(a[1].equals("1")); + case "forget" -> instances.remove(a[1]); + default -> throw new IllegalArgumentException(line); + } + for (var e : instances.entrySet()) out.println(rig.describe(e.getKey(), e.getValue())); + rig.flush(out); + } + } + System.exit(0); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java new file mode 100644 index 000000000..8edef9325 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java @@ -0,0 +1,204 @@ +package dev.horizonlab.parity; + +import com.mojang.blaze3d.audio.*; +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.ByteBuffer; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import javax.sound.sampled.AudioFormat; +import net.minecraft.client.OptionInstance; +import net.minecraft.client.Options; +import net.minecraft.client.resources.sounds.SoundInstance; +import net.minecraft.client.sounds.*; +import net.minecraft.network.chat.contents.TranslatableContents; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.SoundSource; +import org.lwjgl.openal.AL10; + +/** + * A real vanilla SoundManager/SoundEngine running on OpenAL Soft's "No Output" + * device (ALSOFT_DRIVERS=null), shared by the audio oracles. + * + * Determinism: the sound executor runs each task inline (the model where the + * sound thread keeps up between client ticks); static sounds get one silent + * hour-long buffer (they play until stopped or "finished" by the script) and + * streams play endless silence. Everything else, the + * channel pools, AL source parameters, lifetimes and bookkeeping, is the real + * code and the real OpenAL implementation. + */ +public final class VanillaSoundRig { + static Object unsafe; + static Method allocate; + + static T make(Class type) throws Exception { + if (unsafe == null) { + var u = Class.forName("sun.misc.Unsafe"); + unsafe = field(u, "theUnsafe").get(null); + allocate = u.getMethod("allocateInstance", Class.class); + } + return type.cast(allocate.invoke(unsafe, type)); + } + + static Field field(Class type, String name) throws Exception { + var f = type.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + static Object get(Object target, Class type, String name) throws Exception { + return field(type, name).get(target); + } + + static void set(Object target, Class type, String name, Object value) throws Exception { + field(type, name).set(target, value); + } + + /** Runs every task on the calling thread. */ + public static final class Inline extends SoundEngineExecutor { + @Override + public void execute(final Runnable command) { + command.run(); + } + + @Override + public void shutDown() { + } + + @Override + public void startUp() { + } + } + + static SoundBuffer silence; + + /** Static sounds: a silent hour; streams: endless silence. */ + public static final class Buffers extends SoundBufferLibrary { + Buffers() { + super(null); + } + + @Override + public CompletableFuture getCompleteBuffer(final Identifier location) { + return CompletableFuture.completedFuture(silence); + } + + @Override + public CompletableFuture getStream(final Identifier location, final boolean looping) { + return CompletableFuture.completedFuture(new Silence()); + } + } + + /** An endless silent stream, a minute per read (it never runs dry between ticks). */ + public static final class Silence implements AudioStream { + static final AudioFormat FORMAT = new AudioFormat(8000.0F, 8, 1, false, false); + + @Override + public AudioFormat getFormat() { + return FORMAT; + } + + @Override + public ByteBuffer read(final int expectedSize) { + ByteBuffer data = ByteBuffer.allocateDirect(8000 * 60); + for (int i = 0; i < data.capacity(); i++) data.put(i, (byte) 0x80); + return data; + } + + @Override + public void close() { + } + } + + public final SoundManager manager; + public final SoundEngine engine; + public final Options options; + public final List heard = new ArrayList<>(); + + public VanillaSoundRig(Path root) throws Exception { + manager = VanillaSoundEventOracle.load(root); + engine = (SoundEngine) get(manager, SoundManager.class, "soundEngine"); + options = (Options) get(engine, SoundEngine.class, "options"); + var inline = make(Inline.class); + set(engine, SoundEngine.class, "executor", inline); + set(get(engine, SoundEngine.class, "channelAccess"), ChannelAccess.class, "executor", inline); + set(engine, SoundEngine.class, "soundBuffers", make(Buffers.class)); + Library library = (Library) get(engine, SoundEngine.class, "library"); + library.init(null, DeviceList.query(), false); + ByteBuffer data = ByteBuffer.allocateDirect(8000 * 3600); + for (int i = 0; i < data.capacity(); i++) data.put(i, (byte) 0x80); + silence = new SoundBuffer(data, new AudioFormat(8000.0F, 8, 1, false, false)); + set(engine, SoundEngine.class, "loaded", true); + Method slider = Options.class.getDeclaredMethod("createSoundSliderOptionInstance", String.class, SoundSource.class); + slider.setAccessible(true); + var volumes = new EnumMap>(SoundSource.class); + for (SoundSource source : SoundSource.values()) { + volumes.put(source, (OptionInstance) slider.invoke(options, "soundCategory." + source.getName(), source)); + } + set(options, Options.class, "soundSourceVolumes", volumes); + manager.addListener((sound, event, range) -> { + String subtitle = "-"; + if (event.getSubtitle() != null && event.getSubtitle().getContents() instanceof TranslatableContents t) subtitle = t.getKey(); + heard.add(String.format("notify %s %s %08x %s %016x %016x %016x", sound.getIdentifier(), subtitle, Float.floatToRawIntBits(range), + sound.isLooping(), Double.doubleToRawLongBits(sound.getX()), Double.doubleToRawLongBits(sound.getY()), + Double.doubleToRawLongBits(sound.getZ()))); + }); + } + + /** Set a sound source volume option without its change callback. */ + public void volume(SoundSource source, double value) throws Exception { + set(options.getSoundSourceOptionInstance(source), OptionInstance.class, "value", value); + } + + /** The channel of an instance, or null. */ + @SuppressWarnings("unchecked") + public Channel channel(SoundInstance instance) throws Exception { + var map = (Map) get(engine, SoundEngine.class, "instanceToChannel"); + var handle = map.get(instance); + return handle == null ? null : (Channel) get(handle, ChannelAccess.ChannelHandle.class, "channel"); + } + + /** The channel's end: what OpenAL does when a non-looping buffer runs out. */ + public void finish(SoundInstance instance) throws Exception { + var channel = channel(instance); + if (channel != null) channel.stop(); + } + + static String fbits(float v) { + return String.format("%08x", Float.floatToRawIntBits(v)); + } + + /** One line describing an instance: activity and its AL source. */ + public String describe(String name, SoundInstance instance) throws Exception { + StringBuilder sb = new StringBuilder(" ").append(name).append(" active=").append(manager.isActive(instance)); + var channel = channel(instance); + if (channel == null) { + sb.append(" channel=-"); + } else { + int source = (int) get(channel, Channel.class, "source"); + boolean initialized = ((java.util.concurrent.atomic.AtomicBoolean) get(channel, Channel.class, "initialized")).get(); + if (!initialized) { + sb.append(" channel=released"); + } else { + float[] pos = new float[3]; + AL10.alGetSourcefv(source, AL10.AL_POSITION, pos); + sb.append(String.format(" state=%x gain=%s pitch=%s pos=%s,%s,%s rel=%d loop=%d model=%x max=%s rolloff=%s ref=%s", + AL10.alGetSourcei(source, AL10.AL_SOURCE_STATE), fbits(AL10.alGetSourcef(source, AL10.AL_GAIN)), + fbits(AL10.alGetSourcef(source, AL10.AL_PITCH)), fbits(pos[0]), fbits(pos[1]), fbits(pos[2]), + AL10.alGetSourcei(source, AL10.AL_SOURCE_RELATIVE), AL10.alGetSourcei(source, AL10.AL_LOOPING), + AL10.alGetSourcei(source, 0xD000), fbits(AL10.alGetSourcef(source, AL10.AL_MAX_DISTANCE)), + fbits(AL10.alGetSourcef(source, AL10.AL_ROLLOFF_FACTOR)), fbits(AL10.alGetSourcef(source, AL10.AL_REFERENCE_DISTANCE)))); + } + } + return sb.toString(); + } + + /** Print and clear the notifications, then the channel counts. */ + public void flush(PrintWriter out) { + for (String h : heard) out.println(h); + heard.clear(); + out.println(" " + manager.getChannelDebugString()); + } +} diff --git a/tools/audio_harness.py b/tools/audio_harness.py index bfd18e05e..41e0fa9dd 100644 --- a/tools/audio_harness.py +++ b/tools/audio_harness.py @@ -54,8 +54,11 @@ def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args= input_hash = lab.digest(inputs, 'sha256') def run(command, log, env=None): - with (build / (log + '.log')).open('w') as out: - subprocess.run(list(map(str, command)), cwd=lab.ROOT, check=True, timeout=timeout, stdout=out, stderr=subprocess.STDOUT, env=env) + with (build / (log + ".log")).open("w") as out: + try: + subprocess.run(list(map(str, command)), cwd=lab.ROOT, check=True, timeout=timeout, stdout=out, stderr=subprocess.STDOUT, env=env) + except subprocess.CalledProcessError: + raise SystemExit(f"{log} failed: see {build / (log + '.log')}") from None classes = build / 'classes' classes.mkdir(exist_ok=True) diff --git a/tools/test_sound_engine_parity.py b/tools/test_sound_engine_parity.py new file mode 100644 index 000000000..383ca24b2 --- /dev/null +++ b/tools/test_sound_engine_parity.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Compare the sound engine's bookkeeping with the vanilla 26.3 client. + +The oracle runs the real `SoundManager`/`SoundEngine` on OpenAL Soft's "No +Output" device (see VanillaSoundRig) and replays scripts of plays (simple, +biome loop, underwater loop and sub-sound instances), stops (by instance, by +sound and/or source, all), category gains, source volume options and +refreshes, channel ends, delayed and queued sounds, pauses and client ticks. +After every step it prints each instance's `isActive` and the AL source the +engine configured (state, gain, pitch, position, relative, looping, distance +model, max distance, rolloff, reference distance), the subtitle notifications +and the channel pool counts. Horizon's `SoundEngine` replays the scripts +against a backend that records the same AL source fields. +""" +import json +import random + +try: + from . import audio_harness as h +except ImportError: + import audio_harness as h + + +def dbits(v): + import struct + return struct.pack('>d', v).hex() + + +class Script: + def __init__(self, events, streams): + self.lines = [] + self.events, self.streams = events, streams + + def add(self, *parts): + self.lines.append(' '.join(map(str, parts))) + + def play(self, name, event, source=4, volume=1.0, pitch=1.0, at=(0.0, 0.0, 0.0), looping=0, delay=0, linear=True, relative=0, seed=0, kind='simple'): + self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(dbits, at), looping, delay, + 'linear' if linear else 'none', relative, seed) + + def tick(self, n=1, paused=0): + for _ in range(n): + self.add('tick', paused) + + def reset(self): + self.add('stopmatch', '-', '-') + for source in range(11): + self.add('volume', source, h.bits(1.0)) + self.tick() + + +def scripted(s): + stone, cave, click = 'minecraft:block.stone.break', 'minecraft:ambient.cave', 'minecraft:ui.button.click' + music, loop, uloop = 'minecraft:music.game', 'minecraft:ambient.crimson_forest.loop', 'minecraft:ambient.underwater.loop' + # Positional and relative sounds, lifetimes and channel ends. + s.play('a', stone, 4, 1.0, 0.8, (10.5, 64.0, -3.25), seed=5) + s.play('b', click, 10, 0.25, 1.0, linear=False, relative=1, seed=6) + s.play('c', cave, 8, 4.0, 1.0, (100.0, 20.0, 100.0), seed=7) + s.play('d', stone, 4, 1.5, 3.0, (0.5, 0.5, 0.5), seed=8) + s.play('e', stone, 4, 0.5, 0.1, (1.0, 2.0, 3.0), seed=9) + s.tick(3) + s.add('finish', 'a') + s.tick(25) + s.add('finish', 'b') + s.add('stop', 'c') + s.tick(2) + s.reset() + # Volumes: options, category gains, refreshes, silent starts. + s.add('volume', 4, h.bits(0.5)) + s.add('volume', 0, h.bits(0.75)) + s.play('a', stone, 4, 1.0, 1.0, (1.0, 1.0, 1.0), seed=1) + s.add('volume', 4, h.bits(0.0)) + s.play('b', stone, 4, 1.0, 1.0, (1.0, 1.0, 1.0), seed=2) + s.add('volume', 1, h.bits(0.0)) + s.play('m', music, 1, 1.0, 1.0, linear=False, relative=1, seed=3) + s.add('refresh', 4) + s.add('volume', 4, h.bits(0.3)) + s.add('refresh', 0) + s.add('gain', 1, h.bits(0.5)) + s.add('gain', 1, h.bits(1.5)) + s.add('gain', 4, h.bits(-0.2)) + s.add('volume', 1, h.bits(1.0)) + s.add('refresh', 1) + s.tick(2) + s.add('volume', 0, h.bits(2.0)) + s.add('refresh', 0) + s.reset() + # Biome loops: fades, crossfade, stopping, removal. + s.play('l1', loop, kind='loop', seed=11) + s.add('fade', 'l1', 'in') + s.tick(45) + s.play('l2', 'minecraft:ambient.warped_forest.loop', kind='loop', seed=12) + s.add('fade', 'l1', 'out') + s.add('fade', 'l2', 'in') + s.tick(50) + s.add('fade', 'l2', 'out') + s.tick(10) + s.add('fade', 'l2', 'in') + s.tick(60) + s.add('volume', 8, h.bits(0.0)) + s.play('l3', loop, kind='loop', seed=13) + s.tick(3) + s.reset() + # Underwater loop and sub-sounds. + s.add('player', 1, 0) + s.play('u', uloop, kind='uloop', seed=21) + s.play('v', 'minecraft:ambient.underwater.loop.additions.rare', kind='usub', seed=22) + s.tick(50) + s.add('player', 0, 0) + s.tick(5) + s.add('player', 1, 0) + s.tick(5) + s.add('player', 0, 0) + s.tick(30) + s.add('player', 1, 1) + s.play('u2', uloop, kind='uloop', seed=23) + s.tick(3) + s.add('player', 0, 0) + s.reset() + # Queued tickables, delayed and manually looped sounds. + s.play('q', loop, kind='loop', seed=31) + s.add('stop', 'q') + s.tick(25) + s.add('queue', 'q') + s.add('fade', 'q', 'in') + s.tick(3) + s.play('w', stone, 4, 1.0, 1.0, (2.0, 2.0, 2.0), seed=32) + s.add('delayed', 'w', 5) + s.tick(7) + s.play('r', stone, 4, 1.0, 1.0, (3.0, 3.0, 3.0), looping=1, delay=4, seed=33) + s.tick(22) + s.add('finish', 'r') + s.tick(8) + s.add('finish', 'r') + s.tick(6) + s.play('n', stone, 4, 1.0, 1.0, (3.0, 3.0, 3.0), looping=1, seed=34) + s.tick(2) + s.reset() + # Stopping by source and sound, pauses. + s.play('a', stone, 4, seed=41) + s.play('b', stone, 5, seed=42) + s.play('c', cave, 8, seed=43) + s.play('m', music, 1, linear=False, relative=1, seed=44) + s.play('u', click, 10, linear=False, relative=1, seed=45) + s.add('pause') + s.tick(1, paused=1) + s.add('stop', 'm') + s.tick(1, paused=1) + s.add('resume') + s.add('stopmatch', stone, '-') + s.tick(25) + s.add('stopmatch', '-', 8) + s.add('stopmatch', click, 4) + s.add('stopmatch', click, 10) + s.tick(2) + s.reset() + # Unknown, empty and intentionally empty events; replaying an instance. + for i, event in enumerate(['minecraft:not.a.sound', 'minecraft:intentionally_empty', 'minecraft:empty', 'minecraft:entity.generic.eat']): + s.play(f'x{i}', event, 6, seed=50 + i) + s.add('replay', 'x3') + s.tick(25) + s.reset() + # Channel pools. + for i in range(252): + s.play('p', stone, 4, 1.0, 1.0, (float(i), 0.0, 0.0), seed=i) + for i in range(10): + s.play('s', music, 1, linear=False, relative=1, seed=i) + s.tick(2) + s.add('stopmatch', '-', '-') + s.tick(1) + + +def fuzz(s, rng, steps): + names = ['f0', 'f1', 'f2', 'f3', 'f4', 'f5'] + live = set() + for _ in range(steps): + op = rng.random() + name = rng.choice(names) + if op < 0.25: + kind = rng.choice(['simple', 'simple', 'simple', 'loop', 'uloop', 'usub']) + event = rng.choice(s.streams if kind != 'simple' and rng.random() < 0.5 else s.events) + at = tuple(rng.choice([0.0, rng.uniform(-200, 200)]) for _ in range(3)) + s.play(name, event, rng.randrange(11), rng.choice([1.0, 0.5, 2.0, 0.0, 4.0, rng.uniform(0, 3)]), rng.choice([1.0, 0.5, 2.5, rng.uniform(0.2, 3)]), + at, int(rng.random() < 0.2), rng.choice([0, 0, 0, 3]), rng.random() < 0.7, int(rng.random() < 0.3), rng.getrandbits(63), kind) + live.add(name) + elif not live: + s.tick() + elif op < 0.32: + s.add('finish', rng.choice(sorted(live))) + elif op < 0.36: + s.add('stop', rng.choice(sorted(live))) + elif op < 0.40: + s.add('fade', rng.choice(sorted(live)), rng.choice(['in', 'out'])) + elif op < 0.42: + s.add('stopmatch', rng.choice(['-', rng.choice(s.events)]), rng.choice(['-', rng.randrange(11)])) + elif op < 0.45: + s.add('volume', rng.randrange(11), h.bits(rng.choice([0.0, 1.0, 0.5, rng.random()]))) + elif op < 0.48: + s.add('refresh', rng.randrange(11)) + elif op < 0.51: + s.add('gain', rng.randrange(11), h.bits(rng.choice([0.0, 1.0, 0.3, 1.2]))) + elif op < 0.53: + s.add('player', int(rng.random() < 0.6), int(rng.random() < 0.05)) + elif op < 0.55: + s.add('replay', rng.choice(sorted(live))) + elif op < 0.56: + s.add('pause') + s.tick(rng.randrange(1, 4), paused=1) + s.add('resume') + elif op < 0.57: + s.add('forget', name) + live.discard(name) + else: + s.tick(rng.randrange(1, 6)) + + +def fixtures(): + sounds = json.loads((h.RESOURCES / 'assets/minecraft/sounds.json').read_text()) + names = sorted(sounds) + streams = sorted('minecraft:' + n for n in names if any(isinstance(e, dict) and e.get('stream') for e in sounds[n].get('sounds', []))) + rng = random.Random(0x454e47494e45) + events = sorted(set(['minecraft:' + rng.choice(names) for _ in range(60)] + ['minecraft:ambient.cave', 'minecraft:block.stone.break'])) + s = Script(events, streams) + scripted(s) + for _ in range(40): + s.reset() + fuzz(s, rng, 150) + return s.lines + + +def main(): + lines = fixtures() + matched, report = h.run_harness( + 'sound-engine', 'VanillaSoundEngineOracle', 'sound_engine_fixture', ''.join(l + '\n' for l in lines), + extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java'], + java_args=[h.RESOURCES], rust_args=[h.RESOURCES], + scope='Real SoundEngine (OpenAL Soft null device, inline executor, silent static buffers, never-ready streams): play results, ' + 'AL source parameters set by play/tickInGameSound/refreshCategoryVolume (gain from calculateVolume, clamped pitch, linear ' + 'attenuation distance, looping, position, relative), isActive, the 20-tick minimum lifetime, channel ends, stop by instance/sound/source/all, ' + 'pauseAllExcept/resume, tickMusicWhenPaused, queued tickables, playDelayed and manual looping, LoopSoundInstance, ' + 'UnderLiquidAmbientSoundInstance and UnderLiquidSubSound ticks, subtitle notifications and ranges, and the 247/8 channel pools. ' + 'Not compared: decoded sample output, OpenAL panning/HRTF and distance gain inside the mixer, asset loading timing.') + print(f'{matched:,} sound engine lines match the pinned client ({len(lines):,} steps): {report}', flush=True) + + +if __name__ == '__main__': + main()