From 07519df062f44d81ff082de6e40cdf6d2ab9d920 Mon Sep 17 00:00:00 2001 From: RVZO6 Date: Sat, 24 Oct 2026 23:23:59 -0400 Subject: [PATCH 1/4] Handle server stop-sound packets through the existing sound engine Decode source/event selection flags, including 26.3 UI source 10, and route them to Audio.stop_sounds. Compare all 36 native Java codec selections and round-trip their bytes; reject invalid sources and truncated packets. Co-Authored-By: Codex (gpt-6.1-sol) --- crates/horizon-client/src/game/remote.rs | 3 ++ .../examples/stop_sound_probe.rs | 31 ++++++++++++++++ crates/horizon-protocol/src/packets/play.rs | 37 +++++++++++++++++++ .../parity/VanillaStopSoundWireOracle.java | 30 +++++++++++++++ tools/test_stop_sound_wire_parity.py | 35 ++++++++++++++++++ 5 files changed, 136 insertions(+) create mode 100644 crates/horizon-protocol/examples/stop_sound_probe.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStopSoundWireOracle.java create mode 100644 tools/test_stop_sound_wire_parity.py diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index aa0490655..a5d67f61f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1790,6 +1790,9 @@ impl Game<'_> { self.audio.play(&name, Some(at), p.volume, p.pitch); } } + C::StopSound(p) => self + .audio + .stop_sounds(p.sound.as_deref(), p.source.map(|s| s as usize)), C::AddEntity(p) => { let kind = self .remote diff --git a/crates/horizon-protocol/examples/stop_sound_probe.rs b/crates/horizon-protocol/examples/stop_sound_probe.rs new file mode 100644 index 000000000..d09478bd5 --- /dev/null +++ b/crates/horizon-protocol/examples/stop_sound_probe.rs @@ -0,0 +1,31 @@ +use horizon_protocol::{ + buf::{Codec, Reader, Writer}, + packets::play::StopSound, +}; +use std::{error::Error, io::Write}; +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let mut out = std::fs::File::create(&args[2])?; + for line in std::fs::read_to_string(&args[1])?.lines() { + let input: serde_json::Value = serde_json::from_str(line)?; + let hex = input["wire"].as_str().unwrap(); + let bytes: Vec = (0..hex.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&hex[i..i + 2], 16)) + .collect::>()?; + let mut reader = Reader::new(&bytes); + let packet = StopSound::read(&mut reader)?; + assert_eq!(reader.remaining(), 0); + let mut writer = Writer::new(); + StopSound::write(&packet, &mut writer); + assert_eq!(writer.data, bytes); + writeln!( + out, + "{}", + serde_json::json!({"source":packet.source,"sound":packet.sound}) + )?; + } + assert!(StopSound::read(&mut Reader::new(&[1, 11])).is_err()); + assert!(StopSound::read(&mut Reader::new(&[3])).is_err()); + Ok(()) +} diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 42e3ba686..519568282 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -1118,6 +1118,42 @@ packet!(SoundEntity { pitch: f32 => Float, seed: i64 => Long, }); + +/// ClientboundStopSoundPacket: bit 0 selects a source, bit 1 an event id. +#[derive(Clone, Debug, PartialEq)] +pub struct StopSound { + pub source: Option, + pub sound: Option, +} +impl Codec for StopSound { + fn read(r: &mut Reader) -> crate::Result { + let flags = r.u8()?; + let source = if flags & 1 != 0 { + let value = r.varint()?; + if !(0..11).contains(&value) { + return Err(crate::Error::new("invalid sound source")); + } + Some(value) + } else { + None + }; + let sound = if flags & 2 != 0 { + Some(r.string(32767)?) + } else { + None + }; + Ok(Self { source, sound }) + } + fn write(p: &Self, w: &mut Writer) { + w.u8(u8::from(p.source.is_some()) | (u8::from(p.sound.is_some()) << 1)); + if let Some(source) = p.source { + w.varint(source); + } + if let Some(sound) = &p.sound { + w.string(sound); + } + } +} /// One entry of ClientboundCommandsPacket: a literal or an argument node. #[derive(Clone, Debug, PartialEq)] pub struct CommandNode { @@ -1678,6 +1714,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { SetTitlesAnimation(TitlesAnimation) = SET_TITLES_ANIMATION, Sound(Sound) = SOUND, SoundEntity(SoundEntity) = SOUND_ENTITY, + StopSound(StopSound) = STOP_SOUND, StartConfiguration(Empty) = START_CONFIGURATION, SwingAnimation(SwingAnimation) = SWING_ANIMATION, SystemChat(SystemChat) = SYSTEM_CHAT, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStopSoundWireOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStopSoundWireOracle.java new file mode 100644 index 000000000..aebeba486 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStopSoundWireOracle.java @@ -0,0 +1,30 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import io.netty.buffer.Unpooled; +import java.nio.file.*; +import java.util.*; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundStopSoundPacket; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.SoundSource; + +/** Every source/event selection combination through the native stream codec. */ +public final class VanillaStopSoundWireOracle { + public static void main(String[] args) throws Exception { + var out = new ArrayList(); + for (int source = -1; source < SoundSource.values().length; source++) { + for (String sound : new String[]{null, "minecraft:entity.pig.ambient", "example:custom"}) { + var packet = new ClientboundStopSoundPacket(sound == null ? null : Identifier.parse(sound), source < 0 ? null : SoundSource.values()[source]); + var buf = new FriendlyByteBuf(Unpooled.buffer()); + ClientboundStopSoundPacket.STREAM_CODEC.encode(buf, packet); + byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); buf.release(); + var result = new JsonObject(); result.addProperty("wire", HexFormat.of().formatHex(bytes)); + result.add("source", source < 0 ? JsonNull.INSTANCE : new JsonPrimitive(source)); + result.add("sound", sound == null ? JsonNull.INSTANCE : new JsonPrimitive(sound)); + out.add(new Gson().toJson(result)); + } + } + Files.write(Path.of(args[0]), out); + } +} diff --git a/tools/test_stop_sound_wire_parity.py b/tools/test_stop_sound_wire_parity.py new file mode 100644 index 000000000..480e760a5 --- /dev/null +++ b/tools/test_stop_sound_wire_parity.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Stop-sound packet bytes and selections against the native Java codec.""" +import json +import os +try: + from . import lab, test_rust_parity as base, oracle_harness as harness +except ImportError: + import lab + import test_rust_parity as base + import oracle_harness as harness + + +def main(): + build=lab.LOCAL/'stop-sound-wire-parity'; build.mkdir(exist_ok=True) + (build/'report.json').unlink(missing_ok=True) + lock,jars,libraries=base.verify_artifacts() + cp=os.pathsep.join(map(str,[jars['server'],*libraries])); classes=build/'classes';classes.mkdir(exist_ok=True) + source=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStopSoundWireOracle.java' + sources=[source,lab.ROOT/'crates/horizon-protocol/src/packets/play.rs',lab.ROOT/'crates/horizon-client/src/game/remote.rs'] + tested=base.source_hashes(sources) + run=lambda cmd,name:harness.run_logged(cmd,build,name) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',cp,'-d',classes,source],'compile-java') + run(['java','-cp',str(classes)+os.pathsep+cp,'dev.horizonlab.parity.VanillaStopSoundWireOracle',build/'java.jsonl'],'java') + run(['cargo','build','-p','horizon-protocol','--example','stop_sound_probe'],'compile-rust') + run([lab.cargo_target()/'debug/examples/stop_sound_probe',build/'java.jsonl',build/'rust.jsonl'],'rust') + java=[json.loads(x) for x in (build/'java.jsonl').read_text().splitlines()] + rust=[json.loads(x) for x in (build/'rust.jsonl').read_text().splitlines()] + assert len(java)==len(rust)==36 + assert all({'source':a.get('source'),'sound':a.get('sound')}==b for a,b in zip(java,rust)) + base.ensure_sources_unchanged(sources,tested) + lab.write_json(build/'report.json',{'pass':True,'cases':len(java),'sources_sha256':tested}) + print(f'Stop sound: {len(java)} native wire selections match and re-encode byte for byte') + + +if __name__=='__main__':main() From b0918f3be1cc93b5ee286fef80242bf5531eeaab Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 06:07:43 +0100 Subject: [PATCH 2/4] /stopsound: send each targeted server player the stop-sound packet StopSoundCommand sends ClientboundStopSoundPacket to every target. The command stopped the server's own sounds instead, so on the server thread (single player's default) and for LAN guests nothing stopped. Co-Authored-By: Claude Opus 5.5 --- .../src/game/commands/world_cmds.rs | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 1f7504d8a..d7e47417c 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -345,7 +345,26 @@ impl Game<'_> { Some(Arg::Resource(s)) => Some(s.clone()), _ => None, }; - self.audio.stop_sounds(sound.as_deref(), source); + // StopSoundCommand: each target's connection gets the packet; the + // window's own player stops its sounds. + let packet = C::StopSound(play::StopSound { + source: source.map(|s| s as i32), + sound: sound.clone(), + }); + for &t in &targets { + match t { + Target::Player if self.lan_acting.is_some() => { + self.guest_packets.push(packet.clone()); + } + Target::Player => self.audio.stop_sounds(sound.as_deref(), source), + Target::Guest(conn) => { + if let Some(host) = self.lan.as_ref() { + host.hub.send_to(conn, &packet); + } + } + _ => {} + } + } let key = match (source, &sound) { (Some(_), Some(_)) => "commands.stopsound.success.source.sound", (Some(_), None) => "commands.stopsound.success.source.any", From b15e46c3af88db311c634afd48082ffe9b4c4a41 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 06:26:45 +0100 Subject: [PATCH 3/4] lan_e2e stopsound: each target's client gets the stop (status counts stops) Sounds can't be observed playing without an audio device, so the control status counts each stopped selection, as it counts the sounds heard. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/audio.rs | 12 ++++++++ crates/horizon-client/src/game/control.rs | 1 + tools/lan_e2e.py | 37 +++++++++++++++++++++++ 3 files changed, 50 insertions(+) diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index e59ffd867..be6628ece 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -161,6 +161,9 @@ pub struct Audio { /// How many times each positional sound played (the control socket's `status`), /// with or without an audio device. pub heard: std::collections::BTreeMap, + /// How many times each selection was stopped ("record *", "* minecraft:…", `*` for + /// any), with or without an audio device, as `heard`. + pub stopped: std::collections::BTreeMap, } fn decode(path: &Path) -> Option<(Vec, u32)> { use symphonia::core::{ @@ -595,6 +598,7 @@ impl Audio { source_override: None, capture: None, heard: Default::default(), + stopped: Default::default(), } } #[cfg(not(feature = "audio"))] @@ -825,6 +829,14 @@ impl Audio { /// and/or a source. pub fn stop_sounds(&mut self, event: Option<&str>, source: Option) { let event = event.map(crate::sound_events::normalize); + let selection = format!( + "{} {}", + source + .and_then(|s| crate::settings::SOUND_SOURCES.get(s)) + .map_or("*", |s| s), + event.as_deref().unwrap_or("*") + ); + *self.stopped.entry(selection).or_default() += 1; self.engine .stop_matching(event.as_deref(), source, &mut self.backend); } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 205a66074..d48f657ed 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -981,6 +981,7 @@ impl Game<'_> { status["destroying"] = json!(destroying); status["physical_keys"] = json!(physical_keys); status["heard"] = json!(self.audio.heard); + status["stopped_sounds"] = json!(self.audio.stopped); // Boats, minecarts, armor stands, item frames and paintings. status["objects"] = json!(self.objects_status()); status["lightning"] = json!({"bolts": self.bolts.len(), "struck": self.lightning_seen[0], diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 3ece4b448..98de75b3f 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -228,6 +228,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - villagers: the guest sees each villager's and zombie villager's type, profession and level as the host has them, and an unemployed villager that takes a composter becomes a farmer on the guest too (the guest used to draw every villager as an unemployed plains one). +- stopsound: the host's and the guest's own /stopsound, by source and by event, reach their own + client's sounds, and the host's /stopsound of the guest only the guest's (StopSoundCommand + sends each target its packet). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -5496,5 +5499,39 @@ CHECKS += ['villagers'] CHECK_FNS.update(villagers=check_villagers) +def check_stopsound(host, guest, out): + """StopSoundCommand sends each target ClientboundStopSoundPacket: a player's own /stopsound by + source and by event reaches its own client's sound engine, and the host's /stopsound of the + guest reaches the guest's (sounds stopped, counted in the status as `heard` is, audio or not).""" + event = 'minecraft:music_disc.cat' + + def stopped(game): + return game('status')['stopped_sounds'] + + seen = {} + for game in (host, guest): + before = stopped(game) + game('command', command='stopsound @s record') + game('command', command=f'stopsound @s * {event}') + game.wait(10) + after = stopped(game) + seen[game.name] = {k: after.get(k, 0) - before.get(k, 0) for k in after} + assert seen[game.name].get('record *') == 1 and seen[game.name].get(f'* {event}') == 1, \ + f'{game.name}: its own /stopsound did not reach its client: {seen}' + before = {g.name: stopped(g) for g in (host, guest)} + host('command', command=f'stopsound {GUEST_NAME}') + guest.wait(10) + for game in (host, guest): + after = stopped(game) + seen[f'{game.name}-by-host'] = after.get('* *', 0) - before[game.name].get('* *', 0) + assert seen['guest-by-host'] == 1 and seen['host-by-host'] == 0, \ + f"the host's /stopsound of the guest stopped the wrong client: {seen}" + return seen + + +CHECKS += ['stopsound'] +CHECK_FNS.update(stopsound=check_stopsound) + + if __name__ == '__main__': main() From ea0905e8a2ccfe461bb422adcf6ce744639f880c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 08:58:25 +0100 Subject: [PATCH 4/4] lan_e2e: no blank lines inside the docstring after the merge Co-Authored-By: Claude Sonnet 5.5 --- tools/lan_e2e.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index ff8424126..0c8979f0a 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -243,8 +243,6 @@ address. The script then checks, from both sides, what a guest's game used to ge - stopsound: the host's and the guest's own /stopsound, by source and by event, reach their own client's sounds, and the host's /stopsound of the guest only the guest's (StopSoundCommand sends each target its packet). - - - hero-trading: the host and the guest each trade 20 wheat for an emerald, paying 14 with Hero I and 12 with Hero III; clearing the effect restores the ordinary price (#1365). - falling: an item and a falling block the host summons high up fall smoothly on the guest, a