Merge pull request #1729 from RVZO6/fix/stop-sound-packet

Client: honor server stop-sound event and source filters
This commit is contained in:
Ludovic Marie
2026-10-25 09:06:02 +01:00
committed by GitHub
9 changed files with 206 additions and 1 deletions
+12
View File
@@ -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<String, u32>,
/// How many times each selection was stopped ("record *", "* minecraft:…", `*` for
/// any), with or without an audio device, as `heard`.
pub stopped: std::collections::BTreeMap<String, u32>,
}
fn decode(path: &Path) -> Option<(Vec<f32>, 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<usize>) {
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);
}
@@ -353,7 +353,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",
@@ -991,6 +991,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],
+3
View File
@@ -1826,6 +1826,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
@@ -0,0 +1,31 @@
use horizon_protocol::{
buf::{Codec, Reader, Writer},
packets::play::StopSound,
};
use std::{error::Error, io::Write};
fn main() -> Result<(), Box<dyn Error>> {
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<u8> = (0..hex.len())
.step_by(2)
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16))
.collect::<Result<_, _>>()?;
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(())
}
@@ -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<i32>,
pub sound: Option<String>,
}
impl Codec<StopSound> for StopSound {
fn read(r: &mut Reader) -> crate::Result<Self> {
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,
@@ -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<String>();
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);
}
}
+37
View File
@@ -240,6 +240,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).
- 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
@@ -5709,6 +5712,40 @@ 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)
def check_riding_teleport(host, guest, out):
"""#1473: a chat /tp dismounts each player and leaves the horse behind in both modes;
teleporting another player exercises the guest-target command path too."""
+35
View File
@@ -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()