diff --git a/packages/cultnet-rs/src/lib.rs b/packages/cultnet-rs/src/lib.rs index 3e8a3c94..5aa121af 100644 --- a/packages/cultnet-rs/src/lib.rs +++ b/packages/cultnet-rs/src/lib.rs @@ -1,6 +1,7 @@ mod contracts; mod idunn_deployment_brake; mod idunn_lifecycle_brake; +mod media_stream_contracts; mod provider_health_contracts; mod runtime_authority_contracts; mod service_identity; @@ -19,6 +20,7 @@ mod transport; pub use contracts::*; pub use idunn_deployment_brake::*; pub use idunn_lifecycle_brake::*; +pub use media_stream_contracts::*; pub use provider_health_contracts::*; pub use runtime_authority_contracts::*; pub use service_identity::*; diff --git a/packages/cultnet-rs/src/media_stream_contracts.rs b/packages/cultnet-rs/src/media_stream_contracts.rs new file mode 100644 index 00000000..e47b3a28 --- /dev/null +++ b/packages/cultnet-rs/src/media_stream_contracts.rs @@ -0,0 +1,194 @@ +//! 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. +//! +//! # 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, + #[cultcache(key = 10)] + pub deadline_ticks: i64, + #[cultcache(key = 11)] + pub chunk_index: u16, + #[cultcache(key = 12)] + pub chunk_count: u16, + #[cultcache(key = 13)] + pub payload: Vec, +} + +/// 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, + #[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)] + pub payload: Vec, +} + +/// 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)] + pub payload: Vec, +} + +/// 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, + #[cultcache(key = 4)] + pub missing_frame_ids: Vec, + #[cultcache(key = 5)] + pub late_frame_ids: Vec, + #[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, +} diff --git a/packages/cultnet-rs/tests/media_stream_contracts.rs b/packages/cultnet-rs/tests/media_stream_contracts.rs new file mode 100644 index 00000000..9d2fc664 --- /dev/null +++ b/packages/cultnet-rs/tests/media_stream_contracts.rs @@ -0,0 +1,227 @@ +//! 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!( + matches!(&slots[13], Value::Binary(_) | Value::Array(_)), + "slot 13 is the payload; see payload_should_encode_as_messagepack_bin \ + for which of the two it ought to be" + ); +} + +/// Ignored until `cultcache-rs-derive` grows a `bytes` hint. +/// +/// The derive writes its own `Serialize` and calls `serialize_element` per slot, +/// so a `Vec` field goes out as a MessagePack array of integers. C#, +/// TypeScript and Python all emit `bin` for byte fields, which makes Rust the +/// divergent runtime and these records unreadable by the reference +/// implementation. `#[serde(with = "serde_bytes")]` cannot fix it — the derive +/// ignores serde attributes. +/// +/// It also costs 1.45x on every media byte: an 848-byte payload encodes to 1234 +/// bytes as an integer array against 851 as `bin`. +/// +/// The fix is not local to this file. Changing byte encoding globally would +/// invalidate every signature in the Idunn authority chain, because signatures +/// are taken over the whole positional serialization and canonical hashes over +/// the same bytes. It needs an opt-in hint so these three media records can +/// adopt `bin` without moving the signature-bearing ones. Owned by the Swarm +/// Migration work; un-ignore this when the hint lands. +#[test] +#[ignore = "blocked on a `bytes` opt-in hint in cultcache-rs-derive"] +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" + ); +}