Merge the media stream contract into CultLib

This commit is contained in:
Meta Vens 2026-09-10 02:32:21 +02:00
commit 05e0925143
12 changed files with 1406 additions and 2 deletions

View file

@ -955,6 +955,7 @@ fn connect_rudp_client(
socket.set_read_timeout(Some(poll_interval))?;
let mut client =
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
media_delivery: None,
runtime_id: runtime_id.to_string(),
socket,
mode: cultnet_rs::CultNetRudpSocketMode::Client,

View file

@ -163,6 +163,7 @@ fn client(target: SocketAddr, id: u32) -> Result<CultNetRudpSocketTransportConne
let socket = UdpSocket::bind("127.0.0.1:0")?;
socket.set_nonblocking(true)?;
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
media_delivery: None,
runtime_id: "test-client".into(),
socket,
mode: CultNetRudpSocketMode::Client,

View file

@ -0,0 +1,177 @@
//! Measures what a media channel actually costs on the wire under loss.
//!
//! The claim under test: a reliable media channel retransmits lost packets, so
//! it adds load exactly when the link has least to give, while an unreliable one
//! drops them and holds its rate. Run both halves through `cultnet-impair` with
//! a `loss_basis_points` profile and compare bytes on the wire against bytes of
//! payload offered.
//!
//! ```text
//! media_delivery_probe recv <bind_addr> <expect_count>
//! media_delivery_probe send <endpoint> <reliable|unreliable> <payload_bytes> <count>
//! ```
//!
//! The sender reports amplification: wire bytes divided by offered payload
//! bytes. At 1.0 nothing was retransmitted. Well above 1.0 under loss is the
//! pathology.
use std::env;
use std::net::{SocketAddr, UdpSocket};
use std::time::{Duration, Instant};
use anyhow::{Result, anyhow};
use cultnet_rs::{
CultNetRudpServerHubOptions, CultNetRudpSocketTransportConnection,
CultNetRudpSocketTransportOptions, CultNetTransportDelivery,
};
const CHANNEL: &str = "media";
const DRAIN: Duration = Duration::from_secs(5);
fn main() -> Result<()> {
let args: Vec<String> = env::args().collect();
match args.get(1).map(String::as_str) {
Some("recv") => recv(
args.get(2).ok_or_else(|| anyhow!("bind addr"))?.parse()?,
args.get(3).ok_or_else(|| anyhow!("expect count"))?.parse()?,
),
Some("send") => send(
args.get(2).ok_or_else(|| anyhow!("endpoint"))?.parse()?,
match args.get(3).map(String::as_str) {
Some("unreliable") => CultNetTransportDelivery::Unreliable,
Some("reliable") => CultNetTransportDelivery::Reliable,
other => return Err(anyhow!("delivery must be reliable|unreliable, got {other:?}")),
},
args.get(4).ok_or_else(|| anyhow!("payload bytes"))?.parse()?,
args.get(5).ok_or_else(|| anyhow!("count"))?.parse()?,
args.get(6).map(|v| v.parse()).transpose()?.unwrap_or(12.0),
),
_ => Err(anyhow!(
"usage: media_delivery_probe recv <bind> <count> | send <endpoint> <reliable|unreliable> <bytes> <count>"
)),
}
}
fn recv(bind: SocketAddr, expect: u64) -> Result<()> {
let socket = UdpSocket::bind(bind)?;
socket.set_nonblocking(true)?;
let mut hub = cultnet_rs::CultNetRudpServerHub::new(CultNetRudpServerHubOptions::new(
"probe-recv",
socket,
0x0BE0_0001,
))?;
println!("listening on {bind}, expecting {expect} frames");
let started = Instant::now();
let mut frames = 0u64;
let mut payload_bytes = 0u64;
let mut last_progress = Instant::now();
loop {
while let Some(event) = hub.receive_event_once()? {
if let cultnet_rs::CultNetRudpServerEvent::Frame { frame, .. } = event
&& frame.channel_id == CHANNEL
{
frames += 1;
payload_bytes += frame.payload.len() as u64;
last_progress = Instant::now();
}
}
if frames >= expect || last_progress.elapsed() > DRAIN {
break;
}
std::thread::sleep(Duration::from_micros(200));
}
let stats = hub.stats();
let elapsed = started.elapsed().as_secs_f64();
println!("RESULT recv frames={frames} expected={expect} payload_bytes={payload_bytes}");
println!(
"RESULT recv wire_bytes_in={} wire_bytes_out={} elapsed_s={elapsed:.2} delivered_pct={:.2}",
stats.bytes_received,
stats.bytes_sent,
(frames as f64 / expect as f64) * 100.0
);
Ok(())
}
fn send(
endpoint: SocketAddr,
delivery: CultNetTransportDelivery,
payload_bytes: usize,
count: u64,
target_mbps: f64,
) -> Result<()> {
let socket = UdpSocket::bind("0.0.0.0:0")?;
socket.set_nonblocking(true)?;
let mut options =
CultNetRudpSocketTransportOptions::client("probe-send", socket, endpoint, 0x0BE0_0001);
options.media_delivery = Some(delivery);
options.media_reliable_expire_after_ms = None;
let mut transport = CultNetRudpSocketTransportConnection::new(options)?;
transport.connect(b"probe".to_vec())?;
let deadline = Instant::now() + Duration::from_secs(10);
while !transport.connected() {
let _ = transport.receive_once()?;
transport.poll_resends()?;
if Instant::now() >= deadline {
return Err(anyhow!("timed out connecting to {endpoint}"));
}
std::thread::sleep(Duration::from_millis(2));
}
// Pace to a realistic media rate. An unpaced blast overruns the receiver's
// socket buffer and manufactures loss that has nothing to do with the link.
let per_packet = Duration::from_secs_f64((payload_bytes as f64 * 8.0) / (target_mbps * 1e6));
let payload = vec![0xA5u8; payload_bytes];
let offered = payload_bytes as u64 * count;
let started = Instant::now();
let mut sent = 0u64;
let mut would_block = 0u64;
while sent < count {
match transport.send(CHANNEL, payload.clone()) {
Ok(()) => sent += 1,
Err(error) if error.to_string().contains("would block") => {
would_block += 1;
transport.poll_resends()?;
let _ = transport.receive_once()?;
std::thread::sleep(Duration::from_micros(500));
}
Err(error) => return Err(error),
}
if sent % 64 == 0 {
let _ = transport.receive_once()?;
transport.poll_resends()?;
}
let due = started + per_packet.mul_f64(sent as f64);
if let Some(wait) = due.checked_duration_since(Instant::now()) {
std::thread::sleep(wait);
}
}
let send_elapsed = started.elapsed();
// Let retransmission run: this is where a reliable channel spends what an
// unreliable one does not.
let drain_start = Instant::now();
while drain_start.elapsed() < DRAIN {
let _ = transport.receive_once()?;
transport.poll_resends()?;
std::thread::sleep(Duration::from_millis(1));
}
let stats = transport.stats();
let amplification = stats.bytes_sent as f64 / offered as f64;
println!(
"RESULT send delivery={delivery:?} payload_bytes={payload_bytes} count={count} offered={offered} target_mbps={target_mbps}"
);
println!(
"RESULT send wire_bytes={} amplification={amplification:.3} send_s={:.2} total_s={:.2} would_block={would_block} reliable_expired={}",
stats.bytes_sent,
send_elapsed.as_secs_f64(),
started.elapsed().as_secs_f64(),
stats.reliable_packets_expired
);
Ok(())
}

View file

@ -319,6 +319,7 @@ impl CultMesh {
let socket = bind_rudp_socket(&options)?;
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
media_reliable_expire_after_ms: None,
media_delivery: None,
runtime_id: runtime_id.into(),
socket,
mode: CultNetRudpSocketMode::Server,
@ -343,6 +344,7 @@ impl CultMesh {
let socket = bind_rudp_socket(&options)?;
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
media_reliable_expire_after_ms: None,
media_delivery: None,
runtime_id: runtime_id.into(),
socket,
mode: CultNetRudpSocketMode::Client,

View file

@ -1,6 +1,8 @@
mod contracts;
mod idunn_deployment_brake;
mod idunn_lifecycle_brake;
mod media_stream_contracts;
mod media_stream_wire;
mod provider_health_contracts;
mod runtime_authority_contracts;
mod service_identity;
@ -19,6 +21,8 @@ mod transport;
pub use contracts::*;
pub use idunn_deployment_brake::*;
pub use idunn_lifecycle_brake::*;
pub use media_stream_contracts::*;
pub use media_stream_wire::*;
pub use provider_health_contracts::*;
pub use runtime_authority_contracts::*;
pub use service_identity::*;

View file

@ -0,0 +1,200 @@
//! CultMesh Media Stream: the typed contract for carrying live audio and video
//! over CultNet.
//!
//! These records describe a media stream and nothing about who produced it. A
//! capture broker, an editor runtime, a recorder, or a synthetic source may all
//! publish them; an OBS bridge, a compositor, a recorder, or a browser lowering
//! may all consume them. Producers advertise their streams through Odin and
//! consumers resolve them there, so neither end needs to name the other.
//!
//! They lived in `odin-core` as `muninn.media_*`, named after the one producer
//! that happened to emit them first. Every field here is producer-agnostic — the
//! name was the only coupling, and a second producer would have had to
//! impersonate Muninn or fork the shape.
//!
//! # Layout is wire contract
//!
//! CultCache encodes these positionally. Field order and `key` indices are the
//! wire format: append new fields with `default` at the next free index, never
//! reorder or renumber. `missing_video_chunk_keys` shows the pattern.
//!
//! Payloads carry `bytes` so they serialize as MessagePack `bin` rather than an
//! array of integers, which is what the C#, TypeScript and Python runtimes
//! expect and what keeps a 848-byte payload at 851 bytes instead of 1234. Note
//! that this is the derive's own attribute — `#[serde(with = "serde_bytes")]`
//! is inert here, because `DatabaseEntry` writes its own `Serialize`.
//!
//! # Timebase
//!
//! `pts_ticks`, `duration_ticks` and `deadline_ticks` are expressed in
//! `timebase_num / timebase_den` units, carried per record so a consumer never
//! has to assume a producer's clock. `deadline_ticks` is the presentation
//! deadline past which a late arrival is worth dropping rather than displaying.
//!
//! # Reliability
//!
//! Nothing here specifies a delivery guarantee. Whether a stream rides a
//! reliable or lossy CultNet channel, and whether it carries parity, is a
//! transport decision made per stream — not a property of the payload shape.
//! Video parity shards exist for producers that choose forward error correction;
//! audio currently has no parity record, and a producer emitting audio on a
//! lossy channel needs one.
use cultcache_rs::DatabaseEntry;
pub const GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA: &str = "gamecult.media_video_access_unit.v1";
pub const GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA: &str = "gamecult.media_video_parity_shard.v2";
pub const GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA: &str = "gamecult.media_audio_packet.v1";
pub const GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA: &str = "gamecult.media_receiver_feedback.v1";
/// One coded video access unit, possibly split across `chunk_count` records
/// sharing a `frame_id`. A consumer reassembles by `(stream_id, session_id,
/// frame_id)` and orders by `chunk_index`.
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "gamecult.media_video_access_unit",
schema = "gamecult.media_video_access_unit.v1"
)]
pub struct GameCultMediaVideoAccessUnitRecord {
#[cultcache(key = 0)]
pub stream_id: String,
#[cultcache(key = 1)]
pub session_id: String,
#[cultcache(key = 2)]
pub frame_id: u64,
#[cultcache(key = 3)]
pub codec: String,
#[cultcache(key = 4)]
pub pts_ticks: i64,
#[cultcache(key = 5)]
pub duration_ticks: u32,
#[cultcache(key = 6)]
pub timebase_num: u32,
#[cultcache(key = 7)]
pub timebase_den: u32,
#[cultcache(key = 8)]
pub keyframe: bool,
#[cultcache(key = 9)]
pub dependency_frame_id: Option<u64>,
#[cultcache(key = 10)]
pub deadline_ticks: i64,
#[cultcache(key = 11)]
pub chunk_index: u16,
#[cultcache(key = 12)]
pub chunk_count: u16,
#[cultcache(key = 13, bytes)]
pub payload: Vec<u8>,
}
/// Forward-error-correction parity for one video access unit. Carries the
/// framing fields of the access unit it protects so a receiver can recover
/// without having seen the original, plus the shard geometry needed to run
/// recovery: `parity_index` within `parity_count`, and the chunk sizes the
/// parity was computed over.
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "gamecult.media_video_parity_shard",
schema = "gamecult.media_video_parity_shard.v2"
)]
pub struct GameCultMediaVideoParityShardRecord {
#[cultcache(key = 0)]
pub stream_id: String,
#[cultcache(key = 1)]
pub session_id: String,
#[cultcache(key = 2)]
pub frame_id: u64,
#[cultcache(key = 3)]
pub codec: String,
#[cultcache(key = 4)]
pub pts_ticks: i64,
#[cultcache(key = 5)]
pub duration_ticks: u32,
#[cultcache(key = 6)]
pub timebase_num: u32,
#[cultcache(key = 7)]
pub timebase_den: u32,
#[cultcache(key = 8)]
pub keyframe: bool,
#[cultcache(key = 9)]
pub dependency_frame_id: Option<u64>,
#[cultcache(key = 10)]
pub deadline_ticks: i64,
#[cultcache(key = 11)]
pub chunk_count: u16,
#[cultcache(key = 12)]
pub parity_index: u16,
#[cultcache(key = 13)]
pub parity_count: u16,
#[cultcache(key = 14)]
pub chunk_payload_bytes: u32,
#[cultcache(key = 15)]
pub last_chunk_payload_bytes: u32,
#[cultcache(key = 16, bytes)]
pub payload: Vec<u8>,
}
/// One coded audio packet. Unlike video these are not chunked: a packet is
/// whole or it is absent, and `payload` carries whatever `codec` names.
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "gamecult.media_audio_packet",
schema = "gamecult.media_audio_packet.v1"
)]
pub struct GameCultMediaAudioPacketRecord {
#[cultcache(key = 0)]
pub stream_id: String,
#[cultcache(key = 1)]
pub session_id: String,
#[cultcache(key = 2)]
pub packet_id: u64,
#[cultcache(key = 3)]
pub codec: String,
#[cultcache(key = 4)]
pub pts_ticks: i64,
#[cultcache(key = 5)]
pub duration_ticks: u32,
#[cultcache(key = 6)]
pub timebase_num: u32,
#[cultcache(key = 7)]
pub timebase_den: u32,
#[cultcache(key = 8)]
pub deadline_ticks: i64,
#[cultcache(key = 9, bytes)]
pub payload: Vec<u8>,
}
/// What a receiver observed, published back to the producer so it can adapt:
/// what decoded, what is missing, what arrived too late, and how much queue and
/// jitter the receiver is carrying.
///
/// This is the only record here that flows consumer-to-producer. A producer is
/// free to ignore it; it reports observation, it does not issue commands.
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "gamecult.media_receiver_feedback",
schema = "gamecult.media_receiver_feedback.v1"
)]
pub struct GameCultMediaReceiverFeedbackRecord {
#[cultcache(key = 0)]
pub stream_id: String,
#[cultcache(key = 1)]
pub session_id: String,
#[cultcache(key = 2)]
pub receiver_id: String,
#[cultcache(key = 3)]
pub highest_decodable_frame_id: Option<u64>,
#[cultcache(key = 4)]
pub missing_frame_ids: Vec<u64>,
#[cultcache(key = 5)]
pub late_frame_ids: Vec<u64>,
#[cultcache(key = 6)]
pub requested_keyframe: bool,
#[cultcache(key = 7)]
pub jitter_us: i64,
#[cultcache(key = 8)]
pub decode_queue_us: i64,
#[cultcache(key = 9)]
pub observed_at: String,
#[cultcache(key = 10, default)]
pub missing_video_chunk_keys: Vec<String>,
}

View file

@ -0,0 +1,447 @@
//! How a CultMesh Media Stream record travels: the envelope both ends must
//! agree on.
//!
//! The records in `media_stream_contracts` describe media. This describes how
//! one reaches a peer — wrapped in `cultnet.document_put_raw.v0` with a schema
//! id, a record key, and provenance. It lives here because a producer and a
//! consumer that never link each other still have to agree on it exactly, and
//! the last time they did not, one end was Rust and the other was 6,515 lines
//! of C++ that had drifted.
//!
//! # No producer's name belongs in a shared envelope
//!
//! The Muninn implementation this replaces hardcoded `"muninn-media:"` into
//! every message id and `"muninn.media"` into every tag, so a second producer
//! would have had to label its traffic as Muninn's. The producer namespace is a
//! parameter here: see [`MediaWireProvenance`].
//!
//! # Record keys are addresses, not decoration
//!
//! A key identifies one piece of media within a session, so a consumer can tell
//! a retransmission from a new frame and a chunk from its siblings. The shapes
//! are fixed by this module rather than by each producer, because a consumer
//! parses them.
use anyhow::{Result, anyhow};
use crate::contracts::{
CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding, CultNetWireContract,
decode_cultnet_message_from_slice, encode_cultnet_message_to_vec,
};
use crate::media_stream_contracts::{
GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA, GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA,
GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA, GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA,
GameCultMediaAudioPacketRecord, GameCultMediaReceiverFeedbackRecord,
GameCultMediaVideoAccessUnitRecord, GameCultMediaVideoParityShardRecord,
};
/// The CultNet channel media rides.
pub const GAMECULT_MEDIA_CHANNEL: &str = "media";
/// One media record on its way somewhere.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GameCultMediaWireRecord {
Video(GameCultMediaVideoAccessUnitRecord),
VideoParity(GameCultMediaVideoParityShardRecord),
Audio(GameCultMediaAudioPacketRecord),
Feedback(GameCultMediaReceiverFeedbackRecord),
}
/// Who is sending, and when. `producer` namespaces message ids and tags so a
/// stream can be attributed without the envelope knowing any producer by name.
#[derive(Clone, Copy, Debug)]
pub struct MediaWireProvenance<'a> {
pub stored_at: &'a str,
pub runtime_id: &'a str,
pub role: &'a str,
pub producer: &'a str,
}
impl MediaWireProvenance<'_> {
fn validate(&self) -> Result<()> {
for (name, value) in [
("stored_at", self.stored_at),
("runtime_id", self.runtime_id),
("role", self.role),
("producer", self.producer),
] {
if value.is_empty() {
return Err(anyhow!("media wire provenance {name} must be non-empty"));
}
}
Ok(())
}
}
impl GameCultMediaWireRecord {
pub fn schema_id(&self) -> &'static str {
match self {
Self::Video(_) => GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA,
Self::VideoParity(_) => GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA,
Self::Audio(_) => GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA,
Self::Feedback(_) => GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA,
}
}
/// Addresses this record within its session.
pub fn record_key(&self) -> String {
match self {
Self::Video(record) => format!(
"{}:{}:video:{}:{}",
record.stream_id, record.session_id, record.frame_id, record.chunk_index
),
Self::VideoParity(record) => format!(
"{}:{}:video-parity:{}:{}",
record.stream_id, record.session_id, record.frame_id, record.parity_index
),
Self::Audio(record) => format!(
"{}:{}:audio:{}",
record.stream_id, record.session_id, record.packet_id
),
Self::Feedback(record) => format!(
"{}:{}:feedback:{}",
record.stream_id, record.session_id, record.receiver_id
),
}
}
/// The record's own MessagePack form.
///
/// Serializing the record directly is only correct because the payload
/// fields carry `#[cultcache(key = N, bytes)]`. Muninn previously mirrored
/// each record into a parallel tuple struct — every field restated, in
/// order, by hand — solely so `#[serde(with = "serde_bytes")]` could be
/// applied to the payload, because the `DatabaseEntry` derive does not read
/// serde attributes. Those shadow structs are gone; the derive emits `bin`
/// itself now. Do not reintroduce one.
fn payload_bytes(&self) -> Result<Vec<u8>> {
match self {
Self::Video(record) => rmp_serde::to_vec(record),
Self::VideoParity(record) => rmp_serde::to_vec(record),
Self::Audio(record) => rmp_serde::to_vec(record),
Self::Feedback(record) => rmp_serde::to_vec(record),
}
.map_err(Into::into)
}
}
/// Wraps a media record for the wire.
pub fn encode_media_wire_record(
record: &GameCultMediaWireRecord,
provenance: MediaWireProvenance<'_>,
) -> Result<Vec<u8>> {
provenance.validate()?;
let schema_id = record.schema_id();
let record_key = record.record_key();
let message = CultNetMessage::DocumentPutRaw {
message_id: format!(
"{}-media:{}:{}",
provenance.producer,
schema_id,
record_key.replace(':', "-")
),
document: CultNetRawDocumentRecord {
schema_id: schema_id.to_string(),
record_key,
stored_at: provenance.stored_at.to_string(),
payload_encoding: CultNetRawPayloadEncoding::Messagepack,
payload: record.payload_bytes()?,
source_runtime_id: Some(provenance.runtime_id.to_string()),
source_agent_id: None,
source_role: Some(provenance.role.to_string()),
tags: Some(vec![format!("{}.media", provenance.producer)]),
},
};
encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0).map_err(Into::into)
}
/// Unwraps a media record from the wire.
pub fn decode_media_wire_record(payload: &[u8]) -> Result<GameCultMediaWireRecord> {
let message = decode_cultnet_message_from_slice(payload, CultNetWireContract::CultNetSchemaV0)?;
let CultNetMessage::DocumentPutRaw { document, .. } = message else {
return Err(anyhow!("expected cultnet.document_put_raw.v0"));
};
if document.payload_encoding != CultNetRawPayloadEncoding::Messagepack {
return Err(anyhow!("media document payload must be MessagePack"));
}
let record = match document.schema_id.as_str() {
GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA => {
let record: GameCultMediaVideoAccessUnitRecord =
rmp_serde::from_slice(&document.payload)?;
validate_video_record(&record)?;
GameCultMediaWireRecord::Video(record)
}
GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA => {
let record: GameCultMediaVideoParityShardRecord =
rmp_serde::from_slice(&document.payload)?;
validate_video_parity_record(&record)?;
GameCultMediaWireRecord::VideoParity(record)
}
GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA => {
let record: GameCultMediaAudioPacketRecord =
rmp_serde::from_slice(&document.payload)?;
validate_audio_record(&record)?;
GameCultMediaWireRecord::Audio(record)
}
GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA => {
let record: GameCultMediaReceiverFeedbackRecord =
rmp_serde::from_slice(&document.payload)?;
validate_feedback_record(&record)?;
GameCultMediaWireRecord::Feedback(record)
}
other => return Err(anyhow!("unsupported media schema {other}")),
};
// The key is derived from the record's own contents, so a mismatch means the
// envelope and its payload disagree about what this is. Admitting it would
// let a consumer address media by a key its producer never meant.
let expected = record.record_key();
if document.record_key != expected {
return Err(anyhow!(
"record key mismatch: envelope says {}, record derives {expected}",
document.record_key
));
}
Ok(record)
}
// ---------------------------------------------------------------------------
// Validation
//
// Moved here from Muninn with the envelope. A decoder that does not validate
// leaves each consumer to invent its own idea of a well-formed record, which is
// how the C++ receiver and the Rust sender came to disagree while both looked
// correct in isolation. Muninn's tests for these came too; they now cover the
// contract rather than one producer's copy of it.
// ---------------------------------------------------------------------------
/// Addresses one chunk of a video frame. The string form appears in receiver
/// feedback and is parsed by consumers, so its shape is contract.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct VideoChunkKey {
pub frame_id: u64,
pub chunk_index: u16,
}
impl VideoChunkKey {
pub fn new(frame_id: u64, chunk_index: u16) -> Self {
Self {
frame_id,
chunk_index,
}
}
pub fn parse(value: &str) -> Result<Self> {
if value.matches(':').count() != 1 {
return Err(anyhow!(
"video chunk key must contain exactly one ':' separator"
));
}
let (frame_id, chunk_index) = value
.split_once(':')
.ok_or_else(|| anyhow!("video chunk key must be '<frame_id>:<chunk_index>'"))?;
Ok(Self {
frame_id: frame_id
.parse()
.map_err(|_| anyhow!("video chunk key frame_id must be an integer"))?,
chunk_index: chunk_index
.parse()
.map_err(|_| anyhow!("video chunk key chunk_index must be an integer"))?,
})
}
pub fn as_feedback_key(&self) -> String {
format!("{}:{}", self.frame_id, self.chunk_index)
}
}
pub fn video_chunk_feedback_key(frame_id: u64, chunk_index: u16) -> String {
VideoChunkKey::new(frame_id, chunk_index).as_feedback_key()
}
pub fn normalize_video_chunk_feedback_keys(keys: Vec<String>) -> Result<Vec<String>> {
let mut parsed = keys
.iter()
.map(|key| VideoChunkKey::parse(key))
.collect::<Result<Vec<_>>>()?;
parsed.sort_unstable();
parsed.dedup();
Ok(parsed
.into_iter()
.map(|key| key.as_feedback_key())
.collect())
}
pub fn validate_video_record(record: &GameCultMediaVideoAccessUnitRecord) -> Result<()> {
if record.stream_id.is_empty() {
return Err(anyhow!("video media record stream_id must be non-empty"));
}
if record.session_id.is_empty() {
return Err(anyhow!("video media record session_id must be non-empty"));
}
if record.codec.is_empty() {
return Err(anyhow!("video media record codec must be non-empty"));
}
if record.timebase_num == 0 || record.timebase_den == 0 {
return Err(anyhow!("video media record timebase must be non-zero"));
}
if record.duration_ticks == 0 {
return Err(anyhow!(
"video media record duration_ticks must be greater than zero"
));
}
if record.deadline_ticks < record.pts_ticks {
return Err(anyhow!(
"video media record deadline_ticks must not precede pts_ticks"
));
}
if record.chunk_count == 0 {
return Err(anyhow!("video media record chunk_count must be non-zero"));
}
if record.chunk_index >= record.chunk_count {
return Err(anyhow!(
"video media record chunk_index {} is outside chunk_count {}",
record.chunk_index,
record.chunk_count
));
}
if record.payload.is_empty() {
return Err(anyhow!("video media record payload must be non-empty"));
}
Ok(())
}
pub fn validate_video_parity_record(record: &GameCultMediaVideoParityShardRecord) -> Result<()> {
if record.stream_id.is_empty() {
return Err(anyhow!(
"video parity media record stream_id must be non-empty"
));
}
if record.session_id.is_empty() {
return Err(anyhow!(
"video parity media record session_id must be non-empty"
));
}
if record.codec.is_empty() {
return Err(anyhow!("video parity media record codec must be non-empty"));
}
if record.timebase_num == 0 || record.timebase_den == 0 {
return Err(anyhow!(
"video parity media record timebase must be non-zero"
));
}
if record.duration_ticks == 0 {
return Err(anyhow!(
"video parity media record duration_ticks must be greater than zero"
));
}
if record.deadline_ticks < record.pts_ticks {
return Err(anyhow!(
"video parity media record deadline_ticks must not precede pts_ticks"
));
}
if record.chunk_count == 0 {
return Err(anyhow!(
"video parity media record chunk_count must be non-zero"
));
}
if record.parity_count == 0 || record.parity_index >= record.parity_count {
return Err(anyhow!(
"video parity media record has invalid parity stripe metadata"
));
}
if record.parity_count > record.chunk_count {
return Err(anyhow!(
"video parity media record parity_count exceeds chunk_count"
));
}
if record.chunk_payload_bytes == 0 || record.last_chunk_payload_bytes == 0 {
return Err(anyhow!(
"video parity media record chunk lengths must be non-zero"
));
}
if record.last_chunk_payload_bytes > record.chunk_payload_bytes {
return Err(anyhow!(
"video parity media record last chunk length exceeds regular chunk length"
));
}
if record.payload.is_empty() {
return Err(anyhow!(
"video parity media record payload must be non-empty"
));
}
if record.payload.len() > record.chunk_payload_bytes as usize {
return Err(anyhow!(
"video parity media record payload exceeds declared chunk length"
));
}
Ok(())
}
pub fn validate_audio_record(record: &GameCultMediaAudioPacketRecord) -> Result<()> {
if record.stream_id.is_empty() {
return Err(anyhow!("audio media record stream_id must be non-empty"));
}
if record.session_id.is_empty() {
return Err(anyhow!("audio media record session_id must be non-empty"));
}
if record.codec.is_empty() {
return Err(anyhow!("audio media record codec must be non-empty"));
}
if record.timebase_num == 0 || record.timebase_den == 0 {
return Err(anyhow!("audio media record timebase must be non-zero"));
}
if record.duration_ticks == 0 {
return Err(anyhow!(
"audio media record duration_ticks must be greater than zero"
));
}
if record.deadline_ticks < record.pts_ticks {
return Err(anyhow!(
"audio media record deadline_ticks must not precede pts_ticks"
));
}
if record.payload.is_empty() {
return Err(anyhow!("audio media record payload must be non-empty"));
}
Ok(())
}
pub fn validate_feedback_record(record: &GameCultMediaReceiverFeedbackRecord) -> Result<()> {
if record.stream_id.is_empty() {
return Err(anyhow!(
"receiver feedback media record stream_id must be non-empty"
));
}
if record.session_id.is_empty() {
return Err(anyhow!(
"receiver feedback media record session_id must be non-empty"
));
}
if record.receiver_id.is_empty() {
return Err(anyhow!(
"receiver feedback media record receiver_id must be non-empty"
));
}
if record.observed_at.is_empty() {
return Err(anyhow!(
"receiver feedback media record observed_at must be non-empty"
));
}
if record.jitter_us < 0 {
return Err(anyhow!(
"receiver feedback media record jitter_us must be non-negative"
));
}
if record.decode_queue_us < 0 {
return Err(anyhow!(
"receiver feedback media record decode_queue_us must be non-negative"
));
}
normalize_video_chunk_feedback_keys(record.missing_video_chunk_keys.clone())?;
Ok(())
}

View file

@ -1210,6 +1210,8 @@ pub struct CultNetRudpSocketTransportOptions {
pub max_pending_reliable_packets: Option<u32>,
pub reconnect_policy: Option<CultNetReconnectPolicy>,
pub media_reliable_expire_after_ms: Option<u64>,
/// `None` means the historical default, `Reliable`.
pub media_delivery: Option<CultNetTransportDelivery>,
}
impl CultNetRudpSocketTransportOptions {
@ -1221,6 +1223,7 @@ impl CultNetRudpSocketTransportOptions {
) -> Self {
Self {
media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS),
media_delivery: None,
runtime_id: runtime_id.into(),
socket,
mode: CultNetRudpSocketMode::Client,
@ -1239,6 +1242,7 @@ impl CultNetRudpSocketTransportOptions {
pub fn server(runtime_id: impl Into<String>, socket: UdpSocket, connection_id: u32) -> Self {
Self {
media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS),
media_delivery: None,
runtime_id: runtime_id.into(),
socket,
mode: CultNetRudpSocketMode::Server,
@ -1280,12 +1284,15 @@ pub struct CultNetRudpServerHubOptions {
pub max_pending_reliable_packets: Option<u32>,
pub max_peers: usize,
pub media_reliable_expire_after_ms: Option<u64>,
/// `None` means the historical default, `Reliable`.
pub media_delivery: Option<CultNetTransportDelivery>,
}
impl CultNetRudpServerHubOptions {
pub fn new(runtime_id: impl Into<String>, socket: UdpSocket, connection_id: u32) -> Self {
Self {
media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS),
media_delivery: None,
runtime_id: runtime_id.into(),
socket,
connection_id,
@ -1372,6 +1379,7 @@ impl CultNetRudpServerHub {
options.runtime_id,
RudpTransportProfileOptions {
media_reliable_expire_after_ms: options.media_reliable_expire_after_ms,
media_delivery: options.media_delivery,
transport_id: options.transport_id,
host: Some(local_addr.ip().to_string()),
port: Some(local_addr.port()),
@ -1451,6 +1459,7 @@ impl CultNetRudpServerHub {
channel_id,
now_ms(),
channel_reliable_expire_after_ms(&self.profile, channel_id),
channel_delivery(&self.profile, channel_id),
),
self.max_fragment_bytes,
)?
@ -1671,6 +1680,7 @@ impl CultNetRudpSocketTransportConnection {
options.runtime_id,
RudpTransportProfileOptions {
media_reliable_expire_after_ms: options.media_reliable_expire_after_ms,
media_delivery: options.media_delivery,
transport_id: options.transport_id,
host: Some(local_addr.ip().to_string()),
port: Some(local_addr.port()),
@ -1738,6 +1748,7 @@ impl CultNetRudpSocketTransportConnection {
channel_id,
now_ms(),
channel_reliable_expire_after_ms(&self.profile, channel_id),
channel_delivery(&self.profile, channel_id),
);
let packets =
self.session
@ -1759,6 +1770,7 @@ impl CultNetRudpSocketTransportConnection {
channel_id,
now_ms(),
channel_reliable_expire_after_ms(&self.profile, channel_id),
channel_delivery(&self.profile, channel_id),
);
// This lineage has no reliable-expiry concept, so every reliable channel is
// already non-expiring. Restore the expiry half of this guard if one is added.
@ -2073,6 +2085,8 @@ pub struct RudpTransportProfileOptions {
pub max_pending_reliable_packets: Option<u32>,
pub reconnect_policy: Option<CultNetReconnectPolicy>,
pub media_reliable_expire_after_ms: Option<u64>,
/// `None` means the historical default, `Reliable`.
pub media_delivery: Option<CultNetTransportDelivery>,
}
pub fn create_rudp_transport_profile(
@ -2125,7 +2139,9 @@ pub fn create_rudp_transport_profile(
},
CultNetTransportChannel {
channel_id: "media".to_string(),
delivery: CultNetTransportDelivery::Reliable,
delivery: options
.media_delivery
.unwrap_or(CultNetTransportDelivery::Reliable),
ordering: CultNetTransportOrdering::Unordered,
max_payload_bytes: options.max_payload_bytes,
max_fragment_bytes: options.max_fragment_bytes,
@ -2254,10 +2270,30 @@ fn channel_reliable_expire_after_ms(
.and_then(|channel| channel.reliable_expire_after_ms)
}
/// The advertised profile owns each channel's delivery, for the same reason it
/// owns expiry: a send path that hardcodes reliability can disagree with the
/// profile the peer was shown, and then no one can say what the channel does.
///
/// Falls back to `Reliable` for a channel the profile does not describe, which
/// is what every channel got before delivery was configurable.
fn channel_delivery(
profile: &CultNetTransportProfile,
channel_id: &str,
) -> CultNetTransportDelivery {
profile
.transports
.iter()
.flat_map(|transport| transport.channels.iter())
.find(|channel| channel.channel_id == channel_id)
.map(|channel| channel.delivery)
.unwrap_or(CultNetTransportDelivery::Reliable)
}
fn channel_send_options(
channel_id: &str,
now_ms: u64,
reliable_expire_after_ms: Option<u64>,
delivery: CultNetTransportDelivery,
) -> CultNetRudpSendOptions {
match channel_id {
"schema" => CultNetRudpSendOptions {
@ -2274,8 +2310,11 @@ fn channel_send_options(
now_ms,
reliable_expire_after_ms: None,
},
// The one channel whose delivery a caller chooses. Media that has gone
// stale is worth dropping, not retransmitting: a reliable media channel
// under loss adds load exactly when the link has least to give.
"media" => CultNetRudpSendOptions {
reliable: true,
reliable: matches!(delivery, CultNetTransportDelivery::Reliable),
ordered: false,
sequenced: false,
now_ms,

View file

@ -359,6 +359,7 @@ fn rudp_transport_profile_advertises_state_and_realtime_channels() {
let profile = create_rudp_transport_profile(
"rust-rudp",
cultnet_rs::RudpTransportProfileOptions {
media_delivery: None,
transport_id: Some("public-rudp".to_string()),
host: Some("127.0.0.1".to_string()),
port: Some(7777),
@ -1248,6 +1249,7 @@ fn rudp_socket_transport_handshakes_and_carries_reliable_ordered_schema_frames()
let connection_id = 0x1020_3040;
let mut server =
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
media_delivery: None,
runtime_id: "rust-rudp-server".to_string(),
socket: server_socket,
mode: CultNetRudpSocketMode::Server,
@ -1264,6 +1266,7 @@ fn rudp_socket_transport_handshakes_and_carries_reliable_ordered_schema_frames()
})?;
let mut client =
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
media_delivery: None,
runtime_id: "rust-rudp-client".to_string(),
socket: client_socket,
mode: CultNetRudpSocketMode::Client,
@ -1340,6 +1343,7 @@ fn rudp_socket_transport_carries_fragmented_reliable_ordered_schema_frames() ->
let connection_id = 0x1020_3041;
let mut server =
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
media_delivery: None,
runtime_id: "rust-rudp-fragment-server".to_string(),
socket: server_socket,
mode: CultNetRudpSocketMode::Server,
@ -1356,6 +1360,7 @@ fn rudp_socket_transport_carries_fragmented_reliable_ordered_schema_frames() ->
})?;
let mut client =
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
media_delivery: None,
runtime_id: "rust-rudp-fragment-client".to_string(),
socket: client_socket,
mode: CultNetRudpSocketMode::Client,
@ -1470,6 +1475,7 @@ fn rudp_socket_flush_waits_for_large_fragment_delivery() -> Result<()> {
let connection_id = 0x1020_3043;
let mut server =
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
media_delivery: None,
runtime_id: "rust-rudp-window-server".into(),
socket: server_socket,
mode: CultNetRudpSocketMode::Server,
@ -1486,6 +1492,7 @@ fn rudp_socket_flush_waits_for_large_fragment_delivery() -> Result<()> {
})?;
let mut client =
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions {
media_delivery: None,
runtime_id: "rust-rudp-window-client".into(),
socket: client_socket,
mode: CultNetRudpSocketMode::Client,

View file

@ -0,0 +1,92 @@
//! Media delivery is the caller's choice, and the advertised profile is where
//! that choice lives.
//!
//! Before this, `media` was hardcoded `Reliable` in two places — the profile
//! builder and the per-channel send options — so no caller could say otherwise.
//! A producer asking for an unreliable media lane got a reliable one that
//! retransmits under loss, which adds load exactly when the link has least to
//! give. Muninn asked for that lane by passing no expiry, meaning "unreliable,
//! so expiry is moot", and got reliable-with-no-expiry instead: retransmit
//! forever.
//!
//! The default stays `Reliable` so every existing consumer is untouched.
use std::net::UdpSocket;
use cultnet_rs::{
CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions,
CultNetTransportDelivery,
};
fn media_channel_delivery(
media_delivery: Option<CultNetTransportDelivery>,
) -> (CultNetTransportDelivery, Option<u64>) {
let socket = UdpSocket::bind("127.0.0.1:0").expect("binds");
let endpoint = "127.0.0.1:5204".parse().expect("parses");
let mut options = CultNetRudpSocketTransportOptions::client("test-media", socket, endpoint, 7);
options.media_delivery = media_delivery;
options.media_reliable_expire_after_ms = None;
let transport = CultNetRudpSocketTransportConnection::new(options).expect("opens");
let channel = transport
.profile
.transports
.first()
.expect("a transport")
.channels
.iter()
.find(|channel| channel.channel_id == "media")
.expect("a media channel");
(channel.delivery, channel.reliable_expire_after_ms)
}
#[test]
fn media_defaults_to_reliable_so_existing_consumers_do_not_move() {
let (delivery, _) = media_channel_delivery(None);
assert_eq!(delivery, CultNetTransportDelivery::Reliable);
}
#[test]
fn a_caller_can_ask_for_an_unreliable_media_lane() {
let (delivery, expiry) = media_channel_delivery(Some(CultNetTransportDelivery::Unreliable));
assert_eq!(delivery, CultNetTransportDelivery::Unreliable);
assert_eq!(
expiry, None,
"an unreliable channel has nothing to expire; the pairing should stay honest"
);
}
#[test]
fn asking_for_reliable_explicitly_matches_the_default() {
let (explicit, _) = media_channel_delivery(Some(CultNetTransportDelivery::Reliable));
let (defaulted, _) = media_channel_delivery(None);
assert_eq!(explicit, defaulted);
}
/// The channels whose semantics are fixed by design must not drift with this.
#[test]
fn the_other_channels_keep_their_fixed_delivery() {
let socket = UdpSocket::bind("127.0.0.1:0").expect("binds");
let endpoint = "127.0.0.1:5204".parse().expect("parses");
let mut options = CultNetRudpSocketTransportOptions::client("test-media", socket, endpoint, 8);
options.media_delivery = Some(CultNetTransportDelivery::Unreliable);
let transport = CultNetRudpSocketTransportConnection::new(options).expect("opens");
let channels = &transport
.profile
.transports
.first()
.expect("a transport")
.channels;
let delivery_of = |id: &str| {
channels
.iter()
.find(|channel| channel.channel_id == id)
.unwrap_or_else(|| panic!("channel {id}"))
.delivery
};
assert_eq!(delivery_of("schema"), CultNetTransportDelivery::Reliable);
assert_eq!(delivery_of("realtime"), CultNetTransportDelivery::Unreliable);
}

View file

@ -0,0 +1,217 @@
//! The CultMesh Media Stream records are a wire contract shared by producers and
//! consumers that never link each other. These tests pin the properties a
//! consumer is entitled to rely on: positional layout, declared field order, and
//! tolerance of records written before an appended field existed.
use cultcache_rs::DatabaseEntry;
use cultnet_rs::{
GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA, GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA,
GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA, GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA,
GameCultMediaAudioPacketRecord, GameCultMediaReceiverFeedbackRecord,
GameCultMediaVideoAccessUnitRecord, GameCultMediaVideoParityShardRecord,
};
use rmpv::Value;
fn access_unit() -> GameCultMediaVideoAccessUnitRecord {
GameCultMediaVideoAccessUnitRecord {
stream_id: "raven-primary-av".to_string(),
session_id: "session-1".to_string(),
frame_id: 4242,
codec: "h264".to_string(),
pts_ticks: 90_000,
duration_ticks: 3_000,
timebase_num: 1,
timebase_den: 90_000,
keyframe: true,
dependency_frame_id: None,
deadline_ticks: 108_000,
chunk_index: 2,
chunk_count: 5,
payload: vec![0xDE, 0xAD, 0xBE, 0xEF],
}
}
fn audio_packet() -> GameCultMediaAudioPacketRecord {
GameCultMediaAudioPacketRecord {
stream_id: "raven-primary-av".to_string(),
session_id: "session-1".to_string(),
packet_id: 77,
codec: "opus".to_string(),
pts_ticks: 48_000,
duration_ticks: 960,
timebase_num: 1,
timebase_den: 48_000,
deadline_ticks: 96_000,
payload: vec![1, 2, 3],
}
}
fn decode_as_value(bytes: &[u8]) -> Value {
rmp_serde::from_slice(bytes).expect("records decode as generic MessagePack")
}
/// The declared `key` indices are the wire layout, not documentation. A consumer
/// in another language reads position 2 for `frame_id` and position 13 for
/// `payload`; reordering the struct would silently break it.
#[test]
fn video_access_unit_encodes_as_a_positional_array() {
let encoded = rmp_serde::to_vec(&access_unit()).expect("encodes");
let Value::Array(slots) = decode_as_value(&encoded) else {
panic!("access units must encode as a positional array");
};
assert_eq!(slots.len(), 14, "field count is wire contract");
assert_eq!(slots[0].as_str(), Some("raven-primary-av"));
assert_eq!(slots[2].as_u64(), Some(4242), "slot 2 is frame_id");
assert_eq!(slots[3].as_str(), Some("h264"));
assert_eq!(slots[8].as_bool(), Some(true), "slot 8 is keyframe");
assert!(slots[9].is_nil(), "an absent dependency stays nil, not 0");
assert_eq!(slots[12].as_u64(), Some(5), "slot 12 is chunk_count");
assert_eq!(
slots[13].as_slice(),
Some([0xDE, 0xAD, 0xBE, 0xEF].as_slice()),
"slot 13 is the payload, carried as bin"
);
}
/// Payloads must reach the wire as MessagePack `bin`, not as an array of
/// integers. The C#, TypeScript and Python runtimes all read byte fields as
/// `bin`, so a payload serialized as a sequence is unreadable by the reference
/// implementation, and costs 1.45x besides: 848 bytes encode to 1234 as an
/// integer array against 851 as `bin`.
///
/// This is what the derive's `bytes` attribute buys. `#[serde(with =
/// "serde_bytes")]` will not do it — `DatabaseEntry` emits its own `Serialize`
/// and reads only its own `cultcache` attribute namespace.
#[test]
fn payload_should_encode_as_messagepack_bin() {
let encoded = rmp_serde::to_vec(&access_unit()).expect("encodes");
let Value::Array(slots) = decode_as_value(&encoded) else {
panic!("access units must encode as a positional array");
};
assert_eq!(
slots[13].as_slice(),
Some([0xDE, 0xAD, 0xBE, 0xEF].as_slice()),
"payloads belong on the wire as bin, not as an array of integers"
);
}
#[test]
fn audio_packets_are_whole_and_carry_their_own_timebase() {
let encoded = rmp_serde::to_vec(&audio_packet()).expect("encodes");
let Value::Array(slots) = decode_as_value(&encoded) else {
panic!("audio packets must encode as a positional array");
};
assert_eq!(slots.len(), 10, "field count is wire contract");
assert_eq!(slots[2].as_u64(), Some(77), "slot 2 is packet_id");
assert_eq!(slots[6].as_u64(), Some(1), "slot 6 is timebase_num");
assert_eq!(slots[7].as_u64(), Some(48_000), "slot 7 is timebase_den");
let decoded: GameCultMediaAudioPacketRecord =
rmp_serde::from_slice(&encoded).expect("round-trips");
assert_eq!(decoded, audio_packet());
}
#[test]
fn parity_shards_carry_the_geometry_recovery_needs() {
let shard = GameCultMediaVideoParityShardRecord {
stream_id: "raven-primary-av".to_string(),
session_id: "session-1".to_string(),
frame_id: 4242,
codec: "h264".to_string(),
pts_ticks: 90_000,
duration_ticks: 3_000,
timebase_num: 1,
timebase_den: 90_000,
keyframe: false,
dependency_frame_id: Some(4241),
deadline_ticks: 108_000,
chunk_count: 5,
parity_index: 1,
parity_count: 2,
chunk_payload_bytes: 1024,
last_chunk_payload_bytes: 512,
payload: vec![9, 9, 9],
};
let encoded = rmp_serde::to_vec(&shard).expect("encodes");
let Value::Array(slots) = decode_as_value(&encoded) else {
panic!("parity shards must encode as a positional array");
};
assert_eq!(slots.len(), 17, "field count is wire contract");
assert_eq!(slots[12].as_u64(), Some(1), "slot 12 is parity_index");
assert_eq!(slots[13].as_u64(), Some(2), "slot 13 is parity_count");
assert_eq!(
slots[15].as_u64(),
Some(512),
"slot 15 is last_chunk_payload_bytes, which recovery needs to size the tail"
);
let decoded: GameCultMediaVideoParityShardRecord =
rmp_serde::from_slice(&encoded).expect("round-trips");
assert_eq!(decoded, shard);
}
/// `missing_video_chunk_keys` was appended after producers were already writing
/// feedback. A record written without it must still decode, or the append was a
/// breaking change wearing a `default` attribute.
#[test]
fn receiver_feedback_decodes_records_written_before_its_last_field() {
let without_appended_field = Value::Array(vec![
Value::from("raven-primary-av"),
Value::from("session-1"),
Value::from("starfire-obs"),
Value::from(4200u64),
Value::Array(vec![Value::from(4198u64)]),
Value::Array(vec![Value::from(4199u64)]),
Value::from(true),
Value::from(1_500i64),
Value::from(9_000i64),
Value::from("2026-09-09T00:00:00Z"),
]);
let mut bytes = Vec::new();
rmpv::encode::write_value(&mut bytes, &without_appended_field).expect("writes legacy record");
let decoded: GameCultMediaReceiverFeedbackRecord =
rmp_serde::from_slice(&bytes).expect("a pre-append record must still decode");
assert_eq!(decoded.receiver_id, "starfire-obs");
assert_eq!(decoded.highest_decodable_frame_id, Some(4200));
assert!(decoded.requested_keyframe);
assert!(
decoded.missing_video_chunk_keys.is_empty(),
"the appended field defaults rather than failing the decode"
);
}
/// The published constants and the derived type identity must not drift apart;
/// a consumer resolving by schema id and a producer registering by type would
/// then disagree without either failing to compile.
#[test]
fn published_schema_constants_match_the_derived_identity() {
assert_eq!(
GameCultMediaVideoAccessUnitRecord::SCHEMA_NAME,
GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA
);
assert_eq!(
GameCultMediaVideoParityShardRecord::SCHEMA_NAME,
GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA
);
assert_eq!(
GameCultMediaAudioPacketRecord::SCHEMA_NAME,
GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA
);
assert_eq!(
GameCultMediaReceiverFeedbackRecord::SCHEMA_NAME,
GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA
);
assert_eq!(
GameCultMediaAudioPacketRecord::TYPE,
"gamecult.media_audio_packet"
);
}

View file

@ -0,0 +1,217 @@
//! The envelope, and one proof that removing Muninn's shadow structs changed
//! nothing on the wire.
use cultnet_rs::{
GAMECULT_MEDIA_CHANNEL, GameCultMediaAudioPacketRecord, GameCultMediaReceiverFeedbackRecord,
GameCultMediaVideoAccessUnitRecord, GameCultMediaVideoParityShardRecord,
GameCultMediaWireRecord, MediaWireProvenance, decode_media_wire_record,
encode_media_wire_record,
};
use serde::Serialize;
fn provenance() -> MediaWireProvenance<'static> {
MediaWireProvenance {
stored_at: "unix:1000",
runtime_id: "raven",
role: "muninn.media",
producer: "muninn",
}
}
fn access_unit() -> GameCultMediaVideoAccessUnitRecord {
GameCultMediaVideoAccessUnitRecord {
stream_id: "raven-primary-av".to_string(),
session_id: "session-1".to_string(),
frame_id: 4242,
codec: "h264".to_string(),
pts_ticks: 90_000,
duration_ticks: 3_000,
timebase_num: 1,
timebase_den: 90_000,
keyframe: true,
dependency_frame_id: None,
deadline_ticks: 108_000,
chunk_index: 2,
chunk_count: 5,
payload: (0u8..=255).collect(),
}
}
/// Muninn's `VideoAccessUnitWirePayload`, reproduced exactly as it was.
///
/// It existed only so `#[serde(with = "serde_bytes")]` could reach the payload,
/// because the `DatabaseEntry` derive ignores serde attributes. Every other
/// field was restated by hand, in order, and had to stay in step with the record
/// by discipline alone.
#[derive(Serialize)]
struct LegacyVideoAccessUnitWirePayload<'a>(
&'a str,
&'a str,
u64,
&'a str,
i64,
u32,
u32,
u32,
bool,
Option<u64>,
i64,
u16,
u16,
#[serde(with = "serde_bytes")] &'a [u8],
);
/// If these differ, deleting the shadow structs was a wire break rather than a
/// simplification, and every existing consumer would need to move in step.
#[test]
fn the_derive_reproduces_the_hand_written_wire_payload_byte_for_byte() {
let record = access_unit();
let legacy = LegacyVideoAccessUnitWirePayload(
&record.stream_id,
&record.session_id,
record.frame_id,
&record.codec,
record.pts_ticks,
record.duration_ticks,
record.timebase_num,
record.timebase_den,
record.keyframe,
record.dependency_frame_id,
record.deadline_ticks,
record.chunk_index,
record.chunk_count,
&record.payload,
);
let from_derive = rmp_serde::to_vec(&record).expect("record encodes");
let from_shadow = rmp_serde::to_vec(&legacy).expect("shadow struct encodes");
assert_eq!(
from_derive, from_shadow,
"the `bytes` attribute must reproduce what serde_bytes produced by hand"
);
}
#[test]
fn a_video_record_round_trips_through_the_envelope() {
let record = GameCultMediaWireRecord::Video(access_unit());
let wire = encode_media_wire_record(&record, provenance()).expect("encodes");
assert_eq!(decode_media_wire_record(&wire).expect("decodes"), record);
}
#[test]
fn every_variant_round_trips() {
let variants = vec![
GameCultMediaWireRecord::Video(access_unit()),
GameCultMediaWireRecord::VideoParity(GameCultMediaVideoParityShardRecord {
stream_id: "s".to_string(),
session_id: "x".to_string(),
frame_id: 1,
codec: "h264".to_string(),
pts_ticks: 0,
duration_ticks: 1,
timebase_num: 1,
timebase_den: 90_000,
keyframe: false,
dependency_frame_id: Some(0),
deadline_ticks: 1,
chunk_count: 4,
parity_index: 1,
parity_count: 2,
chunk_payload_bytes: 848,
last_chunk_payload_bytes: 400,
payload: vec![1, 2, 3],
}),
GameCultMediaWireRecord::Audio(GameCultMediaAudioPacketRecord {
stream_id: "s".to_string(),
session_id: "x".to_string(),
packet_id: 9,
codec: "opus".to_string(),
pts_ticks: 0,
duration_ticks: 960,
timebase_num: 1,
timebase_den: 48_000,
deadline_ticks: 1,
payload: vec![4, 5, 6],
}),
GameCultMediaWireRecord::Feedback(GameCultMediaReceiverFeedbackRecord {
stream_id: "s".to_string(),
session_id: "x".to_string(),
receiver_id: "starfire-obs".to_string(),
highest_decodable_frame_id: Some(41),
missing_frame_ids: vec![42],
late_frame_ids: vec![43],
requested_keyframe: true,
jitter_us: 500,
decode_queue_us: 2_000,
observed_at: "unix:1000".to_string(),
missing_video_chunk_keys: vec!["42:1".to_string()],
}),
];
for record in variants {
let wire = encode_media_wire_record(&record, provenance()).expect("encodes");
assert_eq!(
decode_media_wire_record(&wire).expect("decodes"),
record,
"variant {} did not survive the envelope",
record.schema_id()
);
}
}
/// Record keys address one piece of media within a session. A consumer parses
/// them, so their shape is contract.
#[test]
fn record_keys_distinguish_chunks_parity_and_senders() {
let mut second_chunk = access_unit();
second_chunk.chunk_index = 3;
let first = GameCultMediaWireRecord::Video(access_unit()).record_key();
let second = GameCultMediaWireRecord::Video(second_chunk).record_key();
assert_ne!(first, second, "chunks of one frame must not share a key");
assert!(first.contains(":video:"), "got {first}");
}
/// A shared envelope must not label another producer's traffic as Muninn's.
#[test]
fn the_producer_namespace_is_the_callers_not_the_envelopes() {
let record = GameCultMediaWireRecord::Video(access_unit());
let theirs = MediaWireProvenance {
stored_at: "unix:1000",
runtime_id: "nightwing",
role: "brokkr.media",
producer: "brokkr",
};
let wire = encode_media_wire_record(&record, theirs).expect("encodes");
let text = String::from_utf8_lossy(&wire);
assert!(text.contains("brokkr-media:"), "message id names the producer");
assert!(text.contains("brokkr.media"), "tag names the producer");
assert!(
!text.contains("muninn"),
"the envelope must not name a producer the caller did not supply"
);
}
#[test]
fn provenance_must_be_complete() {
let record = GameCultMediaWireRecord::Video(access_unit());
for blank in ["stored_at", "runtime_id", "role", "producer"] {
let mut incomplete = provenance();
match blank {
"stored_at" => incomplete.stored_at = "",
"runtime_id" => incomplete.runtime_id = "",
"role" => incomplete.role = "",
_ => incomplete.producer = "",
}
let error = encode_media_wire_record(&record, incomplete)
.expect_err("empty provenance must be refused");
assert!(error.to_string().contains(blank), "got {error}");
}
}
#[test]
fn the_media_channel_is_named_once() {
assert_eq!(GAMECULT_MEDIA_CHANNEL, "media");
}