Skip to content

Commit 0720f53

Browse files
authored
Downgrade desktop Huddles to audio protocol v2 (block#6610)
## Summary - negotiate Huddle audio protocol v2 on desktop - decode the released one-byte peer-index prefix - retain roster-driven playout resets and document the missing v3 epoch fence ## Testing - `just desktop-tauri-fmt-check` - `just desktop-tauri-clippy` - `just desktop-tauri-test` Signed-off-by: kenny lopez <[email protected]>
1 parent e236329 commit 0720f53

3 files changed

Lines changed: 82 additions & 81 deletions

File tree

‎desktop/src-tauri/src/huddle/playout.rs‎

Lines changed: 22 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ use tokio_util::sync::CancellationToken;
3333
use super::human_floor::HumanFloor;
3434
use super::jitter::{PeerJitterBuffer, SAMPLE_RATE_HZ};
3535
use super::relay_api::{WsStream, REMOTE_SPEECH_THRESHOLD};
36-
use super::wire::{FrameHeader, FLAG_DTX, V2_HEADER_LEN};
36+
use super::wire::{parse_relay_frame, FLAG_DTX};
3737

3838
/// Speaker-tick window for emitting `huddle-active-speakers`. Active set is
3939
/// cleared each tick — peers that didn't send a frame in the last window are
@@ -149,18 +149,11 @@ fn is_agent_peer(
149149
})
150150
}
151151

152-
/// Whether `peer_idx` is currently occupied at exactly `epoch`, per the
153-
/// authoritative roster. A frame is deliverable only when both match: an index
154-
/// absent from the roster is stale, and a slot reused by a later occupant has
155-
/// advanced its epoch, so a departed occupant's in-flight frame is fenced
156-
/// rather than mis-attributed to the new occupant. A legacy relay omits the
157-
/// epoch, which degrades to `0` on both sides, making the fence a no-op.
158-
fn is_current_occupant(
159-
peer_idx: u8,
160-
epoch: u8,
161-
index_to_epoch: &std::collections::HashMap<u8, u8>,
162-
) -> bool {
163-
index_to_epoch.get(&peer_idx) == Some(&epoch)
152+
/// Whether `peer_idx` is currently occupied per the authoritative roster.
153+
/// Protocol v2 media carries only the peer index, so roster presence is the
154+
/// strongest routing boundary available until the relay supports v3 epochs.
155+
fn is_current_occupant(peer_idx: u8, index_to_epoch: &std::collections::HashMap<u8, u8>) -> bool {
156+
index_to_epoch.contains_key(&peer_idx)
164157
}
165158

166159
fn same_occupancy(
@@ -196,7 +189,7 @@ fn f32_samples_to_le_bytes(samples: &[f32]) -> Vec<u8> {
196189
/// One remote peer's slot: jitter buffer + dedicated rodio Player.
197190
///
198191
/// Per-frame seq/timestamp come from the v2 wire header (sender-authored).
199-
/// The relay forwards `peer_index | epoch | header | opus_bytes` opaquely; we
192+
/// The relay forwards `peer_index | header | opus_bytes` opaquely; we
200193
/// parse the header here and pass the sender's own monotonic seq + 48 kHz media
201194
/// timestamp into NetEq.
202195
struct PeerSlot {
@@ -422,22 +415,19 @@ pub(crate) async fn run_playout_recv_loop(
422415
msg = ws_rx.next() => {
423416
match msg {
424417
Some(Ok(WsMsg::Binary(data))) => {
425-
// Wire shape (v2): [peer_index: u8][epoch: u8][header: 8 bytes][opus payload...]
426-
// The minimum size is 2 (peer_index + epoch) + 8 (header) + ≥1 Opus byte.
427-
if data.len() <= 2 + V2_HEADER_LEN {
418+
// Wire shape (v2): [peer_index: u8][header: 8 bytes][opus payload...]
419+
// The minimum size is 1 (peer index) + 8 (header) + ≥1 Opus byte.
420+
let Some((peer_idx, header, opus_bytes)) = parse_relay_frame(&data) else {
421+
eprintln!(
422+
"buzz-desktop: dropping malformed v2 audio relay frame ({} bytes)",
423+
data.len(),
424+
);
428425
continue;
429-
}
430-
let peer_idx = data[0];
431-
let epoch = data[1];
432-
// Fence the peer-index reuse race: a frame authored by a
433-
// departed occupant that arrives after its index is
434-
// reassigned carries the old epoch. Drop it rather than
435-
// mis-attribute stale audio (and the new occupant's
436-
// human/agent STT policy) to whoever grabbed the index.
437-
// An index absent from the roster is also stale. A slot
438-
// with no known epoch (legacy relay) degrades to 0 on
439-
// both sides, so the fence is a no-op there.
440-
if !is_current_occupant(peer_idx, epoch, &index_to_epoch) {
426+
};
427+
// Protocol v2 has no media epoch. Drop frames for slots
428+
// absent from the control roster; delayed frames after
429+
// an index is reassigned cannot be fenced until v3.
430+
if !is_current_occupant(peer_idx, &index_to_epoch) {
441431
continue;
442432
}
443433
// Suppress only an agent stream synthesized and
@@ -446,21 +436,6 @@ pub(crate) async fn run_playout_recv_loop(
446436
if is_locally_synthesized_peer(peer_idx, &local_tts_publishers) {
447437
continue;
448438
}
449-
let after_idx = &data[2..];
450-
let Some((header, opus_bytes)) = FrameHeader::parse(after_idx)
451-
else {
452-
// Malformed v2 frame: header parse only fails when
453-
// the slice is too short, which `if data.len() <= ...`
454-
// already guards. Defensive log + drop.
455-
eprintln!(
456-
"buzz-desktop: dropping malformed audio frame from peer {peer_idx} ({} bytes)",
457-
data.len(),
458-
);
459-
continue;
460-
};
461-
if opus_bytes.is_empty() {
462-
continue;
463-
}
464439
let is_dtx = (header.flags & FLAG_DTX) != 0;
465440
// Only count non-DTX arrivals toward the UI's
466441
// active-speaker set. DTX/comfort packets are emitted
@@ -771,34 +746,16 @@ mod tests {
771746
);
772747
}
773748

774-
/// Causal regression for the peer-index reuse race (Jude's blocking
775-
/// finding): a frame authored by a departed occupant that arrives after
776-
/// its slot is reassigned to a new occupant carries the stale epoch and
777-
/// must be fenced, never mis-attributed to the new occupant.
778749
#[test]
779-
fn stale_epoch_frame_is_fenced_after_its_index_is_reused() {
750+
fn v2_media_is_routed_only_for_current_roster_indices() {
780751
let mut index_to_epoch = std::collections::HashMap::new();
781-
// Slot 3 first occupied at epoch 0.
782752
index_to_epoch.insert(3_u8, 0_u8);
783753
assert!(
784-
is_current_occupant(3, 0, &index_to_epoch),
754+
is_current_occupant(3, &index_to_epoch),
785755
"current occupant's frame is delivered"
786756
);
787-
788-
// The occupant departs and a new peer reuses slot 3 at epoch 1.
789-
index_to_epoch.insert(3, 1);
790-
assert!(
791-
!is_current_occupant(3, 0, &index_to_epoch),
792-
"in-flight frame from the departed occupant (epoch 0) is fenced"
793-
);
794-
assert!(
795-
is_current_occupant(3, 1, &index_to_epoch),
796-
"the new occupant's frame (epoch 1) is delivered"
797-
);
798-
799-
// A frame for an index absent from the roster is stale.
800757
assert!(
801-
!is_current_occupant(9, 0, &index_to_epoch),
758+
!is_current_occupant(9, &index_to_epoch),
802759
"frame for an unoccupied index is dropped"
803760
);
804761
}

‎desktop/src-tauri/src/huddle/relay_api.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,9 @@ async fn connect_authenticated_audio_socket(
114114
"type": "auth",
115115
"event": event_json,
116116
"parent_channel_id": parent_channel_id,
117+
// Use the released v2 contract while deployed relays remain capped at
118+
// v2. Relay-to-client media therefore has a one-byte peer-index prefix;
119+
// see huddle::wire for the compatibility tradeoff.
117120
"protocol_version": super::wire::PROTOCOL_VERSION,
118121
});
119122
ws_tx

‎desktop/src-tauri/src/huddle/wire.rs‎

Lines changed: 57 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,18 @@
77
//!
88
//! No per-frame metadata; receiver synthesizes sequence/timestamp on arrival.
99
//! Kept for backward compatibility — relay still admits v1 clients into
10-
//! v1-pinned rooms — but new clients always speak v3.
10+
//! v1-pinned rooms — but new clients speak v2 while deployed relays remain
11+
//! capped at the released v2 contract.
1112
//!
12-
//! ## v2 (released)
13+
//! ## v2 (compatibility contract)
1314
//!
1415
//! Client → relay: `<header: [u8; 8]><opus_bytes>`
1516
//! Relay → client: `<peer_index: u8><header: [u8; 8]><opus_bytes>`
1617
//!
17-
//! ## v3 (this commit)
18-
//!
19-
//! Client → relay: `<header: [u8; 8]><opus_bytes>`
20-
//! Relay → client: `<peer_index: u8><epoch: u8><header: [u8; 8]><opus_bytes>`
21-
//!
22-
//! The relay prefixes each forwarded frame with the sender's stable
23-
//! `peer_index` and the current occupancy `epoch` of that index. The epoch
24-
//! advances each time a slot is reused by a new occupant, so a client can
25-
//! fence a frame authored by a departed occupant that arrives after its index
26-
//! is reassigned — it carries the stale epoch and is dropped rather than
27-
//! mis-attributed. The client's own send path is unaffected: it emits only
28-
//! `<header><opus_bytes>` and the relay stamps the prefix.
18+
//! Protocol v2 does not carry v3's occupancy epoch in media frames. The
19+
//! control-plane roster still resets decoder and playout state when an index is
20+
//! reassigned, but v2 cannot fence a delayed packet from the previous occupant
21+
//! after that reassignment.
2922
//!
3023
//! Header layout (8 bytes, network byte order, big-endian):
3124
//!
@@ -44,13 +37,13 @@
4437
//! * `level_dbov` is client-authored telemetry. The relay parses it for
4538
//! logging/active-speaker hints, clamps invalid values into range, and
4639
//! **never** uses it for trust decisions (admission, moderation, etc.).
47-
//! * Negotiation lives in the WS auth message (`protocol_version: 3`), not
40+
//! * Negotiation lives in the WS auth message (`protocol_version: 2`), not
4841
//! in any bit of `flags`. Mixed-version rooms are rejected at the relay
4942
//! with `upgrade_required`.
5043
5144
/// Wire protocol version this client speaks. Bumped only when the frame
5245
/// layout itself changes; the relay tracks pinned per-room.
53-
pub const PROTOCOL_VERSION: u8 = 3;
46+
pub const PROTOCOL_VERSION: u8 = 2;
5447

5548
/// Length of the v2 per-frame header in bytes.
5649
pub const V2_HEADER_LEN: usize = 8;
@@ -135,6 +128,19 @@ impl FrameHeader {
135128
}
136129
}
137130

131+
/// Parse a complete relay-to-client v2 frame.
132+
///
133+
/// The released v2 contract has exactly one relay-authored prefix byte: the
134+
/// sender's peer index. A non-empty Opus payload must follow the fixed header.
135+
pub fn parse_relay_frame(bytes: &[u8]) -> Option<(u8, FrameHeader, &[u8])> {
136+
let (&peer_index, framed_audio) = bytes.split_first()?;
137+
let (header, opus_payload) = FrameHeader::parse(framed_audio)?;
138+
if opus_payload.is_empty() {
139+
return None;
140+
}
141+
Some((peer_index, header, opus_payload))
142+
}
143+
138144
/// Compute a dBov audio level for a normalized f32 PCM frame.
139145
///
140146
/// "dBov" is RMS expressed in dB relative to full scale (where full scale =
@@ -218,6 +224,41 @@ mod tests {
218224
assert_eq!(tail, b"opus-bytes");
219225
}
220226

227+
#[test]
228+
fn relay_frame_uses_the_v2_one_byte_peer_prefix() {
229+
let header = FrameHeader {
230+
seq: 0x0102,
231+
ts_48k: 960,
232+
level_dbov: -20,
233+
flags: 0,
234+
};
235+
let mut frame = vec![7];
236+
frame.extend_from_slice(&header.encode());
237+
frame.extend_from_slice(b"opus");
238+
239+
let (peer_index, parsed_header, opus_payload) =
240+
parse_relay_frame(&frame).expect("valid v2 relay frame");
241+
assert_eq!(peer_index, 7);
242+
assert_eq!(parsed_header, header);
243+
assert_eq!(opus_payload, b"opus");
244+
}
245+
246+
#[test]
247+
fn relay_frame_rejects_a_missing_opus_payload() {
248+
let mut frame = vec![7];
249+
frame.extend_from_slice(
250+
&FrameHeader {
251+
seq: 1,
252+
ts_48k: 960,
253+
level_dbov: -20,
254+
flags: 0,
255+
}
256+
.encode(),
257+
);
258+
259+
assert!(parse_relay_frame(&frame).is_none());
260+
}
261+
221262
/// Bytes in big-endian network order, matching Max's spec. This pins
222263
/// the byte layout against accidental endianness changes.
223264
#[test]

0 commit comments

Comments
 (0)