diff --git a/Cargo.lock b/Cargo.lock index 9a2818c..5b3e913 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -169,7 +169,7 @@ dependencies = [ [[package]] name = "cultcache-rs" version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=89687fceb4d0af32e672738a18c352f1b3b744df#89687fceb4d0af32e672738a18c352f1b3b744df" +source = "git+https://github.com/GameCult/CultLib.git?rev=4160ab560b15150d8054c5c7f557711ad244b8e0#4160ab560b15150d8054c5c7f557711ad244b8e0" dependencies = [ "anyhow", "chrono", @@ -187,7 +187,7 @@ dependencies = [ [[package]] name = "cultcache-rs-derive" version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=89687fceb4d0af32e672738a18c352f1b3b744df#89687fceb4d0af32e672738a18c352f1b3b744df" +source = "git+https://github.com/GameCult/CultLib.git?rev=4160ab560b15150d8054c5c7f557711ad244b8e0#4160ab560b15150d8054c5c7f557711ad244b8e0" dependencies = [ "proc-macro2", "quote", @@ -197,7 +197,7 @@ dependencies = [ [[package]] name = "cultnet-rs" version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=89687fceb4d0af32e672738a18c352f1b3b744df#89687fceb4d0af32e672738a18c352f1b3b744df" +source = "git+https://github.com/GameCult/CultLib.git?rev=4160ab560b15150d8054c5c7f557711ad244b8e0#4160ab560b15150d8054c5c7f557711ad244b8e0" dependencies = [ "aes-gcm", "anyhow", @@ -599,6 +599,7 @@ name = "ratatoskr-core" version = "0.1.0" dependencies = [ "anyhow", + "chrono", "cultnet-rs", ] diff --git a/README.md b/README.md index 326d67a..0bffc05 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ does not know or care which producer it is attached to. crates/ratatoskr-core/ Rust. The transport-facing half. src/receiver.rs Subscription over cultnet-rs. No transport of its own. src/video.rs Chunks and parity in, whole access units out. + src/feedback.rs What the receiver says back, and how often. src/ffi.rs The C ABI, deliberately small. plugin/ include/ratatoskr.h Hand-written header. Small enough to read in one sitting. @@ -86,6 +87,20 @@ Audio is not chunked on the wire and carries no parity, so audio packets pass through as sent. The previous receiver's GF(256) audio erasure code had no producer; it is not missing here, it never existed on this contract. +The return path is `gamecult.media_receiver_feedback`, built by CultLib's +`build_receiver_feedback` so both ends agree on its shape, and sent back down +the producer's own session on the media channel. A frame still waiting is +asked for by chunk after 64 ms, then every 32 ms, three times — the previous +receiver's field-tested cadence — and a repair request never asks for a +keyframe, because it exists so that one is not needed. A frame given up on is +reported late and, once per 500 ms, a keyframe is requested, since whatever +depended on it cannot be decoded either. `highest_decodable_frame_id` is the +newest frame actually handed to the renderer. `jitter_us` and +`decode_queue_us` are sent as zero: the producer reads neither, and "not +measured" is the truth where a plausible number would not be. With no +producer attached, feedback is reported as not sent and counted, never +dropped on the floor. + A payload that arrives on the media channel and fails to decode is surfaced as `Undecodable` and counted, never silently dropped. A consumer that discards what it cannot parse gives a producer no way to learn its stream is unreadable, which @@ -93,9 +108,6 @@ is how the last receiver and sender drifted apart without either noticing. What is not here yet: -- **Receiver feedback.** `gamecult.media_receiver_feedback` is the return path a - producer adapts to. The assembler already names what an expired frame lacked - (`ExpiredFrame::missing_chunk_keys`); nothing here sends it yet. - **The OBS plugin itself.** Roughly 1,200 lines of genuine OBS work — source registration, the ffmpeg audio decode child, the program texture source, the stem IPC — is worth porting from the Mimir plugin rather than rewriting. The diff --git a/crates/ratatoskr-core/Cargo.toml b/crates/ratatoskr-core/Cargo.toml index ce77613..8cfa0ca 100644 --- a/crates/ratatoskr-core/Cargo.toml +++ b/crates/ratatoskr-core/Cargo.toml @@ -12,4 +12,5 @@ crate-type = ["rlib", "cdylib", "staticlib"] [dependencies] anyhow = "1" -cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "89687fceb4d0af32e672738a18c352f1b3b744df", package = "cultnet-rs" } +chrono = "0.4" +cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "4160ab560b15150d8054c5c7f557711ad244b8e0", package = "cultnet-rs" } diff --git a/crates/ratatoskr-core/src/feedback.rs b/crates/ratatoskr-core/src/feedback.rs new file mode 100644 index 0000000..bd4a1ef --- /dev/null +++ b/crates/ratatoskr-core/src/feedback.rs @@ -0,0 +1,213 @@ +//! What the receiver says back, and when. +//! +//! The record is the contract's (`gamecult.media_receiver_feedback`) and its +//! shape is CultLib's `build_receiver_feedback`. This module owns only the +//! receiver-side policy of what goes in one: repair requests for frames still +//! waiting, late reports for frames given up on, and a keyframe request when a +//! reference is gone — no more often than a producer can usefully answer. + +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; + +use anyhow::Result; +use cultnet_rs::{GameCultMediaReceiverFeedbackRecord, ReceiverFeedbackOptions, build_receiver_feedback}; + +use crate::video::{ExpiredFrame, RepairRequest}; + +#[derive(Clone, Debug)] +pub struct FeedbackOptions { + /// A producer answers a keyframe request with an IDR, which costs it + /// bandwidth for a whole GOP. One request per cooldown is enough to + /// resynchronise; more just describes the same loss louder. + pub keyframe_request_cooldown: Duration, +} + +impl Default for FeedbackOptions { + fn default() -> Self { + Self { + keyframe_request_cooldown: Duration::from_millis(500), + } + } +} + +/// Counted from what was said, not what was configured. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct FeedbackStats { + /// Records handed to the transport. + pub sent: u64, + /// Chunk keys asked for again across all records. + pub chunks_requested: u64, + /// Records that carried a keyframe request. + pub keyframes_requested: u64, + /// Records the transport refused, usually because no producer is attached. + pub not_sent: u64, +} + +pub struct FeedbackComposer { + receiver_id: String, + options: FeedbackOptions, + last_keyframe_request: Option, + stats: FeedbackStats, +} + +impl FeedbackComposer { + pub fn new(receiver_id: impl Into, options: FeedbackOptions) -> Self { + Self { + receiver_id: receiver_id.into(), + options, + last_keyframe_request: None, + stats: FeedbackStats::default(), + } + } + + /// One record per stream and session that has something to say. Repairs + /// name the chunks still wanted; expiries name the frames given up on and, + /// once per cooldown, ask for a keyframe, since whatever depended on them + /// cannot be decoded either. + pub fn compose( + &mut self, + repairs: &[RepairRequest], + expired: &[ExpiredFrame], + highest_decodable_frame_id: Option, + now: Instant, + observed_at: &str, + ) -> Result> { + let mut by_stream: BTreeMap<(String, String), (Vec, Vec)> = BTreeMap::new(); + for repair in repairs { + let entry = by_stream + .entry((repair.key.stream_id.clone(), repair.key.session_id.clone())) + .or_default(); + entry.0.extend(repair.missing_chunk_keys.iter().cloned()); + } + for frame in expired { + let entry = by_stream + .entry((frame.key.stream_id.clone(), frame.key.session_id.clone())) + .or_default(); + entry.1.push(frame.key.frame_id); + } + + let mut records = Vec::with_capacity(by_stream.len()); + for ((stream_id, session_id), (missing_video_chunk_keys, late_frame_ids)) in by_stream { + let lost_a_reference = !late_frame_ids.is_empty(); + let requested_keyframe = lost_a_reference && self.keyframe_request_due(now); + let record = build_receiver_feedback(ReceiverFeedbackOptions { + stream_id: &stream_id, + session_id: &session_id, + receiver_id: &self.receiver_id, + highest_decodable_frame_id, + missing_frame_ids: Vec::new(), + missing_video_chunk_keys, + late_frame_ids, + requested_keyframe, + // The producer reads neither today. Zero is "not measured", + // which is the truth; a plausible number would not be. + jitter_us: 0, + decode_queue_us: 0, + observed_at, + })?; + if record.requested_keyframe { + self.last_keyframe_request = Some(now); + self.stats.keyframes_requested += 1; + } + self.stats.chunks_requested += record.missing_video_chunk_keys.len() as u64; + records.push(record); + } + Ok(records) + } + + pub fn record_sent(&mut self) { + self.stats.sent += 1; + } + + pub fn record_not_sent(&mut self) { + self.stats.not_sent += 1; + } + + pub fn stats(&self) -> FeedbackStats { + self.stats + } + + fn keyframe_request_due(&self, now: Instant) -> bool { + self.last_keyframe_request + .is_none_or(|last| now.duration_since(last) >= self.options.keyframe_request_cooldown) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::video::{ExpiryReason, FrameKey}; + + fn key(frame_id: u64) -> FrameKey { + FrameKey { + stream_id: "s".into(), + session_id: "x".into(), + frame_id, + } + } + + #[test] + fn repairs_ask_for_chunks_without_asking_for_a_keyframe() -> Result<()> { + let mut composer = FeedbackComposer::new("starfire.obs", FeedbackOptions::default()); + let repairs = vec![RepairRequest { + key: key(9), + missing_chunk_keys: vec!["9:2".into(), "9:1".into()], + }]; + let records = composer.compose(&repairs, &[], Some(8), Instant::now(), "2026-09-10T00:00:00Z")?; + + assert_eq!(records.len(), 1); + assert_eq!(records[0].missing_video_chunk_keys, vec!["9:1", "9:2"]); + assert!(records[0].late_frame_ids.is_empty()); + assert!(!records[0].requested_keyframe); + assert_eq!(records[0].highest_decodable_frame_id, Some(8)); + assert_eq!(records[0].receiver_id, "starfire.obs"); + assert_eq!(composer.stats().chunks_requested, 2); + Ok(()) + } + + #[test] + fn a_lost_frame_asks_for_a_keyframe_once_per_cooldown() -> Result<()> { + let start = Instant::now(); + let mut composer = FeedbackComposer::new("starfire.obs", FeedbackOptions { keyframe_request_cooldown: Duration::from_millis(100) }); + let lost = |frame_id| ExpiredFrame { + key: key(frame_id), + keyframe: false, + missing_chunk_keys: vec![format!("{frame_id}:1")], + reason: ExpiryReason::Aged, + }; + + let first = composer.compose(&[], &[lost(9)], Some(8), start, "t")?; + assert!(first[0].requested_keyframe); + assert_eq!(first[0].late_frame_ids, vec![9]); + + let second = composer.compose(&[], &[lost(10)], Some(8), start + Duration::from_millis(50), "t")?; + assert!(!second[0].requested_keyframe, "still inside the cooldown"); + assert_eq!(second[0].late_frame_ids, vec![10]); + + let third = composer.compose(&[], &[lost(11)], Some(8), start + Duration::from_millis(150), "t")?; + assert!(third[0].requested_keyframe); + assert_eq!(composer.stats().keyframes_requested, 2); + Ok(()) + } + + #[test] + fn nothing_to_say_yields_no_record() -> Result<()> { + let mut composer = FeedbackComposer::new("r", FeedbackOptions::default()); + assert!(composer.compose(&[], &[], None, Instant::now(), "t")?.is_empty()); + Ok(()) + } + + #[test] + fn streams_are_reported_separately() -> Result<()> { + let mut composer = FeedbackComposer::new("r", FeedbackOptions::default()); + let other = FrameKey { stream_id: "other".into(), session_id: "x".into(), frame_id: 3 }; + let repairs = vec![ + RepairRequest { key: key(9), missing_chunk_keys: vec!["9:1".into()] }, + RepairRequest { key: other, missing_chunk_keys: vec!["3:0".into()] }, + ]; + let records = composer.compose(&repairs, &[], None, Instant::now(), "t")?; + assert_eq!(records.len(), 2); + assert_eq!(records.iter().map(|r| r.stream_id.as_str()).collect::>(), vec!["other", "s"]); + Ok(()) + } +} diff --git a/crates/ratatoskr-core/src/ffi.rs b/crates/ratatoskr-core/src/ffi.rs index b040612..a8eb580 100644 --- a/crates/ratatoskr-core/src/ffi.rs +++ b/crates/ratatoskr-core/src/ffi.rs @@ -15,6 +15,7 @@ use std::ffi::{CStr, c_char, c_int, c_uint}; use std::net::SocketAddr; use std::ptr; +use crate::feedback::FeedbackOptions; use crate::receiver::{MediaEvent, RatatoskrReceiver, ReceiverOptions}; use crate::video::VideoAssemblerOptions; @@ -80,6 +81,7 @@ pub unsafe extern "C" fn ratatoskr_receiver_open( runtime_id, connection_id: connection_id as u32, video: VideoAssemblerOptions::default(), + feedback: FeedbackOptions::default(), }) { Ok(receiver) => { let handle = Box::new(RatatoskrHandle { @@ -122,10 +124,12 @@ pub unsafe extern "C" fn ratatoskr_receiver_poll(handle: *mut RatatoskrHandle) - } // Given-up frames and feedback carry no media for a // renderer; the counters say they happened. - MediaEvent::VideoFrameExpired { .. } | MediaEvent::Feedback { .. } => {} - MediaEvent::Undecodable { reason, .. } | MediaEvent::Rejected { reason } => { - set_last_error(reason) - } + MediaEvent::VideoFrameExpired { .. } + | MediaEvent::Feedback { .. } + | MediaEvent::FeedbackSent { .. } => {} + MediaEvent::Undecodable { reason, .. } + | MediaEvent::Rejected { reason } + | MediaEvent::FeedbackNotSent { reason } => set_last_error(reason), MediaEvent::ProducerAttached { remote } => handle.attached = Some(remote), MediaEvent::ProducerDetached { .. } => handle.attached = None, } @@ -257,6 +261,36 @@ pub unsafe extern "C" fn ratatoskr_receiver_video_stats( } } +/// What was said back to the producer: records sent, chunks asked for again, +/// keyframes requested, and records the transport refused. Any out pointer +/// may be null. +/// +/// # Safety +/// `handle` must be live. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn ratatoskr_receiver_feedback_stats( + handle: *mut RatatoskrHandle, + out_sent: *mut u64, + out_chunks_requested: *mut u64, + out_keyframes_requested: *mut u64, + out_not_sent: *mut u64, +) { + let Some(handle) = (unsafe { handle.as_ref() }) else { + return; + }; + let stats = handle.receiver.feedback_stats(); + for (out, value) in [ + (out_sent, stats.sent), + (out_chunks_requested, stats.chunks_requested), + (out_keyframes_requested, stats.keyframes_requested), + (out_not_sent, stats.not_sent), + ] { + if !out.is_null() { + unsafe { *out = value }; + } + } +} + /// Last error on this thread, valid until the next call that fails. Never null. #[unsafe(no_mangle)] pub extern "C" fn ratatoskr_last_error(buffer: *mut c_char, capacity: usize) -> usize { diff --git a/crates/ratatoskr-core/src/lib.rs b/crates/ratatoskr-core/src/lib.rs index b13ca8e..b2a9748 100644 --- a/crates/ratatoskr-core/src/lib.rs +++ b/crates/ratatoskr-core/src/lib.rs @@ -25,12 +25,17 @@ //! Ratatoskr is a consumer of a general contract. It is not the contract, and it //! has no opinion about who produced the stream. +pub mod feedback; pub mod ffi; mod receiver; pub mod video; pub use receiver::{MediaEvent, RatatoskrReceiver, ReceiverOptions}; -pub use video::{ExpiredFrame, ExpiryReason, FrameKey, VideoAssembler, VideoAssemblerOptions, VideoFrame, VideoStats}; +pub use feedback::{FeedbackOptions, FeedbackStats}; +pub use video::{ + ExpiredFrame, ExpiryReason, FrameKey, RepairRequest, VideoAssembler, VideoAssemblerOptions, + VideoFrame, VideoStats, +}; /// The CultNet channel media rides. Named here once so nothing downstream /// guesses it from a string literal. diff --git a/crates/ratatoskr-core/src/receiver.rs b/crates/ratatoskr-core/src/receiver.rs index 8ed4367..0efd607 100644 --- a/crates/ratatoskr-core/src/receiver.rs +++ b/crates/ratatoskr-core/src/receiver.rs @@ -1,4 +1,5 @@ -//! The subscription: bind, accept a producer, hand back media events. +//! The subscription: bind, accept a producer, hand back media events, and +//! say back what was lost. //! //! Everything below the events is `cultnet-rs`. This file has no sequence //! numbers, no acknowledgement state and no retransmit timers, and it must not @@ -8,15 +9,22 @@ use std::net::{SocketAddr, UdpSocket}; use std::time::Instant; use anyhow::{Context, Result}; +use chrono::{SecondsFormat, Utc}; use cultnet_rs::{ - CultNetRudpServerHub, CultNetRudpServerHubOptions, CultNetRudpServerEvent, - CultNetTransportFrame, GameCultMediaAudioPacketRecord, GameCultMediaReceiverFeedbackRecord, - GameCultMediaWireRecord, decode_media_wire_record, + CultNetRudpServerEvent, CultNetRudpServerHub, CultNetRudpServerHubOptions, + CultNetRudpServerSessionContext, CultNetTransportFrame, GameCultMediaAudioPacketRecord, + GameCultMediaReceiverFeedbackRecord, GameCultMediaWireRecord, MediaWireProvenance, + decode_media_wire_record, encode_media_wire_record, }; use crate::MEDIA_CHANNEL; +use crate::feedback::{FeedbackComposer, FeedbackOptions, FeedbackStats}; use crate::video::{ExpiredFrame, VideoAssembler, VideoAssemblerOptions, VideoFrame, VideoStats}; +/// The producer name Ratatoskr puts on the envelopes it emits. The envelope +/// takes it as a parameter so no consumer's name is baked into the contract. +pub const RATATOSKR_MEDIA_PRODUCER: &str = "ratatoskr"; + #[derive(Clone, Debug)] pub struct ReceiverOptions { /// Where to listen for the producer. @@ -27,6 +35,8 @@ pub struct ReceiverOptions { pub connection_id: u32, /// How incomplete video frames are waited for and given up on. pub video: VideoAssemblerOptions, + /// How often the producer is told. + pub feedback: FeedbackOptions, } /// What the renderer is given. Deliberately not the wire record: a renderer @@ -46,6 +56,11 @@ pub enum MediaEvent { /// Feedback flows the other way; a producer echoing it here is unusual /// but not an error. Feedback { record: Box }, + /// Feedback this receiver handed to the transport for the producer. + FeedbackSent { record: Box }, + /// Feedback that could not be handed to the transport, usually because no + /// producer is attached to tell. + FeedbackNotSent { reason: String }, /// A media payload arrived but is not a media record this build understands. /// /// Surfaced rather than dropped: a consumer that silently discards what it @@ -60,7 +75,10 @@ pub enum MediaEvent { pub struct RatatoskrReceiver { hub: CultNetRudpServerHub, + runtime_id: String, + producer: Option, video: VideoAssembler, + feedback: FeedbackComposer, payloads: u64, payload_bytes: u64, undecodable: u64, @@ -76,7 +94,7 @@ impl RatatoskrReceiver { .context("setting Ratatoskr media receiver nonblocking")?; let hub = CultNetRudpServerHub::new(CultNetRudpServerHubOptions::new( - options.runtime_id, + options.runtime_id.clone(), socket, options.connection_id, )) @@ -84,6 +102,9 @@ impl RatatoskrReceiver { Ok(Self { hub, + feedback: FeedbackComposer::new(options.runtime_id.clone(), options.feedback), + runtime_id: options.runtime_id, + producer: None, video: VideoAssembler::new(options.video), payloads: 0, payload_bytes: 0, @@ -96,8 +117,9 @@ impl RatatoskrReceiver { self.hub.local_addr() } - /// Drains what has arrived. Never blocks; a caller drives this from its own - /// loop so the renderer keeps its own cadence. + /// Drains what has arrived, gives up on what is too old, and tells the + /// producer what is wanted. Never blocks; a caller drives this from its + /// own loop so the renderer keeps its own cadence. pub fn poll(&mut self) -> Result> { let now = Instant::now(); let mut events = Vec::new(); @@ -107,11 +129,17 @@ impl RatatoskrReceiver { events.push(MediaEvent::ProducerAttached { remote: session.remote_addr, }); + self.producer = Some(session); } CultNetRudpServerEvent::Disconnected { session, .. } => { events.push(MediaEvent::ProducerDetached { remote: session.remote_addr, }); + if self.producer.as_ref().is_some_and(|producer| { + producer.session_generation == session.session_generation + }) { + self.producer = None; + } } CultNetRudpServerEvent::Frame { frame, .. } => { if let Some(payload) = media_payload(frame) { @@ -132,15 +160,73 @@ impl RatatoskrReceiver { _ => {} } } + self.hub.poll_resends()?; + + let repairs = self.video.due_repairs(now); + let expired = self.video.expire(now); events.extend( - self.video - .expire(now) - .into_iter() + expired + .iter() + .cloned() .map(|frame| MediaEvent::VideoFrameExpired { frame }), ); + if !repairs.is_empty() || !expired.is_empty() { + let observed_at = Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true); + let records = self.feedback.compose( + &repairs, + &expired, + self.video.highest_delivered_frame_id(), + now, + &observed_at, + )?; + for record in records { + events.push(self.send_feedback(record, &observed_at)); + } + } Ok(events) } + fn send_feedback( + &mut self, + record: GameCultMediaReceiverFeedbackRecord, + stored_at: &str, + ) -> MediaEvent { + let Some(producer) = self.producer.as_ref() else { + self.feedback.record_not_sent(); + return MediaEvent::FeedbackNotSent { + reason: "no producer is attached".to_string(), + }; + }; + let wire = GameCultMediaWireRecord::Feedback(record); + let encoded = encode_media_wire_record( + &wire, + MediaWireProvenance { + stored_at, + runtime_id: &self.runtime_id, + role: "receiver", + producer: RATATOSKR_MEDIA_PRODUCER, + }, + ) + .and_then(|payload| self.hub.send(producer, MEDIA_CHANNEL, payload)); + let GameCultMediaWireRecord::Feedback(record) = wire else { + unreachable!("constructed above"); + }; + match encoded { + Ok(()) => { + self.feedback.record_sent(); + MediaEvent::FeedbackSent { + record: Box::new(record), + } + } + Err(error) => { + self.feedback.record_not_sent(); + MediaEvent::FeedbackNotSent { + reason: format!("{error:#}"), + } + } + } + } + fn admit(&mut self, record: GameCultMediaWireRecord, now: Instant) -> Option { let assembled = match record { GameCultMediaWireRecord::Video(record) => self.video.insert_chunk(record, now), @@ -194,6 +280,11 @@ impl RatatoskrReceiver { pub fn video_stats(&self) -> VideoStats { self.video.stats() } + + /// What was said back to the producer. + pub fn feedback_stats(&self) -> FeedbackStats { + self.feedback.stats() + } } /// Frames on other channels belong to other conversations. @@ -204,16 +295,44 @@ fn media_payload(frame: CultNetTransportFrame) -> Option> { #[cfg(test)] mod tests { use super::*; + use std::time::Duration; + + use cultnet_rs::{ + CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, + CultNetTransportDelivery, GameCultMediaVideoAccessUnitRecord, + }; + + const CONNECTION: u32 = 0x0BE0_0001; fn loopback() -> ReceiverOptions { ReceiverOptions { bind: "127.0.0.1:0".parse().expect("parses"), runtime_id: "ratatoskr-test".to_string(), - connection_id: 0x0BE0_0001, + connection_id: CONNECTION, video: VideoAssemblerOptions::default(), + feedback: FeedbackOptions::default(), } } + fn chunk(frame_id: u64, index: u16, count: u16, payload: Vec) -> GameCultMediaWireRecord { + GameCultMediaWireRecord::Video(GameCultMediaVideoAccessUnitRecord { + stream_id: "s".into(), + session_id: "x".into(), + frame_id, + codec: "h264".into(), + pts_ticks: 0, + duration_ticks: 3_000, + timebase_num: 1, + timebase_den: 90_000, + keyframe: true, + dependency_frame_id: None, + deadline_ticks: 1_800, + chunk_index: index, + chunk_count: count, + payload, + }) + } + #[test] fn a_receiver_binds_and_reports_where() { let receiver = RatatoskrReceiver::open(loopback()).expect("opens"); @@ -227,6 +346,7 @@ mod tests { assert!(receiver.poll().expect("polls").is_empty()); assert_eq!(receiver.delivered(), (0, 0)); assert_eq!(receiver.video_stats(), VideoStats::default()); + assert_eq!(receiver.feedback_stats(), FeedbackStats::default()); } #[test] @@ -266,26 +386,8 @@ mod tests { fn video_records_become_frames_and_audio_stays_as_sent() { let mut receiver = RatatoskrReceiver::open(loopback()).expect("opens"); let now = Instant::now(); - let chunk = |index: u16, payload: Vec| GameCultMediaWireRecord::Video( - cultnet_rs::GameCultMediaVideoAccessUnitRecord { - stream_id: "s".into(), - session_id: "x".into(), - frame_id: 1, - codec: "h264".into(), - pts_ticks: 0, - duration_ticks: 3_000, - timebase_num: 1, - timebase_den: 90_000, - keyframe: true, - dependency_frame_id: None, - deadline_ticks: 1_800, - chunk_index: index, - chunk_count: 2, - payload, - }, - ); - assert_eq!(receiver.admit(chunk(0, vec![1, 2]), now), None); - let Some(MediaEvent::VideoFrame { frame }) = receiver.admit(chunk(1, vec![3]), now) else { + assert_eq!(receiver.admit(chunk(1, 0, 2, vec![1, 2]), now), None); + let Some(MediaEvent::VideoFrame { frame }) = receiver.admit(chunk(1, 1, 2, vec![3]), now) else { panic!("second chunk completes the frame"); }; assert_eq!(frame.bytes, vec![1, 2, 3]); @@ -308,4 +410,115 @@ mod tests { }; assert_eq!(record.payload, vec![9, 9, 9]); } + + /// Feedback with nobody to send it to is reported, not lost silently. + #[test] + fn feedback_without_a_producer_is_reported_not_sent() { + let mut receiver = RatatoskrReceiver::open(ReceiverOptions { + video: VideoAssemblerOptions { + repair_first_wait: Duration::ZERO, + ..Default::default() + }, + ..loopback() + }) + .expect("opens"); + assert_eq!(receiver.admit(chunk(1, 0, 3, vec![1]), Instant::now()), None); + let events = receiver.poll().expect("polls"); + assert!( + matches!(events.as_slice(), [MediaEvent::FeedbackNotSent { reason }] if reason.contains("no producer")), + "got {events:?}" + ); + assert_eq!(receiver.feedback_stats().not_sent, 1); + } + + /// The whole return path over real sockets: a producer connects, loses a + /// chunk on the way, and is told which one — then, when the frame is given + /// up on, that it was late and that a keyframe is wanted. + #[test] + fn a_producer_is_told_what_was_lost() -> Result<()> { + let mut receiver = RatatoskrReceiver::open(ReceiverOptions { + video: VideoAssemblerOptions { + max_frame_age: Duration::from_millis(150), + repair_first_wait: Duration::from_millis(20), + repair_retry_wait: Duration::from_millis(20), + repair_max_requests: 3, + ..Default::default() + }, + ..loopback() + })?; + let receiver_addr = receiver.local_addr()?; + + let socket = UdpSocket::bind("127.0.0.1:0")?; + socket.set_nonblocking(true)?; + let mut options = CultNetRudpSocketTransportOptions::client("producer-test", socket, receiver_addr, CONNECTION); + options.media_delivery = Some(CultNetTransportDelivery::Unreliable); + let mut producer = CultNetRudpSocketTransportConnection::new(options)?; + producer.connect(b"test".to_vec())?; + + fn pump( + receiver: &mut RatatoskrReceiver, + producer: &mut CultNetRudpSocketTransportConnection, + feedback: &mut Vec, + ) -> Result> { + let events = receiver.poll()?; + producer.poll_resends()?; + while let Some(frame) = producer.receive_once()? { + if frame.channel_id == MEDIA_CHANNEL { + if let Ok(GameCultMediaWireRecord::Feedback(record)) = decode_media_wire_record(&frame.payload) { + feedback.push(record); + } + } + } + Ok(events) + } + let mut feedback = Vec::new(); + + let deadline = Instant::now() + Duration::from_secs(3); + while !producer.connected() { + pump(&mut receiver, &mut producer, &mut feedback)?; + assert!(Instant::now() < deadline, "producer never connected"); + std::thread::sleep(Duration::from_millis(2)); + } + + // Three chunks; the middle one never leaves. + let provenance = MediaWireProvenance { stored_at: "t", runtime_id: "producer-test", role: "producer", producer: "test" }; + for index in [0u16, 2] { + let record = chunk(9, index, 3, vec![index as u8; 4]); + producer.send(MEDIA_CHANNEL, encode_media_wire_record(&record, provenance.clone())?)?; + } + + let deadline = Instant::now() + Duration::from_secs(3); + let mut expired = false; + while Instant::now() < deadline { + for event in pump(&mut receiver, &mut producer, &mut feedback)? { + if let MediaEvent::VideoFrameExpired { frame } = event { + assert_eq!(frame.key.frame_id, 9); + expired = true; + } + } + if expired && feedback.iter().any(|record| !record.late_frame_ids.is_empty()) { + break; + } + std::thread::sleep(Duration::from_millis(2)); + } + + let repairs = feedback.iter().filter(|record| !record.missing_video_chunk_keys.is_empty()).collect::>(); + assert!(!repairs.is_empty(), "the producer was never asked for the missing chunk; feedback: {feedback:?}"); + for record in &repairs { + assert_eq!(record.missing_video_chunk_keys, vec!["9:1"]); + assert_eq!(record.receiver_id, "ratatoskr-test"); + assert_eq!(record.stream_id, "s"); + } + assert!(repairs.iter().all(|record| !record.requested_keyframe), "a repair request is not a keyframe request"); + + let late = feedback.iter().find(|record| !record.late_frame_ids.is_empty()).expect("the frame was reported late"); + assert_eq!(late.late_frame_ids, vec![9]); + assert!(late.requested_keyframe, "a lost frame asks for a keyframe"); + + let stats = receiver.feedback_stats(); + assert!(stats.sent >= 2, "{stats:?}"); + assert_eq!(stats.keyframes_requested, 1); + assert_eq!(receiver.video_stats().expired, 1); + Ok(()) + } } diff --git a/crates/ratatoskr-core/src/video.rs b/crates/ratatoskr-core/src/video.rs index 4aa4f93..c0d5c84 100644 --- a/crates/ratatoskr-core/src/video.rs +++ b/crates/ratatoskr-core/src/video.rs @@ -83,6 +83,14 @@ pub struct VideoAssemblerOptions { pub max_pending_frames: usize, /// Completed frames remembered so their late chunks are recognised as late. pub remembered_frames: usize, + /// How long a frame waits for stragglers before its missing chunks are + /// asked for. Below one reorder window this asks for chunks still in + /// flight. + pub repair_first_wait: Duration, + /// How long after a repair request before asking again. + pub repair_retry_wait: Duration, + /// Repair requests per frame before it is left to age out. + pub repair_max_requests: u32, } impl Default for VideoAssemblerOptions { @@ -93,6 +101,11 @@ impl Default for VideoAssemblerOptions { max_frame_age: Duration::from_millis(250), max_pending_frames: 64, remembered_frames: 256, + // The previous receiver's field-tested cadence: 64 ms, then every + // 32 ms, three times. + repair_first_wait: Duration::from_millis(64), + repair_retry_wait: Duration::from_millis(32), + repair_max_requests: 3, } } } @@ -109,6 +122,15 @@ pub struct VideoStats { /// Complete frames withheld because a reference was lost and no keyframe /// has arrived since. pub awaiting_keyframe_discarded: u64, + /// Repair requests raised for frames still waiting. + pub repairs_requested: u64, +} + +/// A frame still waiting, and the chunks it wants asked for again. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RepairRequest { + pub key: FrameKey, + pub missing_chunk_keys: Vec, } /// The metadata every chunk and shard of one frame must agree on. @@ -168,6 +190,8 @@ struct Assembly { parity: BTreeMap, first_seen: Instant, repaired: u16, + repair_requests: u32, + last_repair_request: Option, } impl Assembly { @@ -178,6 +202,8 @@ impl Assembly { parity: BTreeMap::new(), first_seen: now, repaired: 0, + repair_requests: 0, + last_repair_request: None, } } @@ -269,6 +295,7 @@ pub struct VideoAssembler { pending: BTreeMap, remembered: VecDeque, waiting_for_keyframe: bool, + highest_delivered_frame_id: Option, stats: VideoStats, } @@ -286,6 +313,7 @@ impl VideoAssembler { remembered: VecDeque::new(), // A decoder has nothing to build on until the first keyframe. waiting_for_keyframe: true, + highest_delivered_frame_id: None, stats: VideoStats::default(), } } @@ -357,6 +385,38 @@ impl VideoAssembler { .collect() } + /// Frames that have waited long enough that their missing chunks should + /// be asked for, each at most `repair_max_requests` times. Call after + /// draining the transport, before `expire`. + pub fn due_repairs(&mut self, now: Instant) -> Vec { + let mut due = Vec::new(); + for (key, assembly) in &mut self.pending { + if assembly.is_complete() || assembly.repair_requests >= self.options.repair_max_requests { + continue; + } + let (since, wait) = match assembly.last_repair_request { + None => (assembly.first_seen, self.options.repair_first_wait), + Some(last) => (last, self.options.repair_retry_wait), + }; + if now.duration_since(since) < wait { + continue; + } + assembly.repair_requests += 1; + assembly.last_repair_request = Some(now); + self.stats.repairs_requested += 1; + due.push(RepairRequest { + key: key.clone(), + missing_chunk_keys: assembly.missing_chunk_keys(key.frame_id), + }); + } + due + } + + /// The newest frame actually handed to the renderer. + pub fn highest_delivered_frame_id(&self) -> Option { + self.highest_delivered_frame_id + } + pub fn pending_frames(&self) -> usize { self.pending.len() } @@ -427,6 +487,10 @@ impl VideoAssembler { } self.waiting_for_keyframe = false; } + self.highest_delivered_frame_id = Some( + self.highest_delivered_frame_id + .map_or(frame.frame_id, |current| current.max(frame.frame_id)), + ); Some(frame) } @@ -715,6 +779,53 @@ mod tests { Ok(()) } + #[test] + fn repairs_are_asked_for_after_a_wait_then_on_a_retry_cadence_then_not_at_all() -> Result<()> { + let start = Instant::now(); + let mut assembler = VideoAssembler::new(VideoAssemblerOptions { + repair_first_wait: Duration::from_millis(64), + repair_retry_wait: Duration::from_millis(32), + repair_max_requests: 2, + ..Default::default() + }); + let records = chunks(9, true, &[1, 2, 3, 4, 5], 2); + assembler.insert_chunk(records[0].clone(), start)?; + + assert!(assembler.due_repairs(start + Duration::from_millis(63)).is_empty(), "stragglers get a window"); + let first = assembler.due_repairs(start + Duration::from_millis(64)); + assert_eq!(first.len(), 1); + assert_eq!(first[0].key, key(9)); + assert_eq!(first[0].missing_chunk_keys, vec![video_chunk_feedback_key(9, 1), video_chunk_feedback_key(9, 2)]); + assert!(assembler.due_repairs(start + Duration::from_millis(80)).is_empty(), "not before the retry wait"); + + // A repair that arrives narrows the next request. + assembler.insert_chunk(records[1].clone(), start + Duration::from_millis(90))?; + let second = assembler.due_repairs(start + Duration::from_millis(96)); + assert_eq!(second[0].missing_chunk_keys, vec![video_chunk_feedback_key(9, 2)]); + + assert!(assembler.due_repairs(start + Duration::from_millis(200)).is_empty(), "the budget is spent"); + assert_eq!(assembler.stats().repairs_requested, 2); + Ok(()) + } + + #[test] + fn the_highest_delivered_frame_is_what_the_renderer_got() -> Result<()> { + let now = Instant::now(); + let mut assembler = VideoAssembler::default(); + assert_eq!(assembler.highest_delivered_frame_id(), None); + let nine = chunks(9, true, &[1, 2], 2); + assembler.insert_chunk(nine[0].clone(), now)?; + assert_eq!(assembler.highest_delivered_frame_id(), Some(9)); + // A frame withheld for want of a keyframe was not delivered. + let ten = chunks(10, false, &[3, 4, 5], 2); + assembler.insert_chunk(ten[0].clone(), now)?; + assembler.expire(now + Duration::from_secs(1)); + let eleven = chunks(11, false, &[3, 4], 2); + assembler.insert_chunk(eleven[0].clone(), now)?; + assert_eq!(assembler.highest_delivered_frame_id(), Some(9)); + Ok(()) + } + /// The pending set is a bound, not a fuse: reaching it evicts the oldest /// frame and keeps receiving. #[test] diff --git a/plugin/include/ratatoskr.h b/plugin/include/ratatoskr.h index f9be160..3f72b68 100644 --- a/plugin/include/ratatoskr.h +++ b/plugin/include/ratatoskr.h @@ -72,6 +72,15 @@ void ratatoskr_receiver_video_stats(RatatoskrHandle *handle, uint64_t *out_repaired_chunks, uint64_t *out_given_up); +/* What was said back to the producer: records sent, chunks asked for again, + * keyframes requested, and records the transport refused (usually: no producer + * attached). Any out pointer may be NULL. */ +void ratatoskr_receiver_feedback_stats(RatatoskrHandle *handle, + uint64_t *out_sent, + uint64_t *out_chunks_requested, + uint64_t *out_keyframes_requested, + uint64_t *out_not_sent); + /* Last error on this thread. Returns the full length; truncates to capacity. */ size_t ratatoskr_last_error(char *buffer, size_t capacity);