From d346b5236ffda67aae05de55a12de05e4cde708d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 22:18:19 +0100 Subject: [PATCH 1/8] Strip deprecated A/V streaming stack and odin-core from muninn-daemon --- crates/muninn-daemon/Cargo.toml | 2 - crates/muninn-daemon/src/main.rs | 4763 +---------------- crates/muninn-daemon/src/media_packetizer.rs | 2345 -------- crates/muninn-daemon/src/media_send.rs | 1085 ---- crates/muninn-daemon/src/media_send/tests.rs | 1523 ------ crates/muninn-daemon/testdata/clip.h264 | Bin 8855 -> 0 bytes .../testdata/clip.h264.provenance.txt | 7 - 7 files changed, 94 insertions(+), 9631 deletions(-) delete mode 100644 crates/muninn-daemon/src/media_packetizer.rs delete mode 100644 crates/muninn-daemon/src/media_send.rs delete mode 100644 crates/muninn-daemon/src/media_send/tests.rs delete mode 100644 crates/muninn-daemon/testdata/clip.h264 delete mode 100644 crates/muninn-daemon/testdata/clip.h264.provenance.txt diff --git a/crates/muninn-daemon/Cargo.toml b/crates/muninn-daemon/Cargo.toml index c77d6c5..88c36e2 100644 --- a/crates/muninn-daemon/Cargo.toml +++ b/crates/muninn-daemon/Cargo.toml @@ -22,12 +22,10 @@ libc = "0.2" muninn-contracts = { path = "../muninn-contracts" } muninn-move-tracker = { path = "../muninn-move-tracker" } muninn-psmoveapi-tracker = { path = "../muninn-psmoveapi-tracker", optional = true } -odin-core = { workspace = true } rmp-serde = "1.3" serde = { version = "1", features = ["derive"] } serde_bytes = "0.11" serde_json = "1" -socket2 = "0.5" [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.59", features = [ diff --git a/crates/muninn-daemon/src/main.rs b/crates/muninn-daemon/src/main.rs index 0a031d6..806753b 100644 --- a/crates/muninn-daemon/src/main.rs +++ b/crates/muninn-daemon/src/main.rs @@ -1,53 +1,42 @@ mod idunn_presence; -mod media_packetizer; -mod media_send; -use crate::media_packetizer::{AudioPcmStreamSendConfig, VideoAnnexBStreamSendConfig}; -use crate::media_send::{ - MediaSendCore, MediaSendPolicy, clamp_latency_budget_ms, media_intake_channel, - spawn_audio_group_reader, spawn_video_group_reader, -}; use anyhow::{Context, Result, anyhow}; use cultmesh_rs::{ - CultMesh, CultMeshNodeOptions, CultMeshRudpDocumentPublishOptions, CultMeshRudpSnapshotOptions, + CultMesh, CultMeshNodeOptions, CultMeshRudpDocumentPublishOptions, CultMeshSharedMemoryFrameRing, CultMeshStreamBodyTransport, CultMeshStreamCatalog, CultMeshStreamClock, CultMeshStreamDescriptor, CultMeshStreamKind, }; use cultnet_rs::{ - CultNetRudpServerHub, CultNetRudpServerHubOptions, CultNetRudpSocketTransportConnection, - CultNetRudpSocketTransportOptions, - GAMECULT_MEDIA_STREAM_ADVERTISEMENT_SCHEMA, - GAMECULT_MEDIA_STREAM_REQUEST_SCHEMA, GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, - GameCultMediaStreamAdvertisementRecord, GameCultMediaStreamRequestRecord, - GameCultRuntimePresenceHealthRecord, - media_stream_request_key, validate_media_stream_request, + CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, + GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, GameCultRuntimePresenceHealthRecord, }; use muninn_contracts::{ - MUNINN_MOVE_HUE_PROGRAM_SCHEMA, MUNINN_OBS_STREAM_CATALOG_SCHEMA, - MuninnCaptureStreamCommandRecord, MuninnCaptureStreamRecord, MuninnCommandBoundaryCompatRecord, - MuninnHidControllerStateRecord, MuninnMoveControllerStateRecord, - MuninnMoveEvidenceTransportHealthRecord, MuninnMoveHueProgramRecord, MuninnMoveIdentityRecord, - MuninnMoveLightCommandRecord, MuninnMoveMarkerCandidateRecord, MuninnObsStreamCatalogRecord, - MuninnQuestAccessRecord, MuninnRecords, MuninnTelemetrySurfaceRecord, - MuninnTransportProfileCompatRecord, + MUNINN_MOVE_HUE_PROGRAM_SCHEMA, MuninnHidControllerStateRecord, + MuninnMoveControllerStateRecord, MuninnMoveEvidenceTransportHealthRecord, + MuninnMoveHueProgramRecord, MuninnMoveIdentityRecord, MuninnMoveLightCommandRecord, + MuninnMoveMarkerCandidateRecord, MuninnQuestAccessRecord, MuninnRecords, + MuninnTelemetrySurfaceRecord, }; #[cfg(feature = "psmoveapi-tracker")] use muninn_contracts::MuninnMoveTrackerHealthRecord; -use odin_core::{EveProviderAdvertisementRecord, OdinDocuments}; use serde::{Deserialize, Serialize}; -use serde_json::json; use std::collections::{HashMap, HashSet}; use std::env; use std::fs; #[cfg(feature = "psmoveapi-tracker")] use std::io::BufReader; +#[cfg(unix)] +use std::io::ErrorKind; +#[cfg(any(unix, feature = "psmoveapi-tracker"))] +use std::io::Read; #[cfg(any(not(windows), feature = "psmoveapi-tracker"))] use std::io::Write; -use std::io::{ErrorKind, Read}; use std::net::{SocketAddr, UdpSocket}; use std::path::Path; use std::path::PathBuf; -use std::process::{Child, Command, Stdio}; +use std::process::Command; +#[cfg(any(unix, feature = "psmoveapi-tracker"))] +use std::process::Stdio; use std::sync::{ Arc, Mutex, atomic::{AtomicU64, Ordering}, @@ -68,40 +57,8 @@ use std::os::windows::ffi::OsStrExt; #[cfg(windows)] use windows_sys::Win32::UI::Input::XboxController::{XINPUT_GAMEPAD, XINPUT_STATE, XInputGetState}; -const CULTNET_RUDP_PROTOCOL_ID: &str = "cultnet.transport.rudp.v0"; -const MUNINN_MEDIA_RUDP_CONNECTION_ID: u32 = 0x6d75_0001; const MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID: u32 = 0x6d75_0005; -const MUNINN_RUDP_MEDIA_PROFILE_ID: &str = "muninn.rudp.low_latency_h264_lan.v1"; -const MUNINN_RUDP_MEDIA_VIDEO_BITRATE_KBPS: u32 = 12_000; -const MUNINN_RUDP_MEDIA_VBV_FRAME_BUDGETS: u32 = 1; -const MUNINN_RUDP_MEDIA_LOW_DELAY_KEY_FRAME_SCALE: u32 = 4; -const MUNINN_RUDP_MEDIA_VIDEO_DPB_SIZE: u32 = 1; -const MUNINN_RUDP_MEDIA_PACKET_BYTES: usize = 848; -const MUNINN_RUDP_IPV4_UDP_PAYLOAD_BYTES: usize = 1_472; -const MUNINN_RUDP_FIXED_HEADER_BYTES: usize = 36; -const MUNINN_RUDP_MEDIA_MAX_FRAGMENT_BYTES: usize = MUNINN_RUDP_IPV4_UDP_PAYLOAD_BYTES - - MUNINN_RUDP_FIXED_HEADER_BYTES - - crate::media_packetizer::MUNINN_MEDIA_RUDP_CHANNEL.len(); -/// How long a reliable media packet (audio) waits for its acknowledgement -/// before the hub resends it. 5 ms was a July LAN value for the old dialled -/// client; a receiver that polls every 2 ms answers in 3-6 ms, so at 5 ms -/// nearly every audio fragment was resent before its ack arrived and the -/// producer's send loop drowned in retransmits, starving video (measured -/// 2026-09-10: 7 frames in 9 s with audio on, 266 without). Audio expires at -/// the latency budget anyway; 30 ms costs nothing it can feel. -const MUNINN_RUDP_MEDIA_RESEND_DELAY_MS: u64 = 30; -/// What a request that names no latency budget gets, and what the -/// advertisement offers as `default_latency_budget_ms`. It is the request, -/// not this constant, that owns the deadline once one is named. -const MUNINN_RUDP_MEDIA_DEFAULT_LATENCY_BUDGET_MS: u64 = 250; -const MUNINN_RUDP_MEDIA_RECEIVER_GAP_WAIT_MS: u64 = 16; -const MUNINN_RUDP_MEDIA_SOCKET_BUFFER_BYTES: usize = 16 * 1024 * 1024; -const MUNINN_RUDP_ACTIVE_CATALOG_REPUBLISH_MS: u64 = 2_000; -const MUNINN_ODIN_PROVIDER_LEASE_REFRESH_SECONDS: u64 = 30; const PS_MOVE_LED_REPORT_LEN: usize = 49; -const MUNINN_DISABLED_VIDEO_SOURCE_ID: &str = "video:none"; -const MUNINN_DISABLED_AUDIO_SOURCE_ID: &str = "audio:none"; -const MUNINN_DEFAULT_ACTIVATION_STORE_PATH: &str = "C:/Meta/Odin/state/muninn.activate.cc"; const WINDOWS_XINPUT_SOURCE_PREFIX: &str = "xinput://"; const XINPUT_GAMEPAD_DPAD_UP_MASK: u16 = 0x0001; const XINPUT_GAMEPAD_DPAD_DOWN_MASK: u16 = 0x0002; @@ -121,15 +78,10 @@ const XINPUT_GAMEPAD_Y_MASK: u16 = 0x8000; #[derive(Clone, Debug, PartialEq, Eq)] enum Mode { Serve, - Activate, Health, - DryRun, - RequestStream, RequestMoveLight, SetMoveHueProgram, MoveHueProgramStatus, - CaptureStreamStatus, - ObsCatalogStatus, MoveLightStatus, MoveIdentityStatus, MoveSourceStatus, @@ -143,37 +95,8 @@ enum Mode { struct Options { mode: Mode, store_path: PathBuf, - activation_store_path: Option, surface_id: String, - stream_id: String, - stream_filter_explicit: bool, - stream_action: String, host_id: String, - target_host: String, - port: u16, - /// Where receivers dial for media. Muninn listens; it never dials out. - media_rudp_bind: SocketAddr, - /// `host:port` receivers are told to dial, when the bind address is not - /// itself reachable (`0.0.0.0`). - media_rudp_advertise: Option, - media_transport: MediaTransport, - media_packet_bytes: usize, - rudp_video_bitrate_kbps: u32, - rudp_latency_budget_ms: u32, - width: u32, - height: u32, - framerate: u32, - ddagrab_output_index: u32, - capture_video: bool, - capture_audio: bool, - audio_device: String, - audio_source_id_override: Option, - video_sources: Vec, - audio_sources: Vec, - audio_sample_rate: u32, - audio_channels: u32, - ffmpeg_path: String, - loopback_script: PathBuf, log_root: PathBuf, interval_seconds: Option, move_id: String, @@ -215,69 +138,21 @@ struct Options { hid_controller_rudp_target: Option, hid_controller_rudp_bind: Option, hid_controller_rudp_advertise: Option, - command_rudp_advertise: Option, hid_controller_receipt_retention_seconds: u64, } -#[derive(Clone, Debug, PartialEq, Eq)] -struct CatalogSource { - id: String, - label: String, -} - #[derive(Clone, Debug, PartialEq, Eq)] struct MoveMarkerCameraSource { camera_id: String, device_path: PathBuf, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum AudioSourceKind { - Loopback, - Input, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct AudioSourceSpec { - kind: AudioSourceKind, - device: String, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -enum MediaTransport { - Rudp, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct MuninnRudpMediaProfile { - profile_id: &'static str, - video_codec: &'static str, - video_encoder: &'static str, - video_preset: &'static str, - video_tune: &'static str, - video_bitrate_kbps: u32, - media_packet_bytes: usize, - max_fragment_bytes: usize, - video_b_frames: u8, - video_rc_lookahead: u8, - sender_resend_delay_ms: u64, - receiver_gap_wait_ms: u64, -} - #[derive(Clone, Debug, PartialEq, Eq)] struct MoveStateSource { move_id: String, hidraw_path: String, } -#[derive(Clone, Debug, PartialEq, Eq)] -struct MuxPlan { - command_line: String, - command_script: String, - command_file: PathBuf, - targets: Vec, -} - struct ActiveMoveLightCommand { command: MuninnMoveLightCommandRecord, colors: Vec<(u8, u8, u8)>, @@ -286,13 +161,6 @@ struct ActiveMoveLightCommand { next_write_at: Instant, } -struct ActiveCaptureStreamCommand { - command_id: String, - stream_id: String, - command: MuninnCaptureStreamCommandRecord, - child: Child, -} - struct ActiveMoveStateSource { source: MoveStateSource, sequence: u64, @@ -359,14 +227,10 @@ fn main() -> Result<()> { let options = Options::parse(env::args().skip(1))?; match options.mode { Mode::Serve => serve(options), - Mode::Activate => activate(options), Mode::Health => health_check(&options), - Mode::RequestStream => request_capture_stream(options), Mode::RequestMoveLight => request_move_light(options), Mode::SetMoveHueProgram => set_move_hue_program(options), Mode::MoveHueProgramStatus => move_hue_program_status(options), - Mode::CaptureStreamStatus => capture_stream_status(options), - Mode::ObsCatalogStatus => obs_catalog_status(options), Mode::MoveLightStatus => move_light_status(options), Mode::MoveIdentityStatus => move_identity_status(options), Mode::MoveSourceStatus => move_source_status(options), @@ -374,11 +238,6 @@ fn main() -> Result<()> { Mode::ClaimMoveHost => claim_move_host(options), Mode::QuestAccessStatus => quest_access_status(options), Mode::MoveTrackerWorker => run_move_tracker_worker(options), - Mode::DryRun => { - let plan = build_mux_plan(&options, "dry-run".to_string()); - println!("{}", plan.command_line); - Ok(()) - } } } @@ -397,7 +256,6 @@ fn serve(options: Options) -> Result<()> { start_idunn_presence_worker(&options); let mut active_move_marker_cameras = active_move_marker_camera_sources(&options, Arc::clone(&move_hue_program)); - let mut active_capture_streams = Vec::new(); let move_evidence_rudp_sender = start_hid_controller_rudp_ingress( &options, move_evidence_stream @@ -430,81 +288,58 @@ fn serve(options: Options) -> Result<()> { ); } start_move_hue_program_sync_worker(&options, Arc::clone(&move_hue_program)); - start_odin_provider_lease_worker(&options); - let mut answered_requests: HashMap = HashMap::new(); loop { let live_move_sources = serve_move_state_sources(&options, move_runtime_enabled); sync_active_move_state_sources(&mut active_move_states, live_move_sources.clone()); // One failed tick is a failed tick, not the end of the daemon. Store // writes race other processes on Windows and Odin is sometimes away; - // serve is the body that must outlive both. It died on the first - // "failed to atomically replace" on 2026-09-11 and left its activation - // child streaming with nobody answering requests. + // serve is the body that must outlive both. let tick: Result<()> = (|| { - sync_media_stream_requests(&options, &mut answered_requests); - let active_stream_ids = - tick_capture_stream_commands(&options, &mut active_capture_streams)?; - answer_media_stream_requests(&options, &mut answered_requests); - { - let mut node = open_node(&options, "muninn-daemon")?; - reconcile_move_identity_records( - &mut node, - &options, - &live_move_sources, - &active_move_states, - )?; - register_move_light_commands(&mut node, &options, &mut active_move_lights)?; - update_suppressed_default_move_light_paths( - &suppressed_default_move_light_paths, - &active_move_lights, - ); - tick_move_light_commands( - &mut node, - &mut active_move_lights, - &mut HidMoveLightWriter, - )?; - update_suppressed_default_move_light_paths( - &suppressed_default_move_light_paths, - &active_move_lights, - ); - publish_move_controller_states( - &mut node, - &options, - &mut active_move_states, - &mut HidMoveControllerStateReader, - None, - hid_controller_stream.as_mut(), - )?; - let controller_states: Vec = active_move_states - .iter() - .filter_map(|state| state.latest_move_record.clone()) - .collect(); - if let Ok(mut latest) = latest_move_controller_states.lock() { - *latest = controller_states; - } - publish_move_tracker_health(&mut node, &mut active_move_marker_cameras)?; - publish_move_evidence_transport_health( - &mut node, - &options, - move_evidence_transport_health.as_ref(), - )?; - publish_quest_access_if_requested(&mut node, &options)?; - let state = if active_stream_ids.is_empty() { - "idle" - } else { - "streaming" - }; - publish_surface(&mut node, &options, state, &active_stream_ids)?; - publish_runtime_boundary_records( - &mut node, - &options, - state, - &active_stream_ids, - &live_move_sources, - )?; - publish_obs_catalog_idle(&mut node, &options)?; + let mut node = open_node(&options, "muninn-daemon")?; + reconcile_move_identity_records( + &mut node, + &options, + &live_move_sources, + &active_move_states, + )?; + register_move_light_commands(&mut node, &options, &mut active_move_lights)?; + update_suppressed_default_move_light_paths( + &suppressed_default_move_light_paths, + &active_move_lights, + ); + tick_move_light_commands( + &mut node, + &mut active_move_lights, + &mut HidMoveLightWriter, + )?; + update_suppressed_default_move_light_paths( + &suppressed_default_move_light_paths, + &active_move_lights, + ); + publish_move_controller_states( + &mut node, + &options, + &mut active_move_states, + &mut HidMoveControllerStateReader, + None, + hid_controller_stream.as_mut(), + )?; + let controller_states: Vec = active_move_states + .iter() + .filter_map(|state| state.latest_move_record.clone()) + .collect(); + if let Ok(mut latest) = latest_move_controller_states.lock() { + *latest = controller_states; } + publish_move_tracker_health(&mut node, &mut active_move_marker_cameras)?; + publish_move_evidence_transport_health( + &mut node, + &options, + move_evidence_transport_health.as_ref(), + )?; + publish_quest_access_if_requested(&mut node, &options)?; + publish_surface(&mut node, &options, "idle", &[])?; Ok(()) })(); if let Err(error) = tick { @@ -520,7 +355,6 @@ fn serve(options: Options) -> Result<()> { && active_move_lights.is_empty() && active_move_states.is_empty() && active_move_marker_cameras.is_empty() - && active_capture_streams.is_empty() && !has_platform_default_move_lights { return Ok(()); @@ -528,7 +362,6 @@ fn serve(options: Options) -> Result<()> { let sleep = if !active_move_lights.is_empty() || !active_move_states.is_empty() || !active_move_marker_cameras.is_empty() - || !active_capture_streams.is_empty() || has_platform_default_move_lights { Duration::from_millis(250) @@ -577,7 +410,7 @@ fn start_idunn_presence_worker(options: &Options) { .as_millis() .try_into()?; let record = authority.presence(state, &detail, observed_at)?; - let node = activation_node(&options, "muninn-idunn-presence")?; + let node = open_node(&options, "muninn-idunn-presence")?; node.publish_document_to_rudp_catalog( record.target.clone(), &record, @@ -675,430 +508,24 @@ fn start_move_hue_program_sync_worker( runtime_program: Arc>, ) { let options = options.clone(); - let mut activation_options = options.clone(); - activation_options.store_path = options - .activation_store_path - .as_ref() - .cloned() - .unwrap_or_else(|| options.store_path.clone()); thread::spawn(move || { loop { let key = move_hue_program_key(&options.host_id); - let main_program = open_node(&options, "muninn-move-hue-program-sync") + let program = open_node(&options, "muninn-move-hue-program-sync") .ok() - .and_then(|node| node.get::(&key).ok().flatten()); - let activation_program = open_node( - &activation_options, - "muninn-move-hue-program-activation-sync", - ) - .ok() - .and_then(|node| node.get::(&key).ok().flatten()); - let program = [main_program, activation_program] - .into_iter() - .flatten() - .filter(|program| validate_move_hue_program(program).is_ok()) - .max_by_key(|program| unix_timestamp_sort_key(&program.updated_at)); + .and_then(|node| node.get::(&key).ok().flatten()) + .filter(|program| validate_move_hue_program(program).is_ok()); if let Some(program) = program && let Ok(mut current) = runtime_program.lock() && *current != program { - *current = program.clone(); - if let Ok(mut node) = open_node(&options, "muninn-move-hue-program-projection") { - let _ = node.put(&key, &program); - } + *current = program; } thread::sleep(Duration::from_millis(250)); } }); } -const MUNINN_VIDEO_CODECS: [&str; 1] = ["h264"]; -const MUNINN_AUDIO_CODECS: [&str; 1] = ["pcm-f32le-interleaved"]; - -fn activation_node(options: &Options, runtime_id: &str) -> Result { - let mut activation_options = options.clone(); - activation_options.store_path = options - .activation_store_path - .as_ref() - .cloned() - .unwrap_or_else(|| options.store_path.clone()); - open_node(&activation_options, runtime_id) -} - -/// The producer-agnostic request as a Muninn command, or why it cannot be one. -fn command_from_media_stream_request( - options: &Options, - request: &GameCultMediaStreamRequestRecord, -) -> Result { - validate_media_stream_request(request)?; - if !request.video_source_id.is_empty() - && !MUNINN_VIDEO_CODECS.contains(&request.video_codec.as_str()) - { - return Err(anyhow!( - "this producer encodes video as {:?}, not {:?}", - MUNINN_VIDEO_CODECS, - request.video_codec - )); - } - if !request.audio_source_id.is_empty() - && !MUNINN_AUDIO_CODECS.contains(&request.audio_codec.as_str()) - { - return Err(anyhow!( - "this producer emits audio as {:?}, not {:?}", - MUNINN_AUDIO_CODECS, - request.audio_codec - )); - } - Ok(MuninnCaptureStreamCommandRecord { - command_id: request.request_id.clone(), - host_id: options.host_id.clone(), - stream_id: request.stream_id.clone(), - state: "pending".to_string(), - action: request.action.clone(), - // The receiver dials Muninn; the command names nowhere to send. - target_host: String::new(), - port: 0, - obs_target_host: None, - obs_port: 0, - media_transport: "rudp".to_string(), - media_packet_bytes: if request.media_packet_bytes == 0 { - options.media_packet_bytes as u32 - } else { - request.media_packet_bytes - }, - requested_by: request.receiver_id.clone(), - detail: format!("media stream request {}", request.request_id), - // Muninn's own clock, in Muninn's own format. The command engine orders - // commands by comparing these strings; a consumer's RFC 3339 stamp sorts - // below every `unix-` stamp and would lose to any command ever stored. - updated_at: timestamp()?, - rudp_video_bitrate_kbps: request.video_bitrate_kbps, - rudp_latency_budget_ms: request.latency_budget_ms, - video_source_id: if request.video_source_id.is_empty() { - MUNINN_DISABLED_VIDEO_SOURCE_ID.to_string() - } else { - request.video_source_id.clone() - }, - audio_source_id: if request.audio_source_id.is_empty() { - MUNINN_DISABLED_AUDIO_SOURCE_ID.to_string() - } else { - request.audio_source_id.clone() - }, - }) -} - -/// Pulls `gamecult.media_stream_request` documents addressed to this host -/// from Odin and turns each new one into a capture command the existing -/// tick already knows how to run. A request that asks for a codec this -/// producer cannot encode is answered `failed` without becoming a command. -fn sync_media_stream_requests(options: &Options, answered: &mut HashMap) { - let Some(target) = resolve_odin_cultmesh_uri(options) else { - return; - }; - let mut node = match activation_node(options, "muninn-media-stream-requests") { - Ok(node) => node, - Err(error) => { - eprintln!( - "Muninn could not open the activation store for media stream requests: {error:#}" - ); - return; - } - }; - if let Err(error) = node.pull_rudp_catalog_snapshot(CultMeshRudpSnapshotOptions { - target, - runtime_id: format!("muninn-{}-media-stream-requests", options.host_id), - schema_ids: Some(vec![GAMECULT_MEDIA_STREAM_REQUEST_SCHEMA.to_string()]), - connect_timeout: Duration::from_millis(2000), - response_timeout: Duration::from_millis(5000), - resend_delay_ms: 15, - ..CultMeshRudpSnapshotOptions::default() - }) { - eprintln!("Muninn could not pull media stream requests from Odin: {error:#}"); - return; - } - let requests = match node.cache().get_all::() { - Ok(requests) => requests, - Err(error) => { - eprintln!("Muninn could not read media stream requests: {error:#}"); - return; - } - }; - for request in requests { - if request.producer_id != options.host_id || request.state != "pending" { - continue; - } - if answered.contains_key(&request.request_id) { - continue; - } - if let Ok(Some(_)) = node.get::(&request.request_id) { - continue; - } - let command = match command_from_media_stream_request(options, &request) { - Ok(command) => command, - Err(error) => { - answer_media_stream_request( - options, - target, - &request, - "failed", - &format!("{error:#}"), - answered, - ); - continue; - } - }; - if let Err(error) = node.put(&command.command_id, &command) { - eprintln!( - "Muninn could not record media stream request {} as a command: {error:#}", - request.request_id - ); - } - } -} - -/// Writes each request-derived command's outcome back onto the request it -/// came from, so the consumer watches one document. -fn answer_media_stream_requests( - options: &Options, - answered: &mut HashMap, -) { - let Some(target) = resolve_odin_cultmesh_uri(options) else { - return; - }; - let Ok(node) = activation_node(options, "muninn-media-stream-answers") else { - return; - }; - let Ok(requests) = node.cache().get_all::() else { - return; - }; - for request in requests { - if request.producer_id != options.host_id { - continue; - } - let Ok(Some(command)) = node.get::(&request.request_id) - else { - continue; - }; - let state = match command.state.as_str() { - "pending" => "pending", - "running" => "running", - "completed" | "superseded" => "stopped", - _ => "failed", - }; - answer_media_stream_request(options, target, &request, state, &command.detail, answered); - } -} - -fn answer_media_stream_request( - options: &Options, - target: SocketAddr, - request: &GameCultMediaStreamRequestRecord, - state: &str, - detail: &str, - answered: &mut HashMap, -) { - let already = answered.get(&request.request_id); - if already.is_some_and(|(previous_state, previous_detail)| { - previous_state == state && previous_detail == detail - }) { - return; - } - let Ok(updated_at) = timestamp() else { - return; - }; - let answer = GameCultMediaStreamRequestRecord { - state: state.to_string(), - detail: detail.to_string(), - updated_at, - ..request.clone() - }; - let Ok(node) = activation_node(options, "muninn-media-stream-answers") else { - return; - }; - match node.publish_document_to_rudp_catalog( - media_stream_request_key(&request.stream_id, &request.receiver_id), - &answer, - CultMeshRudpDocumentPublishOptions { - target, - runtime_id: muninn_daemon_id(options), - source_role: Some("media-stream-producer".to_string()), - tags: vec!["gamecult.media-stream-request".to_string()], - ..CultMeshRudpDocumentPublishOptions::default() - }, - ) { - Ok(()) => { - answered.insert( - request.request_id.clone(), - (state.to_string(), detail.to_string()), - ); - } - Err(error) => eprintln!( - "Muninn could not answer media stream request {}: {error:#}", - request.request_id - ), - } -} - -/// What this host offers, in the producer-agnostic shape a picker is built -/// from. Published beside the Muninn-specific catalog so nothing that reads -/// the old one breaks while consumers move. -fn media_stream_advertisement( - options: &Options, - streaming: bool, -) -> Result { - let video_sources = video_source_catalog(options); - let audio_sources = audio_source_catalog(options); - Ok(GameCultMediaStreamAdvertisementRecord { - stream_id: options.stream_id.clone(), - producer_id: options.host_id.clone(), - label: format!("{} screen and loopback A/V", options.host_id), - state: if streaming { "streaming" } else { "available" }.to_string(), - video_source_ids: video_sources - .iter() - .map(|source| source.id.clone()) - .collect(), - video_source_labels: video_sources - .iter() - .map(|source| source.label.clone()) - .collect(), - audio_source_ids: audio_sources - .iter() - .map(|source| source.id.clone()) - .collect(), - audio_source_labels: audio_sources - .iter() - .map(|source| source.label.clone()) - .collect(), - video_codecs: MUNINN_VIDEO_CODECS - .iter() - .map(|codec| codec.to_string()) - .collect(), - audio_codecs: MUNINN_AUDIO_CODECS - .iter() - .map(|codec| codec.to_string()) - .collect(), - audio_sample_rate: options.audio_sample_rate, - audio_channels: options.audio_channels, - default_video_bitrate_kbps: options.rudp_video_bitrate_kbps, - default_latency_budget_ms: options.rudp_latency_budget_ms, - media_packet_bytes: options.media_packet_bytes as u32, - media_endpoint: advertised_media_endpoint(options)?, - media_connection_id: MUNINN_MEDIA_RUDP_CONNECTION_ID, - updated_at: timestamp()?, - }) -} - -/// Where receivers are told to dial. `--media-rudp-advertise` wins; else the -/// bind address when it names a real interface; else the host the command -/// ingress advertises, on the media port. A `0.0.0.0` bind with nothing to -/// advertise is an error, not a guess: a wrong address here is a stream -/// nobody can reach and no log line saying why. -fn advertised_media_endpoint(options: &Options) -> Result { - if let Some(advertise) = options - .media_rudp_advertise - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - { - return Ok(advertise.to_string()); - } - if !options.media_rudp_bind.ip().is_unspecified() { - return Ok(options.media_rudp_bind.to_string()); - } - if let Some((host, _)) = options - .command_rudp_advertise - .as_deref() - .and_then(|value| value.rsplit_once(':')) - { - return Ok(format!("{host}:{}", options.media_rudp_bind.port())); - } - Err(anyhow!( - "Muninn cannot advertise a media endpoint: --media-rudp-bind {} names no reachable address and --media-rudp-advertise was not given", - options.media_rudp_bind - )) -} - -fn tick_capture_stream_commands( - options: &Options, - active: &mut Vec, -) -> Result> { - reap_capture_stream_children(options, active)?; - let mut activation_options = options.clone(); - activation_options.store_path = options - .activation_store_path - .as_ref() - .cloned() - .unwrap_or_else(|| options.store_path.clone()); - let mut node = open_node(&activation_options, "muninn-activation-controller")?; - let mut commands = node.cache().get_all::()?; - commands.sort_by(|left, right| left.updated_at.cmp(&right.updated_at)); - let latest_command_by_stream = latest_capture_stream_command_ids(&commands, &options.host_id); - for command in commands { - if command.host_id != options.host_id { - continue; - } - let command_stream_key = canonical_muninn_stream_id(&command.stream_id); - if let Some(latest_command_id) = latest_command_by_stream.get(&command_stream_key) { - if latest_command_id != &command.command_id { - supersede_capture_stream_command(&mut node, command, latest_command_id)?; - continue; - } - } - match (command.action.as_str(), command.state.as_str()) { - ("start", "pending") => { - start_capture_stream_command(options, &mut node, active, command)?; - } - ("stop", "pending") => { - stop_capture_stream_command(&mut node, active, command)?; - } - ("start", "running") => { - if !active - .iter() - .any(|session| session.command_id == command.command_id) - { - start_capture_stream_command(options, &mut node, active, command)?; - } - } - _ => {} - } - } - Ok(active - .iter() - .map(|session| session.stream_id.clone()) - .collect()) -} - -fn pull_odin_obs_catalog_snapshot(node: &mut cultmesh_rs::CultMeshNode, options: &Options) { - let Some(target) = resolve_odin_cultmesh_uri(options) else { - return; - }; - if let Err(error) = node.pull_rudp_catalog_snapshot(CultMeshRudpSnapshotOptions { - target, - runtime_id: format!("muninn-{}-obs-catalog-client", options.host_id), - schema_ids: Some(vec![MUNINN_OBS_STREAM_CATALOG_SCHEMA.to_string()]), - connect_timeout: Duration::from_millis(2000), - response_timeout: Duration::from_millis(5000), - resend_delay_ms: 15, - ..CultMeshRudpSnapshotOptions::default() - }) { - eprintln!("Muninn could not pull OBS catalog from Odin: {error:#}"); - } -} - -fn obs_catalog_status(options: Options) -> Result<()> { - ensure_state_dirs(&options)?; - let mut node = open_node(&options, "muninn-obs-catalog-client")?; - pull_odin_obs_catalog_snapshot(&mut node, &options); - let catalogs = node.cache().get_all::()?; - if catalogs.is_empty() { - return Err(anyhow!( - "Odin did not return any {} records for OBS discovery", - MUNINN_OBS_STREAM_CATALOG_SCHEMA - )); - } - Ok(()) -} - fn resolve_odin_cultmesh_uri(options: &Options) -> Option { let uri = options.odin_cultmesh_uri.as_deref()?.trim(); if uri.is_empty() { @@ -1113,484 +540,6 @@ fn resolve_odin_cultmesh_uri(options: &Options) -> Option { } } -fn latest_capture_stream_command_ids( - commands: &[MuninnCaptureStreamCommandRecord], - host_id: &str, -) -> HashMap { - // Every command competes, terminal ones included: a newer command that - // was already handled must still shadow an older pending one. What must - // not happen is a dead command being re-stamped newer than the command - // that killed it; the terminal writers below keep the record's own stamp. - let mut latest_command_by_stream = HashMap::new(); - for command in commands.iter().filter(|command| command.host_id == host_id) { - latest_command_by_stream.insert( - canonical_muninn_stream_id(&command.stream_id), - command.command_id.clone(), - ); - } - latest_command_by_stream -} - -fn latest_capture_stream_command_key(host_id: &str, stream_id: &str) -> String { - format!( - "{}:{}:capture-stream:latest", - host_id, - canonical_muninn_stream_id(stream_id) - ) -} - -fn supersede_capture_stream_command( - node: &mut cultmesh_rs::CultMeshNode, - command: MuninnCaptureStreamCommandRecord, - latest_command_id: &str, -) -> Result<()> { - if capture_stream_command_is_terminal(&command.state) { - return Ok(()); - } - let command_id = command.command_id.clone(); - node.put( - &command_id, - &MuninnCaptureStreamCommandRecord { - state: "completed".to_string(), - detail: format!("Superseded by newer command {latest_command_id}."), - // The stamp is the command's ordinal, not a last-touched time. A - // superseded record re-stamped now would outrank the command that - // superseded it on the next tick and respawn itself (2026-09-10: - // a July start did exactly that to the stop that ended it). - ..command - }, - )?; - Ok(()) -} - -fn capture_stream_command_is_terminal(state: &str) -> bool { - matches!(state, "completed" | "failed") -} - -fn reap_capture_stream_children( - options: &Options, - active: &mut Vec, -) -> Result<()> { - let Some(activation_store_path) = options.activation_store_path.as_ref() else { - return Ok(()); - }; - let mut index = 0; - while index < active.len() { - match active[index].child.try_wait()? { - Some(status) => { - let mut activation_options = options.clone(); - activation_options.store_path = activation_store_path.clone(); - let mut node = open_node(&activation_options, "muninn-activation-controller")?; - if let Some(command) = - node.get::(&active[index].command_id)? - { - let command_id = command.command_id.clone(); - let state = if status.success() { - "completed" - } else { - "failed" - }; - node.put( - &command_id, - &MuninnCaptureStreamCommandRecord { - state: state.to_string(), - detail: format!( - "activation child exited with {status} at {}", - timestamp()? - ), - ..command - }, - )?; - } - active.remove(index); - } - None => index += 1, - } - } - Ok(()) -} - -fn start_capture_stream_command( - options: &Options, - node: &mut cultmesh_rs::CultMeshNode, - active: &mut Vec, - command: MuninnCaptureStreamCommandRecord, -) -> Result<()> { - let command_stream_key = canonical_muninn_stream_id(&command.stream_id); - if let Some(session) = active - .iter_mut() - .find(|session| session.stream_id == command_stream_key) - { - if capture_stream_commands_start_equivalent(&session.command, &command) { - // The same running command comes through here every tick. Writing - // it back with a fresh stamp made a running command the newest - // forever, so no request could ever outrank it: a July start kept - // winning against every request sent tonight until this was cut. - if session.command_id == command.command_id && command.state == "running" { - return Ok(()); - } - eprintln!( - "Muninn serve kept existing capture stream {} for command {} bitrate_kbps={} latency_budget_ms={}.", - command.stream_id, - command.command_id, - command_rudp_video_bitrate_kbps(&command), - command_rudp_latency_budget_ms(&command) - ); - let running = MuninnCaptureStreamCommandRecord { - state: "running".to_string(), - detail: format!( - "Muninn serve kept existing activation child from command {}.", - session.command_id - ), - ..command.clone() - }; - node.put(&running.command_id, &running)?; - session.command_id = running.command_id.clone(); - session.command = running; - return Ok(()); - } - } - - for session in active.iter_mut() { - if session.stream_id == command_stream_key { - terminate_child_tree(&mut session.child); - let _ = session.child.wait(); - } - } - active.retain(|session| session.stream_id != command_stream_key); - - eprintln!( - "Muninn serve spawning capture stream {} bitrate_kbps={} latency_budget_ms={}.", - command.stream_id, - command_rudp_video_bitrate_kbps(&command), - command_rudp_latency_budget_ms(&command) - ); - let child = spawn_capture_stream_activation(options, &command)?; - // State changes; the stamp is the command's ordinal and stays. - let running = MuninnCaptureStreamCommandRecord { - state: "running".to_string(), - detail: "Muninn serve spawned the local activation child.".to_string(), - ..command.clone() - }; - node.put(&running.command_id, &running)?; - active.push(ActiveCaptureStreamCommand { - command_id: command.command_id.clone(), - stream_id: command_stream_key, - command, - child, - }); - Ok(()) -} - -fn capture_stream_commands_start_equivalent( - active: &MuninnCaptureStreamCommandRecord, - command: &MuninnCaptureStreamCommandRecord, -) -> bool { - active.host_id == command.host_id - && canonical_muninn_stream_id(&active.stream_id) - == canonical_muninn_stream_id(&command.stream_id) - && active.action == "start" - && command.action == "start" - && active.target_host == command.target_host - && active.port == command.port - && active.media_transport == command.media_transport - && active.media_packet_bytes == command.media_packet_bytes - && command_rudp_video_bitrate_kbps(active) == command_rudp_video_bitrate_kbps(command) - && command_rudp_latency_budget_ms(active) == command_rudp_latency_budget_ms(command) - && command_video_source_id(active) == command_video_source_id(command) - && command_audio_source_id(active) == command_audio_source_id(command) -} - -fn command_rudp_video_bitrate_kbps(command: &MuninnCaptureStreamCommandRecord) -> u32 { - if command.rudp_video_bitrate_kbps == 0 { - MUNINN_RUDP_MEDIA_VIDEO_BITRATE_KBPS - } else { - command.rudp_video_bitrate_kbps - } -} - -fn command_rudp_latency_budget_ms(command: &MuninnCaptureStreamCommandRecord) -> u32 { - if command.rudp_latency_budget_ms == 0 { - MUNINN_RUDP_MEDIA_DEFAULT_LATENCY_BUDGET_MS as u32 - } else { - clamp_latency_budget_ms(command.rudp_latency_budget_ms) - } -} - -fn canonical_muninn_stream_id(stream_id: &str) -> String { - for suffix in [".rudp"] { - if let Some(prefix) = stream_id.strip_suffix(suffix) { - return prefix.to_string(); - } - } - if let Some((prefix, suffix)) = stream_id.rsplit_once(':') { - if !suffix.is_empty() && suffix.chars().all(|ch| ch.is_ascii_digit()) { - return prefix.to_string(); - } - } - stream_id.to_string() -} - -fn command_video_source_id(command: &MuninnCaptureStreamCommandRecord) -> &str { - if command.video_source_id.is_empty() { - "display:0" - } else { - command.video_source_id.as_str() - } -} - -fn command_audio_source_id(command: &MuninnCaptureStreamCommandRecord) -> &str { - if command.audio_source_id.is_empty() { - "wasapi-loopback:Realtek" - } else { - command.audio_source_id.as_str() - } -} - -fn command_requests_video(command: &MuninnCaptureStreamCommandRecord) -> bool { - command_video_source_id(command) != MUNINN_DISABLED_VIDEO_SOURCE_ID -} - -fn command_requests_audio(command: &MuninnCaptureStreamCommandRecord) -> bool { - command_audio_source_id(command) != MUNINN_DISABLED_AUDIO_SOURCE_ID -} - -fn stop_capture_stream_command( - node: &mut cultmesh_rs::CultMeshNode, - active: &mut Vec, - command: MuninnCaptureStreamCommandRecord, -) -> Result<()> { - let mut stopped = false; - let command_stream_key = canonical_muninn_stream_id(&command.stream_id); - let mut index = 0; - while index < active.len() { - if active[index].stream_id == command_stream_key { - terminate_child_tree(&mut active[index].child); - let _ = active[index].child.wait(); - active.remove(index); - stopped = true; - } else { - index += 1; - } - } - let command_id = command.command_id.clone(); - node.put( - &command_id, - &MuninnCaptureStreamCommandRecord { - state: "completed".to_string(), - detail: if stopped { - "Muninn serve stopped the active capture stream.".to_string() - } else { - "No active capture stream matched the stop request.".to_string() - }, - updated_at: timestamp()?, - ..command - }, - )?; - Ok(()) -} - -fn terminate_child_tree(child: &mut Child) { - #[cfg(windows)] - { - let _ = Command::new("taskkill.exe") - .args(["/PID", &child.id().to_string(), "/T", "/F"]) - .status(); - } - #[cfg(not(windows))] - { - let _ = child.kill(); - } -} - -fn spawn_capture_stream_activation( - options: &Options, - command: &MuninnCaptureStreamCommandRecord, -) -> Result { - let exe = env::current_exe().context("resolving current Muninn executable")?; - let activation_stderr = options.log_root.join(format!( - "muninn-activation-{}.err.log", - safe_log_component(&command.command_id) - )); - let mut args = vec![ - "activate".to_string(), - "--store".to_string(), - options.store_path.display().to_string(), - "--host".to_string(), - options.host_id.clone(), - "--stream".to_string(), - command.stream_id.clone(), - "--target-host".to_string(), - command.target_host.clone(), - "--port".to_string(), - command.port.to_string(), - "--media-transport".to_string(), - command.media_transport.clone(), - "--media-packet-bytes".to_string(), - command.media_packet_bytes.to_string(), - "--rudp-video-bitrate-kbps".to_string(), - command_rudp_video_bitrate_kbps(command).to_string(), - "--rudp-latency-budget-ms".to_string(), - command_rudp_latency_budget_ms(command).to_string(), - ]; - if command_requests_video(command) { - let output_index = video_source_output_index(command_video_source_id(command)) - .unwrap_or(options.ddagrab_output_index); - args.extend([ - "--ddagrab-output-index".to_string(), - output_index.to_string(), - ]); - } else { - args.push("--no-video".to_string()); - } - if command_requests_audio(command) { - args.extend([ - "--audio-source-id".to_string(), - command_audio_source_id(command).to_string(), - ]); - } else { - args.push("--no-audio".to_string()); - } - args.extend([ - "--media-rudp-bind".to_string(), - options.media_rudp_bind.to_string(), - ]); - args.extend([ - "--audio-sample-rate".to_string(), - options.audio_sample_rate.to_string(), - "--audio-channels".to_string(), - options.audio_channels.to_string(), - "--ffmpeg".to_string(), - options.ffmpeg_path.clone(), - "--loopback-script".to_string(), - options.loopback_script.display().to_string(), - "--log-root".to_string(), - options.log_root.display().to_string(), - ]); - Command::new(exe) - .args(args) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(fs::File::create(&activation_stderr).with_context(|| { - format!( - "creating activation stderr log {}", - activation_stderr.display() - ) - })?) - .spawn() - .context("spawning daemon-owned Muninn capture activation child") -} - -fn video_source_id_for_options(options: &Options) -> String { - if options.capture_video { - format!("display:{}", options.ddagrab_output_index) - } else { - MUNINN_DISABLED_VIDEO_SOURCE_ID.to_string() - } -} - -fn video_source_label_for_options(options: &Options) -> String { - format!( - "{} display {}", - options.host_id, - options.ddagrab_output_index + 1 - ) -} - -fn audio_source_id_for_options(options: &Options) -> String { - if options.capture_audio { - if let Some(source_id) = options.audio_source_id_override.as_ref() { - if parse_audio_source_spec(source_id).is_some() { - return source_id.clone(); - } - } - format!("wasapi-loopback:{}", options.audio_device) - } else { - MUNINN_DISABLED_AUDIO_SOURCE_ID.to_string() - } -} - -fn audio_source_label_for_options(options: &Options) -> String { - let spec = audio_source_spec_for_options(options); - match spec.kind { - AudioSourceKind::Loopback => { - format!("{} loopback ({})", options.host_id, spec.device) - } - AudioSourceKind::Input => format!("{} input ({})", options.host_id, spec.device), - } -} - -fn video_source_catalog(options: &Options) -> Vec { - if options.video_sources.is_empty() { - vec![CatalogSource { - id: video_source_id_for_options(options), - label: video_source_label_for_options(options), - }] - } else { - options.video_sources.clone() - } -} - -fn audio_source_catalog(options: &Options) -> Vec { - if options.audio_sources.is_empty() { - vec![CatalogSource { - id: audio_source_id_for_options(options), - label: audio_source_label_for_options(options), - }] - } else { - options.audio_sources.clone() - } -} - -fn video_source_output_index(source_id: &str) -> Option { - source_id - .strip_prefix("display:") - .and_then(|value| value.parse::().ok()) -} - -fn parse_audio_source_spec(source_id: &str) -> Option { - let (kind, device) = if let Some(value) = source_id.strip_prefix("wasapi-loopback:") { - (AudioSourceKind::Loopback, value) - } else if let Some(value) = source_id.strip_prefix("wasapi-input:") { - (AudioSourceKind::Input, value) - } else { - return None; - }; - let device = device.trim(); - if device.is_empty() { - return None; - } - Some(AudioSourceSpec { - kind, - device: device.to_string(), - }) -} - -fn audio_source_spec_for_options(options: &Options) -> AudioSourceSpec { - if let Some(source_id) = options.audio_source_id_override.as_ref() { - if let Some(spec) = parse_audio_source_spec(source_id) { - return spec; - } - } - AudioSourceSpec { - kind: AudioSourceKind::Loopback, - device: options.audio_device.clone(), - } -} - -fn safe_log_component(value: &str) -> String { - value - .chars() - .map(|ch| { - if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | '_') { - ch - } else { - '_' - } - }) - .collect() -} - fn active_move_state_sources(sources: Vec) -> Vec { sources.into_iter().map(active_move_state_source).collect() } @@ -1963,943 +912,54 @@ struct MoveEvidenceTransportCounters { remote_sends: AtomicU64, } -fn activate(options: Options) -> Result<()> { - activate_rudp(options) -} - -/// A real-time media producer on a host that is also running a game. At -/// normal priority the mux loop is starved whenever the game wants the CPU: -/// measured 2026-09-11 on Raven at 93% total load, video backed up 1.5 s and -/// expired wholesale. High is what OBS offers for the same reason. -/// -/// Windows hands a priority class down to a child only when it is *below* -/// normal, so the capture and encoder children are raised explicitly at -/// spawn (`media_child_priority`). Found the hard way on a live stream: the -/// mux child was above-normal, its encoder was at normal on a host at 99.8% -/// CPU, and 790 chunks per 10 s went missing with a one-second backlog; -/// raising the encoder in place took that to 116 and 60. -#[cfg(windows)] -fn raise_media_process_priority() { - use windows_sys::Win32::System::Threading::{ - GetCurrentProcess, HIGH_PRIORITY_CLASS, SetPriorityClass, - }; - // SAFETY: the current process handle is always valid; SetPriorityClass - // has no memory-safety preconditions. - let raised = unsafe { SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS) }; - if raised == 0 { - eprintln!("Muninn could not raise the media process priority; continuing at normal."); - } -} - -#[cfg(not(windows))] -fn raise_media_process_priority() {} - -/// The priority class a capture or encoder child is spawned with. The video -/// encoder shares the mux loop's class; the audio pipeline runs one below so -/// a PCM pump cannot starve the frames. -#[derive(Clone, Copy)] -enum MediaChildPriority { - Video, - Audio, -} - -#[cfg(windows)] -fn media_child_priority(command: &mut Command, priority: MediaChildPriority) -> &mut Command { - use std::os::windows::process::CommandExt; - use windows_sys::Win32::System::Threading::{ABOVE_NORMAL_PRIORITY_CLASS, HIGH_PRIORITY_CLASS}; - command.creation_flags(match priority { - MediaChildPriority::Video => HIGH_PRIORITY_CLASS, - MediaChildPriority::Audio => ABOVE_NORMAL_PRIORITY_CLASS, - }) -} - -#[cfg(not(windows))] -fn media_child_priority(command: &mut Command, _priority: MediaChildPriority) -> &mut Command { - command -} - -fn activate_rudp(options: Options) -> Result<()> { - raise_media_process_priority(); - ensure_state_dirs(&options)?; - let mut node = open_node(&options, "muninn-activation")?; - let plan = build_mux_plan(&options, timestamp()?); - write_command_file(&plan)?; - - let supervisor_pid = std::process::id(); - let mut restart_count = 0; - - loop { - publish_surface( - &mut node, - &options, - "active", - std::slice::from_ref(&options.stream_id), - )?; - publish_runtime_boundary_records( - &mut node, - &options, - "active", - std::slice::from_ref(&options.stream_id), - &[], - )?; - - match run_rudp_mux_once(&options, &plan, &mut node, supervisor_pid, restart_count) { - Ok(restart) => { - restart_count += 1; - publish_stream( - &mut node, - &options, - &plan, - "restarting", - supervisor_pid, - None, - restart_count, - &restart.detail, - )?; - thread::sleep(restart.delay); - } - Err(error) => { - restart_count += 1; - publish_stream( - &mut node, - &options, - &plan, - "failed", - supervisor_pid, - None, - restart_count, - &format!("RUDP mux failed: {error:#}"), - )?; - return Err(error); - } - } - } -} - -struct RudpMuxRestart { - detail: String, - delay: Duration, -} - -fn rudp_media_activity_detail(options: &Options) -> String { - match (options.capture_video, options.capture_audio) { - (true, true) => "typed video/audio access units are publishing over CultNet RUDP media", - (true, false) => "typed video access units are publishing over CultNet RUDP media", - (false, true) => "typed audio packets are publishing over CultNet RUDP media", - (false, false) => "Muninn RUDP media is idle", - } - .to_string() -} - -fn republish_running_stream_if_due( - node: &mut cultmesh_rs::CultMeshNode, - options: &Options, - plan: &MuxPlan, - supervisor_pid: u32, - mux_pid: u32, - restart_count: u32, - last_stream_publish_at: &mut Instant, -) -> Result<()> { - if last_stream_publish_at.elapsed() - < Duration::from_millis(MUNINN_RUDP_ACTIVE_CATALOG_REPUBLISH_MS) - { - return Ok(()); - } - publish_stream( - node, - options, - plan, - "running", - supervisor_pid, - Some(mux_pid), - restart_count, - &rudp_media_activity_detail(options), - )?; - *last_stream_publish_at = Instant::now(); - Ok(()) -} - -fn run_rudp_mux_once( - options: &Options, - plan: &MuxPlan, - node: &mut cultmesh_rs::CultMeshNode, - supervisor_pid: u32, - restart_count: u32, -) -> Result { - let timestamp = timestamp()?; - let loopback_stderr = options - .log_root - .join(format!("muninn-{timestamp}.loopback.err.log")); - let video_ffmpeg_stderr = options - .log_root - .join(format!("muninn-{timestamp}.ffmpeg-video.err.log")); - let audio_ffmpeg_stderr = options - .log_root - .join(format!("muninn-{timestamp}.ffmpeg-audio.err.log")); - - let mut loopback = if options.capture_audio { - Some( - media_child_priority( - &mut Command::new("powershell.exe"), - MediaChildPriority::Audio, - ) - .args(loopback_args(options)) - .stdout(Stdio::piped()) - .stderr(fs::File::create(&loopback_stderr)?) - .spawn() - .with_context(|| { - format!( - "starting loopback capture {}", - options.loopback_script.display() - ) - })?, - ) - } else { - None - }; - let loopback_stdout = if let Some(process) = loopback.as_mut() { - Some( - process - .stdout - .take() - .context("loopback stdout was not piped")?, - ) - } else { - None - }; - - let mut video_ffmpeg = if options.capture_video { - Some( - media_child_priority( - &mut Command::new(&options.ffmpeg_path), - MediaChildPriority::Video, - ) - .args(rudp_video_ffmpeg_args(options)) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(fs::File::create(&video_ffmpeg_stderr)?) - .spawn() - .with_context(|| format!("starting {} video encoder", options.ffmpeg_path))?, - ) - } else { - None - }; - let video_ffmpeg_stdout = if let Some(process) = video_ffmpeg.as_mut() { - Some( - process - .stdout - .take() - .context("video ffmpeg stdout was not piped")?, - ) - } else { - None - }; - let mut audio_ffmpeg = if options.capture_audio { - Some( - media_child_priority( - &mut Command::new(&options.ffmpeg_path), - MediaChildPriority::Audio, - ) - .args(rudp_audio_ffmpeg_args(options)) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(fs::File::create(&audio_ffmpeg_stderr)?) - .spawn() - .with_context(|| format!("starting {} audio encoder", options.ffmpeg_path))?, - ) - } else { - None - }; - let audio_ffmpeg_stdout = if let Some(process) = audio_ffmpeg.as_mut() { - Some( - process - .stdout - .take() - .context("audio ffmpeg stdout was not piped")?, - ) - } else { - None - }; - let audio_pump = match (loopback_stdout, audio_ffmpeg.as_mut()) { - (Some(mut reader), Some(process)) => { - let mut audio_ffmpeg_stdin = process - .stdin - .take() - .context("audio ffmpeg stdin was not piped")?; - Some(thread::spawn(move || -> Result<()> { - std::io::copy(&mut reader, &mut audio_ffmpeg_stdin)?; - Ok(()) - })) - } - _ => None, - }; - - let mut video_sender = None; - let mut audio_sender = None; - let result = (|| -> Result { - let media_profile = muninn_rudp_media_profile_for_options(options); - let policy = MediaSendPolicy::from_request(options.rudp_latency_budget_ms); - let hub = open_media_rudp_hub(options, &media_profile, &policy)?; - publish_stream( - node, - options, - plan, - "running", - supervisor_pid, - video_ffmpeg - .as_ref() - .map(Child::id) - .or_else(|| audio_ffmpeg.as_ref().map(Child::id)), - restart_count, - &rudp_media_activity_detail(options), - )?; - let mut last_stream_publish_at = Instant::now(); - - let (intake_tx, intake_rx) = media_intake_channel(); - video_sender = if let Some(stdout) = video_ffmpeg_stdout { - Some(spawn_video_group_reader( - intake_tx.clone(), - stdout, - VideoAnnexBStreamSendConfig { - stream_id: options.stream_id.clone(), - session_id: format!("{}:{timestamp}:video", options.host_id), - codec: media_profile.video_codec.to_string(), - first_frame_id: 0, - first_pts_ticks: 0, - frame_duration_ticks: video_frame_duration_ticks(options)?, - timebase_num: 1, - timebase_den: 90_000, - deadline_delay_ticks: policy.video_deadline_delay_ticks(), - max_payload_bytes: options.media_packet_bytes.max(256), - max_pending_bytes: options.media_packet_bytes.max(256) * 4096, - source_runtime_id: options.host_id.clone(), - source_role: "muninn.rudp.video".to_string(), - }, - policy.clone(), - )) - } else { - None - }; - audio_sender = if let Some(stdout) = audio_ffmpeg_stdout { - Some(spawn_audio_group_reader( - intake_tx.clone(), - stdout, - AudioPcmStreamSendConfig { - stream_id: options.stream_id.clone(), - session_id: format!("{}:{timestamp}:audio", options.host_id), - codec: "pcm-f32le-interleaved".to_string(), - first_packet_id: 0, - first_pts_ticks: 0, - packet_duration_ticks: 480, - timebase_num: 1, - timebase_den: options.audio_sample_rate, - deadline_delay_ticks: policy.audio_deadline_delay_ticks(options.audio_sample_rate), - channels: options.audio_channels, - bytes_per_sample: 4, - max_pending_bytes: 480usize - .saturating_mul(options.audio_channels as usize) - .saturating_mul(4) - .saturating_mul(128), - source_runtime_id: options.host_id.clone(), - source_role: "muninn.rudp.audio".to_string(), - }, - policy.clone(), - )) - } else { - None - }; - drop(intake_tx); - - let mut core = MediaSendCore::new(hub, &policy); - loop { - core.intake(&intake_rx, Duration::from_millis(5))?; - if core.send_next(Instant::now())? { - core.service_control(Instant::now())?; - } else if core.finished() { - break Ok(RudpMuxRestart { - detail: format!("encoder stdout ended; {}", core.progress_detail()), - delay: default_rudp_mux_restart_delay(restart_count), - }); - } else { - core.service_control(Instant::now())?; - } - republish_running_stream_if_due( - node, - options, - plan, - supervisor_pid, - video_ffmpeg - .as_ref() - .map(Child::id) - .or_else(|| audio_ffmpeg.as_ref().map(Child::id)) - .unwrap_or(supervisor_pid), - restart_count, - &mut last_stream_publish_at, - )?; - } - })(); - - if let Some(process) = video_ffmpeg.as_mut() { - let _ = process.kill(); - let _ = process.wait(); - } - if let Some(process) = audio_ffmpeg.as_mut() { - let _ = process.kill(); - let _ = process.wait(); - } - if let Some(process) = loopback.as_mut() { - let _ = process.kill(); - let _ = process.wait(); - } - if let Some(pump) = audio_pump { - let _ = pump.join(); - } - if let Some(sender) = video_sender { - let _ = sender.join(); - } - if let Some(sender) = audio_sender { - let _ = sender.join(); - } - result -} - -fn default_rudp_mux_restart_delay(restart_count: u32) -> Duration { - Duration::from_secs((2 + restart_count).min(30) as u64) -} - -/// Muninn listens for receivers here. It used to dial a receiver that had -/// to open a port for it; that put a firewall rule on every viewer's -/// machine. The producer is the host that serves, so the producer listens. -fn open_media_rudp_hub( - options: &Options, - media_profile: &MuninnRudpMediaProfile, - policy: &MediaSendPolicy, -) -> Result { - let socket = UdpSocket::bind(options.media_rudp_bind).with_context(|| { - format!( - "binding Muninn media RUDP listener at {}", - options.media_rudp_bind - ) - })?; - configure_media_rudp_socket_buffers(&socket) - .context("configuring Muninn media RUDP socket buffers")?; - socket - .set_nonblocking(true) - .context("setting Muninn media RUDP listener nonblocking")?; - let hub = CultNetRudpServerHub::new(muninn_media_rudp_hub_options( - socket, - media_profile, - policy, - ))?; - eprintln!( - "Muninn media RUDP listening at {} for receivers dialling connection {:#x}.", - hub.local_addr()?, - MUNINN_MEDIA_RUDP_CONNECTION_ID - ); - Ok(hub) -} - -fn configure_media_rudp_socket_buffers(socket: &UdpSocket) -> Result<()> { - let socket = socket2::SockRef::from(socket); - socket - .set_send_buffer_size(MUNINN_RUDP_MEDIA_SOCKET_BUFFER_BYTES) - .context("setting Muninn media RUDP send buffer")?; - socket - .set_recv_buffer_size(MUNINN_RUDP_MEDIA_SOCKET_BUFFER_BYTES) - .context("setting Muninn media RUDP receive buffer")?; - Ok(()) -} - -/// One session per receiver carries both legs: video lossy under parity on -/// the media channel, audio reliable on its own channel and given up on -/// past the request's latency budget. -fn muninn_media_rudp_hub_options( - socket: UdpSocket, - media_profile: &MuninnRudpMediaProfile, - policy: &MediaSendPolicy, -) -> CultNetRudpServerHubOptions { - let mut options = - CultNetRudpServerHubOptions::new("muninn-media", socket, MUNINN_MEDIA_RUDP_CONNECTION_ID); - options.resend_delay_ms = media_profile.sender_resend_delay_ms; - options.max_fragment_bytes = Some(media_profile.max_fragment_bytes as u32); - options.media_delivery = Some(cultnet_rs::CultNetTransportDelivery::Unreliable); - options.media_reliable_expire_after_ms = Some(policy.latency_budget_ms()); - options -} - -fn video_frame_duration_ticks(options: &Options) -> Result { - if options.framerate == 0 { - return Err(anyhow!("framerate must be greater than zero")); - } - Ok((90_000_u32 / options.framerate).max(1)) -} - fn publish_surface( node: &mut cultmesh_rs::CultMeshNode, options: &Options, state: &str, active_streams: &[String], ) -> Result<()> { - let video_sources = video_source_catalog(options); - let audio_sources = audio_source_catalog(options); let record = MuninnTelemetrySurfaceRecord { surface_id: options.surface_id.clone(), host_id: options.host_id.clone(), state: state.to_string(), available_sources: available_sources(options), stream_affordances: vec![ - "screen.capture.ddagrab".to_string(), - "audio.loopback.wasapi".to_string(), "psmove.light.command".to_string(), "psmove.controller.state".to_string(), "quest.usb.access".to_string(), "quest.input.openxr.witness".to_string(), "quest.video.warp_corrected_input".to_string(), - "audio.input.enumeration.pending".to_string(), - "video.input.enumeration.pending".to_string(), ], active_streams: active_streams.to_vec(), - activation_authority: "muninn.activate.explicit-request".to_string(), - detail: if active_streams.is_empty() { - "Muninn is idle; no capture streams are consuming resources.".to_string() - } else { - "Muninn has explicit active stream requests.".to_string() - }, + activation_authority: "muninn.serve.telemetry".to_string(), + detail: "Muninn telemetry surface is live.".to_string(), updated_at: timestamp()?, - primary_stream_id: options.stream_id.clone(), - primary_stream_label: format!("{} screen and loopback A/V", options.host_id), + primary_stream_id: String::new(), + primary_stream_label: String::new(), command_rudp_target: String::new(), - media_target_host: options.target_host.clone(), - media_port: options.port, - media_packet_bytes: options.media_packet_bytes as u32, - rudp_video_bitrate_kbps: options.rudp_video_bitrate_kbps, - rudp_latency_budget_ms: options.rudp_latency_budget_ms, - video_source_ids: video_sources - .iter() - .map(|source| source.id.clone()) - .collect(), - video_source_labels: video_sources - .iter() - .map(|source| source.label.clone()) - .collect(), - audio_source_ids: audio_sources - .iter() - .map(|source| source.id.clone()) - .collect(), - audio_source_labels: audio_sources - .iter() - .map(|source| source.label.clone()) - .collect(), + media_target_host: String::new(), + media_port: 0, + media_packet_bytes: 0, + rudp_video_bitrate_kbps: 0, + rudp_latency_budget_ms: 0, + video_source_ids: Vec::new(), + video_source_labels: Vec::new(), + audio_source_ids: Vec::new(), + audio_source_labels: Vec::new(), }; node.put("latest", &record)?; node.put(&record.surface_id, &record)?; Ok(()) } -fn publish_runtime_boundary_records( - node: &mut cultmesh_rs::CultMeshNode, - options: &Options, - state: &str, - active_streams: &[String], - live_move_sources: &[MoveStateSource], -) -> Result<()> { - let provider_id = muninn_provider_id(options); - let daemon_id = muninn_daemon_id(options); - let updated_at = timestamp()?; - let available_sources = available_sources(options); - let command_boundary_key = format!("command-boundary:{daemon_id}"); - let transport_profile_key = format!("transport-profile:{daemon_id}"); - let store_path = options.store_path.display().to_string(); - let log_root = options.log_root.display().to_string(); - let stream_id = options.stream_id.clone(); - let activation_store_path = options - .activation_store_path - .as_deref() - .unwrap_or(&options.store_path); - let activation_command = if options.target_host.trim().is_empty() { - None - } else { - let command = format!( - "muninn request-stream --store {} --activate-store {} --host {} --stream {} --target-host {} --port {} --media-transport {}", - store_path, - activation_store_path.display(), - options.host_id, - options.stream_id, - options.target_host, - options.port, - media_transport_cli(&options.media_transport) - ); - Some(command) - }; - let command_lowerings = activation_command - .as_ref() - .map(|command| json!([command])) - .unwrap_or_else(|| json!([])); - let current_transport = "daemon-owned-cultcache-telemetry-store"; - let transport_state = "cultcache-provider-store-only"; - let hid_controller_endpoint = options.hid_controller_rudp_bind.map(|bind| { - options - .hid_controller_rudp_advertise - .clone() - .unwrap_or_else(|| bind.to_string()) - }); - let provider_routes = vec![json!({ - "transport": "cultcache-store", - "address": options.store_path.display().to_string() - })]; - let hid_controller_devices_snake = live_move_sources - .iter() - .map(|source| { - json!({ - "device_id": source.move_id, - "device_kind": hid_controller_kind_from_source(source), - "source_path": source.hidraw_path - }) - }) - .collect::>(); - let hid_controller_devices_camel = live_move_sources - .iter() - .map(|source| { - json!({ - "deviceId": source.move_id, - "deviceKind": hid_controller_kind_from_source(source), - "sourcePath": source.hidraw_path - }) - }) - .collect::>(); - let input_stream_id = format!("muninn:{}:hid-controller-state", options.host_id); - let transport_input_streams = hid_controller_endpoint - .as_ref() - .map(|endpoint| { - let mut streams = vec![json!({ - "stream_id": input_stream_id, - "schema": "muninn.hid_controller_state.v1", - "transport": CULTNET_RUDP_PROTOCOL_ID, - "address": endpoint, - "connection_id": MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID, - "channel_id": "latest", - "producer": "Muninn IO daemon", - "devices": hid_controller_devices_snake - })]; - if let Some(stream_id) = options.move_evidence_stream_id.as_ref() { - streams.push(json!({ - "stream_id": stream_id, - "schema": "mimir.muninn_move_evidence_stream_frame.v1", - "transport": CULTNET_RUDP_PROTOCOL_ID, - "address": endpoint, - "connection_id": MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID, - "channel_id": "move-evidence", - "producer": "Muninn Move evidence runtime" - })); - } - json!(streams) - }) - .unwrap_or_else(|| json!([])); - let provider_input_streams = hid_controller_endpoint - .as_ref() - .map(|endpoint| { - let mut streams = vec![json!({ - "streamId": input_stream_id, - "schema": "muninn.hid_controller_state.v1", - "transport": CULTNET_RUDP_PROTOCOL_ID, - "address": endpoint, - "connectionId": MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID, - "channel": "latest", - "devices": hid_controller_devices_camel - })]; - if let Some(stream_id) = options.move_evidence_stream_id.as_ref() { - streams.push(json!({ - "streamId": stream_id, - "schema": "mimir.muninn_move_evidence_stream_frame.v1", - "transport": CULTNET_RUDP_PROTOCOL_ID, - "address": endpoint, - "connectionId": MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID, - "channel": "move-evidence" - })); - } - json!(streams) - }) - .unwrap_or_else(|| json!([])); - let mut provider_endpoints = vec![json!({ - "transport": "cultcache-store", - "address": options.store_path.display().to_string() - })]; - if let Some(endpoint) = hid_controller_endpoint.as_ref() { - provider_endpoints.push(json!({ - "transport": CULTNET_RUDP_PROTOCOL_ID, - "role": "muninn.hid_controller_state", - "schema": "muninn.hid_controller_state.v1", - "address": endpoint, - "connectionId": MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID, - "channel": "latest" - })); - if options.move_evidence_stream_id.is_some() { - provider_endpoints.push(json!({ - "transport": CULTNET_RUDP_PROTOCOL_ID, - "role": "muninn.move_evidence_stream", - "schema": "mimir.muninn_move_evidence_stream_frame.v1", - "address": endpoint, - "connectionId": MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID, - "channel": "move-evidence" - })); - } - } - let media_profile = muninn_rudp_media_profile_for_options(options); - let command_boundary = MuninnCommandBoundaryCompatRecord { - value: json!({ - "schema": "muninn.command_boundary.v1", - "boundary_id": command_boundary_key, - "daemon_id": daemon_id, - "provider_id": provider_id, - "service_id": provider_id, - "host_id": options.host_id, - "owner": "Muninn telemetry runtime", - "updated_at": updated_at, - "state_store": store_path, - "log_root": log_root, - "lifecycle_authority": "idunn-supervisor-command", - "commands": [ - { - "command": "muninn.capture_stream_command", - "ingress": "cultmesh-document", - "schema": "muninn.capture_stream_command.v1", - "invocation": activation_command, - "state": if activation_command.is_some() { "configured" } else { "missing-media-target" }, - "owns": [ - "explicit capture stream activation", - "ffmpeg/loopback process launch", - "active muninn.capture_stream receipts" - ] - }, - { - "command": "muninn.move_light_command", - "ingress": "cultmesh-document", - "schema": "muninn.move_light_command.v1", - "owns": [ - "PS Move light pulses for attached local controllers" - ] - }, - { - "command": "muninn.set-move-hue-program", - "ingress": "cultmesh-document", - "schema": MUNINN_MOVE_HUE_PROGRAM_SCHEMA, - "record_key": move_hue_program_key(&options.host_id), - "owns": [ - "live Move hue mode", - "cycle duration", - "deterministic update order", - "hold timestamp" - ] - } - ], - "forbidden_authority": "Task Scheduler, HTTP probes, OBS consumers, and one-shot health commands do not own Muninn telemetry truth or stream activation state.", - }), - }; - let transport_profile = MuninnTransportProfileCompatRecord { - value: json!({ - "schema": "muninn.transport_profile.v1", - "profile_id": transport_profile_key, - "daemon_id": daemon_id, - "provider_id": provider_id, - "host_id": options.host_id, - "target_transport": CULTNET_RUDP_PROTOCOL_ID, - "current_transport": current_transport, - "state": transport_state, - "health_contract": serde_json::Value::Null, - "provider_advertisement_schema": "gamecult.eve.provider_advertisement.v1", - "command_boundary_schema": "muninn.command_boundary.v1", - "telemetry_surface_schema": "muninn.telemetry_surface.v1", - "media_profile": { - "profile_id": media_profile.profile_id, - "owner": "Muninn capture runtime", - "strategy": "hardware-codec-owned-prediction-over-fixed-budget-rudp", - "visual_prediction_owner": "NVENC H.264 inter-frame prediction", - "transport_owner": "CultNet RUDP media channel", - "codec": media_profile.video_codec, - "encoder": media_profile.video_encoder, - "encoder_preset": media_profile.video_preset, - "encoder_tune": media_profile.video_tune, - "video_bitrate_kbps": media_profile.video_bitrate_kbps, - "video_bitrate": muninn_rudp_video_bitrate_arg(&media_profile), - "video_maxrate": muninn_rudp_video_bitrate_arg(&media_profile), - "video_bufsize": muninn_rudp_video_vbv_buffer_arg(options, &media_profile), - "video_low_delay_key_frame_scale": MUNINN_RUDP_MEDIA_LOW_DELAY_KEY_FRAME_SCALE, - "media_packet_bytes": media_profile.media_packet_bytes, - "max_fragment_bytes": media_profile.max_fragment_bytes, - "video_b_frames": media_profile.video_b_frames, - "video_gop_frames": muninn_rudp_video_gop_frames(options), - "video_rate_control": "cbr", - "video_rc_lookahead": media_profile.video_rc_lookahead, - "sender_resend_delay_ms": media_profile.sender_resend_delay_ms, - "latency_budget_ms": options.rudp_latency_budget_ms, - "receiver_gap_wait_ms": media_profile.receiver_gap_wait_ms, - "late_media_policy": "drop expired queued media; do not repair frames outside the latency budget", - "recovery": "fixed quarter-second IDR budget with receiver feedback pressure telemetry" - }, - "input_streams": transport_input_streams, - "debug_lowerings": [], - "command_lowerings": command_lowerings, - "cut_line": "Muninn's telemetry store owns provider advertisement, command boundary, transport profile, telemetry surface, and daemon health state. Local CLI activation is a command lowering; health is published by the serve process over CultNet/RUDP.", - "updated_at": updated_at, - }), - }; - let provider_advertisement = EveProviderAdvertisementRecord { - value: json!({ - "schema": "gamecult.eve.provider_advertisement.v1", - "providerId": provider_id, - "daemonId": daemon_id, - "title": muninn_provider_title(options), - "description": muninn_provider_description(options), - "canonicalService": "asgard.muninn", - "locatedService": format!("asgard.{}.muninn", options.host_id), - "verseId": format!("{}.local", options.host_id), - "cultMeshAddress": format!("asgard.{}.muninn/telemetry", options.host_id), - "status": "active", - "mode": "daemon-live", - "updatedAt": updated_at, - "stateStore": store_path, - "surfaceId": options.surface_id, - "streamId": stream_id, - "surfaceState": state, - "availableSources": available_sources, - "activeStreams": active_streams, - "capabilities": muninn_capabilities(options), - "endpoints": provider_endpoints, - "inputStreams": provider_input_streams, - "routes": provider_routes, - "commandSurface": { - "commandBoundaryId": command_boundary_key, - "transportProfileId": transport_profile_key - } - }), - }; - node.put(&provider_id, &provider_advertisement)?; - node.put(&command_boundary_key, &command_boundary)?; - node.put(&transport_profile_key, &transport_profile)?; - Ok(()) -} - -fn start_odin_provider_lease_worker(options: &Options) { - if resolve_odin_cultmesh_uri(options).is_none() { - return; - } - - let options = options.clone(); - thread::spawn(move || { - let mut has_published = false; - loop { - let result = open_node(&options, "muninn-odin-provider-lease") - .and_then(|node| publish_odin_provider_lease(&node, &options)); - match result { - Ok(()) => { - has_published = true; - thread::sleep(Duration::from_secs( - MUNINN_ODIN_PROVIDER_LEASE_REFRESH_SECONDS, - )); - } - Err(error) => { - eprintln!("Muninn could not renew its Odin provider lease: {error:#}"); - thread::sleep(if has_published { - Duration::from_secs(MUNINN_ODIN_PROVIDER_LEASE_REFRESH_SECONDS) - } else { - Duration::from_secs(1) - }); - } - } - } - }); -} - -fn publish_odin_provider_lease(node: &cultmesh_rs::CultMeshNode, options: &Options) -> Result<()> { - let Some(target) = resolve_odin_cultmesh_uri(options) else { - return Ok(()); - }; - let provider_id = muninn_provider_id(options); - let provider = node.get_required::(&provider_id)?; - node.publish_document_to_rudp_catalog( - &provider_id, - &provider, - CultMeshRudpDocumentPublishOptions { - target, - runtime_id: muninn_daemon_id(options), - source_role: Some("muninn.telemetry-provider".to_string()), - tags: vec![ - "provider-lease".to_string(), - "odin-verse-discovery".to_string(), - ], - ..CultMeshRudpDocumentPublishOptions::default() - }, - ) -} - -fn muninn_provider_id(options: &Options) -> String { - format!("muninn.telemetry.{}", options.host_id) -} - -fn muninn_daemon_id(options: &Options) -> String { - match options.host_id.as_str() { - "raven" => "muninn".to_string(), - "starfire" => "starfire-muninn".to_string(), - "nightwing" => "nightwing-muninn".to_string(), - _ => format!("muninn-{}", options.host_id), - } -} - -fn muninn_provider_title(options: &Options) -> String { - format!("Muninn {} Telemetry", title_case_host(&options.host_id)) -} - -fn muninn_provider_description(options: &Options) -> String { - let mut detail = format!( - "Muninn telemetry runtime on {} publishing local capture affordances and typed telemetry state.", - title_case_host(&options.host_id) - ); - if options.quest_adb { - detail.push_str(" Quest USB access is enabled on this body."); - } - if !options.move_state_sources.is_empty() { - detail.push_str(" Move HID/controller evidence is enabled on this body."); - } - detail -} - -fn title_case_host(host_id: &str) -> String { - let mut chars = host_id.chars(); - match chars.next() { - Some(first) => first.to_uppercase().collect::() + chars.as_str(), - None => "Unknown".to_string(), - } -} - -fn muninn_capabilities(options: &Options) -> Vec { - let mut capabilities = vec![ - "screen.capture.ddagrab".to_string(), - "audio.loopback.wasapi".to_string(), - "muninn.telemetry_surface".to_string(), - "muninn.capture_stream".to_string(), - "muninn.command_boundary".to_string(), - "muninn.transport_profile".to_string(), - ]; - if options.quest_adb { - capabilities.push("quest.usb.access".to_string()); - } - if !options.move_state_sources.is_empty() { - capabilities.push("psmove.controller.state".to_string()); - capabilities.push("muninn.move_evidence_stream".to_string()); - } - capabilities -} - fn available_sources(options: &Options) -> Vec { - let mut sources = vec![ - format!("screen:ddagrab:output_idx={}", options.ddagrab_output_index), - format!( - "audio-loopback:wasapi:{}:{}ch@{}", - options.audio_device, options.audio_channels, options.audio_sample_rate - ), - "sensor:microphone:enumeration-pending".to_string(), - "sensor:camera:enumeration-pending".to_string(), - ]; + let mut sources = Vec::new(); + for source in &options.move_state_sources { + sources.push(format!("psmove:state:{}", source.move_id)); + } + for camera in &options.move_marker_camera_sources { + sources.push(format!("psmove:camera:{}", camera.camera_id)); + } if options.quest_adb { sources.push(format!( "sensor:quest:adb:{}", @@ -2914,153 +974,6 @@ fn available_sources(options: &Options) -> Vec { sources } -fn publish_stream( - node: &mut cultmesh_rs::CultMeshNode, - options: &Options, - plan: &MuxPlan, - state: &str, - supervisor_pid: u32, - mux_pid: Option, - restart_count: u32, - detail: &str, -) -> Result<()> { - let record = MuninnCaptureStreamRecord { - stream_id: options.stream_id.clone(), - host_id: options.host_id.clone(), - state: state.to_string(), - video_source: if options.capture_video { - format!( - "ddagrab:output_idx={}:{}x{}@{}", - options.ddagrab_output_index, options.width, options.height, options.framerate - ) - } else { - "disabled".to_string() - }, - audio_source: if options.capture_audio { - format!( - "wasapi-loopback:{}:{}ch@{}", - options.audio_device, options.audio_channels, options.audio_sample_rate - ) - } else { - "disabled".to_string() - }, - transport: media_transport_id(&options.media_transport).to_string(), - targets: plan.targets.clone(), - command_witness: plan.command_file.display().to_string(), - supervisor_pid: Some(supervisor_pid), - mux_pid, - restart_count, - detail: detail.to_string(), - updated_at: timestamp()?, - }; - node.put("latest-stream", &record)?; - node.put(&record.stream_id, &record)?; - Ok(()) -} - -fn publish_obs_catalog_idle(node: &mut cultmesh_rs::CultMeshNode, options: &Options) -> Result<()> { - let mut stream_ids = vec![options.stream_id.clone()]; - let mut labels = vec![format!("{} screen and loopback A/V", options.host_id)]; - let mut urls = vec![String::new()]; - let mut states = vec!["activation-required".to_string()]; - for source in available_sources(options) { - stream_ids.push(format!("{}:{}", options.surface_id, source)); - labels.push(source); - urls.push(String::new()); - states.push("affordance".to_string()); - } - publish_obs_catalog(node, options, stream_ids, labels, urls, states) -} - -fn publish_obs_catalog( - node: &mut cultmesh_rs::CultMeshNode, - options: &Options, - stream_ids: Vec, - labels: Vec, - urls: Vec, - states: Vec, -) -> Result<()> { - let video_sources = video_source_catalog(options); - let audio_sources = audio_source_catalog(options); - let streaming = states - .iter() - .any(|state| state == "running" || state == "streaming"); - let record = MuninnObsStreamCatalogRecord { - catalog_id: "muninn.obs.streams".to_string(), - host_id: options.host_id.clone(), - stream_ids, - labels, - urls, - states, - updated_at: timestamp()?, - command_rudp_target: String::new(), - media_target_host: options.target_host.clone(), - media_port: options.port, - media_packet_bytes: options.media_packet_bytes as u32, - rudp_video_bitrate_kbps: options.rudp_video_bitrate_kbps, - rudp_latency_budget_ms: options.rudp_latency_budget_ms, - video_source_ids: video_sources - .iter() - .map(|source| source.id.clone()) - .collect(), - video_source_labels: video_sources - .iter() - .map(|source| source.label.clone()) - .collect(), - audio_source_ids: audio_sources - .iter() - .map(|source| source.id.clone()) - .collect(), - audio_source_labels: audio_sources - .iter() - .map(|source| source.label.clone()) - .collect(), - }; - node.put("obs", &record)?; - match media_stream_advertisement(options, streaming) { - Ok(advertisement) => { - node.put(&advertisement.stream_id, &advertisement)?; - if let Some(target) = resolve_odin_cultmesh_uri(options) - && let Err(error) = node.publish_document_to_rudp_catalog( - &advertisement.stream_id, - &advertisement, - CultMeshRudpDocumentPublishOptions { - target, - runtime_id: muninn_daemon_id(options), - source_role: Some("media-stream-producer".to_string()), - tags: vec!["gamecult.media-stream-advertisement".to_string()], - ..CultMeshRudpDocumentPublishOptions::default() - }, - ) - { - eprintln!( - "Muninn could not publish its media stream advertisement to Odin: {error:#}" - ); - } - } - Err(error) => eprintln!("Muninn is not advertising its media stream: {error:#}"), - } - if let Some(target) = resolve_odin_cultmesh_uri(options) - && let Err(error) = node.publish_document_to_rudp_catalog( - "obs", - &record, - CultMeshRudpDocumentPublishOptions { - target, - runtime_id: muninn_daemon_id(options), - source_role: Some("muninn.obs-catalog-provider".to_string()), - tags: vec![ - "obs-discovery".to_string(), - "odin-verse-discovery".to_string(), - ], - ..CultMeshRudpDocumentPublishOptions::default() - }, - ) - { - eprintln!("Muninn could not publish OBS catalog to Odin: {error:#}"); - } - Ok(()) -} - fn create_move_evidence_stream(options: &Options) -> Result> { if options.move_state_sources.is_empty() && options.move_marker_camera_sources.is_empty() @@ -5057,7 +2970,13 @@ fn run_hid_controller_rudp_ingress( counters: Option>, ) -> Result<()> { let local_addr = socket.local_addr()?; - println!("Muninn HID controller RUDP stream listening at {local_addr}."); + if let Some(advertise) = options.hid_controller_rudp_advertise.as_deref() { + println!( + "Muninn HID controller RUDP stream listening at {local_addr} (advertised as {advertise})." + ); + } else { + println!("Muninn HID controller RUDP stream listening at {local_addr}."); + } let mut transport = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { media_delivery: None, @@ -8383,43 +6302,6 @@ fn request_move_light(options: Options) -> Result<()> { Ok(()) } -fn request_capture_stream(options: Options) -> Result<()> { - require_media_target_uri(&options)?; - let command = build_capture_stream_command(&options)?; - publish_capture_command_to_odin(&options, &command)?; - println!( - "Published Muninn capture stream command {} {} {} for {} through Odin/CultMesh.", - command.command_id, command.action, command.stream_id, command.host_id - ); - Ok(()) -} - -fn publish_capture_command_to_odin( - options: &Options, - command: &MuninnCaptureStreamCommandRecord, -) -> Result<()> { - let Some(target) = resolve_odin_cultmesh_uri(options) else { - return Err(anyhow!( - "muninn request-stream requires --odin-cultmesh-uri; direct activation-store writes and raw RUDP command targets have been removed" - )); - }; - let node = open_node(options, "muninn-capture-command-odin-publisher")?; - node.publish_document_to_rudp_catalog( - &latest_capture_stream_command_key(&command.host_id, &command.stream_id), - command, - CultMeshRudpDocumentPublishOptions { - target, - runtime_id: "muninn-request-stream".to_string(), - source_role: Some("capture-command-publisher".to_string()), - tags: vec![ - "odin-cultmesh-command-route".to_string(), - "muninn.capture-stream".to_string(), - ], - ..CultMeshRudpDocumentPublishOptions::default() - }, - ) -} - fn move_light_status(options: Options) -> Result<()> { let node = open_node(&options, "muninn-move-light-status")?; let mut commands = node.cache().get_all::()?; @@ -8513,79 +6395,6 @@ fn move_hue_program_status(options: Options) -> Result<()> { Ok(()) } -fn capture_stream_status(options: Options) -> Result<()> { - let mut status_options = options.clone(); - if let Some(activation_store_path) = status_options.activation_store_path.as_ref() { - status_options.store_path = activation_store_path.clone(); - } - let node = open_node(&status_options, "muninn-capture-stream-status")?; - let mut commands = node.cache().get_all::()?; - commands.retain(|command| command.host_id == status_options.host_id); - if let Some(command_id) = status_options.command_id.as_deref() { - commands.retain(|command| command.command_id == command_id); - } - if status_options.stream_filter_explicit && !status_options.stream_id.trim().is_empty() { - commands.retain(|command| command.stream_id == status_options.stream_id); - } - commands.sort_by(|left, right| { - left.stream_id - .cmp(&right.stream_id) - .then(left.command_id.cmp(&right.command_id)) - }); - - if commands.is_empty() { - println!( - "No Muninn capture stream commands found for host {}{}{}.", - status_options.host_id, - if !status_options.stream_filter_explicit || status_options.stream_id.trim().is_empty() - { - "" - } else { - " stream " - }, - if !status_options.stream_filter_explicit || status_options.stream_id.trim().is_empty() - { - "" - } else { - status_options.stream_id.as_str() - } - ); - return Ok(()); - } - - for command in commands { - let target_display = if command.action == "start" { - format!("{}:{}", command.target_host, command.port) - } else { - "n/a".to_string() - }; - let video_source_display = if command.action == "start" { - command_video_source_id(&command).to_string() - } else { - "n/a".to_string() - }; - let audio_source_display = if command.action == "start" { - command_audio_source_id(&command).to_string() - } else { - "n/a".to_string() - }; - println!( - "{} host={} stream={} action={} state={} target={} video_source={} audio_source={} detail={} updated={}", - command.command_id, - command.host_id, - command.stream_id, - command.action, - command.state, - target_display, - video_source_display, - audio_source_display, - command.detail, - command.updated_at - ); - } - Ok(()) -} - fn move_state_status(options: Options) -> Result<()> { let node = open_node(&options, "muninn-move-state-status")?; let mut states = node.cache().get_all::()?; @@ -8840,423 +6649,28 @@ fn build_move_light_command(options: &Options) -> Result Result { - require_media_target_uri(options)?; - if options.stream_action != "start" && options.stream_action != "stop" { - return Err(anyhow!("--stream-action must be start or stop")); - } - let now = timestamp()?; - let command_id = options.command_id.clone().unwrap_or_else(|| { - format!( - "{}:{}:capture-stream:{}:{}", - options.host_id, options.stream_id, options.stream_action, now - ) - }); - Ok(MuninnCaptureStreamCommandRecord { - command_id, - host_id: options.host_id.clone(), - stream_id: options.stream_id.clone(), - state: "pending".to_string(), - action: options.stream_action.clone(), - target_host: options.target_host.clone(), - port: options.port, - obs_target_host: None, - obs_port: 0, - media_transport: media_transport_cli(&options.media_transport).to_string(), - media_packet_bytes: options.media_packet_bytes as u32, - requested_by: "muninn.request-stream".to_string(), - detail: "operator requested a daemon-owned capture stream lifecycle change".to_string(), - updated_at: now, - rudp_video_bitrate_kbps: options.rudp_video_bitrate_kbps, - rudp_latency_budget_ms: options.rudp_latency_budget_ms, - video_source_id: video_source_id_for_options(options), - audio_source_id: audio_source_id_for_options(options), - }) -} - -fn build_mux_plan(options: &Options, timestamp: String) -> MuxPlan { - let command_file = options.log_root.join(format!("muninn-{timestamp}.ps1")); - let loopback_stderr = options - .log_root - .join(format!("muninn-{timestamp}.loopback.err.log")); - let ffmpeg_stderr = options - .log_root - .join(format!("muninn-{timestamp}.ffmpeg.err.log")); - let targets = build_targets(options); - let loopback_args = loopback_args(options); - let ffmpeg_args = ffmpeg_args(options); - let loopback_args_literal = powershell_array_literal(&loopback_args); - let ffmpeg_args_literal = powershell_array_literal(&ffmpeg_args); - let command_line = format!( - "powershell.exe {} | {} {}", - loopback_args - .iter() - .map(|arg| quote_powershell(arg)) - .collect::>() - .join(" "), - options.ffmpeg_path, - ffmpeg_args - .iter() - .map(|arg| quote_powershell(arg)) - .collect::>() - .join(" ") - ); - let command_script = format!( - concat!( - "$ErrorActionPreference = 'Stop'\r\n", - "$ProgressPreference = 'SilentlyContinue'\r\n", - "$loopbackArgs = {0}\r\n", - "$ffmpegArgs = {1}\r\n", - "$loopbackErrorPath = {2}\r\n", - "$ffmpegErrorPath = {3}\r\n", - "function Quote-NativeArgument([string] $Value) {{\r\n", - " if ([string]::IsNullOrEmpty($Value)) {{ return '\"\"' }}\r\n", - " if ($Value -match '[\\s\"]') {{ return '\"' + $Value.Replace('\"', '\\\"') + '\"' }}\r\n", - " return $Value\r\n", - "}}\r\n", - "function Start-RedirectTask([System.IO.StreamReader] $Reader, [string] $Path) {{\r\n", - " return [System.Threading.Tasks.Task]::Run([Action]{{\r\n", - " $writer = [System.IO.StreamWriter]::new($Path, $false, [System.Text.Encoding]::ASCII)\r\n", - " try {{\r\n", - " while (($line = $Reader.ReadLine()) -ne $null) {{ $writer.WriteLine($line); $writer.Flush() }}\r\n", - " }} finally {{ $writer.Dispose() }}\r\n", - " }})\r\n", - "}}\r\n", - "$loopbackInfo = [System.Diagnostics.ProcessStartInfo]::new()\r\n", - "$loopbackInfo.FileName = 'powershell.exe'\r\n", - "$loopbackInfo.UseShellExecute = $false\r\n", - "$loopbackInfo.RedirectStandardOutput = $true\r\n", - "$loopbackInfo.RedirectStandardError = $true\r\n", - "$loopbackInfo.CreateNoWindow = $true\r\n", - "$loopbackInfo.Arguments = ($loopbackArgs | ForEach-Object {{ Quote-NativeArgument $_ }}) -join ' '\r\n", - "$ffmpegInfo = [System.Diagnostics.ProcessStartInfo]::new()\r\n", - "$ffmpegInfo.FileName = {4}\r\n", - "$ffmpegInfo.UseShellExecute = $false\r\n", - "$ffmpegInfo.RedirectStandardInput = $true\r\n", - "$ffmpegInfo.RedirectStandardError = $true\r\n", - "$ffmpegInfo.CreateNoWindow = $true\r\n", - "$ffmpegInfo.Arguments = ($ffmpegArgs | ForEach-Object {{ Quote-NativeArgument $_ }}) -join ' '\r\n", - "$loopback = [System.Diagnostics.Process]::Start($loopbackInfo)\r\n", - "$ffmpeg = [System.Diagnostics.Process]::Start($ffmpegInfo)\r\n", - "$loopbackErrTask = Start-RedirectTask $loopback.StandardError $loopbackErrorPath\r\n", - "$ffmpegErrTask = Start-RedirectTask $ffmpeg.StandardError $ffmpegErrorPath\r\n", - "$buffer = [byte[]]::new(65536)\r\n", - "try {{\r\n", - " while (($read = $loopback.StandardOutput.BaseStream.Read($buffer, 0, $buffer.Length)) -gt 0) {{\r\n", - " $ffmpeg.StandardInput.BaseStream.Write($buffer, 0, $read)\r\n", - " $ffmpeg.StandardInput.BaseStream.Flush()\r\n", - " }}\r\n", - " $ffmpeg.StandardInput.Close()\r\n", - " $ffmpeg.WaitForExit()\r\n", - " $loopback.WaitForExit()\r\n", - " [System.Threading.Tasks.Task]::WaitAll(@($loopbackErrTask, $ffmpegErrTask))\r\n", - " if ($ffmpeg.ExitCode -ne 0) {{ throw ('ffmpeg exited with code ' + $ffmpeg.ExitCode) }}\r\n", - " if ($loopback.ExitCode -ne 0) {{ throw ('loopback exited with code ' + $loopback.ExitCode) }}\r\n", - "}} finally {{\r\n", - " if (-not $ffmpeg.HasExited) {{ $ffmpeg.Kill() }}\r\n", - " if (-not $loopback.HasExited) {{ $loopback.Kill() }}\r\n", - "}}\r\n" - ), - loopback_args_literal, - ffmpeg_args_literal, - quote_powershell(&loopback_stderr.display().to_string()), - quote_powershell(&ffmpeg_stderr.display().to_string()), - quote_powershell(&options.ffmpeg_path) - ); - - MuxPlan { - command_line, - command_script, - command_file, - targets, - } -} - -fn require_media_target_uri(options: &Options) -> Result<()> { - if options.target_host.trim().is_empty() { - return Err(anyhow!( - "--target-host is required for Muninn media activation; provide an Odin/CultMesh media target URI" - )); - } - if !options.target_host.starts_with("cultmesh://") { - return Err(anyhow!( - "Muninn media activation requires a cultmesh:// target URI resolved through Odin; raw hosts, IPs, and ports are not accepted" - )); - } - Ok(()) -} - -fn build_targets(options: &Options) -> Vec { - vec![rudp_endpoint_for_options(options)] -} - -fn rudp_endpoint_for_options(options: &Options) -> String { - format!("{}#{}", options.target_host, options.stream_id) -} - -fn muninn_rudp_media_profile() -> MuninnRudpMediaProfile { - muninn_rudp_media_profile_for_bitrate(MUNINN_RUDP_MEDIA_VIDEO_BITRATE_KBPS) -} - -fn muninn_rudp_media_profile_for_options(options: &Options) -> MuninnRudpMediaProfile { - muninn_rudp_media_profile_for_bitrate(options.rudp_video_bitrate_kbps) -} - -/// Encoder and wire shape. It carries no deadline: the request's latency -/// budget reaches the sender only through `MediaSendPolicy`. -fn muninn_rudp_media_profile_for_bitrate(video_bitrate_kbps: u32) -> MuninnRudpMediaProfile { - MuninnRudpMediaProfile { - profile_id: MUNINN_RUDP_MEDIA_PROFILE_ID, - video_codec: "h264", - video_encoder: "h264_nvenc", - video_preset: "p5", - video_tune: "ull", - video_bitrate_kbps: video_bitrate_kbps.max(1), - media_packet_bytes: MUNINN_RUDP_MEDIA_PACKET_BYTES, - max_fragment_bytes: MUNINN_RUDP_MEDIA_MAX_FRAGMENT_BYTES, - video_b_frames: 0, - video_rc_lookahead: 0, - sender_resend_delay_ms: MUNINN_RUDP_MEDIA_RESEND_DELAY_MS, - receiver_gap_wait_ms: MUNINN_RUDP_MEDIA_RECEIVER_GAP_WAIT_MS, - } -} - -fn muninn_rudp_video_bitrate_arg(profile: &MuninnRudpMediaProfile) -> String { - format!("{}k", profile.video_bitrate_kbps) -} - -fn muninn_rudp_video_vbv_buffer_arg(options: &Options, profile: &MuninnRudpMediaProfile) -> String { - let framerate = options.framerate.max(1); - let frame_budget_kbits = profile.video_bitrate_kbps.div_ceil(framerate).max(1); - let burst_budget_kbits = frame_budget_kbits - .saturating_mul(MUNINN_RUDP_MEDIA_VBV_FRAME_BUDGETS) - .max(frame_budget_kbits); - format!("{burst_budget_kbits}k") -} - -fn muninn_rudp_video_gop_frames(options: &Options) -> u32 { - (options.framerate.max(1).div_ceil(4)).max(1) -} - -fn loopback_args(options: &Options) -> Vec { - let audio_source = audio_source_spec_for_options(options); - vec![ - "-NoProfile".to_string(), - "-ExecutionPolicy".to_string(), - "Bypass".to_string(), - "-File".to_string(), - options.loopback_script.display().to_string(), - "-Output".to_string(), - "stdout".to_string(), - "-SampleRate".to_string(), - options.audio_sample_rate.to_string(), - "-Channels".to_string(), - options.audio_channels.to_string(), - "-Device".to_string(), - audio_source.device, - "-DataFlow".to_string(), - match audio_source.kind { - AudioSourceKind::Loopback => "Render".to_string(), - AudioSourceKind::Input => "Capture".to_string(), - }, - ] - .into_iter() - .chain(match audio_source.kind { - AudioSourceKind::Loopback => vec!["-Loopback".to_string()], - AudioSourceKind::Input => Vec::new(), - }) - .collect() -} - -fn rudp_video_ffmpeg_args(options: &Options) -> Vec { - let profile = muninn_rudp_media_profile_for_options(options); - vec![ - "-hide_banner".to_string(), - "-loglevel".to_string(), - "warning".to_string(), - "-fflags".to_string(), - "nobuffer".to_string(), - "-flags".to_string(), - "low_delay".to_string(), - "-thread_queue_size".to_string(), - "256".to_string(), - "-f".to_string(), - "lavfi".to_string(), - "-i".to_string(), - format!( - "ddagrab=framerate={}:output_idx={}:draw_mouse=1", - options.framerate, options.ddagrab_output_index - ), - "-map".to_string(), - "0:v:0".to_string(), - "-an".to_string(), - "-c:v".to_string(), - profile.video_encoder.to_string(), - "-preset".to_string(), - profile.video_preset.to_string(), - "-tune".to_string(), - profile.video_tune.to_string(), - "-zerolatency".to_string(), - "1".to_string(), - "-bf".to_string(), - profile.video_b_frames.to_string(), - "-delay".to_string(), - "0".to_string(), - "-rc".to_string(), - "cbr".to_string(), - "-rc-lookahead".to_string(), - profile.video_rc_lookahead.to_string(), - "-multipass".to_string(), - "disabled".to_string(), - "-strict_gop".to_string(), - "1".to_string(), - "-ldkfs".to_string(), - MUNINN_RUDP_MEDIA_LOW_DELAY_KEY_FRAME_SCALE.to_string(), - "-spatial_aq".to_string(), - "1".to_string(), - "-temporal_aq".to_string(), - "1".to_string(), - "-aq-strength".to_string(), - "8".to_string(), - "-nonref_p".to_string(), - "1".to_string(), - "-b_ref_mode".to_string(), - "disabled".to_string(), - "-dpb_size".to_string(), - MUNINN_RUDP_MEDIA_VIDEO_DPB_SIZE.to_string(), - "-b:v".to_string(), - muninn_rudp_video_bitrate_arg(&profile), - "-maxrate".to_string(), - muninn_rudp_video_bitrate_arg(&profile), - "-bufsize".to_string(), - muninn_rudp_video_vbv_buffer_arg(options, &profile), - "-g".to_string(), - muninn_rudp_video_gop_frames(options).to_string(), - "-keyint_min".to_string(), - muninn_rudp_video_gop_frames(options).to_string(), - "-forced-idr".to_string(), - "1".to_string(), - "-aud".to_string(), - "1".to_string(), - "-fps_mode".to_string(), - "cfr".to_string(), - "-r".to_string(), - options.framerate.max(1).to_string(), - "-f".to_string(), - profile.video_codec.to_string(), - "pipe:1".to_string(), - ] -} - -fn rudp_audio_ffmpeg_args(options: &Options) -> Vec { - vec![ - "-hide_banner".to_string(), - "-loglevel".to_string(), - "warning".to_string(), - "-fflags".to_string(), - "nobuffer".to_string(), - "-flags".to_string(), - "low_delay".to_string(), - "-thread_queue_size".to_string(), - "256".to_string(), - "-f".to_string(), - "f32le".to_string(), - "-ar".to_string(), - options.audio_sample_rate.to_string(), - "-ac".to_string(), - options.audio_channels.to_string(), - "-i".to_string(), - "pipe:0".to_string(), - "-vn".to_string(), - "-ar".to_string(), - options.audio_sample_rate.to_string(), - "-ac".to_string(), - options.audio_channels.to_string(), - "-f".to_string(), - "f32le".to_string(), - "pipe:1".to_string(), - ] -} - -fn ffmpeg_args(options: &Options) -> Vec { - let _ = options.media_transport; - rudp_video_ffmpeg_args(options) -} - -fn write_command_file(plan: &MuxPlan) -> Result<()> { - fs::write(&plan.command_file, &plan.command_script) - .with_context(|| format!("writing {}", plan.command_file.display())) -} - -fn quote_powershell(value: &str) -> String { - format!("'{}'", value.replace('\'', "''")) -} - -fn powershell_array_literal(values: &[String]) -> String { - let joined = values - .iter() - .map(|value| quote_powershell(value)) - .collect::>() - .join(", "); - format!("@({joined})") -} - fn ensure_state_dirs(options: &Options) -> Result<()> { fs::create_dir_all(&options.log_root) .with_context(|| format!("creating {}", options.log_root.display()))?; if let Some(parent) = options.store_path.parent() { fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?; } - if let Some(parent) = options - .activation_store_path - .as_ref() - .and_then(|path| path.parent()) - { - fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?; - } Ok(()) } -/// Odin's document set, Muninn's own records, and the producer-agnostic media -/// stream contract. Today Odin's document set (odin-core) is registered first -/// and carries identical `muninn.*` type names and schema ids, so -/// `MuninnRecords` registers the same strings again and binds nothing new; -/// cultcache errors at startup if the two ever diverge. Odin's copies are to be -/// deleted, at which point `muninn-contracts` becomes the sole owner of every -/// `muninn.*` binding. The registration stays so that deletion changes nothing -/// here. +/// Muninn's typed records plus Idunn runtime presence health. #[derive(Clone, Copy, Debug, Default)] struct MuninnDocuments; impl cultmesh_rs::CultMeshDocumentSet for MuninnDocuments { fn register_cache(&self, cache: &mut cultcache_rs::CultCache) -> Result<()> { - OdinDocuments.register_cache(cache)?; MuninnRecords.register_cache(cache)?; - cache.register_entry_type::()?; - cache.register_entry_type::()?; cache.register_entry_type::()?; Ok(()) } fn register_documents(&self, registry: &mut cultnet_rs::CultNetDocumentRegistry) -> Result<()> { - OdinDocuments.register_documents(registry)?; MuninnRecords.register_documents(registry)?; - registry.register( - cultnet_rs::CultNetDocumentBinding::for_entry_with_schema_id::< - GameCultMediaStreamAdvertisementRecord, - >( - GAMECULT_MEDIA_STREAM_ADVERTISEMENT_SCHEMA.to_string(), - GAMECULT_MEDIA_STREAM_ADVERTISEMENT_SCHEMA.to_string(), - ), - ); - registry.register( - cultnet_rs::CultNetDocumentBinding::for_entry_with_schema_id::< - GameCultMediaStreamRequestRecord, - >( - GAMECULT_MEDIA_STREAM_REQUEST_SCHEMA.to_string(), - GAMECULT_MEDIA_STREAM_REQUEST_SCHEMA.to_string(), - ), - ); registry.register( cultnet_rs::CultNetDocumentBinding::for_entry_with_schema_id::< GameCultRuntimePresenceHealthRecord, @@ -9286,34 +6700,8 @@ impl Options { let mut options = Options { mode: Mode::Serve, store_path: PathBuf::from("C:/Meta/Odin/state/muninn.telemetry.cc"), - activation_store_path: Some(PathBuf::from(MUNINN_DEFAULT_ACTIVATION_STORE_PATH)), surface_id: "muninn.telemetry.local".to_string(), - stream_id: "muninn.raven.av.rudp".to_string(), - stream_filter_explicit: false, - stream_action: "start".to_string(), host_id: "raven".to_string(), - target_host: String::new(), - port: 5200, - media_rudp_bind: "0.0.0.0:5220".parse().expect("literal socket address"), - media_rudp_advertise: None, - media_transport: MediaTransport::Rudp, - media_packet_bytes: MUNINN_RUDP_MEDIA_PACKET_BYTES, - rudp_video_bitrate_kbps: MUNINN_RUDP_MEDIA_VIDEO_BITRATE_KBPS, - rudp_latency_budget_ms: MUNINN_RUDP_MEDIA_DEFAULT_LATENCY_BUDGET_MS as u32, - width: 1920, - height: 1080, - framerate: 30, - ddagrab_output_index: 0, - capture_video: true, - capture_audio: true, - audio_device: "Realtek".to_string(), - audio_source_id_override: None, - video_sources: Vec::new(), - audio_sources: Vec::new(), - audio_sample_rate: 48000, - audio_channels: 2, - ffmpeg_path: "ffmpeg".to_string(), - loopback_script: PathBuf::from("scripts/wasapi-loopback-capture.ps1"), log_root: PathBuf::from("C:/Meta/Odin/logs/muninn"), interval_seconds: None, move_id: "move-usb".to_string(), @@ -9355,7 +6743,6 @@ impl Options { hid_controller_rudp_target: None, hid_controller_rudp_bind: None, hid_controller_rudp_advertise: None, - command_rudp_advertise: None, hid_controller_receipt_retention_seconds: 3_600, }; @@ -9363,13 +6750,9 @@ impl Options { while let Some(arg) = args.next() { match arg.as_str() { "serve" => options.mode = Mode::Serve, - "activate" => options.mode = Mode::Activate, - "request-stream" => options.mode = Mode::RequestStream, "request-move-light" => options.mode = Mode::RequestMoveLight, "set-move-hue-program" => options.mode = Mode::SetMoveHueProgram, "move-hue-program-status" => options.mode = Mode::MoveHueProgramStatus, - "capture-stream-status" => options.mode = Mode::CaptureStreamStatus, - "obs-catalog-status" => options.mode = Mode::ObsCatalogStatus, "move-light-status" => options.mode = Mode::MoveLightStatus, "move-identity-status" => options.mode = Mode::MoveIdentityStatus, "move-source-status" => options.mode = Mode::MoveSourceStatus, @@ -9378,103 +6761,9 @@ impl Options { "quest-access-status" => options.mode = Mode::QuestAccessStatus, "move-tracker-worker" => options.mode = Mode::MoveTrackerWorker, "--health" => options.mode = Mode::Health, - "--dry-run" => options.mode = Mode::DryRun, "--store" => options.store_path = PathBuf::from(take_value(&mut args, "--store")?), - "--activate-store" => { - options.activation_store_path = - Some(PathBuf::from(take_value(&mut args, "--activate-store")?)) - } "--surface" => options.surface_id = take_value(&mut args, "--surface")?, - "--stream" => { - options.stream_id = take_value(&mut args, "--stream")?; - options.stream_filter_explicit = true; - } - "--stream-action" => { - options.stream_action = take_value(&mut args, "--stream-action")? - } "--host" => options.host_id = take_value(&mut args, "--host")?, - "--target-host" => options.target_host = take_value(&mut args, "--target-host")?, - "--port" => options.port = take_value(&mut args, "--port")?.parse()?, - "--obs-target-host" | "--obs-port" => { - return Err(anyhow!( - "{arg} has been removed; Muninn no longer dials a receiver. Receivers dial the endpoint Muninn advertises from --media-rudp-bind / --media-rudp-advertise" - )); - } - "--media-rudp-bind" => { - options.media_rudp_bind = take_value(&mut args, "--media-rudp-bind")? - .parse() - .context("--media-rudp-bind must be a socket address")? - } - "--media-rudp-advertise" => { - options.media_rudp_advertise = - Some(take_value(&mut args, "--media-rudp-advertise")?) - } - "--media-transport" => { - options.media_transport = - parse_media_transport(&take_value(&mut args, "--media-transport")?)? - } - "--media-packet-bytes" => { - options.media_packet_bytes = - take_value(&mut args, "--media-packet-bytes")?.parse()? - } - "--rudp-video-bitrate-kbps" => { - let bitrate = take_value(&mut args, "--rudp-video-bitrate-kbps")? - .parse() - .context("--rudp-video-bitrate-kbps must be a positive integer")?; - if bitrate == 0 { - return Err(anyhow!( - "--rudp-video-bitrate-kbps must be greater than zero" - )); - } - options.rudp_video_bitrate_kbps = bitrate; - } - "--rudp-latency-budget-ms" => { - let latency_budget = take_value(&mut args, "--rudp-latency-budget-ms")? - .parse() - .context("--rudp-latency-budget-ms must be a positive integer")?; - if latency_budget == 0 { - return Err(anyhow!( - "--rudp-latency-budget-ms must be greater than zero" - )); - } - options.rudp_latency_budget_ms = clamp_latency_budget_ms(latency_budget); - } - "--width" => options.width = take_value(&mut args, "--width")?.parse()?, - "--height" => options.height = take_value(&mut args, "--height")?.parse()?, - "--framerate" => { - options.framerate = take_value(&mut args, "--framerate")?.parse()? - } - "--ddagrab-output-index" => { - options.ddagrab_output_index = - take_value(&mut args, "--ddagrab-output-index")?.parse()? - } - "--no-video" => options.capture_video = false, - "--no-audio" => options.capture_audio = false, - "--audio-device" => options.audio_device = take_value(&mut args, "--audio-device")?, - "--audio-source-id" => { - options.audio_source_id_override = - Some(take_value(&mut args, "--audio-source-id")?) - } - "--video-source" => options.video_sources.push(parse_catalog_source(&take_value( - &mut args, - "--video-source", - )?)?), - "--audio-source" => options.audio_sources.push(parse_catalog_source(&take_value( - &mut args, - "--audio-source", - )?)?), - "--audio-sample-rate" => { - options.audio_sample_rate = - take_value(&mut args, "--audio-sample-rate")?.parse()? - } - "--audio-channels" => { - options.audio_channels = take_value(&mut args, "--audio-channels")?.parse()? - } - "--ffmpeg" => options.ffmpeg_path = take_value(&mut args, "--ffmpeg")?, - "--loopback-script" => { - options.loopback_script = - PathBuf::from(take_value(&mut args, "--loopback-script")?) - } "--log-root" => { options.log_root = PathBuf::from(take_value(&mut args, "--log-root")?) } @@ -9596,12 +6885,6 @@ impl Options { options.quest_video_input_stream_id = Some(take_value(&mut args, "--quest-video-input-stream")?) } - "--odin-cultmesh-rudp" => { - let _ = take_value(&mut args, "--odin-cultmesh-rudp")?; - return Err(anyhow!( - "--odin-cultmesh-rudp has been removed; use --odin-cultmesh-uri cultmesh://odin/rendezvous/provider-catalog and let CultMesh resolve Odin's transport" - )); - } "--odin-cultmesh-uri" => { options.odin_cultmesh_uri = Some(take_value(&mut args, "--odin-cultmesh-uri")?) } @@ -9623,16 +6906,6 @@ impl Options { options.hid_controller_rudp_advertise = Some(take_value(&mut args, "--hid-controller-rudp-advertise")?) } - "--command-rudp-bind" => { - let _ = take_value(&mut args, "--command-rudp-bind")?; - return Err(anyhow!( - "--command-rudp-bind has been removed; the Eve command ingress was quarantined (tag parked/muninn-eve-surface)" - )); - } - "--command-rudp-advertise" => { - options.command_rudp_advertise = - Some(take_value(&mut args, "--command-rudp-advertise")?) - } "--hid-controller-receipt-retention-seconds" => { options.hid_controller_receipt_retention_seconds = take_value( &mut args, @@ -9648,18 +6921,6 @@ impl Options { )); } } - "--capture-command-rudp-bind" => { - let _ = take_value(&mut args, "--capture-command-rudp-bind")?; - return Err(anyhow!( - "--capture-command-rudp-bind has been removed; Muninn serve reads capture commands from Odin/CultMesh discovery" - )); - } - "--capture-command-rudp-target" => { - let _ = take_value(&mut args, "--capture-command-rudp-target")?; - return Err(anyhow!( - "--capture-command-rudp-target has been removed; use --odin-cultmesh-uri so request-stream publishes through Odin/CultMesh" - )); - } "--color" => options.move_colors.push(take_value(&mut args, "--color")?), "--duration-ms" => options .move_durations_ms @@ -9701,11 +6962,6 @@ impl Options { if options.move_hue_cycle_ms == 0 { return Err(anyhow!("--move-hue-cycle-ms must be greater than zero")); } - if !options.capture_video && !options.capture_audio { - return Err(anyhow!( - "Muninn activation must keep at least one leg alive; do not pass both --no-video and --no-audio" - )); - } if options.move_evidence_verse_id.trim().is_empty() { return Err(anyhow!("--move-evidence-verse must be non-empty")); } @@ -9812,48 +7068,6 @@ fn timestamp_ns() -> Result { i64::try_from(nanos).context("system timestamp does not fit i64 nanoseconds") } -fn media_transport_id(transport: &MediaTransport) -> &'static str { - match transport { - MediaTransport::Rudp => CULTNET_RUDP_PROTOCOL_ID, - } -} - -fn media_transport_cli(transport: &MediaTransport) -> &'static str { - match transport { - MediaTransport::Rudp => "rudp", - } -} - -fn parse_media_transport(value: &str) -> Result { - match value.to_ascii_lowercase().as_str() { - "rudp" | "cultnet-rudp" | "cultmesh-rudp" | CULTNET_RUDP_PROTOCOL_ID => { - Ok(MediaTransport::Rudp) - } - _ => Err(anyhow!( - "--media-transport must be one of: rudp, cultnet-rudp" - )), - } -} - -fn parse_catalog_source(value: &str) -> Result { - let Some((id, label)) = value.split_once('=') else { - return Err(anyhow!( - "source catalog entries must be formatted as =" - )); - }; - let id = id.trim(); - let label = label.trim(); - if id.is_empty() || label.is_empty() { - return Err(anyhow!( - "source catalog entries must include a non-empty source id and display label" - )); - } - Ok(CatalogSource { - id: id.to_string(), - label: label.to_string(), - }) -} - fn parse_move_marker_camera_source(value: &str) -> Result { let Some((camera_id, device_path)) = value.split_once('=') else { return Err(anyhow!( @@ -9872,7 +7086,7 @@ fn parse_move_marker_camera_source(value: &str) -> Result &'static str { - "Usage: muninn [serve|activate|request-stream|capture-stream-status|obs-catalog-status|request-move-light|move-light-status|move-identity-status|move-source-status|move-state-status|claim-move-host|quest-access-status] [--store ] [--activate-store ] [--stream-action ] [--target-host ] [--media-transport ] [--media-rudp-bind ] [--media-rudp-advertise ] [--media-packet-bytes ] [--rudp-video-bitrate-kbps ] [--rudp-latency-budget-ms ] [--video-source ] [--audio-source ] [--audio-source-id ] [--no-video] [--no-audio] [--loopback-script ] [--ffmpeg ] [--odin-cultmesh-uri ] [--move-state =] [--move-marker-camera =] [--move-psmoveapi-tracker] [--move-tracker-exposure-milli <0..1000>] [--move-marker-width ] [--move-marker-height ] [--move-marker-fps ] [--move-host ] [--move-evidence-stream ] [--move-evidence-verse ] [--move-evidence-ring-slots ] [--move-evidence-slot-bytes ] [--move-evidence-snapshot ] [--quest-adb] [--quest-serial ] [--quest-input-stream ] [--quest-pose-stream ] [--quest-video-input-stream ] [--dry-run] [--health]\n\nMuninn is Odin's portable telemetry Verse assembler. serve publishes cheap typed telemetry affordances, optional Quest USB access surfaces, and the explicitly configured Move runtime; when serve receives --move-state, --move-marker-camera, --move-host, or --move-evidence-stream it may publish source-local Move controller state, source-local optical marker candidates, typed Move identity records, a CultMesh Move evidence stream, optionally write a latest one-copy Move proof evidence snapshot for Mimir field capture/replay, and keep USB-attached PS Moves claimed to that explicit Bluetooth host; --move-psmoveapi-tracker delegates camera exposure and optical extraction to the reference PSMoveAPI backend while Muninn retains stable-ID light actuation; serve consumes typed capture stream commands from its provider-owned activation store and owns the local ffmpeg/loopback activation child lifecycle, listens for media receivers on --media-rudp-bind and advertises that endpoint (--media-rudp-advertise when the bind address is not reachable as-is), and publishes its discovery advertisement through --odin-cultmesh-uri; activate starts an explicitly requested local CultNet RUDP stream as a daemon child that serves every receiver dialling --media-rudp-bind; request-stream discovers the provider through Odin and sends its typed command to that provider; obs-catalog-status pulls Odin-owned muninn.obs_stream_catalog discovery into the local compatibility store for OBS; capture-stream-status reads typed capture stream command receipts; use --no-video or --no-audio to request one leg over the CultNet RUDP media lane; request-move-light publishes a typed Move light command for Muninn serve to execute; move-light-status reads typed command receipts; move-identity-status reads typed Move identity records; move-source-status prints live Move source discovery; move-state-status reads typed controller-state records; claim-move-host assigns USB-attached PS Moves to a Bluetooth host; quest-access-status reads typed Quest access state." + "Usage: muninn [serve|request-move-light|move-light-status|set-move-hue-program|move-hue-program-status|move-identity-status|move-source-status|move-state-status|claim-move-host|quest-access-status] [--store ] [--surface ] [--host ] [--log-root ] [--interval-seconds ] [--odin-cultmesh-uri ] [--hid-controller-rudp-bind ] [--hid-controller-rudp-advertise ] [--hid-controller-rudp-target ] [--hid-controller-receipt-retention-seconds ] [--move-state =] [--move-marker-camera =] [--move-psmoveapi-tracker] [--move-tracker-exposure-milli <0..1000>] [--move-marker-width ] [--move-marker-height ] [--move-marker-fps ] [--move-host ] [--move-evidence-stream ] [--move-evidence-verse ] [--move-evidence-ring-slots ] [--move-evidence-slot-bytes ] [--move-evidence-snapshot ] [--quest-adb] [--quest-serial ] [--quest-input-stream ] [--quest-pose-stream ] [--quest-video-input-stream ] [--health]\n\nMuninn is the local sensor, PS Move, Quest access, and HID controller telemetry daemon. serve publishes local telemetry state, optional Quest USB access surfaces, and the explicitly configured Move and HID controller runtime; when serve receives --move-state, --move-marker-camera, --move-host, or --move-evidence-stream it publishes Move controller state, optical marker candidates, Move identity records, a CultMesh Move evidence stream, optional proof snapshots, and keeps USB-attached PS Moves claimed to the configured Bluetooth host; --move-psmoveapi-tracker delegates camera exposure and optical extraction to the reference PSMoveAPI backend while Muninn retains stable-ID light actuation; request-move-light publishes a typed Move light command for Muninn serve to execute; move-light-status reads typed command receipts; move-identity-status reads typed Move identity records; move-source-status prints live Move source discovery; move-state-status reads typed controller-state records; claim-move-host assigns USB-attached PS Moves to a Bluetooth host; quest-access-status reads typed Quest access state." } fn parse_move_state_source(value: &str) -> Result { @@ -9895,153 +7109,6 @@ fn parse_move_state_source(value: &str) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::media_send::{MediaKind, QueuedMediaGroup}; - - fn media_stream_request() -> GameCultMediaStreamRequestRecord { - GameCultMediaStreamRequestRecord { - request_id: "req-1".into(), - stream_id: "muninn.raven.av.rudp".into(), - producer_id: "raven".into(), - receiver_id: "starfire.obs".into(), - action: "start".into(), - state: "pending".into(), - video_source_id: "display:0".into(), - audio_source_id: "wasapi-loopback:Realtek".into(), - video_codec: "h264".into(), - audio_codec: "pcm-f32le-interleaved".into(), - video_bitrate_kbps: 8_000, - latency_budget_ms: 200, - media_packet_bytes: 0, - detail: String::new(), - updated_at: "2026-09-10T00:00:00Z".into(), - } - } - - #[test] - fn a_media_stream_request_becomes_the_command_the_tick_already_runs() { - let options = Options::parse(["serve"].into_iter().map(String::from)).unwrap(); - let command = command_from_media_stream_request(&options, &media_stream_request()).unwrap(); - assert_eq!(command.command_id, "req-1"); - assert_eq!(command.host_id, options.host_id); - assert_eq!(command.action, "start"); - assert_eq!(command.state, "pending"); - assert_eq!( - command.obs_target_host, None, - "the receiver dials Muninn, not the reverse" - ); - assert_eq!(command.obs_port, 0); - assert_eq!(command.rudp_video_bitrate_kbps, 8_000); - assert_eq!(command.rudp_latency_budget_ms, 200); - assert_eq!( - command.media_packet_bytes, options.media_packet_bytes as u32, - "zero takes the producer default" - ); - assert_eq!(command.video_source_id, "display:0"); - assert_eq!(command.requested_by, "starfire.obs"); - assert!( - command.updated_at.starts_with("unix-"), - "stamped by Muninn's clock, not the consumer's: {}", - command.updated_at - ); - assert!( - command.updated_at.as_str() > "unix-1783295838", - "a fresh request must outrank a command stored in July; the tick orders by this string" - ); - } - - #[test] - fn an_unsupported_codec_is_refused_with_the_supported_ones_named() { - let options = Options::parse(["serve"].into_iter().map(String::from)).unwrap(); - let mut request = media_stream_request(); - request.video_codec = "av1".into(); - let error = command_from_media_stream_request(&options, &request) - .unwrap_err() - .to_string(); - assert!(error.contains("h264") && error.contains("av1"), "{error}"); - let mut request = media_stream_request(); - request.audio_codec = "opus".into(); - let error = command_from_media_stream_request(&options, &request) - .unwrap_err() - .to_string(); - assert!(error.contains("pcm-f32le-interleaved"), "{error}"); - } - - #[test] - fn omitted_sources_become_the_disabled_sentinels() { - let options = Options::parse(["serve"].into_iter().map(String::from)).unwrap(); - let mut request = media_stream_request(); - request.audio_source_id.clear(); - request.audio_codec.clear(); - let command = command_from_media_stream_request(&options, &request).unwrap(); - assert_eq!(command.audio_source_id, MUNINN_DISABLED_AUDIO_SOURCE_ID); - assert_eq!(command.video_source_id, "display:0"); - } - - #[test] - fn a_stop_carries_no_sources() { - let options = Options::parse(["serve"].into_iter().map(String::from)).unwrap(); - let mut request = media_stream_request(); - request.action = "stop".into(); - request.video_source_id.clear(); - request.audio_source_id.clear(); - request.video_codec.clear(); - request.audio_codec.clear(); - let command = command_from_media_stream_request(&options, &request).unwrap(); - assert_eq!(command.action, "stop"); - } - - /// A wrong advertised address is a stream nobody can reach, so the - /// fallbacks are ordered and the last resort is a refusal, not a guess. - #[test] - fn the_advertised_media_endpoint_is_explicit_or_derived_never_guessed() { - let mut options = Options::parse(["serve"].into_iter().map(String::from)).unwrap(); - let error = advertised_media_endpoint(&options).unwrap_err().to_string(); - assert!( - error.contains("0.0.0.0:5220") && error.contains("--media-rudp-advertise"), - "{error}" - ); - - options.command_rudp_advertise = Some("10.77.0.2:17886".into()); - assert_eq!( - advertised_media_endpoint(&options).unwrap(), - "10.77.0.2:5220", - "the command host, on the media port" - ); - - options.media_rudp_bind = "192.168.1.84:5221".parse().unwrap(); - assert_eq!( - advertised_media_endpoint(&options).unwrap(), - "192.168.1.84:5221", - "a real bind address is itself the endpoint" - ); - - options.media_rudp_advertise = Some("raven.lan:5220".into()); - assert_eq!( - advertised_media_endpoint(&options).unwrap(), - "raven.lan:5220", - "an explicit advertisement wins" - ); - } - - #[test] - fn the_activation_child_is_told_where_to_listen() { - let options = Options::parse( - ["serve", "--media-rudp-bind", "0.0.0.0:6001"] - .into_iter() - .map(String::from), - ) - .unwrap(); - assert_eq!(options.media_rudp_bind.to_string(), "0.0.0.0:6001"); - for removed in ["--obs-target-host", "--obs-port"] { - let error = Options::parse(["serve", removed, "x"].into_iter().map(String::from)) - .unwrap_err() - .to_string(); - assert!( - error.contains("removed") && error.contains("--media-rudp-bind"), - "{error}" - ); - } - } use serde::Deserialize; #[derive(Default)] @@ -10073,271 +7140,11 @@ mod tests { } #[test] - fn serve_is_default_and_does_not_activate_streams() { + fn serve_is_default() { let options = Options::parse([].into_iter()).unwrap(); assert_eq!(options.mode, Mode::Serve); assert!(options.interval_seconds.is_none()); - assert_eq!( - options.activation_store_path, - Some(PathBuf::from(MUNINN_DEFAULT_ACTIVATION_STORE_PATH)) - ); - assert_eq!( - options.rudp_video_bitrate_kbps, - MUNINN_RUDP_MEDIA_VIDEO_BITRATE_KBPS - ); - } - - #[test] - fn serve_can_publish_distinct_activation_store_path() { - let options = Options::parse( - [ - "serve", - "--store", - "C:/Meta/Odin/state/muninn.telemetry.cc", - "--activate-store", - "C:/Meta/Odin/state/muninn.activate.cc", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - - assert_eq!( - options.activation_store_path, - Some(PathBuf::from("C:/Meta/Odin/state/muninn.activate.cc")) - ); - } - - #[test] - fn parse_accepts_independent_obs_source_catalog_entries() { - let options = Options::parse( - [ - "serve", - "--video-source", - "display:0=Raven display 1", - "--video-source", - "display:1=Raven display 2", - "--audio-source", - "wasapi-loopback:Realtek=Raven Realtek loopback", - "--audio-source", - "wasapi-loopback:Headphones=Raven headphones loopback", - "--audio-source", - "wasapi-input:Microphone=Raven microphone input", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - - assert_eq!( - video_source_catalog(&options), - vec![ - CatalogSource { - id: "display:0".to_string(), - label: "Raven display 1".to_string(), - }, - CatalogSource { - id: "display:1".to_string(), - label: "Raven display 2".to_string(), - } - ] - ); - assert_eq!( - audio_source_catalog(&options), - vec![ - CatalogSource { - id: "wasapi-loopback:Realtek".to_string(), - label: "Raven Realtek loopback".to_string(), - }, - CatalogSource { - id: "wasapi-loopback:Headphones".to_string(), - label: "Raven headphones loopback".to_string(), - }, - CatalogSource { - id: "wasapi-input:Microphone".to_string(), - label: "Raven microphone input".to_string(), - } - ] - ); - } - - #[test] - fn parse_audio_source_spec_accepts_loopback_and_input_sources() { - assert_eq!( - parse_audio_source_spec("wasapi-loopback:Realtek"), - Some(AudioSourceSpec { - kind: AudioSourceKind::Loopback, - device: "Realtek".to_string(), - }) - ); - assert_eq!( - parse_audio_source_spec("wasapi-input:Microphone"), - Some(AudioSourceSpec { - kind: AudioSourceKind::Input, - device: "Microphone".to_string(), - }) - ); - } - - #[test] - fn obs_source_catalog_falls_back_to_configured_capture_pair() { - let options = Options::parse( - [ - "serve", - "--host", - "raven", - "--ddagrab-output-index", - "1", - "--audio-device", - "Realtek", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - - assert_eq!( - video_source_catalog(&options), - vec![CatalogSource { - id: "display:1".to_string(), - label: "raven display 2".to_string(), - }] - ); - assert_eq!( - audio_source_catalog(&options), - vec![CatalogSource { - id: "wasapi-loopback:Realtek".to_string(), - label: "raven loopback (Realtek)".to_string(), - }] - ); - } - - #[test] - fn parse_accepts_single_leg_rudp_activation_requests() { - let video_only = Options::parse( - [ - "activate", - "--media-transport", - "rudp", - "--no-audio", - "--stream", - "muninn.raven.video.rudp", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - assert!(video_only.capture_video); - assert!(!video_only.capture_audio); - assert_eq!( - video_source_id_for_options(&video_only), - "display:0".to_string() - ); - assert_eq!( - audio_source_id_for_options(&video_only), - MUNINN_DISABLED_AUDIO_SOURCE_ID.to_string() - ); - - let audio_only = Options::parse( - [ - "activate", - "--media-transport", - "rudp", - "--no-video", - "--stream", - "muninn.raven.audio.rudp", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - assert!(!audio_only.capture_video); - assert!(audio_only.capture_audio); - assert_eq!( - video_source_id_for_options(&audio_only), - MUNINN_DISABLED_VIDEO_SOURCE_ID.to_string() - ); - assert_eq!( - audio_source_id_for_options(&audio_only), - "wasapi-loopback:Realtek".to_string() - ); - } - - #[test] - fn loopback_args_switch_to_capture_mode_for_input_sources() { - let options = Options::parse( - [ - "activate", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--audio-source-id", - "wasapi-input:Microphone (USB Audio)", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - - let args = loopback_args(&options); - assert!(args.contains(&"Capture".to_string())); - assert!(!args.contains(&"-Loopback".to_string())); - assert!(args.contains(&"Microphone (USB Audio)".to_string())); - } - - #[test] - fn parse_rejects_activation_when_both_media_legs_are_disabled() { - let error = Options::parse( - [ - "activate", - "--media-transport", - "rudp", - "--no-video", - "--no-audio", - ] - .into_iter() - .map(String::from), - ) - .unwrap_err() - .to_string(); - - assert!(error.contains("at least one leg alive")); - } - - #[test] - fn media_activation_requires_cultmesh_target_uri() { - let options = Options::parse(["activate"].into_iter().map(String::from)).unwrap(); - - let error = require_media_target_uri(&options).unwrap_err().to_string(); - assert!(error.contains("--target-host is required")); - - let options = Options::parse( - ["activate", "--target-host", "198.51.100.66"] - .into_iter() - .map(String::from), - ) - .unwrap(); - let error = require_media_target_uri(&options).unwrap_err().to_string(); - assert!(error.contains("cultmesh://")); - - let options = Options::parse(["request-stream"].into_iter().map(String::from)).unwrap(); - - let error = build_capture_stream_command(&options) - .unwrap_err() - .to_string(); - assert!(error.contains("--target-host is required")); - } - - #[test] - fn parse_rejects_blank_obs_source_catalog_entries() { - let error = Options::parse( - ["serve", "--video-source", "display:0="] - .into_iter() - .map(String::from), - ) - .unwrap_err(); - - assert!(error.to_string().contains("non-empty source id")); } #[test] @@ -10376,878 +7183,6 @@ mod tests { ); } - #[test] - fn serve_rejects_removed_odin_cultmesh_rudp_startup_target() { - let error = Options::parse( - ["serve", "--odin-cultmesh-rudp", "203.0.113.10:17871"] - .into_iter() - .map(String::from), - ) - .unwrap_err() - .to_string(); - - assert!(error.contains("--odin-cultmesh-rudp has been removed")); - } - - #[test] - fn request_stream_rejects_raw_capture_command_rudp_target() { - let error = Options::parse( - [ - "request-stream", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--capture-command-rudp-target", - "127.0.0.1:17872", - ] - .into_iter() - .map(String::from), - ) - .unwrap_err() - .to_string(); - - assert!(error.contains("--capture-command-rudp-target has been removed")); - } - - #[test] - fn serve_rejects_removed_capture_command_rudp_bind() { - let error = Options::parse( - ["serve", "--capture-command-rudp-bind", "127.0.0.1:17884"] - .into_iter() - .map(String::from), - ) - .unwrap_err() - .to_string(); - - assert!(error.contains("--capture-command-rudp-bind has been removed")); - } - - #[test] - fn request_stream_requires_odin_cultmesh_command_route() { - let options = Options::parse( - [ - "request-stream", - "--host", - "raven", - "--stream", - "muninn.raven.av.rudp", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - let error = request_capture_stream(options).unwrap_err().to_string(); - - assert!(error.contains("request-stream requires --odin-cultmesh-uri")); - } - - #[test] - fn repeated_capture_stream_start_is_equivalent_when_media_shape_matches() { - let options = Options::parse( - [ - "request-stream", - "--host", - "raven", - "--stream", - "muninn.raven.av.rudp", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--port", - "5204", - "--media-transport", - "rudp", - "--media-packet-bytes", - "800", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - let mut active = build_capture_stream_command(&options).unwrap(); - active.command_id = "first-command".to_string(); - active.state = "running".to_string(); - let mut retry = build_capture_stream_command(&options).unwrap(); - retry.command_id = "retry-command".to_string(); - - assert!(capture_stream_commands_start_equivalent(&active, &retry)); - - retry.media_packet_bytes = 940; - assert!(!capture_stream_commands_start_equivalent(&active, &retry)); - } - - #[test] - fn repeated_capture_stream_start_is_not_equivalent_when_split_leg_changes() { - let mut video_only = build_capture_stream_command( - &Options::parse( - [ - "request-stream", - "--media-transport", - "rudp", - "--stream", - "muninn.raven.video.rudp", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--no-audio", - ] - .into_iter() - .map(String::from), - ) - .unwrap(), - ) - .unwrap(); - video_only.command_id = "video-only".to_string(); - video_only.state = "running".to_string(); - - let mut combined = build_capture_stream_command( - &Options::parse( - [ - "request-stream", - "--media-transport", - "rudp", - "--stream", - "muninn.raven.video.rudp", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - ] - .into_iter() - .map(String::from), - ) - .unwrap(), - ) - .unwrap(); - combined.command_id = "combined".to_string(); - - assert!(!capture_stream_commands_start_equivalent( - &video_only, - &combined - )); - assert_eq!( - command_audio_source_id(&video_only), - MUNINN_DISABLED_AUDIO_SOURCE_ID - ); - assert!(command_requests_video(&video_only)); - assert!(!command_requests_audio(&video_only)); - } - - #[test] - fn repeated_capture_stream_start_is_equivalent_across_transport_specific_stream_ids() { - let mut active = build_capture_stream_command( - &Options::parse( - [ - "request-stream", - "--host", - "raven", - "--stream", - "muninn.raven.av.rudp", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--port", - "5204", - "--media-transport", - "rudp", - "--audio-source-id", - "wasapi-loopback:Speakers (Realtek(R) Audio)", - ] - .into_iter() - .map(String::from), - ) - .unwrap(), - ) - .unwrap(); - active.command_id = "active-command".to_string(); - active.state = "running".to_string(); - - let mut retry = build_capture_stream_command( - &Options::parse( - [ - "request-stream", - "--host", - "raven", - "--stream", - "muninn.raven.av.rudp", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--port", - "5204", - "--media-transport", - "rudp", - "--audio-source-id", - "wasapi-loopback:Speakers (Realtek(R) Audio)", - ] - .into_iter() - .map(String::from), - ) - .unwrap(), - ) - .unwrap(); - retry.command_id = "retry-command".to_string(); - - assert_eq!( - canonical_muninn_stream_id(&active.stream_id), - canonical_muninn_stream_id(&retry.stream_id) - ); - assert!(capture_stream_commands_start_equivalent(&active, &retry)); - } - - #[test] - fn latest_capture_stream_command_ids_canonicalizes_transport_specific_variants() { - let mut older = build_capture_stream_command( - &Options::parse( - [ - "request-stream", - "--host", - "raven", - "--stream", - "muninn.raven.av.rudp", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--port", - "5204", - "--media-transport", - "rudp", - ] - .into_iter() - .map(String::from), - ) - .unwrap(), - ) - .unwrap(); - older.command_id = "older-command".to_string(); - older.updated_at = "unix-1000".to_string(); - - let mut newer = older.clone(); - newer.stream_id = "muninn.raven.av.rudp".to_string(); - newer.command_id = "newer-command".to_string(); - newer.updated_at = "unix-2000".to_string(); - - let latest = latest_capture_stream_command_ids(&[older, newer], "raven"); - - assert_eq!(latest.len(), 1); - assert_eq!( - latest.get("muninn.raven.av").map(String::as_str), - Some("newer-command") - ); - } - - /// A newer command that was already handled still shadows an older - /// pending one; the ordering is by the command's own stamp, which the - /// terminal writers no longer touch. - #[test] - fn a_handled_newer_command_still_outranks_an_older_pending_one() { - let options = Options::parse(["serve"].into_iter().map(String::from)).unwrap(); - let mut live = - command_from_media_stream_request(&options, &media_stream_request()).unwrap(); - live.updated_at = "unix-1789080649".to_string(); - let mut handled = live.clone(); - handled.command_id = "handled-later".to_string(); - handled.state = "completed".to_string(); - handled.updated_at = "unix-1789080650".to_string(); - let latest = - latest_capture_stream_command_ids(&[live.clone(), handled.clone()], &options.host_id); - assert_eq!( - latest.get("muninn.raven.av").map(String::as_str), - Some("handled-later") - ); - } - - #[test] - fn media_target_contract_accepts_only_cultmesh_rudp() { - let options = Options::parse( - [ - "activate", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--media-transport", - "rudp", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - assert_eq!(options.media_transport, MediaTransport::Rudp); - assert!(require_media_target_uri(&options).is_ok()); - - let raw_target_options = Options::parse( - ["activate", "--target-host", "198.51.100.66"] - .into_iter() - .map(String::from), - ) - .unwrap(); - let error = require_media_target_uri(&raw_target_options) - .unwrap_err() - .to_string(); - assert!(error.contains("cultmesh://")); - } - - #[test] - fn builds_rudp_media_target_for_obs_plugin_activation() { - let options = Options::parse( - [ - "activate", - "--media-transport", - "rudp", - "--stream", - "muninn.raven.av.rudp", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--port", - "5204", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - - assert_eq!(options.media_packet_bytes, MUNINN_RUDP_MEDIA_PACKET_BYTES); - let plan = build_mux_plan(&options, "test".to_string()); - - assert_eq!( - plan.targets, - vec!["cultmesh://odin/media/muninn-raven-av#muninn.raven.av.rudp"] - ); - assert!(!plan.command_line.contains("tee")); - } - - #[test] - fn build_capture_stream_command_marks_disabled_legs_explicitly() { - let video_only = build_capture_stream_command( - &Options::parse( - [ - "request-stream", - "--media-transport", - "rudp", - "--stream", - "muninn.raven.video.rudp", - "--no-audio", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--port", - "5204", - ] - .into_iter() - .map(String::from), - ) - .unwrap(), - ) - .unwrap(); - assert_eq!(video_only.video_source_id, "display:0"); - assert_eq!(video_only.audio_source_id, MUNINN_DISABLED_AUDIO_SOURCE_ID); - - let audio_only = build_capture_stream_command( - &Options::parse( - [ - "request-stream", - "--media-transport", - "rudp", - "--stream", - "muninn.raven.audio.rudp", - "--no-video", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--port", - "5204", - ] - .into_iter() - .map(String::from), - ) - .unwrap(), - ) - .unwrap(); - assert_eq!(audio_only.video_source_id, MUNINN_DISABLED_VIDEO_SOURCE_ID); - assert_eq!(audio_only.audio_source_id, "wasapi-loopback:Realtek"); - } - - #[test] - fn rudp_video_encoder_outputs_annex_b_h264_for_packetizer() { - let options = Options::parse( - ["activate", "--media-transport", "rudp", "--framerate", "60"] - .into_iter() - .map(String::from), - ) - .unwrap(); - - let args = rudp_video_ffmpeg_args(&options); - let profile = muninn_rudp_media_profile(); - - assert!( - args.windows(2) - .any(|pair| pair[0] == "-f" && pair[1] == "h264") - ); - assert_eq!(profile.profile_id, MUNINN_RUDP_MEDIA_PROFILE_ID); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-tune" && pair[1] == "ull") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-bf" && pair[1] == "0") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-rc" && pair[1] == "cbr") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-rc-lookahead" && pair[1] == "0") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-multipass" && pair[1] == "disabled") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-strict_gop" && pair[1] == "1") - ); - assert!(args.windows(2).any(|pair| pair[0] == "-ldkfs" - && pair[1] == MUNINN_RUDP_MEDIA_LOW_DELAY_KEY_FRAME_SCALE.to_string())); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-spatial_aq" && pair[1] == "1") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-temporal_aq" && pair[1] == "1") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-aq-strength" && pair[1] == "8") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-nonref_p" && pair[1] == "1") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-b_ref_mode" && pair[1] == "disabled") - ); - assert!(args.windows(2).any(|pair| pair[0] == "-dpb_size" - && pair[1] == MUNINN_RUDP_MEDIA_VIDEO_DPB_SIZE.to_string())); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-preset" && pair[1] == "p5") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-b:v" && pair[1] == "12000k") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-maxrate" && pair[1] == "12000k") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-bufsize" && pair[1] == "200k") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-g" && pair[1] == "15") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-keyint_min" && pair[1] == "15") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-forced-idr" && pair[1] == "1") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-aud" && pair[1] == "1") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-fps_mode" && pair[1] == "cfr") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-r" && pair[1] == "60") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-an" && pair[1] == "-c:v") - ); - assert_eq!(args.last().map(String::as_str), Some("pipe:1")); - } - - #[test] - fn rudp_video_encoder_uses_explicit_bitrate_budget() { - let options = Options::parse( - [ - "activate", - "--media-transport", - "rudp", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--framerate", - "30", - "--rudp-video-bitrate-kbps", - "8000", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - - let args = rudp_video_ffmpeg_args(&options); - let profile = muninn_rudp_media_profile_for_options(&options); - - assert_eq!(profile.video_bitrate_kbps, 8000); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-b:v" && pair[1] == "8000k") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-maxrate" && pair[1] == "8000k") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-bufsize" && pair[1] == "267k") - ); - } - - #[test] - fn rudp_video_vbv_buffer_tracks_lan_burst_budget() { - let thirty_fps = Options::parse( - ["activate", "--media-transport", "rudp", "--framerate", "30"] - .into_iter() - .map(String::from), - ) - .unwrap(); - let sixty_fps = Options::parse( - ["activate", "--media-transport", "rudp", "--framerate", "60"] - .into_iter() - .map(String::from), - ) - .unwrap(); - let profile = muninn_rudp_media_profile(); - - assert_eq!( - muninn_rudp_video_vbv_buffer_arg(&thirty_fps, &profile), - "400k" - ); - assert_eq!( - muninn_rudp_video_vbv_buffer_arg(&sixty_fps, &profile), - "200k" - ); - } - - #[test] - fn rudp_video_gop_tracks_quarter_second_recovery_budget() { - let thirty_fps = Options::parse( - ["activate", "--media-transport", "rudp", "--framerate", "30"] - .into_iter() - .map(String::from), - ) - .unwrap(); - let sixty_fps = Options::parse( - ["activate", "--media-transport", "rudp", "--framerate", "60"] - .into_iter() - .map(String::from), - ) - .unwrap(); - - assert_eq!(muninn_rudp_video_gop_frames(&thirty_fps), 8); - assert_eq!(muninn_rudp_video_gop_frames(&sixty_fps), 15); - } - - fn send_single_access_unit( - config: crate::media_packetizer::VideoAnnexBStreamSendConfig, - access_unit: &[u8], - ) -> Vec { - let mut sender = crate::media_packetizer::VideoAnnexBStreamSendState::new(config).unwrap(); - let mut groups = sender.push("2026-06-18T00:00:00Z", access_unit).unwrap(); - groups.extend(sender.finish("2026-06-18T00:00:00Z").unwrap()); - groups.into_iter().flatten().collect() - } - - #[test] - fn default_rudp_media_packet_size_keeps_late_typed_video_wire_under_udp_mtu() { - let mut access_unit = Vec::new(); - access_unit.extend_from_slice(&[0, 0, 0, 1, 0x65]); - access_unit.resize(MUNINN_RUDP_MEDIA_PACKET_BYTES, 0x80); - - let payloads = send_single_access_unit( - crate::media_packetizer::VideoAnnexBStreamSendConfig { - stream_id: "muninn.raven.av.rudp".to_string(), - session_id: "session-1".to_string(), - codec: "h264".to_string(), - first_frame_id: 1_000_000, - first_pts_ticks: 3_000_000_000, - frame_duration_ticks: 3_000, - timebase_num: 1, - timebase_den: 90_000, - deadline_delay_ticks: 1_800, - max_payload_bytes: MUNINN_RUDP_MEDIA_PACKET_BYTES, - max_pending_bytes: MUNINN_RUDP_MEDIA_PACKET_BYTES * 2, - source_runtime_id: "muninn-test".to_string(), - source_role: "media-test".to_string(), - }, - &access_unit, - ); - - assert_eq!(payloads.len(), 1); - assert!( - payloads[0].payload.len() <= MUNINN_RUDP_MEDIA_MAX_FRAGMENT_BYTES, - "typed media payload was {} bytes", - payloads[0].payload.len() - ); - assert!( - payloads[0].payload.len() - + MUNINN_RUDP_FIXED_HEADER_BYTES - + crate::media_packetizer::MUNINN_MEDIA_RUDP_CHANNEL.len() - <= MUNINN_RUDP_IPV4_UDP_PAYLOAD_BYTES - ); - } - - #[test] - fn default_rudp_media_packet_size_keeps_chunked_video_wire_under_rudp_fragment_limit() { - let mut access_unit = Vec::new(); - access_unit.extend_from_slice(&[0, 0, 0, 1, 0x65]); - access_unit.resize(MUNINN_RUDP_MEDIA_PACKET_BYTES * 64, 0x80); - - let payloads = send_single_access_unit( - crate::media_packetizer::VideoAnnexBStreamSendConfig { - stream_id: "muninn.raven.av.rudp".to_string(), - session_id: "raven:2026-06-19T14-56-23Z:video".to_string(), - codec: "h264".to_string(), - first_frame_id: 1_000_000, - first_pts_ticks: 3_000_000_000, - frame_duration_ticks: 1_500, - timebase_num: 1, - timebase_den: 90_000, - deadline_delay_ticks: 1_500, - max_payload_bytes: MUNINN_RUDP_MEDIA_PACKET_BYTES, - max_pending_bytes: MUNINN_RUDP_MEDIA_PACKET_BYTES * 65, - source_runtime_id: "raven".to_string(), - source_role: "muninn.rudp.video".to_string(), - }, - &access_unit, - ); - - assert!(payloads.len() > 1); - let largest = payloads - .iter() - .map(|payload| payload.payload.len()) - .max() - .unwrap(); - assert!( - largest <= MUNINN_RUDP_MEDIA_MAX_FRAGMENT_BYTES, - "largest typed media payload was {largest} bytes" - ); - } - - #[test] - fn rudp_media_hub_serves_lossy_video_and_reliable_audio_on_one_session() { - let socket = UdpSocket::bind("127.0.0.1:0").unwrap(); - let profile = muninn_rudp_media_profile(); - let policy = MediaSendPolicy::from_request(137); - let options = muninn_media_rudp_hub_options(socket, &profile, &policy); - assert_eq!(options.runtime_id, "muninn-media"); - assert_eq!(options.connection_id, MUNINN_MEDIA_RUDP_CONNECTION_ID); - assert_eq!(options.resend_delay_ms, MUNINN_RUDP_MEDIA_RESEND_DELAY_MS); - assert_eq!( - options.max_fragment_bytes, - Some(MUNINN_RUDP_MEDIA_MAX_FRAGMENT_BYTES as u32) - ); - let hub = CultNetRudpServerHub::new(options).unwrap(); - let channels = hub.profile.transports.first().unwrap().channels.clone(); - let channel = |id: &str| { - channels - .iter() - .find(|channel| channel.channel_id == id) - .unwrap() - .clone() - }; - assert_eq!( - channel("media").delivery, - cultnet_rs::CultNetTransportDelivery::Unreliable - ); - assert_eq!( - channel("audio").delivery, - cultnet_rs::CultNetTransportDelivery::Reliable - ); - assert_eq!( - channel("audio").reliable_expire_after_ms, - Some(policy.latency_budget_ms()), - "audio older than the receiver's deadline is not worth a retransmit" - ); - } - - #[test] - fn rudp_audio_encoder_outputs_pcm_for_packetizer() { - let options = Options::parse( - [ - "activate", - "--media-transport", - "rudp", - "--audio-sample-rate", - "48000", - "--audio-channels", - "2", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - - let args = rudp_audio_ffmpeg_args(&options); - - assert!( - args.windows(2) - .any(|pair| pair[0] == "-f" && pair[1] == "f32le") - ); - assert!( - args.windows(2) - .any(|pair| pair[0] == "-vn" && pair[1] == "-ar") - ); - assert_eq!(args.last().map(String::as_str), Some("pipe:1")); - } - - fn options_with_latency_budget(budget_ms: &str) -> Options { - Options::parse( - [ - "activate", - "--media-transport", - "rudp", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - "--framerate", - "30", - "--audio-sample-rate", - "48000", - "--rudp-latency-budget-ms", - budget_ms, - ] - .into_iter() - .map(String::from), - ) - .unwrap() - } - - #[test] - fn the_requests_latency_budget_owns_queue_hub_expiry_and_record_deadlines() { - // Two budgets, both different from the default and from each other, so - // a clamp, an offset or a fallback to the default is visible at one of - // them. - for (budget_ms, video_ticks, audio_ticks) in [(137_u32, 12_330_i64, 6_576_i64), (613, 55_170, 29_424)] - { - let options = options_with_latency_budget(&budget_ms.to_string()); - let policy = MediaSendPolicy::from_request(options.rudp_latency_budget_ms); - let produced_at = Instant::now(); - let group = QueuedMediaGroup::new(MediaKind::Video, produced_at, &policy, Vec::new()); - - assert_eq!( - group.deadline - produced_at, - Duration::from_millis(u64::from(budget_ms)) - ); - assert_eq!(policy.video_deadline_delay_ticks(), video_ticks); - assert_eq!( - policy.audio_deadline_delay_ticks(options.audio_sample_rate), - audio_ticks - ); - let hub_options = muninn_media_rudp_hub_options( - UdpSocket::bind("127.0.0.1:0").unwrap(), - &muninn_rudp_media_profile_for_options(&options), - &policy, - ); - assert_eq!( - hub_options.media_reliable_expire_after_ms, - Some(u64::from(budget_ms)) - ); - } - assert_eq!( - rudp_endpoint_for_options(&options_with_latency_budget("137")), - "cultmesh://odin/media/muninn-raven-av#muninn.raven.av.rudp" - ); - } - - #[test] - fn a_request_naming_no_latency_budget_gets_250_ms_and_the_advertisement_says_so() { - assert_eq!(MUNINN_RUDP_MEDIA_DEFAULT_LATENCY_BUDGET_MS, 250); - let options = Options::parse([].into_iter()).unwrap(); - assert_eq!(options.rudp_latency_budget_ms, 250); - let advertised = Options::parse( - ["serve", "--media-rudp-advertise", "127.0.0.1:5220"] - .into_iter() - .map(String::from), - ) - .unwrap(); - let advertisement = media_stream_advertisement(&advertised, false).unwrap(); - assert_eq!(advertisement.default_latency_budget_ms, 250); - - let mut request = media_stream_request(); - request.latency_budget_ms = 0; - let command = command_from_media_stream_request(&options, &request).unwrap(); - assert_eq!(command_rudp_latency_budget_ms(&command), 250); - request.latency_budget_ms = 40; - let command = command_from_media_stream_request(&options, &request).unwrap(); - assert_eq!(command_rudp_latency_budget_ms(&command), 40); - } - - #[test] - fn a_latency_budget_above_the_maximum_is_2000_ms_wherever_it_is_read() { - // The request: the command reads back the clamped budget, and - // it is the same stream as a request that asked for 2000. - let options = Options::parse(["serve"].into_iter().map(String::from)).unwrap(); - let mut request = media_stream_request(); - request.latency_budget_ms = 5_000; - let command = command_from_media_stream_request(&options, &request).unwrap(); - assert_eq!(command_rudp_latency_budget_ms(&command), 2_000); - request.latency_budget_ms = 2_000; - let at_maximum = command_from_media_stream_request(&options, &request).unwrap(); - assert!(capture_stream_commands_start_equivalent(&command, &at_maximum)); - - // The command line an activation is spawned with parses to the same - // clamped value, and so does a raw 5000 typed by an operator. - let store_path = - std::env::temp_dir().join(format!("muninn-clamp-{}.cc", timestamp_ns().unwrap())); - let options = Options::parse( - [ - "serve", - "--store", - store_path.to_str().unwrap(), - "--media-rudp-advertise", - "127.0.0.1:5220", - "--rudp-latency-budget-ms", - "5000", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - assert_eq!(options.rudp_latency_budget_ms, 2_000); - - // Advertised. - let advertisement = media_stream_advertisement(&options, false).unwrap(); - assert_eq!(advertisement.default_latency_budget_ms, 2_000); - - // Reported. - let mut node = open_node(&options, "muninn-clamp-test").unwrap(); - publish_runtime_boundary_records(&mut node, &options, "idle", &[], &[]).unwrap(); - let transport = node - .get_required::("transport-profile:muninn") - .unwrap(); - assert_eq!( - transport.value["media_profile"]["latency_budget_ms"].as_u64(), - Some(2_000) - ); - } - - #[test] - fn idle_surface_advertises_affordances_without_active_streams() { - let options = Options::parse([].into_iter()).unwrap(); - let sources = available_sources(&options); - - assert!(sources.iter().any(|source| source.starts_with("screen:"))); - assert!( - sources - .iter() - .any(|source| source.starts_with("audio-loopback:")) - ); - } - #[test] fn move_hue_program_command_updates_typed_live_state() { let store_path = std::env::temp_dir().join(format!( @@ -11597,144 +7532,6 @@ mod tests { assert_eq!(options.command_id.as_deref(), Some("cmd-1")); } - #[test] - fn capture_stream_status_accepts_stream_and_command_filters() { - let options = Options::parse( - [ - "capture-stream-status", - "--host", - "raven", - "--stream", - "muninn.probe.video.rudp", - "--command", - "cmd-1", - "--activate-store", - "C:/Meta/Odin/state/muninn.activate.cc", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - - assert_eq!(options.mode, Mode::CaptureStreamStatus); - assert_eq!(options.host_id, "raven"); - assert_eq!(options.stream_id, "muninn.probe.video.rudp"); - assert!(options.stream_filter_explicit); - assert_eq!(options.command_id.as_deref(), Some("cmd-1")); - assert_eq!( - options.activation_store_path, - Some(PathBuf::from("C:/Meta/Odin/state/muninn.activate.cc")) - ); - } - - #[test] - fn capture_stream_status_uses_default_activation_store_path() { - let options = Options::parse( - ["capture-stream-status", "--host", "raven"] - .into_iter() - .map(String::from), - ) - .unwrap(); - - assert_eq!( - options.activation_store_path, - Some(PathBuf::from(MUNINN_DEFAULT_ACTIVATION_STORE_PATH)) - ); - } - - #[test] - fn capture_stream_status_does_not_filter_on_default_stream_id() { - let options = Options::parse( - ["capture-stream-status", "--host", "raven"] - .into_iter() - .map(String::from), - ) - .unwrap(); - - assert_eq!(options.mode, Mode::CaptureStreamStatus); - assert_eq!(options.host_id, "raven"); - assert_eq!(options.stream_id, "muninn.raven.av.rudp"); - assert!(!options.stream_filter_explicit); - } - - #[test] - fn tick_capture_stream_commands_supersedes_older_nonterminal_receipts() { - let store_path = std::env::temp_dir().join(format!( - "muninn-capture-command-supersede-{}.cc", - timestamp_ns().unwrap() - )); - let options = Options::parse( - [ - "serve", - "--host", - "raven", - "--store", - store_path.to_str().unwrap(), - "--activate-store", - store_path.to_str().unwrap(), - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - let mut older = build_capture_stream_command( - &Options::parse( - [ - "request-stream", - "--host", - "raven", - "--stream", - "muninn.probe.video.rudp", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - ] - .into_iter() - .map(String::from), - ) - .unwrap(), - ) - .unwrap(); - older.command_id = "older-command".to_string(); - older.updated_at = "unix-1000".to_string(); - older.state = "pending".to_string(); - - let mut newer = older.clone(); - newer.command_id = "newer-command".to_string(); - newer.updated_at = "unix-2000".to_string(); - newer.state = "completed".to_string(); - newer.detail = "already handled elsewhere".to_string(); - - let mut node = open_node(&options, "muninn-capture-command-supersede-test").unwrap(); - node.put(&older.command_id, &older).unwrap(); - node.put(&newer.command_id, &newer).unwrap(); - drop(node); - - let active = &mut Vec::new(); - let active_stream_ids = tick_capture_stream_commands(&options, active).unwrap(); - - assert!(active_stream_ids.is_empty()); - - let node = open_node(&options, "muninn-capture-command-supersede-status").unwrap(); - let superseded = node - .get_required::("older-command") - .unwrap(); - let latest = node - .get_required::("newer-command") - .unwrap(); - assert_eq!(superseded.state, "completed"); - assert_eq!( - superseded.detail, - "Superseded by newer command newer-command." - ); - assert_eq!(latest.state, "completed"); - assert_eq!(latest.detail, "already handled elsewhere"); - assert_eq!( - superseded.updated_at, "unix-1000", - "superseding keeps the dead command's own stamp; re-stamping it would let it outrank its successor" - ); - let _ = fs::remove_file(store_path); - } - #[test] fn move_state_status_accepts_move_filter() { let options = Options::parse( @@ -12217,329 +8014,6 @@ Device 00:07:04:A8:00:D0 (public) assert!(!help_text().contains("daemon health")); } - #[test] - fn runtime_boundary_names_each_host_daemon_and_its_transport() { - for (host, daemon_id) in [ - ("raven", "muninn"), - ("starfire", "starfire-muninn"), - ("nightwing", "nightwing-muninn"), - ] { - let store_path = std::env::temp_dir().join(format!( - "muninn-boundary-{host}-{}.cc", - timestamp_ns().unwrap() - )); - let options = Options::parse( - ["serve", "--host", host, "--store", store_path.to_str().unwrap()] - .into_iter() - .map(String::from), - ) - .unwrap(); - let mut node = open_node(&options, "muninn-boundary-host-test").unwrap(); - - publish_runtime_boundary_records(&mut node, &options, "idle", &[], &[]).unwrap(); - - let boundary = node - .get_required::(&format!( - "command-boundary:{daemon_id}" - )) - .unwrap(); - let transport = node - .get_required::(&format!( - "transport-profile:{daemon_id}" - )) - .unwrap(); - for record in [&boundary.value, &transport.value] { - assert_eq!( - record.get("daemon_id").and_then(|value| value.as_str()), - Some(daemon_id), - "{host}" - ); - } - assert_eq!( - transport.value.get("current_transport").and_then(|value| value.as_str()), - Some("daemon-owned-cultcache-telemetry-store"), - "{host}" - ); - assert_eq!( - transport.value.get("state").and_then(|value| value.as_str()), - Some("cultcache-provider-store-only"), - "{host}" - ); - let _ = fs::remove_file(store_path); - } - } - - #[test] - fn runtime_boundary_records_use_explicit_activation_store_path() { - let store_path = - std::env::temp_dir().join(format!("muninn-boundary-{}.cc", timestamp_ns().unwrap())); - let options = Options::parse( - [ - "serve", - "--host", - "raven", - "--store", - store_path.to_str().unwrap(), - "--activate-store", - "C:/Meta/Odin/state/muninn.activate.cc", - "--target-host", - "cultmesh://odin/media/muninn-raven-av", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - let mut node = open_node(&options, "muninn-boundary-test").unwrap(); - - publish_runtime_boundary_records(&mut node, &options, "idle", &[], &[]).unwrap(); - - let boundary = node - .get_required::("command-boundary:muninn") - .unwrap(); - let transport = node - .get_required::("transport-profile:muninn") - .unwrap(); - let provider = node - .get_required::("muninn.telemetry.raven") - .unwrap(); - - let invocation = boundary - .value - .get("commands") - .and_then(|commands| commands.as_array()) - .and_then(|commands| commands.first()) - .and_then(|command| command.get("invocation")) - .and_then(|value| value.as_str()) - .unwrap(); - assert!(invocation.contains("C:/Meta/Odin/state/muninn.activate.cc")); - assert!(invocation.contains(store_path.to_str().unwrap())); - assert!(invocation.contains("request-stream")); - assert!(invocation.contains("--target-host cultmesh://odin/media/muninn-raven-av")); - - assert_eq!( - boundary.value.get("daemon_id").and_then(|value| value.as_str()), - Some("muninn") - ); - assert!(boundary.value.get("health_publication").is_none()); - assert!(transport.value.get("health_contract").is_some_and(|value| value.is_null())); - - let command_lowerings = transport - .value - .get("command_lowerings") - .and_then(|value| value.as_array()) - .unwrap(); - assert!(command_lowerings.iter().any(|value| { - value - .as_str() - .is_some_and(|entry| entry.contains("C:/Meta/Odin/state/muninn.activate.cc")) - })); - - let media_profile = transport - .value - .get("media_profile") - .and_then(|value| value.as_object()) - .unwrap(); - assert_eq!( - media_profile - .get("profile_id") - .and_then(|value| value.as_str()), - Some(MUNINN_RUDP_MEDIA_PROFILE_ID) - ); - assert_eq!( - media_profile - .get("strategy") - .and_then(|value| value.as_str()), - Some("hardware-codec-owned-prediction-over-fixed-budget-rudp") - ); - assert_eq!( - media_profile - .get("visual_prediction_owner") - .and_then(|value| value.as_str()), - Some("NVENC H.264 inter-frame prediction") - ); - assert_eq!( - media_profile - .get("transport_owner") - .and_then(|value| value.as_str()), - Some("CultNet RUDP media channel") - ); - assert_eq!( - media_profile - .get("video_rate_control") - .and_then(|value| value.as_str()), - Some("cbr") - ); - assert_eq!( - media_profile - .get("video_rc_lookahead") - .and_then(|value| value.as_u64()), - Some(0) - ); - assert_eq!( - media_profile - .get("video_bitrate") - .and_then(|value| value.as_str()), - Some("12000k") - ); - assert_eq!( - media_profile - .get("video_bufsize") - .and_then(|value| value.as_str()), - Some("400k") - ); - assert_eq!( - media_profile - .get("video_low_delay_key_frame_scale") - .and_then(|value| value.as_u64()), - Some(MUNINN_RUDP_MEDIA_LOW_DELAY_KEY_FRAME_SCALE as u64) - ); - assert_eq!( - media_profile - .get("media_packet_bytes") - .and_then(|value| value.as_u64()), - Some(MUNINN_RUDP_MEDIA_PACKET_BYTES as u64) - ); - assert_eq!( - media_profile - .get("max_fragment_bytes") - .and_then(|value| value.as_u64()), - Some(MUNINN_RUDP_MEDIA_MAX_FRAGMENT_BYTES as u64) - ); - assert_eq!( - media_profile - .get("receiver_gap_wait_ms") - .and_then(|value| value.as_u64()), - Some(MUNINN_RUDP_MEDIA_RECEIVER_GAP_WAIT_MS) - ); - assert_eq!( - media_profile - .get("latency_budget_ms") - .and_then(|value| value.as_u64()), - Some(MUNINN_RUDP_MEDIA_DEFAULT_LATENCY_BUDGET_MS) - ); - for retired in [ - "sender_queue_deadline_ms", - "sender_reliable_expire_after_ms", - "receiver_assembly_deadline_ms", - ] { - assert!( - media_profile.get(retired).is_none(), - "{retired} was a second name for the request budget" - ); - } - assert_eq!( - media_profile - .get("sender_resend_delay_ms") - .and_then(|value| value.as_u64()), - Some(MUNINN_RUDP_MEDIA_RESEND_DELAY_MS) - ); - assert_eq!( - media_profile - .get("late_media_policy") - .and_then(|value| value.as_str()), - Some("drop expired queued media; do not repair frames outside the latency budget") - ); - - let routes = provider - .value - .get("routes") - .and_then(|value| value.as_array()) - .unwrap(); - assert!(!routes.iter().any(|route| { - route - .get("address") - .and_then(|value| value.as_str()) - .is_some_and(|entry| entry.contains("C:/Meta/Odin/state/muninn.activate.cc")) - })); - let _ = fs::remove_file(store_path); - } - - #[test] - fn runtime_boundary_advertises_hid_and_move_evidence_streams() { - let store_path = std::env::temp_dir().join(format!( - "muninn-boundary-hid-sources-{}.cc", - timestamp_ns().unwrap() - )); - let options = Options::parse( - [ - "serve", - "--host", - "starfire", - "--store", - store_path.to_str().unwrap(), - "--move-evidence-stream", - "muninn:nightwing:move-evidence", - "--hid-controller-rudp-bind", - "0.0.0.0:17888", - "--hid-controller-rudp-advertise", - "198.51.100.66:17888", - "--command-rudp-advertise", - "198.51.100.66:17889", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - let mut node = open_node(&options, "muninn-boundary-hid-sources-test").unwrap(); - let live_sources = vec![MoveStateSource { - move_id: "nav-windows-psnav-0".to_string(), - hidraw_path: "windows-psmove://nav".to_string(), - }]; - - publish_runtime_boundary_records(&mut node, &options, "idle", &[], &live_sources).unwrap(); - - let provider = node - .get_required::("muninn.telemetry.starfire") - .unwrap(); - let streams = provider - .value - .get("inputStreams") - .and_then(|value| value.as_array()) - .unwrap(); - let hid_stream = streams.first().unwrap(); - assert_eq!(streams.len(), 2); - assert_eq!( - hid_stream.get("streamId").and_then(|value| value.as_str()), - Some("muninn:starfire:hid-controller-state") - ); - assert_eq!( - hid_stream.get("address").and_then(|value| value.as_str()), - Some("198.51.100.66:17888") - ); - let devices = hid_stream - .get("devices") - .and_then(|value| value.as_array()) - .unwrap(); - assert_eq!( - devices - .first() - .and_then(|device| device.get("deviceId")) - .and_then(|value| value.as_str()), - Some("nav-windows-psnav-0") - ); - assert_eq!( - devices - .first() - .and_then(|device| device.get("deviceKind")) - .and_then(|value| value.as_str()), - Some("ps3-navigation") - ); - let evidence_stream = &streams[1]; - assert_eq!( - evidence_stream - .get("streamId") - .and_then(|value| value.as_str()), - Some("muninn:nightwing:move-evidence") - ); - assert_eq!( - evidence_stream - .get("channel") - .and_then(|value| value.as_str()), - Some("move-evidence") - ); - let _ = fs::remove_file(store_path); - } - #[test] fn ps3_navigation_hid_report_uses_live_stick_bytes() { let source = MoveStateSource { @@ -12576,55 +8050,6 @@ Device 00:07:04:A8:00:D0 (public) assert_eq!(axes[2], 1.0); } - #[test] - fn runtime_boundary_reports_explicit_rudp_video_bitrate() { - let store_path = std::env::temp_dir().join(format!( - "muninn-boundary-bitrate-{}.cc", - timestamp_ns().unwrap() - )); - let options = Options::parse( - [ - "serve", - "--store", - store_path.to_str().unwrap(), - "--host", - "raven", - "--media-transport", - "rudp", - "--rudp-video-bitrate-kbps", - "8000", - ] - .into_iter() - .map(String::from), - ) - .unwrap(); - let mut node = open_node(&options, "muninn-boundary-bitrate-test").unwrap(); - - publish_runtime_boundary_records(&mut node, &options, "idle", &[], &[]).unwrap(); - - let transport = node - .get_required::("transport-profile:muninn") - .unwrap(); - let media_profile = transport - .value - .get("media_profile") - .and_then(|value| value.as_object()) - .unwrap(); - assert_eq!( - media_profile - .get("video_bitrate") - .and_then(|value| value.as_str()), - Some("8000k") - ); - assert_eq!( - media_profile - .get("video_bufsize") - .and_then(|value| value.as_str()), - Some("267k") - ); - let _ = fs::remove_file(store_path); - } - #[test] fn move_identity_status_reads_reopened_store() { let store_path = std::env::temp_dir().join(format!( diff --git a/crates/muninn-daemon/src/media_packetizer.rs b/crates/muninn-daemon/src/media_packetizer.rs deleted file mode 100644 index 3462d05..0000000 --- a/crates/muninn-daemon/src/media_packetizer.rs +++ /dev/null @@ -1,2345 +0,0 @@ -use anyhow::{Context, Result, anyhow}; -use cultnet_rs::{ - GameCultMediaAudioPacketRecord, GameCultMediaVideoAccessUnitRecord, - GameCultMediaVideoParityShardRecord, -}; -use std::collections::BTreeMap; - -/// Re-exported so this module stays the one place Muninn's media code imports -/// from, while the definitions live in CultLib where the consumer can reach -/// them too. -pub use cultnet_rs::{ - GAMECULT_MEDIA_AUDIO_CHANNEL as MUNINN_AUDIO_RUDP_CHANNEL, - GAMECULT_MEDIA_CHANNEL as MUNINN_MEDIA_RUDP_CHANNEL, GameCultMediaWireRecord, - MediaWireProvenance, decode_media_wire_record, encode_media_wire_record, - validate_video_record, video_chunk_feedback_key, -}; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct VideoAccessUnit { - pub bytes: Vec, - pub keyframe: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct NalUnit<'a> { - start: usize, - end: usize, - payload: &'a [u8], - nal_type: u8, -} - -pub fn video_annex_b_access_units(codec: &str, input: &[u8]) -> Result> { - match normalized_video_codec(codec).as_deref() { - Some("h264") => h264_annex_b_access_units(input), - Some("h265") => h265_annex_b_access_units(input), - Some("av1") => Err(anyhow!( - "AV1 access unit splitting is not Annex B; provide an AV1 OBU packetizer" - )), - _ => Err(anyhow!("unsupported Annex B video codec {codec}")), - } -} - -pub fn h264_annex_b_access_units(input: &[u8]) -> Result> { - let nal_units = annex_b_nal_units(input, "H.264", h264_nal_type)?; - let mut access_units = Vec::new(); - let mut current_start = None; - let mut current_end = 0_usize; - let mut current_has_vcl = false; - let mut current_keyframe = false; - - for nal in nal_units { - let starts_new = if nal.nal_type == 9 { - current_start.is_some() - } else if is_h264_vcl_nal(nal.nal_type) { - current_has_vcl && h264_first_mb_in_slice(nal.payload).unwrap_or(1) == 0 - } else { - false - }; - - if starts_new { - if let Some(start) = current_start { - access_units.push(VideoAccessUnit { - bytes: input[start..current_end].to_vec(), - keyframe: current_keyframe, - }); - } - current_start = None; - current_has_vcl = false; - current_keyframe = false; - } - - if current_start.is_none() { - current_start = Some(nal.start); - } - current_end = nal.end; - if is_h264_vcl_nal(nal.nal_type) { - current_has_vcl = true; - } - if nal.nal_type == 5 { - current_keyframe = true; - } - } - - if let Some(start) = current_start { - access_units.push(VideoAccessUnit { - bytes: input[start..current_end].to_vec(), - keyframe: current_keyframe, - }); - } - - Ok(access_units) -} - -pub fn h265_annex_b_access_units(input: &[u8]) -> Result> { - let nal_units = annex_b_nal_units(input, "H.265", h265_nal_type)?; - let mut access_units = Vec::new(); - let mut current_start = None; - let mut current_end = 0_usize; - let mut current_has_vcl = false; - let mut current_keyframe = false; - - for nal in nal_units { - let starts_new = if nal.nal_type == 35 { - current_start.is_some() - } else if is_h265_vcl_nal(nal.nal_type) { - current_has_vcl && h265_first_slice_segment_in_pic(nal.payload).unwrap_or(false) - } else { - current_has_vcl && is_h265_pre_vcl_boundary_nal(nal.nal_type) - }; - - if starts_new { - if let Some(start) = current_start { - access_units.push(VideoAccessUnit { - bytes: input[start..current_end].to_vec(), - keyframe: current_keyframe, - }); - } - current_start = None; - current_has_vcl = false; - current_keyframe = false; - } - - if current_start.is_none() { - current_start = Some(nal.start); - } - current_end = nal.end; - if is_h265_vcl_nal(nal.nal_type) { - current_has_vcl = true; - } - if is_h265_irap_nal(nal.nal_type) { - current_keyframe = true; - } - } - - if let Some(start) = current_start { - access_units.push(VideoAccessUnit { - bytes: input[start..current_end].to_vec(), - keyframe: current_keyframe, - }); - } - - Ok(access_units) -} - -pub struct VideoFramePacketizeOptions<'a> { - pub stream_id: &'a str, - pub session_id: &'a str, - pub codec: &'a str, - pub frame_id: u64, - pub pts_ticks: i64, - pub duration_ticks: u32, - pub timebase_num: u32, - pub timebase_den: u32, - pub deadline_ticks: i64, - pub max_payload_bytes: usize, -} - -pub struct VideoAnnexBStreamSendConfig { - pub stream_id: String, - pub session_id: String, - pub codec: String, - pub first_frame_id: u64, - pub first_pts_ticks: i64, - pub frame_duration_ticks: u32, - pub timebase_num: u32, - pub timebase_den: u32, - pub deadline_delay_ticks: i64, - pub max_payload_bytes: usize, - pub max_pending_bytes: usize, - pub source_runtime_id: String, - pub source_role: String, -} - -pub struct AudioPacketizeOptions<'a> { - pub stream_id: &'a str, - pub session_id: &'a str, - pub codec: &'a str, - pub packet_id: u64, - pub pts_ticks: i64, - pub duration_ticks: u32, - pub timebase_num: u32, - pub timebase_den: u32, - pub deadline_ticks: i64, -} - -pub struct AudioPacketWireOptions<'a> { - pub packetize: AudioPacketizeOptions<'a>, - pub stored_at: &'a str, - pub source_runtime_id: &'a str, - pub source_role: &'a str, -} - -pub struct AudioPcmStreamSendConfig { - pub stream_id: String, - pub session_id: String, - pub codec: String, - pub first_packet_id: u64, - pub first_pts_ticks: i64, - pub packet_duration_ticks: u32, - pub timebase_num: u32, - pub timebase_den: u32, - pub deadline_delay_ticks: i64, - pub channels: u32, - pub bytes_per_sample: u32, - pub max_pending_bytes: usize, - pub source_runtime_id: String, - pub source_role: String, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MuninnMediaSendPayload { - pub channel_id: &'static str, - pub payload: Vec, -} - -/// Everything one video access unit puts on the wire: its chunks and, until -/// the FEC cut replaces it, their parity. A group is sent whole or not at -/// all, because parity for a frame that never completes is wasted bandwidth. -pub type MuninnMediaPayloadGroup = Vec; - -pub struct VideoAnnexBStreamSendState { - config: VideoAnnexBStreamSendConfig, - pending: Vec, - next_frame_id: u64, - next_pts_ticks: i64, - dropped_access_units: u64, - /// Set by an overflow drop: the slices that follow belong to the dropped - /// access unit and are discarded up to the next access-unit boundary. - discarding_tail: bool, -} - -impl VideoAnnexBStreamSendState { - pub fn new(config: VideoAnnexBStreamSendConfig) -> Result { - if matches!(normalized_video_codec(&config.codec), None | Some("av1")) { - return Err(anyhow!( - "Annex B stream sender requires H.264/AVC or H.265/HEVC codec" - )); - } - if config.stream_id.is_empty() { - return Err(anyhow!("stream_id must be non-empty")); - } - if config.session_id.is_empty() { - return Err(anyhow!("session_id must be non-empty")); - } - if config.frame_duration_ticks == 0 { - return Err(anyhow!("frame_duration_ticks must be greater than zero")); - } - if config.timebase_num == 0 || config.timebase_den == 0 { - return Err(anyhow!("video timebase must be non-zero")); - } - if config.deadline_delay_ticks < 0 { - return Err(anyhow!("deadline_delay_ticks must be non-negative")); - } - if config.max_payload_bytes == 0 { - return Err(anyhow!("max_payload_bytes must be greater than zero")); - } - if config.max_pending_bytes == 0 { - return Err(anyhow!("max_pending_bytes must be greater than zero")); - } - if config.source_runtime_id.is_empty() { - return Err(anyhow!("source_runtime_id must be non-empty")); - } - if config.source_role.is_empty() { - return Err(anyhow!("source_role must be non-empty")); - } - - Ok(Self { - next_frame_id: config.first_frame_id, - next_pts_ticks: config.first_pts_ticks, - config, - pending: Vec::new(), - dropped_access_units: 0, - discarding_tail: false, - }) - } - - /// One group per completed access unit. Whatever is still pending after - /// that is a single unfinished access unit; when it outgrows - /// `max_pending_bytes` it is dropped and counted, never an error that - /// would restart the stream. The dropped unit consumes its frame id, so a - /// receiver sees the gap, and its remaining slices are discarded up to the - /// next access-unit boundary instead of being emitted as a frame of their - /// own. - pub fn push(&mut self, stored_at: &str, bytes: &[u8]) -> Result> { - if !bytes.is_empty() { - self.pending.extend_from_slice(bytes); - } - let groups = self.emit_available(stored_at, false)?; - if self.pending.len() > self.config.max_pending_bytes { - self.pending.clear(); - if !self.discarding_tail { - self.dropped_access_units += 1; - self.advance_frame_clock()?; - self.discarding_tail = true; - } - } - Ok(groups) - } - - pub fn finish(&mut self, stored_at: &str) -> Result> { - self.emit_available(stored_at, true) - } - - /// Access units dropped for outgrowing `max_pending_bytes`, cumulative. - pub fn dropped_access_units(&self) -> u64 { - self.dropped_access_units - } - - pub fn pending_bytes(&self) -> usize { - self.pending.len() - } - - pub fn next_frame_id(&self) -> u64 { - self.next_frame_id - } - - fn emit_available( - &mut self, - stored_at: &str, - flush_last: bool, - ) -> Result> { - if stored_at.is_empty() { - return Err(anyhow!("stored_at must be non-empty")); - } - // After a drop the tail of the dropped access unit arrives with no - // start code in front of it; skip to the next one. - if let Some((start, _)) = find_annex_b_start_code(&self.pending, 0) - && start > 0 - { - self.pending.drain(..start); - } - if self.pending.is_empty() { - return Ok(Vec::new()); - } - if self.discarding_tail && !self.discard_leftover_slices(flush_last)? { - return Ok(Vec::new()); - } - if self.pending.is_empty() { - return Ok(Vec::new()); - } - - let access_units = match video_annex_b_access_units(&self.config.codec, &self.pending) { - Ok(access_units) => access_units, - Err(error) - if error.to_string().contains("has no start codes") - || error.to_string().contains("has no NAL payloads") => - { - return Ok(Vec::new()); - } - Err(error) => return Err(error), - }; - let emit_count = if flush_last { - access_units.len() - } else { - access_units.len().saturating_sub(1) - }; - if emit_count == 0 { - return Ok(Vec::new()); - } - - let mut groups = Vec::with_capacity(emit_count); - let mut emitted_bytes = 0_usize; - for access_unit in access_units.iter().take(emit_count) { - emitted_bytes = emitted_bytes - .checked_add(access_unit.bytes.len()) - .ok_or_else(|| anyhow!("emitted Annex B byte count overflow"))?; - let deadline_ticks = self - .next_pts_ticks - .checked_add(self.config.deadline_delay_ticks) - .ok_or_else(|| anyhow!("video deadline_ticks overflow"))?; - let records = packetize_video_access_unit( - VideoFramePacketizeOptions { - stream_id: &self.config.stream_id, - session_id: &self.config.session_id, - codec: &self.config.codec, - frame_id: self.next_frame_id, - pts_ticks: self.next_pts_ticks, - duration_ticks: self.config.frame_duration_ticks, - timebase_num: self.config.timebase_num, - timebase_den: self.config.timebase_den, - deadline_ticks, - max_payload_bytes: self.config.max_payload_bytes, - }, - access_unit, - )?; - let wire_records = video_wire_records_with_parity(&records)?; - groups.push(wire_payloads_to_media_send(encode_media_wire_records( - &wire_records, - stored_at, - &self.config.source_runtime_id, - &self.config.source_role, - )?)); - self.advance_frame_clock()?; - } - - self.pending.drain(..emitted_bytes); - Ok(groups) - } - - /// While the tail of a dropped access unit is being discarded: if the - /// pending bytes open with a continuation slice, drops that leftover access - /// unit (up to the next boundary) and stops discarding; if they open on a - /// boundary, stops discarding and leaves them alone. `false` means it - /// cannot tell yet (the leftover is not complete) and the caller must wait - /// for more bytes. - fn discard_leftover_slices(&mut self, flush_last: bool) -> Result { - let codec = self.config.codec.as_str(); - let nal_units = match normalized_video_codec(codec) { - Some("h265") => annex_b_nal_units(&self.pending, "H.265", h265_nal_type), - _ => annex_b_nal_units(&self.pending, "H.264", h264_nal_type), - }; - let Ok(nal_units) = nal_units else { - return Ok(false); - }; - let first = &nal_units[0]; - let continuation = match normalized_video_codec(codec) { - Some("h265") => { - is_h265_vcl_nal(first.nal_type) - && !h265_first_slice_segment_in_pic(first.payload).unwrap_or(false) - } - _ => { - is_h264_vcl_nal(first.nal_type) - && h264_first_mb_in_slice(first.payload).unwrap_or(1) != 0 - } - }; - if !continuation { - self.discarding_tail = false; - return Ok(true); - } - let access_units = video_annex_b_access_units(codec, &self.pending)?; - if access_units.len() >= 2 { - self.pending.drain(..access_units[0].bytes.len()); - } else if flush_last { - self.pending.clear(); - } else { - return Ok(false); - } - self.discarding_tail = false; - Ok(true) - } - - fn advance_frame_clock(&mut self) -> Result<()> { - self.next_frame_id = self - .next_frame_id - .checked_add(1) - .ok_or_else(|| anyhow!("video frame_id overflow"))?; - self.next_pts_ticks = self - .next_pts_ticks - .checked_add(i64::from(self.config.frame_duration_ticks)) - .ok_or_else(|| anyhow!("video pts_ticks overflow"))?; - Ok(()) - } -} - -pub struct AudioPcmStreamSendState { - config: AudioPcmStreamSendConfig, - pending: Vec, - next_packet_id: u64, - next_pts_ticks: i64, -} - -impl AudioPcmStreamSendState { - pub fn new(config: AudioPcmStreamSendConfig) -> Result { - if config.stream_id.is_empty() { - return Err(anyhow!("stream_id must be non-empty")); - } - if config.session_id.is_empty() { - return Err(anyhow!("session_id must be non-empty")); - } - if config.codec.is_empty() { - return Err(anyhow!("codec must be non-empty")); - } - if config.packet_duration_ticks == 0 { - return Err(anyhow!("packet_duration_ticks must be greater than zero")); - } - if config.timebase_num == 0 || config.timebase_den == 0 { - return Err(anyhow!("audio timebase must be non-zero")); - } - if config.deadline_delay_ticks < 0 { - return Err(anyhow!("deadline_delay_ticks must be non-negative")); - } - if config.channels == 0 { - return Err(anyhow!("audio channels must be non-zero")); - } - if config.bytes_per_sample == 0 { - return Err(anyhow!("audio bytes_per_sample must be non-zero")); - } - if config.max_pending_bytes == 0 { - return Err(anyhow!("max_pending_bytes must be greater than zero")); - } - if config.source_runtime_id.is_empty() { - return Err(anyhow!("source_runtime_id must be non-empty")); - } - if config.source_role.is_empty() { - return Err(anyhow!("source_role must be non-empty")); - } - - Ok(Self { - next_packet_id: config.first_packet_id, - next_pts_ticks: config.first_pts_ticks, - config, - pending: Vec::new(), - }) - } - - pub fn push(&mut self, stored_at: &str, bytes: &[u8]) -> Result> { - if !bytes.is_empty() { - self.pending.extend_from_slice(bytes); - } - if self.pending.len() > self.config.max_pending_bytes { - return Err(anyhow!( - "PCM stream sender pending buffer exceeded {} bytes without a complete packet", - self.config.max_pending_bytes - )); - } - self.emit_available(stored_at) - } - - pub fn finish(&mut self, stored_at: &str) -> Result> { - let payloads = self.emit_available(stored_at)?; - if !self.pending.is_empty() { - return Err(anyhow!( - "PCM stream sender finished with {} trailing bytes", - self.pending.len() - )); - } - Ok(payloads) - } - - fn emit_available(&mut self, stored_at: &str) -> Result> { - if stored_at.is_empty() { - return Err(anyhow!("stored_at must be non-empty")); - } - - let bytes_per_frame = usize::try_from(self.config.channels) - .ok() - .and_then(|channels| { - usize::try_from(self.config.bytes_per_sample) - .ok() - .map(|bytes_per_sample| channels.saturating_mul(bytes_per_sample)) - }) - .ok_or_else(|| anyhow!("PCM stream sender bytes_per_frame overflow"))?; - let bytes_per_packet = bytes_per_frame - .checked_mul(self.config.packet_duration_ticks as usize) - .ok_or_else(|| anyhow!("PCM stream sender bytes_per_packet overflow"))?; - if bytes_per_packet == 0 { - return Err(anyhow!( - "PCM stream sender bytes_per_packet must be non-zero" - )); - } - let complete_packets = self.pending.len() / bytes_per_packet; - if complete_packets == 0 { - return Ok(Vec::new()); - } - - let mut payloads = Vec::with_capacity(complete_packets); - for packet_index in 0..complete_packets { - let start = packet_index * bytes_per_packet; - let end = start + bytes_per_packet; - let deadline_ticks = self - .next_pts_ticks - .checked_add(self.config.deadline_delay_ticks) - .ok_or_else(|| anyhow!("audio deadline_ticks overflow"))?; - payloads.push(audio_packet_send_payload( - AudioPacketWireOptions { - packetize: AudioPacketizeOptions { - stream_id: &self.config.stream_id, - session_id: &self.config.session_id, - codec: &self.config.codec, - packet_id: self.next_packet_id, - pts_ticks: self.next_pts_ticks, - duration_ticks: self.config.packet_duration_ticks, - timebase_num: self.config.timebase_num, - timebase_den: self.config.timebase_den, - deadline_ticks, - }, - stored_at, - source_runtime_id: &self.config.source_runtime_id, - source_role: &self.config.source_role, - }, - &self.pending[start..end], - )?); - self.advance_packet_clock()?; - } - - self.pending.drain(..complete_packets * bytes_per_packet); - Ok(payloads) - } - - fn advance_packet_clock(&mut self) -> Result<()> { - self.next_packet_id = self - .next_packet_id - .checked_add(1) - .ok_or_else(|| anyhow!("audio packet_id overflow"))?; - self.next_pts_ticks = self - .next_pts_ticks - .checked_add(i64::from(self.config.packet_duration_ticks)) - .ok_or_else(|| anyhow!("audio pts_ticks overflow"))?; - Ok(()) - } -} - -pub fn packetize_video_access_unit( - options: VideoFramePacketizeOptions<'_>, - access_unit: &VideoAccessUnit, -) -> Result> { - if options.stream_id.is_empty() { - return Err(anyhow!("stream_id must be non-empty")); - } - if options.session_id.is_empty() { - return Err(anyhow!("session_id must be non-empty")); - } - if options.codec.is_empty() { - return Err(anyhow!("codec must be non-empty")); - } - if options.timebase_num == 0 || options.timebase_den == 0 { - return Err(anyhow!("video timebase must be non-zero")); - } - if options.duration_ticks == 0 { - return Err(anyhow!("video duration_ticks must be greater than zero")); - } - if options.deadline_ticks < options.pts_ticks { - return Err(anyhow!("video deadline_ticks must not precede pts_ticks")); - } - if options.max_payload_bytes == 0 { - return Err(anyhow!("max_payload_bytes must be greater than zero")); - } - if access_unit.bytes.is_empty() { - return Err(anyhow!("access unit payload must be non-empty")); - } - - let chunk_count = access_unit.bytes.len().div_ceil(options.max_payload_bytes); - if chunk_count > u16::MAX as usize { - return Err(anyhow!("video access unit requires more than 65535 chunks")); - } - - let mut records = Vec::with_capacity(chunk_count); - for (chunk_index, payload) in access_unit - .bytes - .chunks(options.max_payload_bytes) - .enumerate() - { - records.push(GameCultMediaVideoAccessUnitRecord { - stream_id: options.stream_id.to_string(), - session_id: options.session_id.to_string(), - frame_id: options.frame_id, - codec: options.codec.to_string(), - pts_ticks: options.pts_ticks, - duration_ticks: options.duration_ticks, - timebase_num: options.timebase_num, - timebase_den: options.timebase_den, - keyframe: access_unit.keyframe, - dependency_frame_id: if access_unit.keyframe - || !access_unit_references_previous_frame(options.codec, access_unit) - { - None - } else { - options.frame_id.checked_sub(1) - }, - deadline_ticks: options.deadline_ticks, - chunk_index: chunk_index as u16, - chunk_count: chunk_count as u16, - payload: payload.to_vec(), - }); - } - - Ok(records) -} - -const MUNINN_VIDEO_PARITY_STRIPES: u16 = 16; - -pub fn build_video_parity_shards( - chunks: &[GameCultMediaVideoAccessUnitRecord], -) -> Result> { - if chunks.len() <= 1 { - return Ok(Vec::new()); - } - let first = chunks - .first() - .ok_or_else(|| anyhow!("video parity requires at least one chunk"))?; - validate_video_record(first)?; - if chunks.len() != first.chunk_count as usize { - return Err(anyhow!( - "video parity requires all chunks: expected {}, received {}", - first.chunk_count, - chunks.len() - )); - } - - let mut by_index = BTreeMap::new(); - for chunk in chunks { - validate_video_record(chunk)?; - if chunk.stream_id != first.stream_id - || chunk.session_id != first.session_id - || chunk.frame_id != first.frame_id - || chunk.codec != first.codec - || chunk.pts_ticks != first.pts_ticks - || chunk.duration_ticks != first.duration_ticks - || chunk.timebase_num != first.timebase_num - || chunk.timebase_den != first.timebase_den - || chunk.keyframe != first.keyframe - || chunk.dependency_frame_id != first.dependency_frame_id - || chunk.deadline_ticks != first.deadline_ticks - || chunk.chunk_count != first.chunk_count - { - return Err(anyhow!("video parity chunks have mixed metadata")); - } - if by_index.insert(chunk.chunk_index, chunk).is_some() { - return Err(anyhow!( - "video parity received duplicate chunk_index {}", - chunk.chunk_index - )); - } - } - - let mut chunk_payload_len = 0_usize; - let mut last_chunk_payload_bytes = 0_u32; - for index in 0..first.chunk_count { - let chunk = by_index - .get(&index) - .ok_or_else(|| anyhow!("video parity missing chunk_index {index}"))?; - chunk_payload_len = chunk_payload_len.max(chunk.payload.len()); - if index == first.chunk_count - 1 { - last_chunk_payload_bytes = u32::try_from(chunk.payload.len()) - .context("video parity last chunk payload length exceeds u32")?; - } - } - let chunk_payload_bytes = u32::try_from(chunk_payload_len) - .context("video parity chunk payload length exceeds u32")?; - let parity_count = first.chunk_count.min(MUNINN_VIDEO_PARITY_STRIPES); - let mut records = Vec::with_capacity(parity_count as usize); - for parity_index in 0..parity_count { - let mut parity_len = 0_usize; - for index in (parity_index..first.chunk_count).step_by(parity_count as usize) { - let chunk = by_index.get(&index).expect("chunk index was checked above"); - parity_len = parity_len.max(chunk.payload.len()); - } - if parity_len == 0 { - continue; - } - let mut parity = vec![0_u8; parity_len]; - for index in (parity_index..first.chunk_count).step_by(parity_count as usize) { - let chunk = by_index.get(&index).expect("chunk index was checked above"); - for (offset, byte) in chunk.payload.iter().enumerate() { - parity[offset] ^= *byte; - } - } - records.push(GameCultMediaVideoParityShardRecord { - stream_id: first.stream_id.clone(), - session_id: first.session_id.clone(), - frame_id: first.frame_id, - codec: first.codec.clone(), - pts_ticks: first.pts_ticks, - duration_ticks: first.duration_ticks, - timebase_num: first.timebase_num, - timebase_den: first.timebase_den, - keyframe: first.keyframe, - dependency_frame_id: first.dependency_frame_id, - deadline_ticks: first.deadline_ticks, - chunk_count: first.chunk_count, - parity_index, - parity_count, - chunk_payload_bytes, - last_chunk_payload_bytes, - payload: parity, - }); - } - Ok(records) -} - -fn video_wire_records_with_parity( - frame_records: &[GameCultMediaVideoAccessUnitRecord], -) -> Result> { - let mut wire_records: Vec = frame_records - .iter() - .cloned() - .map(GameCultMediaWireRecord::Video) - .collect(); - for parity in build_video_parity_shards(frame_records)? { - wire_records.push(GameCultMediaWireRecord::VideoParity(parity)); - } - Ok(wire_records) -} - -pub fn packetize_audio_packet( - options: AudioPacketizeOptions<'_>, - payload: &[u8], -) -> Result { - if options.stream_id.is_empty() { - return Err(anyhow!("stream_id must be non-empty")); - } - if options.session_id.is_empty() { - return Err(anyhow!("session_id must be non-empty")); - } - if options.codec.is_empty() { - return Err(anyhow!("codec must be non-empty")); - } - if options.timebase_num == 0 || options.timebase_den == 0 { - return Err(anyhow!("audio timebase must be non-zero")); - } - if options.duration_ticks == 0 { - return Err(anyhow!("audio duration_ticks must be greater than zero")); - } - if options.deadline_ticks < options.pts_ticks { - return Err(anyhow!("audio deadline_ticks must not precede pts_ticks")); - } - if payload.is_empty() { - return Err(anyhow!("audio packet payload must be non-empty")); - } - - Ok(GameCultMediaAudioPacketRecord { - stream_id: options.stream_id.to_string(), - session_id: options.session_id.to_string(), - packet_id: options.packet_id, - codec: options.codec.to_string(), - pts_ticks: options.pts_ticks, - duration_ticks: options.duration_ticks, - timebase_num: options.timebase_num, - timebase_den: options.timebase_den, - deadline_ticks: options.deadline_ticks, - payload: payload.to_vec(), - }) -} - -/// Muninn's producer name on the wire. The envelope in CultLib takes this as a -/// parameter so it never has to know any producer; this is where Muninn says -/// who it is, once. -pub const MUNINN_MEDIA_PRODUCER: &str = "muninn"; - -fn muninn_provenance<'a>( - stored_at: &'a str, - source_runtime_id: &'a str, - source_role: &'a str, -) -> MediaWireProvenance<'a> { - MediaWireProvenance { - stored_at, - runtime_id: source_runtime_id, - role: source_role, - producer: MUNINN_MEDIA_PRODUCER, - } -} - -pub fn encode_media_wire_records( - records: &[GameCultMediaWireRecord], - stored_at: &str, - source_runtime_id: &str, - source_role: &str, -) -> Result>> { - let provenance = muninn_provenance(stored_at, source_runtime_id, source_role); - records - .iter() - .map(|record| encode_media_wire_record(record, provenance)) - .collect() -} - -pub fn encode_audio_packet_wire_record( - options: AudioPacketWireOptions<'_>, - payload: &[u8], -) -> Result> { - let record = packetize_audio_packet(options.packetize, payload)?; - encode_media_wire_record( - &GameCultMediaWireRecord::Audio(record), - muninn_provenance( - options.stored_at, - options.source_runtime_id, - options.source_role, - ), - ) -} - -/// Audio rides its own channel so the transport can carry it reliably -/// beside lossy video on one session. -pub fn audio_packet_send_payload( - options: AudioPacketWireOptions<'_>, - payload: &[u8], -) -> Result { - encode_audio_packet_wire_record(options, payload).map(|payload| MuninnMediaSendPayload { - channel_id: MUNINN_AUDIO_RUDP_CHANNEL, - payload, - }) -} - -fn wire_payloads_to_media_send(payloads: Vec>) -> Vec { - payloads - .into_iter() - .map(wire_payload_to_media_send) - .collect() -} - -fn wire_payload_to_media_send(payload: Vec) -> MuninnMediaSendPayload { - MuninnMediaSendPayload { - channel_id: MUNINN_MEDIA_RUDP_CHANNEL, - payload, - } -} - -fn normalized_video_codec(codec: &str) -> Option<&'static str> { - match codec.trim().to_ascii_lowercase().as_str() { - "h264" | "h.264" | "avc" | "avc1" | "video/avc" => Some("h264"), - "h265" | "h.265" | "hevc" | "hev1" | "hvc1" | "video/hevc" => Some("h265"), - "av1" | "av01" | "video/av1" => Some("av1"), - _ => None, - } -} - -fn annex_b_nal_units<'a>( - input: &'a [u8], - codec_name: &str, - nal_type: fn(&[u8]) -> Option, -) -> Result>> { - let mut starts = Vec::new(); - let mut offset = 0_usize; - while let Some((start, prefix_len)) = find_annex_b_start_code(input, offset) { - starts.push((start, prefix_len)); - offset = start + prefix_len; - } - - if starts.is_empty() { - return Err(anyhow!("{codec_name} Annex B stream has no start codes")); - } - - let mut nal_units = Vec::new(); - for index in 0..starts.len() { - let (start, prefix_len) = starts[index]; - let payload_start = start + prefix_len; - let end = starts - .get(index + 1) - .map(|(next_start, _)| *next_start) - .unwrap_or(input.len()); - if payload_start >= end { - continue; - } - let payload = &input[payload_start..end]; - if let Some(nal_type) = nal_type(payload) { - nal_units.push(NalUnit { - start, - end, - payload, - nal_type, - }); - } - } - - if nal_units.is_empty() { - return Err(anyhow!("{codec_name} Annex B stream has no NAL payloads")); - } - - Ok(nal_units) -} - -fn find_annex_b_start_code(input: &[u8], from: usize) -> Option<(usize, usize)> { - let mut index = from; - while index + 3 <= input.len() { - if input[index..].starts_with(&[0, 0, 1]) { - return Some((index, 3)); - } - if index + 4 <= input.len() && input[index..].starts_with(&[0, 0, 0, 1]) { - return Some((index, 4)); - } - index += 1; - } - None -} - -fn is_h264_vcl_nal(nal_type: u8) -> bool { - matches!(nal_type, 1..=5) -} - -fn access_unit_references_previous_frame(codec: &str, access_unit: &VideoAccessUnit) -> bool { - if access_unit.keyframe { - return false; - } - match normalized_video_codec(codec).as_deref() { - Some("h264") => h264_access_unit_has_reference_vcl(&access_unit.bytes).unwrap_or(true), - _ => true, - } -} - -fn h264_access_unit_has_reference_vcl(input: &[u8]) -> Result { - let nal_units = annex_b_nal_units(input, "H.264", h264_nal_type)?; - Ok(nal_units - .iter() - .any(|nal| is_h264_vcl_nal(nal.nal_type) && h264_nal_ref_idc(nal.payload) > 0)) -} - -fn h264_nal_type(payload: &[u8]) -> Option { - payload.first().map(|byte| byte & 0x1f) -} - -fn h264_nal_ref_idc(payload: &[u8]) -> u8 { - payload - .first() - .map(|byte| (byte >> 5) & 0x03) - .unwrap_or_default() -} - -fn h264_first_mb_in_slice(nal_payload: &[u8]) -> Option { - if nal_payload.len() < 2 { - return None; - } - let rbsp = h264_ebsp_to_rbsp(&nal_payload[1..]); - read_unsigned_exp_golomb(&rbsp) -} - -fn is_h265_vcl_nal(nal_type: u8) -> bool { - nal_type <= 31 -} - -fn is_h265_irap_nal(nal_type: u8) -> bool { - matches!(nal_type, 16..=21) -} - -fn is_h265_pre_vcl_boundary_nal(nal_type: u8) -> bool { - matches!(nal_type, 32..=34 | 39 | 40) -} - -fn h265_nal_type(payload: &[u8]) -> Option { - if payload.len() < 2 { - return None; - } - Some((payload[0] >> 1) & 0x3f) -} - -fn h265_first_slice_segment_in_pic(nal_payload: &[u8]) -> Option { - if nal_payload.len() < 3 { - return None; - } - let rbsp = h264_ebsp_to_rbsp(&nal_payload[2..]); - rbsp.first().map(|byte| (byte & 0x80) != 0) -} - -fn h264_ebsp_to_rbsp(payload: &[u8]) -> Vec { - let mut rbsp = Vec::with_capacity(payload.len()); - let mut zero_count = 0_u8; - for &byte in payload { - if zero_count >= 2 && byte == 0x03 { - zero_count = 0; - continue; - } - rbsp.push(byte); - zero_count = if byte == 0 { zero_count + 1 } else { 0 }; - } - rbsp -} - -fn read_unsigned_exp_golomb(payload: &[u8]) -> Option { - let mut reader = BitReader::new(payload); - let mut leading_zero_bits = 0_u32; - while reader.read_bit()? == 0 { - leading_zero_bits += 1; - if leading_zero_bits > 63 { - return None; - } - } - - let mut value = 1_u64; - for _ in 0..leading_zero_bits { - value = (value << 1) | u64::from(reader.read_bit()?); - } - Some(value - 1) -} - -struct BitReader<'a> { - bytes: &'a [u8], - bit_index: usize, -} - -impl<'a> BitReader<'a> { - fn new(bytes: &'a [u8]) -> Self { - Self { - bytes, - bit_index: 0, - } - } - - fn read_bit(&mut self) -> Option { - if self.bit_index >= self.bytes.len() * 8 { - return None; - } - let byte = self.bytes[self.bit_index / 8]; - let shift = 7 - (self.bit_index % 8); - self.bit_index += 1; - Some((byte >> shift) & 1) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use cultnet_rs::{ - CultNetMessage, CultNetWireContract, GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA, - ReceiverFeedbackOptions, VideoChunkKey, build_receiver_feedback, - decode_cultnet_message_from_slice, encode_cultnet_message_to_vec, - }; - - fn start_code() -> [u8; 4] { - [0, 0, 0, 1] - } - - #[test] - fn splits_h264_annex_b_access_units_on_aud_boundaries() -> Result<()> { - let mut stream = Vec::new(); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[0x09, 0xf0]); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[0x67, 0x42, 0x00, 0x1f]); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[0x65, 0x80]); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[0x09, 0xf0]); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[0x41, 0x80]); - - let access_units = h264_annex_b_access_units(&stream)?; - - assert_eq!(access_units.len(), 2); - assert!(access_units[0].keyframe); - assert!(!access_units[1].keyframe); - assert!(access_units[0].bytes.starts_with(&start_code())); - assert!(access_units[1].bytes.starts_with(&start_code())); - Ok(()) - } - - #[test] - fn splits_h264_annex_b_access_units_on_new_slice_zero() -> Result<()> { - let mut stream = Vec::new(); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[0x65, 0x80]); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[0x41, 0x80]); - - let access_units = h264_annex_b_access_units(&stream)?; - - assert_eq!(access_units.len(), 2); - assert!(access_units[0].keyframe); - assert!(!access_units[1].keyframe); - Ok(()) - } - - #[test] - fn video_annex_b_dispatches_h264_aliases() -> Result<()> { - let mut stream = Vec::new(); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[0x65, 0x80]); - - let access_units = video_annex_b_access_units("AVC", &stream)?; - - assert_eq!(access_units.len(), 1); - assert!(access_units[0].keyframe); - Ok(()) - } - - fn h265_nal(nal_type: u8, slice_first: Option) -> Vec { - let mut nal = vec![nal_type << 1, 0x01]; - if let Some(first) = slice_first { - nal.push(if first { 0x80 } else { 0x00 }); - } else { - nal.push(0x00); - } - nal - } - - #[test] - fn splits_h265_annex_b_access_units_on_aud_boundaries() -> Result<()> { - let mut stream = Vec::new(); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&h265_nal(35, None)); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&h265_nal(32, None)); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&h265_nal(33, None)); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&h265_nal(34, None)); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&h265_nal(19, Some(true))); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&h265_nal(35, None)); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&h265_nal(1, Some(true))); - - let access_units = h265_annex_b_access_units(&stream)?; - - assert_eq!(access_units.len(), 2); - assert!(access_units[0].keyframe); - assert!(!access_units[1].keyframe); - assert!(access_units[0].bytes.starts_with(&start_code())); - assert!(access_units[1].bytes.starts_with(&start_code())); - Ok(()) - } - - #[test] - fn splits_h265_annex_b_access_units_on_first_slice_flag() -> Result<()> { - let mut stream = Vec::new(); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&h265_nal(19, Some(true))); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&h265_nal(1, Some(true))); - - let access_units = h265_annex_b_access_units(&stream)?; - - assert_eq!(access_units.len(), 2); - assert!(access_units[0].keyframe); - assert!(!access_units[1].keyframe); - Ok(()) - } - - #[test] - fn video_annex_b_dispatches_hevc_aliases() -> Result<()> { - let mut stream = Vec::new(); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&h265_nal(19, Some(true))); - - let access_units = video_annex_b_access_units("HEVC", &stream)?; - - assert_eq!(access_units.len(), 1); - assert!(access_units[0].keyframe); - Ok(()) - } - - #[test] - fn video_annex_b_rejects_av1_without_obu_packetizer() { - let error = video_annex_b_access_units("av1", &[1, 2, 3]).unwrap_err(); - - assert!( - error - .to_string() - .contains("AV1 access unit splitting is not Annex B") - ); - } - - #[test] - fn video_annex_b_rejects_unknown_codec() { - let error = video_annex_b_access_units("vp9", &[1, 2, 3]).unwrap_err(); - - assert!( - error - .to_string() - .contains("unsupported Annex B video codec vp9") - ); - } - - #[test] - fn packetizes_access_unit_into_typed_video_chunks() -> Result<()> { - let access_unit = VideoAccessUnit { - bytes: vec![1, 2, 3, 4, 5], - keyframe: false, - }; - - let records = packetize_video_access_unit( - VideoFramePacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "h264", - frame_id: 9, - pts_ticks: 27_000, - duration_ticks: 3_000, - timebase_num: 1, - timebase_den: 90_000, - deadline_ticks: 28_800, - max_payload_bytes: 2, - }, - &access_unit, - )?; - - assert_eq!(records.len(), 3); - assert_eq!(records[0].chunk_index, 0); - assert_eq!(records[0].chunk_count, 3); - assert_eq!(records[0].dependency_frame_id, Some(8)); - assert_eq!(records[2].payload, vec![5]); - Ok(()) - } - - #[test] - fn builds_video_parity_shards_for_burst_loss_recovery() -> Result<()> { - let access_unit = VideoAccessUnit { - bytes: (1_u8..=40).collect(), - keyframe: false, - }; - let records = packetize_video_access_unit( - VideoFramePacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "h264", - frame_id: 9, - pts_ticks: 27_000, - duration_ticks: 3_000, - timebase_num: 1, - timebase_den: 90_000, - deadline_ticks: 28_800, - max_payload_bytes: 2, - }, - &access_unit, - )?; - - let parity = build_video_parity_shards(&records)?; - - assert_eq!(records.len(), 20); - assert_eq!(parity.len(), 16); - assert!( - parity.iter().enumerate().all( - |(index, shard)| shard.parity_index == index as u16 && shard.parity_count == 16 - ) - ); - assert!(parity.iter().all(|shard| shard.chunk_payload_bytes == 2)); - - let mut recovered_tail = Vec::new(); - for missing_index in 16_u16..20 { - let shard = parity - .iter() - .find(|shard| shard.parity_index == missing_index % shard.parity_count) - .expect("tail chunk stripe exists"); - let mut recovered = shard.payload.clone(); - for chunk in records.iter().filter(|chunk| { - chunk.chunk_index != missing_index - && chunk.chunk_index % shard.parity_count == shard.parity_index - }) { - for (offset, byte) in chunk.payload.iter().enumerate() { - recovered[offset] ^= *byte; - } - } - recovered.truncate(records[missing_index as usize].payload.len()); - recovered_tail.extend(recovered); - } - let expected_tail: Vec = records[16..20] - .iter() - .flat_map(|record| record.payload.iter().copied()) - .collect(); - assert_eq!(recovered_tail, expected_tail); - Ok(()) - } - - #[test] - fn rejects_zero_duration_video_access_units() { - let access_unit = VideoAccessUnit { - bytes: vec![1, 2, 3], - keyframe: true, - }; - - let error = packetize_video_access_unit( - VideoFramePacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "h264", - frame_id: 9, - pts_ticks: 27_000, - duration_ticks: 0, - timebase_num: 1, - timebase_den: 90_000, - deadline_ticks: 28_800, - max_payload_bytes: 2, - }, - &access_unit, - ) - .unwrap_err(); - - assert!( - error - .to_string() - .contains("video duration_ticks must be greater than zero") - ); - } - - #[test] - fn rejects_video_deadline_before_pts() { - let access_unit = VideoAccessUnit { - bytes: vec![1, 2, 3], - keyframe: true, - }; - - let error = packetize_video_access_unit( - VideoFramePacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "h264", - frame_id: 9, - pts_ticks: 27_000, - duration_ticks: 3_000, - timebase_num: 1, - timebase_den: 90_000, - deadline_ticks: 26_999, - max_payload_bytes: 2, - }, - &access_unit, - ) - .unwrap_err(); - - assert!( - error - .to_string() - .contains("video deadline_ticks must not precede pts_ticks") - ); - } - - #[test] - fn video_chunk_key_round_trips_feedback_key() -> Result<()> { - let key = VideoChunkKey::parse("42:7")?; - - assert_eq!(key, VideoChunkKey::new(42, 7)); - assert_eq!(key.as_feedback_key(), "42:7"); - assert_eq!(video_chunk_feedback_key(42, 7), "42:7"); - Ok(()) - } - - #[test] - fn rejects_malformed_video_chunk_keys() { - let error = VideoChunkKey::parse("42:7:extra").unwrap_err(); - - assert!(error.to_string().contains("exactly one")); - } - - #[test] - fn packetizes_audio_payload_into_typed_packet() -> Result<()> { - let record = packetize_audio_packet( - AudioPacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "opus", - packet_id: 12, - pts_ticks: 48_000, - duration_ticks: 960, - timebase_num: 1, - timebase_den: 48_000, - deadline_ticks: 48_960, - }, - &[0xf8, 0xff, 0xfe], - )?; - - assert_eq!(record.stream_id, "muninn.raven.av.rudp"); - assert_eq!(record.codec, "opus"); - assert_eq!(record.packet_id, 12); - assert_eq!(record.payload, vec![0xf8, 0xff, 0xfe]); - Ok(()) - } - - #[test] - fn rejects_empty_audio_payloads() { - let error = packetize_audio_packet( - AudioPacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "opus", - packet_id: 12, - pts_ticks: 48_000, - duration_ticks: 960, - timebase_num: 1, - timebase_den: 48_000, - deadline_ticks: 48_960, - }, - &[], - ) - .unwrap_err(); - - assert!(error.to_string().contains("payload must be non-empty")); - } - - #[test] - fn rejects_zero_duration_audio_packets() { - let error = packetize_audio_packet( - AudioPacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "opus", - packet_id: 12, - pts_ticks: 48_000, - duration_ticks: 0, - timebase_num: 1, - timebase_den: 48_000, - deadline_ticks: 48_960, - }, - &[0xf8, 0xff, 0xfe], - ) - .unwrap_err(); - - assert!( - error - .to_string() - .contains("audio duration_ticks must be greater than zero") - ); - } - - #[test] - fn rejects_audio_deadline_before_pts() { - let error = packetize_audio_packet( - AudioPacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "opus", - packet_id: 12, - pts_ticks: 48_000, - duration_ticks: 960, - timebase_num: 1, - timebase_den: 48_000, - deadline_ticks: 47_999, - }, - &[0xf8, 0xff, 0xfe], - ) - .unwrap_err(); - - assert!( - error - .to_string() - .contains("audio deadline_ticks must not precede pts_ticks") - ); - } - - #[test] - fn media_wire_round_trips_video_document() -> Result<()> { - let access_unit = VideoAccessUnit { - bytes: vec![1, 2, 3], - keyframe: true, - }; - let record = packetize_video_access_unit( - VideoFramePacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "h264", - frame_id: 9, - pts_ticks: 27_000, - duration_ticks: 3_000, - timebase_num: 1, - timebase_den: 90_000, - deadline_ticks: 28_800, - max_payload_bytes: 4, - }, - &access_unit, - )? - .remove(0); - - let wire = encode_media_wire_record( - &GameCultMediaWireRecord::Video(record.clone()), - muninn_provenance("2026-06-18T00:00:00Z", "muninn-test", "media-test"), - )?; - - assert_eq!( - decode_media_wire_record(&wire)?, - GameCultMediaWireRecord::Video(record) - ); - Ok(()) - } - - #[test] - fn media_wire_round_trips_video_parity_document() -> Result<()> { - let access_unit = VideoAccessUnit { - bytes: vec![1, 2, 3, 4, 5], - keyframe: false, - }; - let records = packetize_video_access_unit( - VideoFramePacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "h264", - frame_id: 9, - pts_ticks: 27_000, - duration_ticks: 3_000, - timebase_num: 1, - timebase_den: 90_000, - deadline_ticks: 28_800, - max_payload_bytes: 2, - }, - &access_unit, - )?; - let parity = build_video_parity_shards(&records)? - .into_iter() - .next() - .expect("multi-chunk frame gets parity"); - - let wire = encode_media_wire_record( - &GameCultMediaWireRecord::VideoParity(parity.clone()), - muninn_provenance("2026-06-18T00:00:00Z", "muninn-test", "media-test"), - )?; - - assert_eq!( - decode_media_wire_record(&wire)?, - GameCultMediaWireRecord::VideoParity(parity) - ); - Ok(()) - } - - fn stream_send_config() -> VideoAnnexBStreamSendConfig { - VideoAnnexBStreamSendConfig { - stream_id: "muninn.raven.av.rudp".to_string(), - session_id: "session-1".to_string(), - codec: "h264".to_string(), - first_frame_id: 9, - first_pts_ticks: 27_000, - frame_duration_ticks: 3_000, - timebase_num: 1, - timebase_den: 90_000, - deadline_delay_ticks: 1_800, - max_payload_bytes: 16, - max_pending_bytes: 64, - source_runtime_id: "muninn-test".to_string(), - source_role: "media-test".to_string(), - } - } - - /// Push two access units through the sender and return every video data - /// record (parity excluded) it put on the wire, in order. - fn sent_video_records( - config: VideoAnnexBStreamSendConfig, - second_slice_header: u8, - ) -> Result> { - let mut stream = Vec::new(); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[0x65, 0x80]); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[second_slice_header, 0x80]); - let mut sender = VideoAnnexBStreamSendState::new(config)?; - let mut payloads = flat(sender.push("2026-06-18T00:00:00Z", &stream)?); - payloads.extend(flat(sender.finish("2026-06-18T00:00:00Z")?)); - let mut records = Vec::new(); - for payload in &payloads { - if let GameCultMediaWireRecord::Video(record) = - decode_media_wire_record(&payload.payload)? - { - records.push(record); - } - } - Ok(records) - } - - #[test] - fn annex_b_stream_send_state_times_records_from_the_configured_clock() -> Result<()> { - let mut config = stream_send_config(); - config.codec = "avc".to_string(); - - let records = sent_video_records(config, 0x41)?; - - assert_eq!(records.len(), 2); - assert_eq!(records[0].frame_id, 9); - assert_eq!(records[0].pts_ticks, 27_000); - assert_eq!(records[0].deadline_ticks, 28_800); - assert!(records[0].keyframe); - assert_eq!(records[1].frame_id, 10); - assert_eq!(records[1].pts_ticks, 30_000); - assert_eq!(records[1].deadline_ticks, 31_800); - assert_eq!(records[1].dependency_frame_id, Some(9)); - assert_eq!(records[1].codec, "avc"); - Ok(()) - } - - #[test] - fn annex_b_stream_send_state_leaves_non_reference_p_frames_without_dependency() -> Result<()> { - let records = sent_video_records(stream_send_config(), 0x01)?; - - assert_eq!(records.len(), 2); - assert!(records[0].keyframe); - assert_eq!(records[0].dependency_frame_id, None); - assert!(!records[1].keyframe); - assert_eq!(records[1].dependency_frame_id, None); - Ok(()) - } - - #[test] - fn annex_b_stream_send_state_rejects_negative_deadline_delay() { - let mut config = stream_send_config(); - config.deadline_delay_ticks = -1; - - let error = match VideoAnnexBStreamSendState::new(config) { - Ok(_) => panic!("a negative deadline delay must not create a sender"), - Err(error) => error, - }; - - assert!( - error - .to_string() - .contains("deadline_delay_ticks must be non-negative") - ); - } - - #[test] - fn media_wire_batches_sender_records_and_reencodes_them_identically() -> Result<()> { - let mut stream = Vec::new(); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[0x65, 0x80]); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[0x41, 0x80]); - let mut sender = VideoAnnexBStreamSendState::new(stream_send_config())?; - let mut payloads = flat(sender.push("2026-06-18T00:00:00Z", &stream)?); - payloads.extend(flat(sender.finish("2026-06-18T00:00:00Z")?)); - assert!(payloads.len() >= 2); - let wire_records = payloads - .iter() - .map(|payload| decode_media_wire_record(&payload.payload)) - .collect::>>()?; - - let wire = encode_media_wire_records( - &wire_records, - "2026-06-18T00:00:00Z", - "muninn-test", - "media-test", - )?; - - assert_eq!(wire.len(), payloads.len()); - for (encoded, original) in wire.iter().zip(&payloads) { - assert_eq!(encoded, &original.payload); - } - Ok(()) - } - - #[test] - fn annex_b_stream_send_state_emits_only_completed_frames() -> Result<()> { - let mut first_frame = Vec::new(); - first_frame.extend_from_slice(&start_code()); - first_frame.extend_from_slice(&[0x65, 0x80]); - let mut second_frame = Vec::new(); - second_frame.extend_from_slice(&start_code()); - second_frame.extend_from_slice(&[0x41, 0x80]); - let mut sender = VideoAnnexBStreamSendState::new(stream_send_config())?; - - let first_push = sender.push("2026-06-18T00:00:00Z", &first_frame)?; - - assert!(first_push.is_empty()); - assert_eq!(sender.next_frame_id(), 9); - assert_eq!(sender.pending_bytes(), first_frame.len()); - - let second_push = sender.push("2026-06-18T00:00:00Z", &second_frame)?; - - assert_eq!(second_push.len(), 1); - assert_eq!(second_push[0].len(), 1); - assert_eq!(second_push[0][0].channel_id, MUNINN_MEDIA_RUDP_CHANNEL); - let GameCultMediaWireRecord::Video(first) = - decode_media_wire_record(&second_push[0][0].payload)? - else { - panic!("expected video media record"); - }; - assert_eq!(first.frame_id, 9); - assert_eq!(first.pts_ticks, 27_000); - assert!(first.keyframe); - assert_eq!(sender.next_frame_id(), 10); - assert_eq!(sender.pending_bytes(), second_frame.len()); - - let tail = sender.finish("2026-06-18T00:00:00Z")?; - - assert_eq!(tail.len(), 1); - assert_eq!(tail[0].len(), 1); - let GameCultMediaWireRecord::Video(second) = decode_media_wire_record(&tail[0][0].payload)? - else { - panic!("expected video media record"); - }; - assert_eq!(second.frame_id, 10); - assert_eq!(second.pts_ticks, 30_000); - assert_eq!(second.dependency_frame_id, Some(9)); - assert_eq!(sender.pending_bytes(), 0); - assert_eq!(sender.next_frame_id(), 11); - Ok(()) - } - - #[test] - fn annex_b_stream_send_state_rejects_non_annex_b_codecs() { - let mut config = stream_send_config(); - config.codec = "av1".to_string(); - - let error = match VideoAnnexBStreamSendState::new(config) { - Ok(_) => panic!("AV1 must not create an Annex B stream sender"), - Err(error) => error, - }; - - assert!( - error - .to_string() - .contains("Annex B stream sender requires H.264/AVC or H.265/HEVC codec") - ); - } - - /// `(frame_id, whole access unit bytes)` for each group, chunks rejoined. - fn frames_of(groups: &[MuninnMediaPayloadGroup]) -> Result)>> { - groups - .iter() - .map(|group| { - let mut frame_id = None; - let mut bytes = Vec::new(); - for payload in group { - if let GameCultMediaWireRecord::Video(record) = - decode_media_wire_record(&payload.payload)? - { - frame_id = Some(record.frame_id); - bytes.extend_from_slice(&record.payload); - } - } - Ok((frame_id.expect("a group carries video chunks"), bytes)) - }) - .collect() - } - - #[test] - fn an_overflow_drop_consumes_its_frame_id_and_discards_the_leftover_slices() -> Result<()> { - let mut config = stream_send_config(); - config.max_pending_bytes = 16; - config.max_payload_bytes = 64; - let mut sender = VideoAnnexBStreamSendState::new(config)?; - let stored_at = "2026-06-18T00:00:00Z"; - let nal = |header: [u8; 2], filler: &[u8]| { - [&start_code()[..], &header[..], filler].concat() - }; - - // Frame 9 whole, then the head of a frame that outgrows the ceiling. - let mut first = nal([0x65, 0x80], &[0xA1]); - first.extend(nal([0x41, 0x80], &[0xB2; 30])); - let groups = frames_of(&sender.push(stored_at, &first)?)?; - assert_eq!(groups, vec![(9, nal([0x65, 0x80], &[0xA1]))]); - assert_eq!(sender.dropped_access_units(), 1); - assert_eq!(sender.next_frame_id(), 11, "the dropped frame 10 is spent"); - - // Its second slice (first_mb_in_slice != 0) arrives alone: nothing can - // be decided yet, and nothing is emitted. - assert!(sender.push(stored_at, &nal([0x41, 0x40], &[0xC3]))?.is_empty()); - assert_eq!(sender.dropped_access_units(), 1); - - // Then two whole frames follow: the leftover slice goes with frame 10. - let mut next = nal([0x41, 0x80], &[0xD4]); - next.extend(nal([0x41, 0x80], &[0xE5])); - let mut groups = frames_of(&sender.push(stored_at, &next)?)?; - groups.extend(frames_of(&sender.finish(stored_at)?)?); - assert_eq!( - groups, - vec![ - (11, nal([0x41, 0x80], &[0xD4])), - (12, nal([0x41, 0x80], &[0xE5])), - ] - ); - assert_eq!(sender.dropped_access_units(), 1); - Ok(()) - } - - #[test] - fn a_leftover_spanning_two_pushes_is_discarded_whole() -> Result<()> { - let mut config = stream_send_config(); - config.max_pending_bytes = 16; - config.max_payload_bytes = 64; - let mut sender = VideoAnnexBStreamSendState::new(config)?; - let stored_at = "2026-06-18T00:00:00Z"; - let nal = |header: [u8; 2], filler: &[u8]| { - [&start_code()[..], &header[..], filler].concat() - }; - - let mut first = nal([0x65, 0x80], &[0xA1]); - first.extend(nal([0x41, 0x80], &[0xB2; 30])); - assert_eq!(sender.push(stored_at, &first)?.len(), 1); - assert_eq!(sender.dropped_access_units(), 1); - - // The dropped frame's second and third slices (first_mb_in_slice 1 - // and 3) arrive in separate pushes. Neither is a frame, and neither - // may come out as one. - assert!(sender.push(stored_at, &nal([0x41, 0x40], &[0xC3]))?.is_empty()); - assert!(sender.push(stored_at, &nal([0x41, 0x20], &[0xC4]))?.is_empty()); - assert_eq!(sender.next_frame_id(), 11); - - let mut next = nal([0x41, 0x80], &[0xD4]); - next.extend(nal([0x41, 0x80], &[0xE5])); - let mut groups = frames_of(&sender.push(stored_at, &next)?)?; - groups.extend(frames_of(&sender.finish(stored_at)?)?); - assert_eq!( - groups, - vec![ - (11, nal([0x41, 0x80], &[0xD4])), - (12, nal([0x41, 0x80], &[0xE5])), - ], - "both leftover slices went with the dropped frame" - ); - assert_eq!(sender.dropped_access_units(), 1); - Ok(()) - } - - #[test] - fn a_stream_that_resumes_on_a_frame_boundary_after_an_overflow_loses_nothing_more() -> Result<()> { - let mut config = stream_send_config(); - config.max_pending_bytes = 16; - let mut sender = VideoAnnexBStreamSendState::new(config)?; - let stored_at = "2026-06-18T00:00:00Z"; - let nal = |header: [u8; 2], filler: &[u8]| { - [&start_code()[..], &header[..], filler].concat() - }; - - assert!(sender.push(stored_at, &nal([0x65, 0x80], &[0xB2; 30]))?.is_empty()); - assert_eq!(sender.next_frame_id(), 10); - - // The next bytes open on a new frame, not on a leftover slice. - let mut next = nal([0x41, 0x80], &[0xD4]); - next.extend(nal([0x41, 0x80], &[0xE5])); - let groups = frames_of(&sender.push(stored_at, &next)?)?; - assert_eq!(groups.len(), 1); - assert_eq!(groups[0].0, 10); - Ok(()) - } - - fn flat(groups: Vec) -> Vec { - groups.into_iter().flatten().collect() - } - - #[test] - fn annex_b_stream_send_state_drops_and_counts_an_oversize_access_unit_instead_of_erroring() - -> Result<()> { - let mut config = stream_send_config(); - config.max_pending_bytes = 8; - let mut sender = VideoAnnexBStreamSendState::new(config)?; - - // One access unit that never completes and is larger than the ceiling. - let mut oversize = start_code().to_vec(); - oversize.extend_from_slice(&[0x65, 0x80, 1, 2, 3, 4, 5, 6, 7, 8]); - let groups = sender.push("2026-06-18T00:00:00Z", &oversize)?; - - assert!(groups.is_empty()); - assert_eq!(sender.dropped_access_units(), 1); - assert_eq!(sender.pending_bytes(), 0); - - // The tail of the dropped unit has no start code and is skipped; the - // stream then carries on with the next access units. - let mut next = vec![9, 9, 9]; - next.extend_from_slice(&start_code()); - next.extend_from_slice(&[0x65, 0x80]); - next.extend_from_slice(&start_code()); - next.extend_from_slice(&[0x41, 0x80]); - let groups = sender.push("2026-06-18T00:00:00Z", &next)?; - - assert_eq!(groups.len(), 1); - assert_eq!(sender.dropped_access_units(), 1); - let GameCultMediaWireRecord::Video(record) = - decode_media_wire_record(&groups[0][0].payload)? - else { - panic!("expected video media record"); - }; - assert!(record.keyframe); - Ok(()) - } - - #[test] - fn annex_b_stream_send_state_returns_one_group_per_access_unit_with_all_its_chunks_and_parity() - -> Result<()> { - // Three chunks of 16 bytes plus a short fourth: one access unit. - let mut stream = start_code().to_vec(); - stream.extend_from_slice(&[0x65, 0x80]); - stream.resize(52, 0xAB); - stream.extend_from_slice(&start_code()); - stream.extend_from_slice(&[0x41, 0x80]); - let mut sender = VideoAnnexBStreamSendState::new(stream_send_config())?; - - let mut groups = sender.push("2026-06-18T00:00:00Z", &stream)?; - groups.extend(sender.finish("2026-06-18T00:00:00Z")?); - - assert_eq!(groups.len(), 2); - let mut frame_ids_per_group = Vec::new(); - for group in &groups { - let mut ids = std::collections::BTreeSet::new(); - let mut data = 0; - let mut parity = 0; - for payload in group { - match decode_media_wire_record(&payload.payload)? { - GameCultMediaWireRecord::Video(record) => { - ids.insert(record.frame_id); - data += 1; - } - GameCultMediaWireRecord::VideoParity(record) => { - ids.insert(record.frame_id); - parity += 1; - } - other => panic!("unexpected record {other:?}"), - } - } - assert_eq!(ids.len(), 1, "a group carries exactly one frame"); - frame_ids_per_group.push((ids.into_iter().next().unwrap(), data, parity)); - } - assert_eq!(frame_ids_per_group[0], (9, 4, 4)); - assert_eq!(frame_ids_per_group[1], (10, 1, 0)); - Ok(()) - } - - #[test] - fn media_wire_encodes_audio_packet_for_sender() -> Result<()> { - let wire = encode_audio_packet_wire_record( - AudioPacketWireOptions { - packetize: AudioPacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "opus", - packet_id: 12, - pts_ticks: 48_000, - duration_ticks: 960, - timebase_num: 1, - timebase_den: 48_000, - deadline_ticks: 48_960, - }, - stored_at: "2026-06-18T00:00:00Z", - source_runtime_id: "muninn-test", - source_role: "media-test", - }, - &[0xf8, 0xff, 0xfe], - )?; - - let decoded = decode_media_wire_record(&wire)?; - let GameCultMediaWireRecord::Audio(decoded) = decoded else { - panic!("expected audio media record"); - }; - assert_eq!(decoded.packet_id, 12); - assert_eq!(decoded.codec, "opus"); - assert_eq!(decoded.payload, vec![0xf8, 0xff, 0xfe]); - Ok(()) - } - - #[test] - fn media_send_payload_pins_audio_to_media_channel() -> Result<()> { - let payload = audio_packet_send_payload( - AudioPacketWireOptions { - packetize: AudioPacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "opus", - packet_id: 12, - pts_ticks: 48_000, - duration_ticks: 960, - timebase_num: 1, - timebase_den: 48_000, - deadline_ticks: 48_960, - }, - stored_at: "2026-06-18T00:00:00Z", - source_runtime_id: "muninn-test", - source_role: "media-test", - }, - &[0xf8, 0xff, 0xfe], - )?; - - assert_eq!(payload.channel_id, MUNINN_AUDIO_RUDP_CHANNEL, "audio rides its own channel"); - let GameCultMediaWireRecord::Audio(record) = decode_media_wire_record(&payload.payload)? - else { - panic!("expected audio media record"); - }; - assert_eq!(record.packet_id, 12); - Ok(()) - } - - #[test] - fn media_wire_round_trips_audio_document() -> Result<()> { - let record = packetize_audio_packet( - AudioPacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "opus", - packet_id: 12, - pts_ticks: 48_000, - duration_ticks: 960, - timebase_num: 1, - timebase_den: 48_000, - deadline_ticks: 48_960, - }, - &[0xf8, 0xff, 0xfe], - )?; - - let wire = encode_media_wire_record( - &GameCultMediaWireRecord::Audio(record.clone()), - muninn_provenance("2026-06-18T00:00:00Z", "muninn-test", "media-test"), - )?; - - assert_eq!( - decode_media_wire_record(&wire)?, - GameCultMediaWireRecord::Audio(record) - ); - Ok(()) - } - - #[test] - fn media_wire_round_trips_feedback_document() -> Result<()> { - let record = build_receiver_feedback(ReceiverFeedbackOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - receiver_id: "starfire.obs", - highest_decodable_frame_id: Some(40), - missing_frame_ids: vec![42], - missing_video_chunk_keys: vec![video_chunk_feedback_key(42, 2)], - late_frame_ids: vec![39], - requested_keyframe: true, - jitter_us: 700, - decode_queue_us: 2_000, - observed_at: "2026-06-18T00:00:00Z", - })?; - - let wire = encode_media_wire_record( - &GameCultMediaWireRecord::Feedback(record.clone()), - muninn_provenance("2026-06-18T00:00:00Z", "muninn-test", "media-test"), - )?; - - assert_eq!( - decode_media_wire_record(&wire)?, - GameCultMediaWireRecord::Feedback(record) - ); - Ok(()) - } - - /// A real capture from the deployed C++ OBS bridge, kept as the record of a - /// deliberate break rather than deleted. - /// - /// It carries `muninn.media_receiver_feedback.v1`. The media schemas were - /// renamed to `gamecult.media_*` because they describe media and nothing - /// about who produced it, and the `muninn.` prefix was the only thing tying - /// a general contract to one producer. That rename means the deployed bridge - /// can no longer be understood, which is accepted: it is being replaced by - /// Ratatoskr, and a compatibility path accepting both names would preserve - /// exactly the ownership confusion the rename removes. - /// - /// If this ever starts passing, someone has reintroduced the old schema id. - #[test] - fn the_previous_generation_bridge_is_deliberately_no_longer_understood() -> Result<()> { - let wire = hex_fixture( - "83ad736368656d6156657273696f6ebb63756c746e65742e646f63756d656e745f7075745f7261772e7630a96d6573736167654964d96a6d756e696e6e2d6d656469613a6d756e696e6e2e6d656469615f72656365697665725f666565646261636b2e76313a6d756e696e6e2e726176656e2e61762e727564703a726176656e3a746573743a766964656f3a666565646261636b3a73746172666972652e6f6273a8646f63756d656e7489a8736368656d614964d9216d756e696e6e2e6d656469615f72656365697665725f666565646261636b2e7631a97265636f72644b6579d93b6d756e696e6e2e726176656e2e61762e727564703a726176656e3a746573743a766964656f3a666565646261636b3a73746172666972652e6f6273a873746f7265644174ac756e69782d6d733a31303030af7061796c6f6164456e636f64696e67ab6d6573736167657061636ba77061796c6f6164c4539bb46d756e696e6e2e726176656e2e61762e72756470b0726176656e3a746573743a766964656fac73746172666972652e6f62732990912ac30000ac756e69782d6d733a3130303092a434323a31a434323a33af736f7572636552756e74696d654964a87374617266697265ad736f757263654167656e744964c0aa736f75726365526f6c65a96d696d69722e6f6273a47461677391ac6d756e696e6e2e6d65646961", - )?; - - let error = decode_media_wire_record(&wire) - .expect_err("the muninn.* media schemas are retired"); - assert!( - error.to_string().contains("muninn.media_receiver_feedback.v1"), - "the refusal should name what it refused, got {error}" - ); - Ok(()) - } - - #[test] - fn media_wire_rejects_invalid_video_record_timing() -> Result<()> { - let access_unit = VideoAccessUnit { - bytes: vec![1, 2, 3], - keyframe: true, - }; - let mut record = packetize_video_access_unit( - VideoFramePacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "h264", - frame_id: 9, - pts_ticks: 27_000, - duration_ticks: 3_000, - timebase_num: 1, - timebase_den: 90_000, - deadline_ticks: 28_800, - max_payload_bytes: 4, - }, - &access_unit, - )? - .remove(0); - record.deadline_ticks = 26_999; - let wire = encode_media_wire_record( - &GameCultMediaWireRecord::Video(record), - muninn_provenance("2026-06-18T00:00:00Z", "muninn-test", "media-test"), - )?; - - let error = decode_media_wire_record(&wire).unwrap_err(); - - assert!( - error - .to_string() - .contains("video media record deadline_ticks must not precede pts_ticks") - ); - Ok(()) - } - - #[test] - fn media_wire_rejects_invalid_audio_record_payload() -> Result<()> { - let mut record = packetize_audio_packet( - AudioPacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "opus", - packet_id: 12, - pts_ticks: 48_000, - duration_ticks: 960, - timebase_num: 1, - timebase_den: 48_000, - deadline_ticks: 48_960, - }, - &[0xf8, 0xff, 0xfe], - )?; - record.payload.clear(); - let wire = encode_media_wire_record( - &GameCultMediaWireRecord::Audio(record), - muninn_provenance("2026-06-18T00:00:00Z", "muninn-test", "media-test"), - )?; - - let error = decode_media_wire_record(&wire).unwrap_err(); - - assert!( - error - .to_string() - .contains("audio media record payload must be non-empty") - ); - Ok(()) - } - - #[test] - fn media_wire_rejects_invalid_feedback_record_pressure() -> Result<()> { - let mut record = build_receiver_feedback(ReceiverFeedbackOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - receiver_id: "starfire.obs", - highest_decodable_frame_id: Some(40), - missing_frame_ids: vec![42], - missing_video_chunk_keys: vec![video_chunk_feedback_key(42, 2)], - late_frame_ids: vec![39], - requested_keyframe: true, - jitter_us: 700, - decode_queue_us: 2_000, - observed_at: "2026-06-18T00:00:00Z", - })?; - record.decode_queue_us = -1; - let wire = encode_media_wire_record( - &GameCultMediaWireRecord::Feedback(record), - muninn_provenance("2026-06-18T00:00:00Z", "muninn-test", "media-test"), - )?; - - let error = decode_media_wire_record(&wire).unwrap_err(); - - assert!( - error - .to_string() - .contains("receiver feedback media record decode_queue_us must be non-negative") - ); - Ok(()) - } - - #[test] - fn media_wire_rejects_mismatched_record_key() -> Result<()> { - let record = packetize_audio_packet( - AudioPacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "opus", - packet_id: 12, - pts_ticks: 48_000, - duration_ticks: 960, - timebase_num: 1, - timebase_den: 48_000, - deadline_ticks: 48_960, - }, - &[0xf8, 0xff, 0xfe], - )?; - let wire = encode_media_wire_record( - &GameCultMediaWireRecord::Audio(record), - muninn_provenance("2026-06-18T00:00:00Z", "muninn-test", "media-test"), - )?; - let CultNetMessage::DocumentPutRaw { - message_id, - mut document, - } = decode_cultnet_message_from_slice(&wire, CultNetWireContract::CultNetSchemaV0)? - else { - panic!("expected raw document put"); - }; - document.record_key = "wrong:key".to_string(); - let tampered = encode_cultnet_message_to_vec( - &CultNetMessage::DocumentPutRaw { - message_id, - document, - }, - CultNetWireContract::CultNetSchemaV0, - )?; - - let error = decode_media_wire_record(&tampered).unwrap_err(); - - assert!(error.to_string().contains("record key mismatch")); - Ok(()) - } - - #[test] - fn media_wire_rejects_unsupported_schema() -> Result<()> { - let record = packetize_audio_packet( - AudioPacketizeOptions { - stream_id: "muninn.raven.av.rudp", - session_id: "session-1", - codec: "opus", - packet_id: 12, - pts_ticks: 48_000, - duration_ticks: 960, - timebase_num: 1, - timebase_den: 48_000, - deadline_ticks: 48_960, - }, - &[0xf8, 0xff, 0xfe], - )?; - let wire = encode_media_wire_record( - &GameCultMediaWireRecord::Audio(record), - muninn_provenance("2026-06-18T00:00:00Z", "muninn-test", "media-test"), - )?; - let CultNetMessage::DocumentPutRaw { - message_id, - mut document, - } = decode_cultnet_message_from_slice(&wire, CultNetWireContract::CultNetSchemaV0)? - else { - panic!("expected raw document put"); - }; - document.schema_id = "muninn.media_unknown.v1".to_string(); - let tampered = encode_cultnet_message_to_vec( - &CultNetMessage::DocumentPutRaw { - message_id, - document, - }, - CultNetWireContract::CultNetSchemaV0, - )?; - - let error = decode_media_wire_record(&tampered).unwrap_err(); - - assert!( - error - .to_string() - .contains("unsupported media schema") - ); - Ok(()) - } - - #[test] - fn media_wire_rejects_non_raw_document_messages() -> Result<()> { - let wire = encode_cultnet_message_to_vec( - &CultNetMessage::DocumentPut { - message_id: "not-raw-media".to_string(), - document: cultnet_rs::CultNetDocumentRecord { - schema_id: GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA.to_string(), - record_key: "muninn.raven.av.rudp:session-1:audio:12".to_string(), - stored_at: "2026-06-18T00:00:00Z".to_string(), - payload: serde_json::json!({ "packet_id": 12 }), - source_runtime_id: Some("muninn-test".to_string()), - source_agent_id: None, - source_role: Some("media-test".to_string()), - tags: Some(vec!["muninn.media".to_string()]), - }, - }, - CultNetWireContract::CultNetSchemaV0, - )?; - - let error = decode_media_wire_record(&wire).unwrap_err(); - - assert!( - error - .to_string() - .contains("expected cultnet.document_put_raw.v0") - ); - Ok(()) - } - - fn hex_fixture(value: &str) -> Result> { - if value.len() % 2 != 0 { - return Err(anyhow!("hex fixture must have an even length")); - } - let mut bytes = Vec::with_capacity(value.len() / 2); - for index in (0..value.len()).step_by(2) { - let byte = u8::from_str_radix(&value[index..index + 2], 16) - .with_context(|| format!("parsing hex fixture byte at offset {index}"))?; - bytes.push(byte); - } - Ok(bytes) - } -} diff --git a/crates/muninn-daemon/src/media_send.rs b/crates/muninn-daemon/src/media_send.rs deleted file mode 100644 index 08ff860..0000000 --- a/crates/muninn-daemon/src/media_send.rs +++ /dev/null @@ -1,1085 +0,0 @@ -//! The media send path: the one place that decides when a frame is too old. -//! -//! **Owner.** `MediaSendCore` owns the bounded group queues, the hub, the -//! receiver-feedback intake, the repair cache and its budget, and the progress -//! counters. `run_rudp_mux_once` spawns the encoders and publishes; it feeds -//! this module bytes and never decides a deadline. -//! -//! **One deadline owner.** `MediaSendPolicy::latency_budget` comes from the -//! request's `latency_budget_ms` and is the only source of a deadline. A group -//! is stamped `produced_at + latency_budget` when it leaves the packetizer; a -//! repair inherits the deadline of the frame it repairs; the hub's reliable -//! expiry and the record deadline ticks derive from the same budget. -//! -//! **Priority.** The send loop moves one payload per step and chooses the -//! payload afresh each time: audio first, then repairs, then video. Audio that -//! arrives while a video group is half sent, or while the socket is full, -//! goes out before the video group's next payload; nothing holds audio behind -//! video for longer than one payload. The group deadline is checked before -//! every payload; a group that outlives it mid-send is abandoned and counted -//! `groups_cut_short`. -//! -//! **Bounds.** Between the encoder and the socket every queue has a count -//! bound (`MEDIA_GROUP_CHANNEL_BOUND`, the per-kind group caps) and a time -//! bound (the group deadline). Crossing either drops whole groups, oldest -//! first, and counts them. The video cap is 512 groups of at most one access -//! unit each, and an access unit is at most `max_pending_bytes` (848 * 4096 -//! bytes at the default packet size), so the count cap alone implies a worst -//! case of about 1.7 GiB; in practice the deadline empties the queue long -//! before that. - -use crate::media_packetizer::{ - AudioPcmStreamSendConfig, AudioPcmStreamSendState, GameCultMediaWireRecord, - MUNINN_MEDIA_RUDP_CHANNEL, MuninnMediaPayloadGroup, MuninnMediaSendPayload, - VideoAnnexBStreamSendConfig, VideoAnnexBStreamSendState, decode_media_wire_record, - video_chunk_feedback_key, -}; -use anyhow::{Context, Result}; -use cultnet_rs::{ - CultNetRudpServerEvent, CultNetRudpServerHub, CultNetRudpServerSessionContext, - CultNetTransportFrame, GameCultMediaReceiverFeedbackRecord, -}; -use std::collections::{HashMap, VecDeque}; -use std::io::{ErrorKind, Read}; -use std::sync::mpsc; -use std::thread; -use std::time::{Duration, Instant}; - -pub const MEDIA_SEND_AUDIO_GROUP_CAP: usize = 256; -pub const MEDIA_SEND_VIDEO_GROUP_CAP: usize = 512; -/// The longest latency budget a request may claim (the old default). Above -/// this the queues stop being bounded in time. -pub const MEDIA_SEND_MAX_LATENCY_BUDGET_MS: u32 = 2_000; - -/// The one clamp on a requested latency budget. Everything that reads a budget -/// from a request or a command line passes it through here; nothing else -/// clamps. -pub fn clamp_latency_budget_ms(requested_ms: u32) -> u32 { - requested_ms.clamp(1, MEDIA_SEND_MAX_LATENCY_BUDGET_MS) -} -/// Groups the reader threads may have handed over and the send loop not yet -/// taken. Small on purpose: the caps above are where a backlog lives. -pub const MEDIA_GROUP_CHANNEL_BOUND: usize = 8; - -const REPAIR_CACHE_CHUNKS: usize = 16_384; -pub const REPAIR_BURST_CHUNKS: usize = 2_048; -pub const REPAIR_INITIAL_CHUNKS_PER_SECOND: usize = 4_096; -const REPAIR_MIN_CHUNKS_PER_SECOND: usize = 8; -const REPAIR_MAX_CHUNKS_PER_SECOND: usize = 16_384; -const REPAIR_ADD_CHUNKS_PER_SECOND: usize = 2_048; -const REPAIR_RECOVERY_INTERVAL_MS: u64 = 2_000; -const REPAIR_MAX_FEEDBACK_PER_POLL: usize = 32; -const REPAIR_MAX_CHUNKS_PER_POLL: usize = 256; -/// A receiver that has said nothing for this long (Ratatoskr pings every -/// second or so) is dropped so its payloads stop being sent into the void. -const RECEIVER_TIMEOUT_MS: u64 = 6_000; -pub const SEND_PACE_EVERY_PAYLOADS: usize = 4; -pub const SEND_PACE_SLEEP_US: u64 = 250; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum MediaKind { - Video, - Audio, -} - -/// What the request decided about sending. Nothing else mints a deadline. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct MediaSendPolicy { - pub latency_budget: Duration, - pub video_pace_every_payloads: usize, - pub video_pace_sleep: Duration, -} - -impl MediaSendPolicy { - pub fn from_request(latency_budget_ms: u32) -> Self { - Self { - latency_budget: Duration::from_millis(u64::from(clamp_latency_budget_ms( - latency_budget_ms, - ))), - video_pace_every_payloads: SEND_PACE_EVERY_PAYLOADS, - video_pace_sleep: Duration::from_micros(SEND_PACE_SLEEP_US), - } - } - - pub fn latency_budget_ms(&self) -> u64 { - self.latency_budget.as_millis() as u64 - } - - /// The video record deadline, in the 90 kHz video timebase. - pub fn video_deadline_delay_ticks(&self) -> i64 { - i64::try_from(self.latency_budget_ms().saturating_mul(90)).unwrap_or(i64::MAX) - } - - /// The audio record deadline, in samples at `sample_rate`. - pub fn audio_deadline_delay_ticks(&self, sample_rate: u32) -> i64 { - if sample_rate == 0 { - return 1_024; - } - i64::try_from( - self.latency_budget_ms() - .saturating_mul(u64::from(sample_rate)) - / 1_000, - ) - .unwrap_or(i64::MAX) - .max(1_024) - } -} - -/// One access unit with its parity, or one audio packet. It is sent whole or -/// not at all, and it dies at `deadline`. -pub struct QueuedMediaGroup { - pub kind: MediaKind, - pub deadline: Instant, - pub payloads: MuninnMediaPayloadGroup, -} - -impl QueuedMediaGroup { - pub fn new( - kind: MediaKind, - produced_at: Instant, - policy: &MediaSendPolicy, - payloads: MuninnMediaPayloadGroup, - ) -> Self { - Self { - kind, - deadline: produced_at + policy.latency_budget, - payloads, - } - } - - /// Sendable at the deadline itself, expired one instant after. - pub fn expired(&self, now: Instant) -> bool { - now > self.deadline - } -} - -/// What a reader thread hands the send loop. -pub enum MediaIntake { - Group(QueuedMediaGroup), - /// Video access units the packetizer dropped for outgrowing its ceiling. - VideoDropped(u64), -} - -pub type MediaIntakeSender = mpsc::SyncSender>; -pub type MediaIntakeReceiver = mpsc::Receiver>; - -pub fn media_intake_channel() -> (MediaIntakeSender, MediaIntakeReceiver) { - mpsc::sync_channel(MEDIA_GROUP_CHANNEL_BOUND) -} - -#[derive(Default)] -struct PendingMediaGroups { - audio: VecDeque, - video: VecDeque, -} - -impl PendingMediaGroups { - /// `true` when the queue was at its cap and its oldest group was dropped - /// to make room. - fn push(&mut self, group: QueuedMediaGroup) -> bool { - let (queue, cap) = match group.kind { - MediaKind::Audio => (&mut self.audio, MEDIA_SEND_AUDIO_GROUP_CAP), - MediaKind::Video => (&mut self.video, MEDIA_SEND_VIDEO_GROUP_CAP), - }; - let dropped = queue.len() >= cap; - if dropped { - queue.pop_front(); - } - queue.push_back(group); - dropped - } - - fn is_empty(&self) -> bool { - self.audio.is_empty() && self.video.is_empty() - } -} - -/// Counted where it happens. `groups_dropped_*` is a cap crossing; -/// `groups_expired` is a group whose deadline passed with none of it sent; -/// `groups_cut_short` is one whose deadline passed with part of it already on -/// the wire, which is the only way a partial frame can leave. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct MediaSendStats { - pub groups_sent: u64, - pub payloads_sent: u64, - pub groups_dropped_audio: u64, - pub groups_dropped_video: u64, - pub groups_expired: u64, - pub groups_cut_short: u64, -} - -impl MediaSendStats { - pub fn groups_lost(&self) -> u64 { - self.groups_dropped_audio - + self.groups_dropped_video - + self.groups_expired - + self.groups_cut_short - } - - /// Accounts for one group the send loop has finished with. - fn record_group(&mut self, outcome: &GroupSend, group_payloads: usize) { - match outcome { - GroupSend::Complete => { - self.groups_sent += 1; - self.payloads_sent += group_payloads as u64; - } - GroupSend::DeadlinePassed { payloads_out: 0 } => self.groups_expired += 1, - GroupSend::DeadlinePassed { payloads_out } => { - self.payloads_sent += *payloads_out as u64; - self.groups_cut_short += 1; - } - } - } -} - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct MuninnRudpReceiverFeedbackStats { - pub feedback_records: u64, - pub requested_keyframes: u64, - pub late_frames: u64, - pub missing_video_chunks: u64, - pub repaired_video_chunks: u64, - pub deferred_repair_chunks: u64, - pub repair_chunks_per_second: usize, - pub highest_decodable_frame_id: Option, -} - -#[derive(Debug)] -pub struct MuninnRudpRepairBudget { - chunks_per_second: usize, - min_chunks_per_second: usize, - max_chunks_per_second: usize, - add_chunks_per_second: usize, - recovery_interval: Duration, - max_available_chunks: usize, - available_chunks: usize, - last_refill_at: Instant, - last_rate_adjust_at: Instant, - last_queue_dropped: u64, -} - -impl MuninnRudpRepairBudget { - pub fn new(chunks_per_second: usize, max_available_chunks: usize) -> Self { - let now = Instant::now(); - let max_available_chunks = max_available_chunks.max(1); - Self { - chunks_per_second: chunks_per_second.max(1), - min_chunks_per_second: REPAIR_MIN_CHUNKS_PER_SECOND, - max_chunks_per_second: REPAIR_MAX_CHUNKS_PER_SECOND, - add_chunks_per_second: REPAIR_ADD_CHUNKS_PER_SECOND, - recovery_interval: Duration::from_millis(REPAIR_RECOVERY_INTERVAL_MS), - max_available_chunks, - available_chunks: max_available_chunks, - last_refill_at: now, - last_rate_adjust_at: now, - last_queue_dropped: 0, - } - } - - pub fn chunks_per_second(&self) -> usize { - self.chunks_per_second - } - - pub fn take(&mut self, requested_chunks: usize, now: Instant, queue_dropped: u64) -> usize { - self.adjust_rate(now, queue_dropped, requested_chunks); - self.refill(now); - let allowed = requested_chunks.min(self.available_chunks); - self.available_chunks -= allowed; - allowed - } - - fn adjust_rate(&mut self, now: Instant, queue_dropped: u64, requested_chunks: usize) { - if queue_dropped > self.last_queue_dropped { - self.chunks_per_second = (self.chunks_per_second / 2).max(self.min_chunks_per_second); - self.available_chunks = self.available_chunks.min(self.chunks_per_second); - self.last_queue_dropped = queue_dropped; - self.last_rate_adjust_at = now; - return; - } - self.last_queue_dropped = queue_dropped; - if requested_chunks == 0 - || now.saturating_duration_since(self.last_rate_adjust_at) < self.recovery_interval - { - return; - } - if self.chunks_per_second < self.max_chunks_per_second { - self.chunks_per_second = self - .chunks_per_second - .saturating_add(self.add_chunks_per_second) - .min(self.max_chunks_per_second); - self.last_rate_adjust_at = now; - } - } - - fn refill(&mut self, now: Instant) { - let elapsed_ms = now - .saturating_duration_since(self.last_refill_at) - .as_millis() as usize; - if elapsed_ms == 0 { - return; - } - let refill_chunks = elapsed_ms.saturating_mul(self.chunks_per_second) / 1_000; - if refill_chunks == 0 { - return; - } - self.available_chunks = self - .available_chunks - .saturating_add(refill_chunks) - .min(self.max_available_chunks); - self.last_refill_at = now; - } -} - -#[derive(Debug)] -struct RepairEntry { - payload: MuninnMediaSendPayload, - /// The deadline of the frame group the chunk left in. A repair never - /// gets a deadline of its own. - deadline: Instant, -} - -#[derive(Debug)] -pub struct RecentVideoChunkRepairCache { - max_entries: usize, - order: VecDeque, - entries: HashMap, -} - -impl RecentVideoChunkRepairCache { - pub fn new(max_entries: usize) -> Self { - Self { - max_entries, - order: VecDeque::new(), - entries: HashMap::new(), - } - } - - pub fn remember(&mut self, payload: &MuninnMediaSendPayload, deadline: Instant) -> Result<()> { - let Some(key) = video_repair_cache_key_from_payload(payload)? else { - return Ok(()); - }; - let entry = RepairEntry { - payload: payload.clone(), - deadline, - }; - if self.entries.contains_key(&key) { - self.entries.insert(key, entry); - return Ok(()); - } - self.order.push_back(key.clone()); - self.entries.insert(key, entry); - while self.entries.len() > self.max_entries { - let Some(expired) = self.order.pop_front() else { - break; - }; - self.entries.remove(&expired); - } - Ok(()) - } - - /// The chunks the receiver is missing that are still inside their frame's - /// deadline at `now`, each with that deadline. - pub fn repair_payloads_for_feedback( - &self, - feedback: &GameCultMediaReceiverFeedbackRecord, - now: Instant, - ) -> Vec<(MuninnMediaSendPayload, Instant)> { - feedback - .missing_video_chunk_keys - .iter() - .filter_map(|chunk_key| { - self.entries.get(&video_repair_cache_key( - &feedback.stream_id, - &feedback.session_id, - chunk_key, - )) - }) - .filter(|entry| now <= entry.deadline) - .map(|entry| (entry.payload.clone(), entry.deadline)) - .collect() - } -} - -fn video_repair_cache_key(stream_id: &str, session_id: &str, chunk_key: &str) -> String { - format!("{stream_id}:{session_id}:video:{chunk_key}") -} - -fn video_repair_cache_key_from_payload(payload: &MuninnMediaSendPayload) -> Result> { - if payload.channel_id != MUNINN_MEDIA_RUDP_CHANNEL { - return Ok(None); - } - let GameCultMediaWireRecord::Video(video) = decode_media_wire_record(&payload.payload)? else { - return Ok(None); - }; - Ok(Some(video_repair_cache_key( - &video.stream_id, - &video.session_id, - &video_chunk_feedback_key(video.frame_id, video.chunk_index), - ))) -} - -#[derive(Debug)] -pub struct MuninnRudpMediaSendPacer { - payloads_since_pause: usize, - every_payloads: usize, - sleep_for: Duration, -} - -impl MuninnRudpMediaSendPacer { - pub fn new(every_payloads: usize, sleep_for: Duration) -> Self { - Self { - payloads_since_pause: 0, - every_payloads: every_payloads.max(1), - sleep_for, - } - } - - fn observe_sent_payload(&mut self) { - if self.sleep_for.is_zero() { - return; - } - self.payloads_since_pause = self.payloads_since_pause.saturating_add(1); - if self.payloads_since_pause < self.every_payloads { - return; - } - self.payloads_since_pause = 0; - thread::sleep(self.sleep_for); - } -} - -pub fn is_would_block_error(error: &anyhow::Error) -> bool { - error.chain().any(|cause| { - cause - .downcast_ref::() - .is_some_and(|io| io.kind() == ErrorKind::WouldBlock) - || cause.to_string().contains("os error 10035") - }) -} - -#[derive(Debug, PartialEq, Eq)] -enum SendOutcome { - Sent, - /// The socket is full: resends were polled, and the caller tries again on - /// its next step, choosing again what is most urgent. - SocketFull, - /// The session this send was addressed to no longer exists, or was - /// replaced by a newer generation. The receiver left; that is not an error. - ReceiverGone, -} - -/// Whether the hub still holds exactly the session `receiver` names. -fn receiver_is_live(hub: &CultNetRudpServerHub, receiver: &CultNetRudpServerSessionContext) -> bool { - hub.session(receiver.remote_addr) - .is_some_and(|live| live.session_generation == receiver.session_generation) -} - -/// One payload to one receiver, once. It never waits, so a full socket cannot -/// hold a queued audio packet behind video. A receiver that has left is -/// reported as gone, not as a failure: the send loop serves every receiver and -/// one leaving must not stop it. Every other hub error propagates. -fn try_send( - hub: &mut CultNetRudpServerHub, - receiver: &CultNetRudpServerSessionContext, - payload: &MuninnMediaSendPayload, - socket_full: bool, -) -> Result { - if !receiver_is_live(hub, receiver) { - return Ok(SendOutcome::ReceiverGone); - } - let sent = if socket_full { - Err(std::io::Error::from(ErrorKind::WouldBlock).into()) - } else { - hub.send(receiver, payload.channel_id, payload.payload.clone()) - }; - match sent { - Ok(()) => Ok(SendOutcome::Sent), - Err(error) if is_would_block_error(&error) => { - poll_resends(hub)?; - thread::yield_now(); - Ok(SendOutcome::SocketFull) - } - Err(error) => Err(error).context("sending typed Muninn media payload"), - } -} - -fn poll_resends(hub: &mut CultNetRudpServerHub) -> Result<()> { - match hub.poll_resends() { - Ok(()) => Ok(()), - Err(error) if is_would_block_error(&error) => Ok(()), - Err(error) => Err(error).context("polling Muninn RUDP media resends"), - } -} - -#[derive(Debug)] -enum GroupSend { - Complete, - /// The deadline passed after `payloads_out` payloads had gone out. - DeadlinePassed { payloads_out: usize }, -} - -/// A group being sent, one payload at a time, to the receivers there were when -/// it started. A payload with nobody to send it to is not a failure; the -/// progress line says how many receivers there are. -struct InFlight { - group: QueuedMediaGroup, - receivers: Vec, - payload: usize, - receiver: usize, -} - -impl InFlight { - /// Payloads that have reached at least one receiver. - fn payloads_out(&self) -> usize { - self.payload + usize::from(self.receiver > 0) - } -} - -/// A repair chunk waiting for the socket: one payload to the receiver that -/// asked, dead at the deadline of the frame it repairs. -struct PendingRepair { - receiver: CultNetRudpServerSessionContext, - payload: MuninnMediaSendPayload, - deadline: Instant, -} - -pub struct MediaSendCore { - hub: CultNetRudpServerHub, - queues: PendingMediaGroups, - repair_cache: RecentVideoChunkRepairCache, - repair_budget: MuninnRudpRepairBudget, - video_pacer: MuninnRudpMediaSendPacer, - audio_pacer: MuninnRudpMediaSendPacer, - audio_in_flight: Option, - video_in_flight: Option, - repairs: VecDeque, - /// Test seam: while set, the socket reports itself full. - #[cfg(test)] - pub(crate) socket_full: std::sync::Arc, - stats: MediaSendStats, - feedback: MuninnRudpReceiverFeedbackStats, - handled_keyframe_requests: u64, - disconnected: bool, -} - -impl MediaSendCore { - pub fn new(hub: CultNetRudpServerHub, policy: &MediaSendPolicy) -> Self { - Self { - hub, - queues: PendingMediaGroups::default(), - repair_cache: RecentVideoChunkRepairCache::new(REPAIR_CACHE_CHUNKS), - repair_budget: MuninnRudpRepairBudget::new( - REPAIR_INITIAL_CHUNKS_PER_SECOND, - REPAIR_BURST_CHUNKS, - ), - video_pacer: MuninnRudpMediaSendPacer::new( - policy.video_pace_every_payloads, - policy.video_pace_sleep, - ), - audio_pacer: MuninnRudpMediaSendPacer::new(0, Duration::ZERO), - audio_in_flight: None, - video_in_flight: None, - repairs: VecDeque::new(), - #[cfg(test)] - socket_full: Default::default(), - stats: MediaSendStats::default(), - feedback: MuninnRudpReceiverFeedbackStats::default(), - handled_keyframe_requests: 0, - disconnected: false, - } - } - - #[cfg(test)] - pub fn stats(&self) -> &MediaSendStats { - &self.stats - } - - #[cfg(test)] - pub fn feedback(&self) -> &MuninnRudpReceiverFeedbackStats { - &self.feedback - } - - #[cfg(test)] - pub fn hub(&self) -> &CultNetRudpServerHub { - &self.hub - } - - /// Nothing queued and every reader gone: the encoders have ended. - pub fn finished(&self) -> bool { - self.disconnected && !self.has_work() - } - - fn has_work(&self) -> bool { - !self.queues.is_empty() - || self.audio_in_flight.is_some() - || self.video_in_flight.is_some() - || !self.repairs.is_empty() - } - - /// Takes what the reader threads have produced. Waits up to `wait` for the - /// first group only when nothing is queued to send. - pub fn intake(&mut self, rx: &MediaIntakeReceiver, wait: Duration) -> Result<()> { - if self.disconnected { - return Ok(()); - } - if !self.has_work() { - match rx.recv_timeout(wait) { - Ok(item) => self.accept(item?), - Err(mpsc::RecvTimeoutError::Timeout) => return Ok(()), - Err(mpsc::RecvTimeoutError::Disconnected) => { - self.disconnected = true; - return Ok(()); - } - } - } - loop { - match rx.try_recv() { - Ok(item) => self.accept(item?), - Err(mpsc::TryRecvError::Empty) => return Ok(()), - Err(mpsc::TryRecvError::Disconnected) => { - self.disconnected = true; - return Ok(()); - } - } - } - } - - fn accept(&mut self, item: MediaIntake) { - match item { - MediaIntake::Group(group) => self.enqueue(group), - MediaIntake::VideoDropped(count) => { - self.stats.groups_dropped_video += count; - self.log_loss_milestone(); - } - } - } - - pub fn enqueue(&mut self, group: QueuedMediaGroup) { - let kind = group.kind; - if self.queues.push(group) { - match kind { - MediaKind::Audio => self.stats.groups_dropped_audio += 1, - MediaKind::Video => self.stats.groups_dropped_video += 1, - } - self.log_loss_milestone(); - } - } - - /// One step of the send loop: moves at most one payload toward the wire and - /// says whether there was anything to do. The next payload is chosen afresh - /// every step, audio first, then repairs, then video, so a video group in - /// progress or a full socket never holds audio back. A group whose - /// deadline has passed at `now`, before or after part of it went out, is - /// abandoned whole. - pub fn send_next(&mut self, now: Instant) -> Result { - #[cfg(test)] - let socket_full = self.socket_full.load(std::sync::atomic::Ordering::Relaxed); - #[cfg(not(test))] - let socket_full = false; - if self.step_group(MediaKind::Audio, now, socket_full)? - || self.step_repair(now, socket_full)? - { - return Ok(true); - } - self.step_group(MediaKind::Video, now, socket_full) - } - - fn step_group(&mut self, kind: MediaKind, now: Instant, socket_full: bool) -> Result { - let in_flight = match kind { - MediaKind::Audio => &mut self.audio_in_flight, - MediaKind::Video => &mut self.video_in_flight, - }; - if in_flight.is_none() { - let queue = match kind { - MediaKind::Audio => &mut self.queues.audio, - MediaKind::Video => &mut self.queues.video, - }; - let Some(group) = queue.pop_front() else { - return Ok(false); - }; - *in_flight = Some(InFlight { - group, - receivers: self.hub.sessions(), - payload: 0, - receiver: 0, - }); - } - let flight = in_flight.as_mut().expect("in flight was just filled"); - - if flight.group.expired(now) { - let outcome = GroupSend::DeadlinePassed { - payloads_out: flight.payloads_out(), - }; - let group_payloads = flight.group.payloads.len(); - *in_flight = None; - self.stats.record_group(&outcome, group_payloads); - self.log_loss_milestone(); - return Ok(true); - } - - if let Some(payload) = flight.group.payloads.get(flight.payload) { - if let Some(receiver) = flight.receivers.get(flight.receiver) { - match try_send(&mut self.hub, receiver, payload, socket_full)? { - SendOutcome::SocketFull => return Ok(true), - SendOutcome::Sent => flight.receiver += 1, - // Leaves the group; the next receiver slides into this slot. - SendOutcome::ReceiverGone => { - flight.receivers.remove(flight.receiver); - } - } - if flight.receiver < flight.receivers.len() { - return Ok(true); - } - } - flight.receiver = 0; - flight.payload += 1; - match kind { - MediaKind::Video => self.video_pacer.observe_sent_payload(), - MediaKind::Audio => self.audio_pacer.observe_sent_payload(), - } - if flight.payload < flight.group.payloads.len() { - return Ok(true); - } - } - - let flight = in_flight.take().expect("in flight is set"); - self.stats - .record_group(&GroupSend::Complete, flight.group.payloads.len()); - if kind == MediaKind::Video { - for payload in &flight.group.payloads { - self.repair_cache.remember(payload, flight.group.deadline)?; - } - } - if self.stats.groups_sent == 1 || self.stats.groups_sent % 900 == 0 { - eprintln!("{}", self.progress_detail()); - } - Ok(true) - } - - /// Sends the oldest queued repair chunk that is still inside its frame's - /// deadline at `now`; the ones already past it are discarded. - fn step_repair(&mut self, now: Instant, socket_full: bool) -> Result { - while let Some(repair) = self.repairs.front() { - if now > repair.deadline { - self.repairs.pop_front(); - continue; - } - match try_send(&mut self.hub, &repair.receiver, &repair.payload, socket_full)? { - SendOutcome::Sent => { - self.repairs.pop_front(); - self.feedback.repaired_video_chunks = - self.feedback.repaired_video_chunks.saturating_add(1); - self.video_pacer.observe_sent_payload(); - } - SendOutcome::SocketFull => {} - SendOutcome::ReceiverGone => { - let gone = repair.receiver.clone(); - self.repairs.retain(|queued| queued.receiver != gone); - } - } - return Ok(true); - } - Ok(false) - } - - /// Receiver feedback, repairs, keyframe pressure and resends. - pub fn service_control(&mut self, now: Instant) -> Result<()> { - self.poll_feedback(now)?; - if self.feedback.requested_keyframes > self.handled_keyframe_requests { - self.handled_keyframe_requests = self.feedback.requested_keyframes; - eprintln!( - "Muninn RUDP receiver requested a fresh keyframe; continuing current low-latency encoder session until explicit encoder control exists." - ); - } - poll_resends(&mut self.hub) - } - - fn poll_feedback(&mut self, now: Instant) -> Result<()> { - for gone in self.hub.remove_timed_out_sessions(RECEIVER_TIMEOUT_MS) { - eprintln!( - "Muninn media receiver {} at {} went silent and was dropped.", - String::from_utf8_lossy(&gone.connect_payload), - gone.remote_addr - ); - } - let mut feedback_processed = 0_usize; - loop { - match self.hub.receive_event_once() { - Ok(Some(CultNetRudpServerEvent::Connected { session })) => { - eprintln!( - "Muninn media receiver {} attached from {}.", - String::from_utf8_lossy(&session.connect_payload), - session.remote_addr - ); - } - Ok(Some(CultNetRudpServerEvent::Disconnected { session, reason })) => { - eprintln!( - "Muninn media receiver {} at {} disconnected: {}.", - String::from_utf8_lossy(&session.connect_payload), - session.remote_addr, - String::from_utf8_lossy(&reason) - ); - } - Ok(Some(CultNetRudpServerEvent::Frame { session, frame })) => { - if feedback_processed >= REPAIR_MAX_FEEDBACK_PER_POLL { - return Ok(()); - } - feedback_processed += 1; - let repairs = record_receiver_feedback( - &frame, - &mut self.feedback, - &self.repair_cache, - now, - )?; - let requested = repairs.len(); - let allowed = self.repair_budget.take( - requested.min(REPAIR_MAX_CHUNKS_PER_POLL), - now, - self.stats.groups_lost(), - ); - self.feedback.repair_chunks_per_second = self.repair_budget.chunks_per_second(); - self.feedback.deferred_repair_chunks = self - .feedback - .deferred_repair_chunks - .saturating_add(requested.saturating_sub(allowed) as u64); - // Repairs are queued for the receiver that asked, not for - // everyone; the send step sends each one inside the - // deadline of its own frame, after any waiting audio. The - // queue is bounded by the repair budget times the deadline. - self.repairs.extend( - repairs - .into_iter() - .take(allowed) - .map(|(payload, deadline)| PendingRepair { - receiver: session.clone(), - payload, - deadline, - }), - ); - } - Ok(Some(CultNetRudpServerEvent::Pong { .. })) => {} - Ok(None) => return Ok(()), - Err(error) if is_would_block_error(&error) => return Ok(()), - Err(error) => return Err(error).context("polling Muninn RUDP media feedback"), - } - } - } - - fn log_loss_milestone(&self) { - let lost = self.stats.groups_lost(); - // Loss can arrive in the hundreds per second; the first and every - // 300th is enough to see it without flooding the log. - if lost == 1 || lost % 300 == 0 { - eprintln!("{}", self.progress_detail()); - } - } - - pub fn progress_detail(&self) -> String { - format!( - "Muninn RUDP media progress: receivers={} groups_sent={} payloads_sent={} groups_dropped_audio={} groups_dropped_video={} groups_expired={} groups_cut_short={} reliable_expired={} receiver_feedback={} receiver_keyframes={} receiver_late_frames={} receiver_missing_chunks={} receiver_repaired_chunks={} receiver_deferred_repairs={} repair_rate={} receiver_highest_decodable={}; pending_audio={} pending_video={}", - self.hub.sessions().len(), - self.stats.groups_sent, - self.stats.payloads_sent, - self.stats.groups_dropped_audio, - self.stats.groups_dropped_video, - self.stats.groups_expired, - self.stats.groups_cut_short, - self.hub.stats().reliable_packets_expired, - self.feedback.feedback_records, - self.feedback.requested_keyframes, - self.feedback.late_frames, - self.feedback.missing_video_chunks, - self.feedback.repaired_video_chunks, - self.feedback.deferred_repair_chunks, - self.feedback.repair_chunks_per_second, - self.feedback - .highest_decodable_frame_id - .map(|frame_id| frame_id.to_string()) - .unwrap_or_else(|| "none".to_string()), - self.queues.audio.len(), - self.queues.video.len(), - ) - } - - #[cfg(test)] - pub(crate) fn queued_groups(&self, kind: MediaKind) -> usize { - match kind { - MediaKind::Audio => self.queues.audio.len(), - MediaKind::Video => self.queues.video.len(), - } - } - - #[cfg(test)] - pub(crate) fn queued_payload_bytes(&self, kind: MediaKind) -> usize { - match kind { - MediaKind::Audio => &self.queues.audio, - MediaKind::Video => &self.queues.video, - } - .iter() - .flat_map(|group| &group.payloads) - .map(|payload| payload.payload.len()) - .sum() - } - - #[cfg(test)] - pub(crate) fn oldest_deadline(&self, kind: MediaKind) -> Option { - match kind { - MediaKind::Audio => self.queues.audio.front(), - MediaKind::Video => self.queues.video.front(), - } - .map(|group| group.deadline) - } -} - -fn record_receiver_feedback( - frame: &CultNetTransportFrame, - stats: &mut MuninnRudpReceiverFeedbackStats, - repair_cache: &RecentVideoChunkRepairCache, - now: Instant, -) -> Result> { - if frame.channel_id != MUNINN_MEDIA_RUDP_CHANNEL { - return Ok(Vec::new()); - } - - let GameCultMediaWireRecord::Feedback(feedback) = decode_media_wire_record(&frame.payload)? - else { - return Ok(Vec::new()); - }; - - let repairs = repair_cache.repair_payloads_for_feedback(&feedback, now); - stats.feedback_records = stats.feedback_records.saturating_add(1); - if feedback.requested_keyframe { - stats.requested_keyframes = stats.requested_keyframes.saturating_add(1); - } - stats.late_frames = stats - .late_frames - .saturating_add(feedback.late_frame_ids.len() as u64); - stats.missing_video_chunks = stats - .missing_video_chunks - .saturating_add(feedback.missing_video_chunk_keys.len() as u64); - if let Some(frame_id) = feedback.highest_decodable_frame_id { - stats.highest_decodable_frame_id = Some( - stats - .highest_decodable_frame_id - .map(|current| current.max(frame_id)) - .unwrap_or(frame_id), - ); - } - Ok(repairs) -} - -/// Reads Annex B from `reader`, packetizes it, and hands one group per access -/// unit to the send loop, stamped with the request's deadline. -pub fn spawn_video_group_reader( - tx: MediaIntakeSender, - mut reader: R, - config: VideoAnnexBStreamSendConfig, - policy: MediaSendPolicy, -) -> thread::JoinHandle<()> -where - R: Read + Send + 'static, -{ - thread::spawn(move || { - if let Err(error) = read_video_groups(&tx, &mut reader, config, &policy) { - let _ = tx.send(Err(error)); - } - }) -} - -pub fn spawn_audio_group_reader( - tx: MediaIntakeSender, - mut reader: R, - config: AudioPcmStreamSendConfig, - policy: MediaSendPolicy, -) -> thread::JoinHandle<()> -where - R: Read + Send + 'static, -{ - thread::spawn(move || { - if let Err(error) = read_audio_groups(&tx, &mut reader, config, &policy) { - let _ = tx.send(Err(error)); - } - }) -} - -fn send_intake(tx: &MediaIntakeSender, item: MediaIntake) -> Result<()> { - tx.send(Ok(item)).context("queueing typed Muninn media") -} - -fn read_video_groups( - tx: &MediaIntakeSender, - reader: &mut R, - config: VideoAnnexBStreamSendConfig, - policy: &MediaSendPolicy, -) -> Result<()> { - let mut sender = VideoAnnexBStreamSendState::new(config)?; - let mut buffer = vec![0_u8; 64 * 1024]; - let mut dropped_reported = 0_u64; - loop { - let read = reader - .read(&mut buffer) - .context("reading encoded Annex B video from ffmpeg stdout")?; - let stored_at = crate::timestamp()?; - let (groups, done) = if read == 0 { - (sender.finish(&stored_at)?, true) - } else { - (sender.push(&stored_at, &buffer[..read])?, false) - }; - for payloads in groups { - send_intake( - tx, - MediaIntake::Group(QueuedMediaGroup::new( - MediaKind::Video, - Instant::now(), - policy, - payloads, - )), - )?; - } - let dropped = sender.dropped_access_units(); - if dropped > dropped_reported { - send_intake(tx, MediaIntake::VideoDropped(dropped - dropped_reported))?; - dropped_reported = dropped; - } - if done { - return Ok(()); - } - } -} - -fn read_audio_groups( - tx: &MediaIntakeSender, - reader: &mut R, - config: AudioPcmStreamSendConfig, - policy: &MediaSendPolicy, -) -> Result<()> { - let mut sender = AudioPcmStreamSendState::new(config)?; - let mut buffer = vec![0_u8; 16 * 1024]; - loop { - let read = reader - .read(&mut buffer) - .context("reading PCM audio from ffmpeg stdout")?; - let stored_at = crate::timestamp()?; - let (payloads, done) = if read == 0 { - (sender.finish(&stored_at)?, true) - } else { - (sender.push(&stored_at, &buffer[..read])?, false) - }; - for payload in payloads { - send_intake( - tx, - MediaIntake::Group(QueuedMediaGroup::new( - MediaKind::Audio, - Instant::now(), - policy, - vec![payload], - )), - )?; - } - if done { - return Ok(()); - } - } -} - -#[cfg(test)] -mod tests; diff --git a/crates/muninn-daemon/src/media_send/tests.rs b/crates/muninn-daemon/src/media_send/tests.rs deleted file mode 100644 index 873afd2..0000000 --- a/crates/muninn-daemon/src/media_send/tests.rs +++ /dev/null @@ -1,1523 +0,0 @@ -use super::*; -use crate::media_packetizer::{MediaWireProvenance, encode_media_wire_record}; -use cultnet_rs::{ - CultNetRudpPacketType, CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, - CultNetTransportDelivery, ReceiverFeedbackOptions, build_receiver_feedback, decode_rudp_packet, -}; -use std::collections::{BTreeMap, BTreeSet}; -use std::io::Cursor; -use std::net::{SocketAddr, UdpSocket}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; - -const CLIP: &[u8] = include_bytes!("../../testdata/clip.h264"); -const STREAM_ID: &str = "muninn.harness.rudp"; -const VIDEO_SESSION_ID: &str = "harness:video"; -const AUDIO_SESSION_ID: &str = "harness:audio"; -const WAIT: Duration = Duration::from_secs(5); - -fn wait_until(timeout: Duration, mut done: impl FnMut() -> bool) -> bool { - let start = Instant::now(); - while start.elapsed() < timeout { - if done() { - return true; - } - thread::sleep(Duration::from_millis(1)); - } - done() -} - -fn video_config() -> VideoAnnexBStreamSendConfig { - VideoAnnexBStreamSendConfig { - stream_id: STREAM_ID.to_string(), - session_id: VIDEO_SESSION_ID.to_string(), - codec: "h264".to_string(), - first_frame_id: 0, - first_pts_ticks: 0, - frame_duration_ticks: 3_000, - timebase_num: 1, - timebase_den: 90_000, - deadline_delay_ticks: 22_500, - max_payload_bytes: 848, - max_pending_bytes: 848 * 4096, - source_runtime_id: "harness".to_string(), - source_role: "muninn.rudp.video".to_string(), - } -} - -fn audio_config() -> AudioPcmStreamSendConfig { - AudioPcmStreamSendConfig { - stream_id: STREAM_ID.to_string(), - session_id: AUDIO_SESSION_ID.to_string(), - codec: "pcm-f32le-interleaved".to_string(), - first_packet_id: 0, - first_pts_ticks: 0, - packet_duration_ticks: 480, - timebase_num: 1, - timebase_den: 48_000, - deadline_delay_ticks: 24_000, - channels: 2, - bytes_per_sample: 4, - max_pending_bytes: 480 * 2 * 4 * 128, - source_runtime_id: "harness".to_string(), - source_role: "muninn.rudp.audio".to_string(), - } -} - -/// Ten audio packets of an ascending f32 ramp: every byte position is -/// distinct, so a reordered or dropped packet cannot pass for the ramp. -fn pcm_ramp() -> Vec { - let samples = 480 * 2 * 10; - (0..samples) - .flat_map(|index| (index as f32 / samples as f32).to_le_bytes()) - .collect() -} - -/// The clip's access units as the packetizer sends them: one group each. -fn clip_groups() -> Vec { - let mut sender = VideoAnnexBStreamSendState::new(video_config()).unwrap(); - let mut groups = sender.push("unix-0", CLIP).unwrap(); - groups.extend(sender.finish("unix-0").unwrap()); - groups -} - -fn group_at( - kind: MediaKind, - produced_at: Instant, - policy: &MediaSendPolicy, - payloads: MuninnMediaPayloadGroup, -) -> QueuedMediaGroup { - QueuedMediaGroup::new(kind, produced_at, policy, payloads) -} - -fn marker_payload(marker: u8) -> MuninnMediaSendPayload { - MuninnMediaSendPayload { - channel_id: MUNINN_MEDIA_RUDP_CHANNEL, - payload: vec![marker], - } -} - -/// `(frame_id, is_parity, chunk or parity index)` of a video wire record. -fn frame_of(payload: &[u8]) -> Option<(u64, bool, u16)> { - match decode_media_wire_record(payload).ok()? { - GameCultMediaWireRecord::Video(record) => Some((record.frame_id, false, record.chunk_index)), - GameCultMediaWireRecord::VideoParity(record) => { - Some((record.frame_id, true, record.parity_index)) - } - _ => None, - } -} - -/// Sends until the core has nothing left to do at `now`. Only for runs where -/// the socket is never full. -fn drain(core: &mut MediaSendCore, now: Instant) { - while core.send_next(now).unwrap() {} -} - -/// `count` one-slice access units with distinct frame ids 0..count, each a -/// single small group. -fn synthetic_groups(count: usize) -> Vec { - let mut sender = VideoAnnexBStreamSendState::new(video_config()).unwrap(); - let mut stream = Vec::new(); - for index in 0..count { - let nal = if index == 0 { 0x65 } else { 0x41 }; - stream.extend_from_slice(&[0, 0, 0, 1, nal, 0x80, index as u8]); - } - let mut groups = sender.push("unix-0", &stream).unwrap(); - groups.extend(sender.finish("unix-0").unwrap()); - assert_eq!(groups.len(), count); - groups -} - -fn one_audio_group() -> MuninnMediaPayloadGroup { - let mut sender = AudioPcmStreamSendState::new(audio_config()).unwrap(); - vec![sender.push("unix-0", &pcm_ramp()).unwrap().remove(0)] -} - -/// Hands the reader one chunk per `read`, so a test decides where a push ends. -struct ChunkedReader(std::collections::VecDeque>); - -impl Read for ChunkedReader { - fn read(&mut self, buffer: &mut [u8]) -> std::io::Result { - match self.0.pop_front() { - Some(chunk) => { - buffer[..chunk.len()].copy_from_slice(&chunk); - Ok(chunk.len()) - } - None => Ok(0), - } - } -} - -fn test_hub(policy: &MediaSendPolicy) -> CultNetRudpServerHub { - let socket = UdpSocket::bind("127.0.0.1:0").unwrap(); - socket.set_nonblocking(true).unwrap(); - CultNetRudpServerHub::new(crate::muninn_media_rudp_hub_options( - socket, - &crate::muninn_rudp_media_profile(), - policy, - )) - .unwrap() -} - -/// The request's budget and no pacing sleeps: the harness is about what the -/// core decides, not about how fast a Windows sender is allowed to go. -fn quiet_policy(latency_budget_ms: u32) -> MediaSendPolicy { - let mut policy = MediaSendPolicy::from_request(latency_budget_ms); - policy.video_pace_sleep = Duration::ZERO; - policy -} - -/// One datagram the hub sent toward the receiver, as the relay saw it. -#[derive(Clone, Debug)] -struct Sent { - packet_type: CultNetRudpPacketType, - channel: String, - payload: Vec, - dropped: bool, -} - -/// A UDP relay between the receiver and the hub. The hub's data packets are -/// dropped by a seeded schedule. Everything is logged before the drop, so -/// tests assert on what the sender put on the wire. -struct DropRelay { - addr: SocketAddr, - log: Arc>>, - stop: Arc, - thread: Option>, -} - -impl DropRelay { - fn start(hub_addr: SocketAddr, drop_percent: u64, seed: u64) -> Self { - let socket = UdpSocket::bind("127.0.0.1:0").unwrap(); - socket - .set_read_timeout(Some(Duration::from_millis(1))) - .unwrap(); - let addr = socket.local_addr().unwrap(); - let log = Arc::new(Mutex::new(Vec::new())); - let stop = Arc::new(AtomicBool::new(false)); - let thread = { - let log = Arc::clone(&log); - let stop = Arc::clone(&stop); - thread::spawn(move || { - let mut client: Option = None; - let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; - let mut buffer = vec![0_u8; 65_535]; - while !stop.load(Ordering::Relaxed) { - let Ok((received, from)) = socket.recv_from(&mut buffer) else { - continue; - }; - if from != hub_addr { - client = Some(from); - let _ = socket.send_to(&buffer[..received], hub_addr); - continue; - } - let Some(client) = client else { continue }; - let Ok(packet) = decode_rudp_packet(&buffer[..received]) else { - continue; - }; - let is_data = packet.packet_type == CultNetRudpPacketType::Data; - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - let dropped = is_data && state % 100 < drop_percent; - log.lock().unwrap().push(Sent { - packet_type: packet.packet_type, - channel: packet.channel_id, - payload: packet.payload, - dropped, - }); - if !dropped { - let _ = socket.send_to(&buffer[..received], client); - } - } - }) - }; - Self { - addr, - log, - stop, - thread: Some(thread), - } - } - - fn data(&self) -> Vec { - self.log - .lock() - .unwrap() - .iter() - .filter(|sent| sent.packet_type == CultNetRudpPacketType::Data) - .cloned() - .collect() - } - - fn channels_on_wire(&self) -> Vec { - self.data().into_iter().map(|sent| sent.channel).collect() - } - - fn frame_ids_on_wire(&self) -> BTreeSet { - self.video_frames_on_wire() - .into_iter() - .map(|(frame_id, _, _)| frame_id) - .collect() - } - - fn video_frames_on_wire(&self) -> Vec<(u64, bool, u16)> { - self.data() - .iter() - .filter(|sent| sent.channel == MUNINN_MEDIA_RUDP_CHANNEL) - .filter_map(|sent| frame_of(&sent.payload)) - .collect() - } -} - -impl Drop for DropRelay { - fn drop(&mut self) { - self.stop.store(true, Ordering::Relaxed); - if let Some(thread) = self.thread.take() { - let _ = thread.join(); - } - } -} - -struct Rig { - core: MediaSendCore, - client: CultNetRudpSocketTransportConnection, - relay: DropRelay, - policy: MediaSendPolicy, -} - -fn rig(latency_budget_ms: u32, drop_percent: u64, seed: u64) -> Rig { - let policy = quiet_policy(latency_budget_ms); - let hub = test_hub(&policy); - let relay = DropRelay::start(hub.local_addr().unwrap(), drop_percent, seed); - let socket = UdpSocket::bind("127.0.0.1:0").unwrap(); - socket.set_nonblocking(true).unwrap(); - let mut options = CultNetRudpSocketTransportOptions::client( - "harness-receiver", - socket, - relay.addr, - crate::MUNINN_MEDIA_RUDP_CONNECTION_ID, - ); - options.media_delivery = Some(CultNetTransportDelivery::Unreliable); - options.max_fragment_bytes = Some(crate::MUNINN_RUDP_MEDIA_MAX_FRAGMENT_BYTES as u32); - let mut client = CultNetRudpSocketTransportConnection::new(options).unwrap(); - let mut core = MediaSendCore::new(hub, &policy); - client.connect(b"harness-receiver".to_vec()).unwrap(); - assert!( - wait_until(WAIT, || { - core.service_control(Instant::now()).unwrap(); - let _ = client.receive_once().unwrap(); - client.connected() && core.hub().sessions().len() == 1 - }), - "receiver never attached through the relay" - ); - Rig { - core, - client, - relay, - policy, - } -} - -// ---- policy, groups and queues ----------------------------------------------------- - -#[test] -fn a_group_is_expired_only_after_its_deadline_and_never_at_it() { - let policy = quiet_policy(250); - let produced_at = Instant::now(); - let group = group_at(MediaKind::Video, produced_at, &policy, Vec::new()); - - assert!(!group.expired(group.deadline)); - assert!(!group.expired(group.deadline - Duration::from_millis(1))); - assert!(group.expired(group.deadline + Duration::from_millis(1))); -} - -#[test] -fn a_zero_request_budget_still_leaves_the_stream_a_millisecond() { - assert_eq!( - MediaSendPolicy::from_request(0).latency_budget, - Duration::from_millis(1) - ); -} - -#[test] -fn a_request_cannot_claim_more_than_the_maximum_latency_budget() { - assert_eq!(MEDIA_SEND_MAX_LATENCY_BUDGET_MS, 2_000); - let millis = |request| MediaSendPolicy::from_request(request).latency_budget; - assert_eq!(millis(u32::MAX), Duration::from_millis(2_000)); - assert_eq!(millis(2_001), Duration::from_millis(2_000)); - assert_eq!(millis(2_000), Duration::from_millis(2_000)); - assert_eq!(millis(1_999), Duration::from_millis(1_999)); - assert_eq!(millis(250), Duration::from_millis(250)); - - // Everything derived from the request follows the clamped budget. - let policy = MediaSendPolicy::from_request(u32::MAX); - let produced_at = Instant::now(); - let group = group_at(MediaKind::Video, produced_at, &policy, Vec::new()); - assert_eq!(group.deadline - produced_at, Duration::from_millis(2_000)); - assert_eq!(policy.latency_budget_ms(), 2_000); - assert_eq!(policy.video_deadline_delay_ticks(), 180_000); - assert_eq!(policy.audio_deadline_delay_ticks(48_000), 96_000); - let hub_options = crate::muninn_media_rudp_hub_options( - UdpSocket::bind("127.0.0.1:0").unwrap(), - &crate::muninn_rudp_media_profile(), - &policy, - ); - assert_eq!(hub_options.media_reliable_expire_after_ms, Some(2_000)); -} - -#[test] -fn the_queue_caps_groups_per_kind_and_drops_the_oldest_first() { - const VIDEO_CAP: usize = 512; - const AUDIO_CAP: usize = 256; - assert_eq!(MEDIA_SEND_VIDEO_GROUP_CAP, VIDEO_CAP); - assert_eq!(MEDIA_SEND_AUDIO_GROUP_CAP, AUDIO_CAP); - let policy = quiet_policy(250); - let mut core = MediaSendCore::new(test_hub(&policy), &policy); - let t0 = Instant::now(); - let over = 37; - for index in 0..(VIDEO_CAP + over) { - core.enqueue(group_at( - MediaKind::Video, - t0 + Duration::from_millis(index as u64), - &policy, - vec![marker_payload(1)], - )); - } - for index in 0..(AUDIO_CAP + 5) { - core.enqueue(group_at( - MediaKind::Audio, - t0 + Duration::from_millis(index as u64), - &policy, - vec![marker_payload(2)], - )); - } - - assert_eq!(core.queued_groups(MediaKind::Video), VIDEO_CAP); - assert_eq!(core.queued_groups(MediaKind::Audio), AUDIO_CAP); - // One byte per group: resident bytes are bounded by the cap times the group size. - assert_eq!(core.queued_payload_bytes(MediaKind::Video), VIDEO_CAP); - assert_eq!(core.queued_payload_bytes(MediaKind::Audio), AUDIO_CAP); - assert_eq!(core.stats().groups_dropped_video, over as u64); - assert_eq!(core.stats().groups_dropped_audio, 5); - // The survivors are the newest: the oldest deadline left is the 38th group's. - assert_eq!( - core.oldest_deadline(MediaKind::Video), - Some(t0 + Duration::from_millis(over as u64) + policy.latency_budget) - ); - assert_eq!( - core.oldest_deadline(MediaKind::Audio), - Some(t0 + Duration::from_millis(5) + policy.latency_budget) - ); -} - -#[test] -fn the_intake_channel_holds_the_reader_at_its_bound_instead_of_growing() { - let policy = quiet_policy(5_000); - let (tx, rx) = media_intake_channel(); - let frames = clip_groups().len(); - assert!(frames > MEDIA_GROUP_CHANNEL_BOUND + 1); - let reader = spawn_video_group_reader(tx, Cursor::new(CLIP.to_vec()), video_config(), policy); - - // Nothing drains, so the reader parks with the channel full. - thread::sleep(Duration::from_millis(300)); - assert!( - !reader.is_finished(), - "an unbounded channel let the reader run to the end" - ); - - let mut received = 0; - wait_until(WAIT, || { - while rx.try_recv().is_ok() { - received += 1; - } - received == frames - }); - assert_eq!(received, frames); - assert!(wait_until(WAIT, || reader.is_finished())); -} - -#[test] -fn a_full_socket_is_recognised_and_any_other_send_error_is_an_error() { - assert!(is_would_block_error(&std::io::Error::from(ErrorKind::WouldBlock).into())); - assert!(is_would_block_error(&anyhow::anyhow!("send failed: os error 10035"))); - assert!(!is_would_block_error(&anyhow::anyhow!("socket closed"))); - - let mut rig = rig(250, 0, 1); - - // A live receiver and a payload the hub refuses is an error. - let receiver = rig.core.hub().sessions()[0].clone(); - let oversize = MuninnMediaSendPayload { - channel_id: MUNINN_MEDIA_RUDP_CHANNEL, - payload: vec![0; 17 * 1024 * 1024], - }; - let error = try_send(&mut rig.core.hub, &receiver, &oversize, false).unwrap_err(); - assert!(!is_would_block_error(&error)); - assert!(format!("{error:#}").contains("sending typed Muninn media payload")); - - // A full socket is not an error: nothing is sent and the caller tries again. - assert_eq!( - try_send(&mut rig.core.hub, &receiver, &marker_payload(1), true).unwrap(), - SendOutcome::SocketFull - ); - thread::sleep(Duration::from_millis(50)); - assert!(rig.relay.data().is_empty()); - assert_eq!( - try_send(&mut rig.core.hub, &receiver, &marker_payload(1), false).unwrap(), - SendOutcome::Sent - ); -} - -#[test] -fn a_receiver_that_is_gone_is_not_an_error_whether_it_left_or_was_replaced() { - let mut rig = rig(250, 0, 1); - let receiver = rig.core.hub().sessions()[0].clone(); - - // Never a session at that endpoint. - let mut stranger = receiver.clone(); - stranger.remote_addr = "127.0.0.1:9".parse().unwrap(); - assert_eq!( - try_send(&mut rig.core.hub, &stranger, &marker_payload(1), false).unwrap(), - SendOutcome::ReceiverGone - ); - - // A session at the endpoint, but not the generation this send was made for. - let mut older = receiver.clone(); - older.session_generation -= 1; - assert_eq!( - try_send(&mut rig.core.hub, &older, &marker_payload(1), false).unwrap(), - SendOutcome::ReceiverGone - ); - - // A session that was live and has left, even with the socket reporting full. - assert!(rig.core.hub.disconnect(&receiver, b"left".to_vec()).unwrap()); - for socket_full in [false, true] { - assert_eq!( - try_send(&mut rig.core.hub, &receiver, &marker_payload(1), socket_full).unwrap(), - SendOutcome::ReceiverGone - ); - } -} - -fn session_named(core: &MediaSendCore, name: &str) -> CultNetRudpServerSessionContext { - core.hub() - .sessions() - .into_iter() - .find(|session| session.connect_payload == name.as_bytes()) - .unwrap_or_else(|| panic!("no session named {name}")) -} - -/// How many video payloads `receiver` has been sent so far. -fn video_heard_by(receiver: &mut CultNetRudpSocketTransportConnection) -> usize { - let mut heard = 0; - while let Some(frame) = receiver.receive_once().unwrap() { - heard += usize::from(frame_of(&frame.payload).is_some()); - } - heard -} - -#[test] -fn the_only_receiver_leaving_mid_frame_ends_the_frame_without_an_error() { - let mut rig = rig(2_000, 0, 1); - let t0 = Instant::now(); - let group = clip_groups() - .into_iter() - .find(|group| group.len() > 3) - .unwrap(); - rig.core - .enqueue(group_at(MediaKind::Video, t0, &rig.policy, group)); - for _ in 0..2 { - assert!(rig.core.send_next(t0).unwrap()); - } - - let receiver = session_named(&rig.core, "harness-receiver"); - assert!(rig.core.hub.disconnect(&receiver, b"left".to_vec()).unwrap()); - drain(&mut rig.core, t0); - - assert!(!rig.core.has_work()); - assert_eq!(rig.core.stats().groups_sent, 1); - assert_eq!(rig.core.stats().groups_lost(), 0); -} - -#[test] -fn a_receiver_that_asked_for_repairs_and_left_takes_its_queued_repairs_with_it() { - let t0 = Instant::now(); - let mut rig = rig(2_000, 0, 1); - let mut other = attach_direct_receiver(&mut rig); - let (_, frame_id, frame_payloads) = send_repairable_frame(&mut rig, t0); - ask_for_chunks(&mut rig, frame_id, &[0, 1], t0, 1); - other - .send( - MUNINN_MEDIA_RUDP_CHANNEL, - feedback_wire(feedback_for( - vec![video_chunk_feedback_key(frame_id, 0)], - false, - )), - ) - .unwrap(); - assert!(wait_until(WAIT, || { - rig.core.service_control(t0).unwrap(); - rig.core.feedback().feedback_records == 2 - })); - assert_eq!(rig.core.repairs.len(), 3); - let asker = session_named(&rig.core, "harness-receiver"); - assert!(rig.core.hub.disconnect(&asker, b"left".to_vec()).unwrap()); - - drain(&mut rig.core, t0); - - assert!(rig.core.repairs.is_empty()); - assert_eq!( - rig.core.feedback().repaired_video_chunks, - 1, - "only the receiver still attached was repaired" - ); - let mut heard = 0; - assert!(wait_until(WAIT, || { - heard += video_heard_by(&mut other); - heard == frame_payloads + 1 - })); -} - -#[test] -fn a_receiver_leaving_mid_frame_does_not_stop_the_other_receivers_stream() { - let t0 = Instant::now(); - let mut rig = rig(2_000, 0, 1); - let mut other = attach_direct_receiver(&mut rig); - let group = clip_groups() - .into_iter() - .find(|group| group.len() > 3) - .unwrap(); - let expected = group.len() * 2; - rig.core - .enqueue(group_at(MediaKind::Video, t0, &rig.policy, group.clone())); - for _ in 0..3 { - assert!(rig.core.send_next(t0).unwrap()); - } - - let leaver = session_named(&rig.core, "harness-receiver"); - assert!(rig.core.hub.disconnect(&leaver, b"left".to_vec()).unwrap()); - rig.core - .enqueue(group_at(MediaKind::Video, t0, &rig.policy, group)); - drain(&mut rig.core, t0); - - assert_eq!(rig.core.stats().groups_sent, 2); - assert_eq!(rig.core.stats().groups_lost(), 0); - let mut heard = 0; - assert!( - wait_until(WAIT, || { - heard += video_heard_by(&mut other); - heard == expected - }), - "the receiver that stayed heard {heard} of {expected} payloads" - ); -} - -#[test] -fn a_blocked_group_is_abandoned_at_its_own_deadline_not_a_budget_after_it_was_dequeued() { - // A 2 s budget, but this group's deadline is 80 ms out: a deadline taken - // from the moment the group left the queue would hold it for two seconds. - let mut rig = rig(MEDIA_SEND_MAX_LATENCY_BUDGET_MS, 0, 1); - let started = Instant::now(); - let mut group = group_at( - MediaKind::Video, - started, - &rig.policy, - (1..=6).map(marker_payload).collect(), - ); - group.deadline = started + Duration::from_millis(80); - rig.core.enqueue(group); - assert!(rig.core.send_next(started).unwrap()); - - rig.core.socket_full.store(true, Ordering::Relaxed); - while rig.core.stats().groups_cut_short == 0 && started.elapsed() < Duration::from_secs(1) { - assert!(rig.core.send_next(Instant::now()).unwrap()); - } - - let elapsed = started.elapsed(); - assert_eq!(rig.core.stats().groups_cut_short, 1); - assert_eq!(rig.core.stats().groups_expired, 0); - assert_eq!(rig.core.stats().groups_sent, 0); - assert_eq!(rig.core.stats().payloads_sent, 1); - assert!( - elapsed >= Duration::from_millis(80), - "abandoned before its deadline, after {elapsed:?}" - ); - assert!( - elapsed < Duration::from_millis(500), - "held past its deadline, until {elapsed:?}" - ); - assert!(!rig.core.has_work()); -} - -#[test] -fn a_group_whose_deadline_passes_mid_send_is_cut_short_and_counted() { - let mut rig = rig(50, 0, 1); - rig.core.video_pacer = MuninnRudpMediaSendPacer::new(1, Duration::from_millis(20)); - let payloads: MuninnMediaPayloadGroup = (1..=6).map(marker_payload).collect(); - rig.core.enqueue(group_at( - MediaKind::Video, - Instant::now(), - &rig.policy, - payloads, - )); - - while rig.core.send_next(Instant::now()).unwrap() {} - - let stats = rig.core.stats().clone(); - assert_eq!(stats.groups_cut_short, 1); - assert_eq!((stats.groups_sent, stats.groups_expired), (0, 0)); - assert!( - (1..6).contains(&stats.payloads_sent), - "some but not all of the group went out: {}", - stats.payloads_sent - ); - assert!(wait_until(WAIT, || rig.relay.data().len() as u64 - == stats.payloads_sent)); - thread::sleep(Duration::from_millis(100)); - assert_eq!(rig.relay.data().len() as u64, stats.payloads_sent); - assert!(rig.core.progress_detail().contains("groups_cut_short=1")); -} - -// ---- priority: audio goes first, one payload at a time ------------------------------- - -#[test] -fn audio_that_arrives_mid_frame_goes_out_before_the_frames_next_payload() { - let mut rig = rig(2_000, 0, 1); - let t0 = Instant::now(); - let video = clip_groups() - .into_iter() - .max_by_key(|group| group.len()) - .unwrap(); - assert!(video.len() >= 6, "the clip has a large frame"); - rig.core - .enqueue(group_at(MediaKind::Video, t0, &rig.policy, video.clone())); - for _ in 0..3 { - assert!(rig.core.send_next(t0).unwrap()); - } - - // The audio comes in through the reader channel while the frame is half sent. - let (tx, rx) = media_intake_channel(); - tx.send(Ok(MediaIntake::Group(group_at( - MediaKind::Audio, - t0, - &rig.policy, - one_audio_group(), - )))) - .unwrap(); - rig.core.intake(&rx, Duration::ZERO).unwrap(); - drain(&mut rig.core, t0); - - // An audio packet is more than one datagram; it is all sent before the - // frame's next payload. - assert!(wait_until(WAIT, || { - rig.relay.video_frames_on_wire().len() == video.len() - && rig.relay.channels_on_wire().iter().any(|channel| channel == "audio") - })); - let channels = rig.relay.channels_on_wire(); - assert_eq!( - channels.iter().position(|channel| channel == "audio"), - Some(3), - "audio waited for exactly the payload already in progress: {channels:?}" - ); - let last_audio = channels.iter().rposition(|channel| channel == "audio").unwrap(); - assert!( - channels[3..=last_audio].iter().all(|channel| channel == "audio"), - "the audio packet went out whole before video resumed: {channels:?}" - ); - assert_eq!(rig.core.stats().groups_sent, 2); -} - -#[test] -fn a_full_socket_never_holds_audio_behind_video() { - let mut rig = rig(2_000, 0, 1); - let t0 = Instant::now(); - let video = clip_groups() - .into_iter() - .max_by_key(|group| group.len()) - .unwrap(); - rig.core - .enqueue(group_at(MediaKind::Video, t0, &rig.policy, video.clone())); - for _ in 0..2 { - assert!(rig.core.send_next(t0).unwrap()); - } - - rig.core.socket_full.store(true, Ordering::Relaxed); - rig.core.enqueue(group_at( - MediaKind::Audio, - t0, - &rig.policy, - one_audio_group(), - )); - for _ in 0..50 { - let step = Instant::now(); - assert!(rig.core.send_next(t0).unwrap()); - assert!( - step.elapsed() < Duration::from_millis(50), - "a blocked step must hand control back, not wait for the socket" - ); - } - thread::sleep(Duration::from_millis(100)); - assert_eq!(rig.relay.data().len(), 2, "nothing went out while it was full"); - - rig.core.socket_full.store(false, Ordering::Relaxed); - assert!(rig.core.send_next(t0).unwrap()); - assert!(wait_until(WAIT, || rig.relay.data().len() >= 3)); - assert_eq!(rig.relay.data()[2].channel, "audio"); - drain(&mut rig.core, t0); - assert_eq!(rig.core.stats().groups_sent, 2); -} - -#[test] -fn audio_goes_out_between_repair_payloads() { - let t0 = Instant::now(); - let mut rig = rig(2_000, 0, 1); - let (_, frame_id, frame_payloads) = send_repairable_frame(&mut rig, t0); - ask_for_chunks(&mut rig, frame_id, &[0, 1], t0, 1); - assert_eq!(rig.core.repairs.len(), 2); - - assert!(rig.core.send_next(t0).unwrap()); - rig.core.enqueue(group_at( - MediaKind::Audio, - t0, - &rig.policy, - one_audio_group(), - )); - drain(&mut rig.core, t0); - - assert!(wait_until(WAIT, || rig.relay.video_frames_on_wire().len() - == frame_payloads + 2)); - let channels = rig.relay.channels_on_wire(); - let tail = &channels[frame_payloads..]; - assert_eq!(tail.first().map(String::as_str), Some(MUNINN_MEDIA_RUDP_CHANNEL)); - assert_eq!(tail.last().map(String::as_str), Some(MUNINN_MEDIA_RUDP_CHANNEL)); - let audio = &tail[1..tail.len() - 1]; - assert!( - !audio.is_empty() && audio.iter().all(|channel| channel == "audio"), - "the audio packet went out between the two repairs: {tail:?}" - ); - assert_eq!(rig.core.feedback().repaired_video_chunks, 2); -} - -#[test] -fn the_send_loop_is_not_finished_while_a_group_or_a_repair_is_still_going_out() { - let t0 = Instant::now(); - let mut rig = rig(2_000, 0, 1); - let (_, frame_id, _) = send_repairable_frame(&mut rig, t0); - rig.core.disconnected = true; - assert!(rig.core.finished(), "nothing left to send"); - - ask_for_chunk(&mut rig, frame_id, t0, 1); - assert!(!rig.core.finished(), "a repair is waiting"); - drain(&mut rig.core, t0); - assert!(rig.core.finished()); - - let group = clip_groups() - .into_iter() - .find(|group| group.len() > 2) - .unwrap(); - rig.core - .enqueue(group_at(MediaKind::Video, t0, &rig.policy, group)); - assert!(rig.core.send_next(t0).unwrap()); - assert!( - !rig.core.finished(), - "the queue is empty but the frame is half sent" - ); - drain(&mut rig.core, t0); - assert!(rig.core.finished()); -} - -// ---- loss leaves a gap the receiver can see -------------------------------------------- - -#[test] -fn a_group_dropped_by_the_queue_cap_leaves_its_frame_id_missing_on_the_wire() { - let mut rig = rig(2_000, 0, 1); - let t0 = Instant::now(); - let over = 3; - let mut groups = synthetic_groups(1 + MEDIA_SEND_VIDEO_GROUP_CAP + over).into_iter(); - rig.core.enqueue(group_at( - MediaKind::Video, - t0, - &rig.policy, - groups.next().unwrap(), - )); - drain(&mut rig.core, t0); - for group in groups { - rig.core - .enqueue(group_at(MediaKind::Video, t0, &rig.policy, group)); - } - drain(&mut rig.core, t0); - - let expected: BTreeSet = std::iter::once(0) - .chain((1 + over as u64)..=(MEDIA_SEND_VIDEO_GROUP_CAP + over) as u64) - .collect(); - assert!(wait_until(WAIT, || rig.relay.frame_ids_on_wire() == expected)); - assert_eq!(rig.core.stats().groups_dropped_video, over as u64); - assert!(!rig.relay.frame_ids_on_wire().contains(&1), "frame 1 is the gap"); -} - -#[test] -fn an_expired_group_leaves_its_frame_id_missing_on_the_wire() { - let mut rig = rig(250, 0, 1); - let t0 = Instant::now(); - let budget = rig.policy.latency_budget; - let groups = synthetic_groups(3); - for (group, produced_at) in groups.into_iter().zip([t0 + 5 * budget, t0, t0 + 5 * budget]) { - rig.core - .enqueue(group_at(MediaKind::Video, produced_at, &rig.policy, group)); - } - - drain(&mut rig.core, t0 + 2 * budget); - - assert!(wait_until(WAIT, || rig.relay.frame_ids_on_wire() - == BTreeSet::from([0, 2]))); - assert_eq!(rig.core.stats().groups_expired, 1); -} - -#[test] -fn an_overflow_drop_leaves_its_frame_id_missing_and_no_partial_frame_on_the_wire() { - let mut rig = rig(2_000, 0, 1); - let mut config = video_config(); - config.max_pending_bytes = 16; - let start = [0, 0, 0, 1]; - let mut first = Vec::new(); - // Frame 0, whole; then the head of a frame that outgrows the ceiling. - first.extend_from_slice(&[&start[..], &[0x65, 0x80, 0xA1]].concat()); - first.extend_from_slice(&[&start[..], &[0x41, 0x80], &[0xB2; 30]].concat()); - let mut second = Vec::new(); - // Its second slice, then two whole frames. - second.extend_from_slice(&[&start[..], &[0x41, 0x40, 0xC3, 0xC3]].concat()); - second.extend_from_slice(&[&start[..], &[0x41, 0x80, 0xD4]].concat()); - second.extend_from_slice(&[&start[..], &[0x41, 0x80, 0xE5]].concat()); - let (tx, rx) = media_intake_channel(); - let reader = spawn_video_group_reader( - tx, - ChunkedReader([first, second].into()), - config, - rig.policy.clone(), - ); - - let started = Instant::now(); - while !rig.core.finished() && started.elapsed() < WAIT { - rig.core.intake(&rx, Duration::from_millis(2)).unwrap(); - drain(&mut rig.core, Instant::now()); - } - assert!(rig.core.finished()); - reader.join().unwrap(); - - assert!(wait_until(WAIT, || rig.relay.frame_ids_on_wire() - == BTreeSet::from([0, 2, 3]))); - assert_eq!(rig.core.stats().groups_dropped_video, 1); - assert_eq!(rig.core.stats().groups_sent, 3); -} - -// ---- moved from the mux: repair budget, feedback intake, repair cache --------------- - -#[test] -fn rudp_repair_budget_backs_off_on_media_drops_and_recovers_when_stable() { - let start = Instant::now(); - let mut budget = MuninnRudpRepairBudget { - chunks_per_second: 64, - min_chunks_per_second: 8, - max_chunks_per_second: 128, - add_chunks_per_second: 8, - recovery_interval: Duration::from_secs(2), - max_available_chunks: 4, - available_chunks: 4, - last_refill_at: start, - last_rate_adjust_at: start, - last_queue_dropped: 0, - }; - - assert_eq!(budget.take(4, start, 0), 4); - assert_eq!(budget.chunks_per_second(), 64); - assert_eq!(budget.take(3, start + Duration::from_millis(10), 1), 0); - assert_eq!(budget.chunks_per_second(), 32); - assert_eq!(budget.take(3, start + Duration::from_secs(1), 1), 3); - assert_eq!(budget.chunks_per_second(), 32); - assert_eq!(budget.take(3, start + Duration::from_secs(3), 1), 3); - assert_eq!(budget.chunks_per_second(), 40); -} - -#[test] -fn default_rudp_repair_budget_has_lan_stream_headroom() { - let mut budget = - MuninnRudpRepairBudget::new(REPAIR_INITIAL_CHUNKS_PER_SECOND, REPAIR_BURST_CHUNKS); - let start = budget.last_refill_at; - - assert_eq!(budget.chunks_per_second(), 4_096); - assert_eq!(budget.take(2_048, start, 0), 2_048); - assert_eq!(budget.take(8_192, start + Duration::from_secs(1), 0), 2_048); - assert_eq!(budget.take(8_192, start + Duration::from_secs(3), 0), 2_048); - assert_eq!(budget.chunks_per_second(), 6_144); - assert_eq!(budget.take(512, start + Duration::from_secs(4), 1), 512); - assert_eq!(budget.chunks_per_second(), 3_072); -} - -fn feedback_for( - missing_chunk_keys: Vec, - requested_keyframe: bool, -) -> GameCultMediaReceiverFeedbackRecord { - build_receiver_feedback(ReceiverFeedbackOptions { - stream_id: STREAM_ID, - session_id: VIDEO_SESSION_ID, - receiver_id: "harness-receiver", - highest_decodable_frame_id: Some(41), - missing_frame_ids: Vec::new(), - missing_video_chunk_keys: missing_chunk_keys, - late_frame_ids: vec![42, 43], - requested_keyframe, - jitter_us: 500, - decode_queue_us: 2_000, - observed_at: "unix:1000", - }) - .unwrap() -} - -fn feedback_wire(feedback: GameCultMediaReceiverFeedbackRecord) -> Vec { - encode_media_wire_record( - &GameCultMediaWireRecord::Feedback(feedback), - MediaWireProvenance { - stored_at: "unix:1000", - runtime_id: "harness", - role: "harness.receiver", - producer: "harness", - }, - ) - .unwrap() -} - -#[test] -fn rudp_media_receiver_feedback_updates_sender_pressure_stats() { - let frame = CultNetTransportFrame { - channel_id: MUNINN_MEDIA_RUDP_CHANNEL.to_string(), - payload: feedback_wire(feedback_for(vec!["42:1".into(), "42:3".into()], true)), - }; - let mut stats = MuninnRudpReceiverFeedbackStats::default(); - let repair_cache = RecentVideoChunkRepairCache::new(16); - - let repairs = - record_receiver_feedback(&frame, &mut stats, &repair_cache, Instant::now()).unwrap(); - - assert_eq!(stats.feedback_records, 1); - assert_eq!(stats.requested_keyframes, 1); - assert_eq!(stats.late_frames, 2); - assert_eq!(stats.missing_video_chunks, 2); - assert_eq!(stats.repaired_video_chunks, 0); - assert_eq!(stats.highest_decodable_frame_id, Some(41)); - assert!(repairs.is_empty()); -} - -#[test] -fn repair_cache_returns_recent_missing_video_chunks_with_their_frames_deadline() { - let groups = clip_groups(); - let payload = groups[0][0].clone(); - let (frame_id, _, chunk_index) = frame_of(&payload.payload).unwrap(); - let feedback = feedback_for( - vec![ - video_chunk_feedback_key(frame_id, chunk_index), - "999:0".to_string(), - ], - false, - ); - let deadline = Instant::now() + Duration::from_millis(250); - - let mut cache = RecentVideoChunkRepairCache::new(16); - cache.remember(&payload, deadline).unwrap(); - let repairs = cache.repair_payloads_for_feedback(&feedback, deadline); - - assert_eq!(repairs, vec![(payload.clone(), deadline)]); - assert!( - cache - .repair_payloads_for_feedback(&feedback, deadline + Duration::from_millis(1)) - .is_empty(), - "a chunk past its frame's deadline is not offered for repair" - ); -} - -// ---- the wire: whole groups, repairs inside their frame's deadline ------------------ - -#[test] -fn a_group_past_its_deadline_puts_nothing_on_the_wire_and_a_live_one_puts_all_of_it() { - let mut rig = rig(250, 0, 1); - let groups = clip_groups(); - let stale = groups[0].clone(); - let live = groups - .iter() - .skip(1) - .find(|group| group.len() > 2) - .expect("the clip has a later multi-chunk frame") - .clone(); - let live_frame = frame_of(&live[0].payload).unwrap().0; - let t0 = Instant::now(); - let budget = rig.policy.latency_budget; - rig.core - .enqueue(group_at(MediaKind::Video, t0, &rig.policy, stale)); - rig.core.enqueue(group_at( - MediaKind::Video, - t0 + 5 * budget, - &rig.policy, - live.clone(), - )); - - // Two budgets after the stale group was made, inside the live group's. - drain(&mut rig.core, t0 + 2 * budget); - - assert_eq!(rig.core.stats().groups_expired, 1); - assert_eq!(rig.core.stats().groups_sent, 1); - assert!(wait_until(WAIT, || { - rig.relay.video_frames_on_wire().len() == live.len() - })); - thread::sleep(Duration::from_millis(100)); - let on_wire = rig.relay.video_frames_on_wire(); - assert_eq!( - on_wire.len(), - live.len(), - "every payload of the live group, and no other" - ); - assert!(on_wire.iter().all(|(frame, _, _)| *frame == live_frame)); - assert!(rig.core.progress_detail().contains("groups_sent=1")); - assert!(rig.core.progress_detail().contains("groups_expired=1")); -} - -#[test] -fn audio_leaves_before_video_on_the_wire() { - let mut rig = rig(250, 0, 1); - let t0 = Instant::now(); - let video = clip_groups().remove(1); - let mut audio_sender = AudioPcmStreamSendState::new(audio_config()).unwrap(); - let audio = audio_sender.push("unix-0", &pcm_ramp()).unwrap().remove(0); - rig.core - .enqueue(group_at(MediaKind::Video, t0, &rig.policy, video)); - rig.core - .enqueue(group_at(MediaKind::Audio, t0, &rig.policy, vec![audio])); - - drain(&mut rig.core, t0); - - assert!(wait_until(WAIT, || !rig.relay.data().is_empty())); - assert_eq!(rig.relay.data()[0].channel, "audio"); -} - -/// Sends the clip's first multi-chunk frame at `t0` and returns its deadline, -/// its frame id and how many payloads it put on the wire. -fn send_repairable_frame(rig: &mut Rig, t0: Instant) -> (Instant, u64, usize) { - let group = clip_groups() - .into_iter() - .find(|group| group.len() > 2) - .unwrap(); - let (frame_id, _, _) = frame_of(&group[0].payload).unwrap(); - let queued = group_at(MediaKind::Video, t0, &rig.policy, group.clone()); - let deadline = queued.deadline; - rig.core.enqueue(queued); - drain(&mut rig.core, t0); - assert!(wait_until(WAIT, || rig.relay.video_frames_on_wire().len() - == group.len())); - (deadline, frame_id, group.len()) -} - -/// The receiver asks for chunks and the sender takes the request in at `at`. -/// Nothing is sent: that is the send step's job, at its own `now`. -fn ask_for_chunk(rig: &mut Rig, frame_id: u64, at: Instant, records_seen: u64) { - ask_for_chunks(rig, frame_id, &[0], at, records_seen); -} - -fn ask_for_chunks(rig: &mut Rig, frame_id: u64, chunks: &[u16], at: Instant, records_seen: u64) { - rig.client - .send( - MUNINN_MEDIA_RUDP_CHANNEL, - feedback_wire(feedback_for( - chunks - .iter() - .map(|chunk| video_chunk_feedback_key(frame_id, *chunk)) - .collect(), - false, - )), - ) - .unwrap(); - assert!( - wait_until(WAIT, || { - rig.core.service_control(at).unwrap(); - rig.core.feedback().feedback_records == records_seen - }), - "the hub never received the feedback" - ); -} - -#[test] -fn a_repair_is_sent_inside_its_frames_deadline_and_not_after_it() { - // Taken before the handshake, so real time is well past it by the time - // anything is sent: a repair that took its deadline from the clock - // instead of its frame would still be alive at the probe below. - let t0 = Instant::now(); - let mut rig = rig(250, 0, 1); - let (deadline, frame_id, frame_payloads) = send_repairable_frame(&mut rig, t0); - let epsilon = Duration::from_millis(2); - - ask_for_chunk(&mut rig, frame_id, deadline - epsilon, 1); - drain(&mut rig.core, deadline - epsilon); - assert!( - wait_until(WAIT, || rig.relay.video_frames_on_wire().len() - == frame_payloads + 1), - "a repair asked for just before the deadline is sent" - ); - assert_eq!(rig.core.feedback().repaired_video_chunks, 1); - - ask_for_chunk(&mut rig, frame_id, deadline + epsilon, 2); - assert!( - rig.core.repairs.is_empty(), - "a chunk already past its frame's deadline is not queued" - ); - drain(&mut rig.core, deadline + epsilon); - thread::sleep(Duration::from_millis(150)); - assert_eq!( - rig.relay.video_frames_on_wire().len(), - frame_payloads + 1, - "a repair asked for just after the deadline is not sent" - ); - assert_eq!(rig.core.feedback().repaired_video_chunks, 1); - assert_eq!(rig.core.feedback().missing_video_chunks, 2); -} - -#[test] -fn a_queued_repair_is_dropped_if_its_frames_deadline_passes_before_it_is_sent() { - let t0 = Instant::now(); - let mut rig = rig(250, 0, 1); - let (deadline, frame_id, frame_payloads) = send_repairable_frame(&mut rig, t0); - let epsilon = Duration::from_millis(2); - - // Alive when the feedback is taken in, dead by the time it is sent. - ask_for_chunk(&mut rig, frame_id, deadline - epsilon, 1); - assert_eq!(rig.core.repairs.len(), 1); - drain(&mut rig.core, deadline + epsilon); - - thread::sleep(Duration::from_millis(150)); - assert_eq!(rig.relay.video_frames_on_wire().len(), frame_payloads); - assert_eq!(rig.core.feedback().repaired_video_chunks, 0); - assert!(rig.core.repairs.is_empty()); -} - -#[test] -fn a_repair_goes_only_to_the_receiver_that_asked_for_it() { - let t0 = Instant::now(); - let mut rig = rig(2_000, 0, 1); - let mut other = attach_direct_receiver(&mut rig); - let (_, frame_id, frame_payloads) = send_repairable_frame(&mut rig, t0); - let heard_by_other = |other: &mut CultNetRudpSocketTransportConnection| { - let mut heard = 0; - while let Some(frame) = other.receive_once().unwrap() { - heard += usize::from(frame_of(&frame.payload).is_some()); - } - heard - }; - let mut other_heard = 0; - assert!(wait_until(WAIT, || { - other_heard += heard_by_other(&mut other); - other_heard == frame_payloads - })); - - ask_for_chunk(&mut rig, frame_id, t0, 1); - drain(&mut rig.core, t0); - - assert!(wait_until(WAIT, || rig.relay.video_frames_on_wire().len() - == frame_payloads + 1)); - thread::sleep(Duration::from_millis(150)); - other_heard += heard_by_other(&mut other); - assert_eq!(other_heard, frame_payloads, "the repair was not for this receiver"); -} - -fn attach_direct_receiver(rig: &mut Rig) -> CultNetRudpSocketTransportConnection { - let socket = UdpSocket::bind("127.0.0.1:0").unwrap(); - socket.set_nonblocking(true).unwrap(); - let mut options = CultNetRudpSocketTransportOptions::client( - "harness-receiver-b", - socket, - rig.core.hub().local_addr().unwrap(), - crate::MUNINN_MEDIA_RUDP_CONNECTION_ID, - ); - options.media_delivery = Some(CultNetTransportDelivery::Unreliable); - options.max_fragment_bytes = Some(crate::MUNINN_RUDP_MEDIA_MAX_FRAGMENT_BYTES as u32); - let mut client = CultNetRudpSocketTransportConnection::new(options).unwrap(); - client.connect(b"harness-receiver-b".to_vec()).unwrap(); - assert!( - wait_until(WAIT, || { - rig.core.service_control(Instant::now()).unwrap(); - let _ = client.receive_once().unwrap(); - rig.client.receive_once().unwrap(); - client.connected() && rig.core.hub().sessions().len() == 2 - }), - "the second receiver never attached" - ); - client -} - -// ---- the harness end to end: the fixture clip and the PCM ramp --------------------- - -#[derive(Default)] -struct Received { - chunks: BTreeMap>, - chunk_counts: BTreeMap, - audio: BTreeMap>, -} - -impl Received { - fn take(&mut self, rig: &mut Rig) { - while let Some(frame) = rig.client.receive_once().unwrap() { - match decode_media_wire_record(&frame.payload).unwrap() { - GameCultMediaWireRecord::Video(record) => { - self.chunks - .entry(record.frame_id) - .or_default() - .insert(record.chunk_index); - self.chunk_counts - .insert(record.frame_id, record.chunk_count); - } - GameCultMediaWireRecord::Audio(record) => { - self.audio.insert(record.packet_id, record.payload); - } - _ => {} - } - } - } - - fn complete_frames(&self) -> BTreeSet { - self.chunks - .iter() - .filter(|(frame, chunks)| chunks.len() == self.chunk_counts[frame] as usize) - .map(|(frame, _)| *frame) - .collect() - } -} - -/// Feeds the fixture through the real readers and the send loop, over the -/// relay, and returns what the receiver assembled. -fn run_clip(rig: &mut Rig, with_audio: bool) -> Received { - let (tx, rx) = media_intake_channel(); - let video = spawn_video_group_reader( - tx.clone(), - Cursor::new(CLIP.to_vec()), - video_config(), - rig.policy.clone(), - ); - let audio = with_audio.then(|| { - spawn_audio_group_reader( - tx.clone(), - Cursor::new(pcm_ramp()), - audio_config(), - rig.policy.clone(), - ) - }); - drop(tx); - let mut received = Received::default(); - let start = Instant::now(); - while !rig.core.finished() && start.elapsed() < WAIT { - rig.core.intake(&rx, Duration::from_millis(2)).unwrap(); - rig.core.send_next(Instant::now()).unwrap(); - rig.core.service_control(Instant::now()).unwrap(); - received.take(rig); - } - assert!(rig.core.finished(), "the send loop never finished the clip"); - let settle = Instant::now(); - while settle.elapsed() < Duration::from_millis(300) { - rig.core.service_control(Instant::now()).unwrap(); - received.take(rig); - thread::sleep(Duration::from_millis(1)); - } - video.join().unwrap(); - if let Some(audio) = audio { - audio.join().unwrap(); - } - received -} - -#[test] -fn the_clip_and_the_pcm_ramp_arrive_whole_through_a_lossless_relay() { - // A budget far above the run time: nothing here may expire. - let mut rig = rig(5_000, 0, 1); - let frames = clip_groups().len() as u64; - - let received = run_clip(&mut rig, true); - - assert_eq!( - received.complete_frames(), - (0..frames).collect::>() - ); - assert_eq!(rig.core.stats().groups_lost(), 0); - let heard: Vec = received.audio.values().flatten().copied().collect(); - assert_eq!(received.audio.len(), 10); - assert_eq!(heard, pcm_ramp(), "the ramp arrived complete and in order"); -} - -#[test] -fn the_seeded_relay_drops_the_same_datagrams_every_run_and_the_sender_carries_on() { - let run = |seed| { - let mut rig = rig(5_000, 30, seed); - let received = run_clip(&mut rig, false); - let dropped: Vec = rig.relay.data().iter().map(|sent| sent.dropped).collect(); - (received.complete_frames(), dropped, rig.core.stats().clone()) - }; - - let (complete_a, dropped_a, stats_a) = run(7); - let (complete_b, dropped_b, _) = run(7); - let (_, dropped_other, _) = run(8); - let frames = clip_groups().len(); - - assert_eq!(dropped_a, dropped_b, "same seed, same drop schedule"); - assert_ne!( - dropped_a, dropped_other, - "a different seed drops different datagrams" - ); - assert_eq!(complete_a, complete_b); - assert!(dropped_a.iter().any(|dropped| *dropped)); - assert!( - complete_a.len() < frames, - "30% loss without parity or repair leaves incomplete frames" - ); - assert_eq!(stats_a.groups_sent, frames as u64); - assert_eq!( - stats_a.groups_lost(), - 0, - "loss on the wire is not a sender-side drop" - ); -} - -#[test] -fn a_group_is_counted_by_what_the_deadline_let_reach_the_wire() { - let mut stats = MediaSendStats::default(); - - stats.record_group(&GroupSend::Complete, 6); - assert_eq!((stats.groups_sent, stats.payloads_sent), (1, 6)); - - // Deadline passed before the first payload: nothing left, so nothing was cut. - stats.record_group(&GroupSend::DeadlinePassed { payloads_out: 0 }, 6); - assert_eq!((stats.groups_expired, stats.groups_cut_short), (1, 0)); - assert_eq!(stats.payloads_sent, 6); - - // Deadline passed with part of the group already out: a partial frame. - stats.record_group(&GroupSend::DeadlinePassed { payloads_out: 2 }, 6); - assert_eq!((stats.groups_expired, stats.groups_cut_short), (1, 1)); - assert_eq!(stats.payloads_sent, 8); - assert_eq!(stats.groups_lost(), 2); -} - -#[test] -fn an_oversize_access_unit_reaches_the_sender_as_a_dropped_video_group_not_an_error() { - let policy = quiet_policy(250); - let mut core = MediaSendCore::new(test_hub(&policy), &policy); - let (tx, rx) = media_intake_channel(); - let mut config = video_config(); - config.max_pending_bytes = 8; - let mut oversize = vec![0, 0, 0, 1, 0x65, 0x80]; - oversize.extend_from_slice(&[7; 20]); - let reader = spawn_video_group_reader(tx, Cursor::new(oversize), config, policy); - - assert!(wait_until(WAIT, || reader.is_finished())); - core.intake(&rx, Duration::from_millis(50)).unwrap(); - core.intake(&rx, Duration::from_millis(50)).unwrap(); - - assert_eq!(core.stats().groups_dropped_video, 1); - assert!(core.finished(), "the stream ended cleanly, it was not restarted by an error"); -} - -// ---- the rules each get a test that fails without them -------------------------------- - -#[test] -fn an_audio_group_past_its_deadline_is_dropped_and_counted_like_a_video_group() { - let mut rig = rig(250, 0, 1); - let t0 = Instant::now(); - let budget = rig.policy.latency_budget; - rig.core.enqueue(group_at( - MediaKind::Audio, - t0, - &rig.policy, - one_audio_group(), - )); - - drain(&mut rig.core, t0 + 2 * budget); - - assert_eq!(rig.core.stats().groups_expired, 1); - assert_eq!(rig.core.stats().groups_sent, 0); - thread::sleep(Duration::from_millis(100)); - assert!(rig.relay.data().is_empty(), "stale audio reached the wire"); -} - -#[test] -fn a_repair_waiting_on_a_full_socket_stays_queued_and_goes_out_when_it_clears() { - let t0 = Instant::now(); - let mut rig = rig(2_000, 0, 1); - let (_, frame_id, frame_payloads) = send_repairable_frame(&mut rig, t0); - ask_for_chunk(&mut rig, frame_id, t0, 1); - assert_eq!(rig.core.repairs.len(), 1); - - rig.core.socket_full.store(true, Ordering::Relaxed); - for _ in 0..5 { - assert!(rig.core.send_next(t0).unwrap()); - } - assert_eq!(rig.core.repairs.len(), 1, "the repair was popped unsent"); - assert_eq!(rig.core.feedback().repaired_video_chunks, 0); - - rig.core.socket_full.store(false, Ordering::Relaxed); - drain(&mut rig.core, t0); - assert!(rig.core.repairs.is_empty()); - assert_eq!(rig.core.feedback().repaired_video_chunks, 1); - assert!(wait_until(WAIT, || rig.relay.video_frames_on_wire().len() - == frame_payloads + 1)); -} - -#[test] -fn a_full_socket_still_polls_resends() { - // Every datagram is dropped, so the audio packets stay unacknowledged and - // the hub owes them a resend. - let mut rig = rig(2_000, 100, 1); - let t0 = Instant::now(); - rig.core.enqueue(group_at( - MediaKind::Audio, - t0, - &rig.policy, - one_audio_group(), - )); - drain(&mut rig.core, t0); - assert!(wait_until(WAIT, || !rig.relay.data().is_empty())); - thread::sleep(Duration::from_millis(50)); - let first_pass = rig.relay.data().len(); - - // Only the full-socket path runs here: no service_control, no other poll. - rig.core.enqueue(group_at( - MediaKind::Video, - t0, - &rig.policy, - vec![marker_payload(1)], - )); - rig.core.socket_full.store(true, Ordering::Relaxed); - let started = Instant::now(); - while started.elapsed() < Duration::from_millis(300) { - assert!(rig.core.send_next(t0).unwrap()); - thread::sleep(Duration::from_millis(5)); - } - - assert!( - wait_until(WAIT, || rig.relay.data().len() > first_pass), - "no resend went out while the socket was full" - ); -} - -#[test] -fn losing_groups_slows_the_repair_budget() { - let t0 = Instant::now(); - let mut rig = rig(2_000, 0, 1); - let (_, frame_id, _) = send_repairable_frame(&mut rig, t0); - - // One group is lost at the sender: it dies before it is sent. - let mut doomed = group_at(MediaKind::Audio, t0, &rig.policy, one_audio_group()); - doomed.deadline = t0; - rig.core.enqueue(doomed); - drain(&mut rig.core, t0 + Duration::from_millis(1)); - assert_eq!(rig.core.stats().groups_lost(), 1); - - ask_for_chunk(&mut rig, frame_id, t0, 1); - - assert_eq!( - rig.core.feedback().repair_chunks_per_second, - REPAIR_INITIAL_CHUNKS_PER_SECOND / 2, - "the budget did not see the loss" - ); -} diff --git a/crates/muninn-daemon/testdata/clip.h264 b/crates/muninn-daemon/testdata/clip.h264 deleted file mode 100644 index 860d9e0f7d6f7c38adce6e7042d880d82318f29f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8855 zcmb8Uc{r4R^fx{m#y(@;XHY4LAvW3-|z4DdH#IvKhAyL=Y7t(&-FUzy5~Kw8vpB6{eyR>Ttr}-GKL2{2E*h$jigw1dZFyx6OmrXJ zeX!wvNNs&RWcX1Xouf#Ut|7|jGK#z5pviU6I&sR@{)jHp@`5$j)7Q_3yJ3yR#fA9! zM^A3rN@I#|wx$9W%quR(&KXg=R z05T%#GFQ_^A#o9LXzjle6Yh)F)Bg6edLINYuI!MD4y}s}#Bm|! zHk8`|U2fN|a@+T}7l6M5=a-o(#3b6f|yJEuos#&YnNpPPwY2&-C=UB3f@y=2C)x#w}ye=a}kluUQo?FiKJKTh*4ht8h) zc`)F~iLO&$&eLB^$jfYoT(BN};TCgJo>y_kx(DC;^%QzJ?#UYIX_!dd#TDhV`PY!% zV26>e$cINshW)p(bmqx6^k_*&$_vGj+yT<}vIcNmtc}@0p-ih_3WruJbz(&|6TnO0 zxhMMooYxm2Vy*XyaY?}^2cQ5^-V_9tt~n^c0>pV4q*Z$%!Tr5IU$rta6ud}p*G>ng zIte22YsuCrGAp6@4bjx@Njl?!YAT1*|6MuKE*U?`E@z!fb?n%<#UHPWO`kcKfJ3bC{zFZCyn5!Az{-wrE0DZ$vX(MG0kU|VTI!^LU)^%pHzHO>p z7#Qe(WC0E5e3xHlJ9i{ZtUa1wjm(e!*>Sb>M4eqpVKzJex)rP*u>hakW4;bwI9vCD z+Ok+T)t)=>VfCTEc_WN1!(6F&=f`-z#Upl(ky-En0JFOTJD08)SJt5nb&3HcDQn9R z-ZbuQw7rnU%MjqbE&eZuMCj>24v+V5-MCB2P+eXCD3RA-UTm5TP(J$Wv~Vh1$`ubF znaT0oNQ2!4&JzVe^11PGKEee~LFA;TUPx6w&*Lp@1zkA<;oZ(<&~X$Y>-M9{l$v7T zwQWz-KbP#@*z7YYX8~hLr!+THRS$MT512Xi0_7j}NSy0DbhSqYkaGWwcIW*$B~7FP z7@F+iKKfi?nx>Z5y692|CTI#Ftv=ih8E-NBj`xbox|sQl7ZbCGPsTXe=io(z3NhFB z;pULKS9ueM?-Ck%{Eze=C~W{=CZ&(5zIo4!05GFv6AF9twDbG{{K*&T^t4Hy-Lbk^ z&R%MLw!%mA&NbThy6bu2KAFR?(jnAFzV-r#v&-X~Hm&e`c*IfAqTrMWDhI*%j4}lX zF!OHFya2`^fZ;)vWzjSshrhGdoR>*^D`RRh^Gim>?~|42g}T(l*O%A~UcY^x5M!)F zu!3@O$>dmCy~5q1PSIl9FPY8!<{Hk1-1NMs#*Zu5GKoOpO6udcj%H=4JbfrMx;@wV? zV;_DGR7t702cbT_E8xi1ELUGC*r0Dc^Dp2NIp}bU>ExJxJ8+Nqjl`?J__>+%4l;Rr zdGE~`BtBg|g(N4AdQ-$4eyIGThR#5&^45bnTgejV&PB!uGiI%EtAjx3NIVk>hfUbo%b zmQ(=~`L-Lc+~s*HiU9?WN0J`NG>v#Xq=iVOpvo%llsCe<4@tWksuza_ z!7=bzjAh97@W96&ZFXb1u5H6AXMBd7qYIHMs3 zK^};|`SeA}>ylB24~*1xm=La)@v^m#bAKaV_Y~vf2w)1iN3S`3i4+q}2k z4O&^7xpbX_{mxXzd~M!eNK{t1rq&%}Sy?3t(O46{=)bp5(A_7hV~gc;zj09LdcV3- zO;WOu*6}BLA(6@MkuEL&!9|@HUj_r6ZLzryfXWPd&l*u!^N6GENT4G1;d>`u9Z{Bc zfOT2u45ybeUhdN1n|`$2!A8h};16dCeGWM=-4VHk`aa%1MN1=3Is?TudLiO3u9~Y| zHhT=Ql(BM^dtZVl11MxuC&?x9q~eC<6ZY#|C1@lx`%s4cNgYH+@8b{lU7&2|Jn4Zo zHl!#R-%Jzz3^%yac=ioLC79>!zH>yXq>=|KcLuh)CQZ>ES9bGdF=#eP2@EUyq_*$O zF%~SMJ@#mkw-6C8LRrq?5D7h)B zd440Fk#l~ApLtwTq#O}5&aBz8rY%G`PBodUEfQDj7d(ejAvp?g;Ql)^6~F$pJw9s& zDK9EzJ5P4;Qvz<4Tv>ie@Aj$nTHzSf1b>86m5p2!JCQ1;th)x~WaZ`h9L5pU=aXSj zgE>`3&P%+Z{Sggw#+D-E=1McgqlZ^fLEN+H4*v=IkDGX6DZcvYoWZ**jErAN`1OO3jh%tZE-3!RRq^+E&%HJTsNasxNB1o;mp~U?iOO=t`@l|i7Go=)w_3`|3Z`Uad4PG9}Mr@Sb>hE}* zi2uH`kz4V(5-MmV<_A)3kBfCB96zBCcyp!;(mnNvPUu_Ox*wBoC5~YwKvFhPR;M&H zAj^eyi7$XA+kBoE4`|wXSA8Lmm4tVMEtaKSE6;li9*-#Bsxy6ZG5xOTiN=_9+TkCc z(y!%+mEe~Pl|HOzPz&3WS=3oWK_Cu7 z!njW%&fO+fsjcugg4#Enk8cZjF0`2R}7E&@|QgV*CRw zFKBTuQTkfMjFM8j4NJQ6Q7>(Z?OA^Wm&EH%;fOvwbIcGI$zPmRw|V-Y7`uO`PUOxA zBt2#_SF5w{%h~9nX$If-W7nGg$vWadgX1HAD%sFdK%8zr z64E5)*H)?awheq>Kd3&-t$%p=(ie_ebvrb-u&oMC)?M>PSR#lK^*&l#!oG{xpPrBk zk_J8V^2TLSFP>ok>|0VzgkI3b0vW0&j9%wq0o3}wem{1Kdac~Ne1OzoB}RCVz@p?Y zd5Jk}v6qp8yQK{0`@1hH$WPGZ!@n!7;m^B&uyl9i9I=ax`Rk%=jv((z`6>>^Snac; z+CNvnrTtl#GmN29X`o{s7>?Q7`Lk#6AVgFWmhGIiL;cUV2c}?Vl%>DGiaw~N%yt@G zKa4DVPMsE3YZ?*EgeA*cKre+xuTk)26B9Adm0~a-mN>cTtK0EngDiQ)4@E4bkO@X~ z`&C;CABuyRyB+;xq$B%Ky};m_`LouEywXX2O0Obg0D>`KZ-16*eKkqquL-6uteF=w zGT6?-wp8Qf!_yqPq<6AJUF-$9L}x%5hz3^})uavq3NBmk)%7;WXVI5)p_PT1!5MD~ z5>+4y7xRjkA?K@D( zy{~gSdlGKus#ofo^&)3EMTH$4y6b;%i|fS9!cKR~{(PG@ZI>*M1TH2}v9ZhMqgCt{ zHzT(5eGas@sCWJA)$x z5^+X2X#@^3SyqrZbS0kqi%v+(|FB46t3rw+2kPG{y@?IlkGPL?#!fuEfxW}Y-735a zXJns?+~6?MG@S+hkzVyGvzTHW!)jrm>9J*J5^ww|ug)Q!?@m;S=Jn@W03y3SY<2*$ zXYTz;_G~8N)kZsj%IWq~hQCwIsMRd-AGt-}wtWtkV|dJ+_2Eo=y25Yx=mgWp?YC<^ zhOD4_FG{P3ZDN8UOSi|#({K`Uaw2NwgqARKfZA8}6D85@We_FVeI`ro0NbsojJ*b_ zGctisy}k{0vAh2aCHXu`OBl53VP@TgYt`%X0gA&-h?y7uJ{-F{}=wtFEfRgOGj|up}sWD$ABmd4cL3s z;ZfSm@}{tkRfp*5KO~hk-7FK)+cF_uA&nR6M12J#?5DI5yVF5r+u5-;xB4$e?RBnW z$Lqrpy9;uG69S0cIRygP@;v|osUXI1BE<`QlSIt7Np8l<&W^7Ds;@%@UZQN^`e*%zhM7_0dEuCStBJY`p> zil>dUTw474@I#S`=vAA2zTX!5(yw{P?oLw?016ud3?P z_Pn%ezN6|b8Ix*z8YgwS@Ej20o`w5nve&;c%ywby8!wo;9K!^=SI$=VM-H0I20rw4 zFs=wBKXXUBK%REyJuMg|3A)xgD1OQa8^?6{BdKYHWv1>zrMLTUX1&;$p)wh9A;fDh&(j)b*ts6 z6T*no7uBegol8kHQ!1%Dmtfp6eSQ6awT&9)Met=A>BHEl^ju0Ezj~AH;sj9XcT?iv zP5uj$0~+UToI8_I7679Gd5-yKA1WFX=F-P`p@J(fcwauR9m0wxvJtJd1w%pOVY2c& zW_h zaL;EPTT@6m=RX<3Kem=3q~)HFz$9hn=lrjnNxkk;olSY5G7_AB@>hdrYEA1e7_s#_ zTY>U$FI_Lt58C5zSJ*#sr6@d)EKy!!`bvQ8^Lo@ z8+Q{$eI@jhlfp{MoW}dp*o8JAAg2eUO2TshaG-5M5A=a{*F9>{d&eu63$g8dL@*c> zHKjRG*J$!CJ2CESvV*06V%#_YU|v*`c0y%b#5s%+xKBxVU+NFty&&_La=oFU6I;8C z#@CmiAWx_qYsR-l#yTkd?DO~q2M1uT!orWp@DTOmzqXa0Fy8qet4E9x16ig9i_NAo zDHSA9fU6fwvr;8=zotCA^H#$m303VtIgx7=9!k)vw@9lmE8b7xp|Axy4dm0?fSD(F z08EI}>Qg*HXL7$P(#o<|luoB9gwK2u1;Yzm^+!V#viZdlMYSF8JtoZE&?*HfBSwVB zXfnLOo1V*$=RDa3P6UeS>pqhjiObb;YCdLcx)$$C{}hs$u`oi>Zv~ebhH^N6p)1{3 zajoG;{m?DQ;l$AU?qI-*jD3mlE>)@sOjuB&$;O;0fH7?}nKHppMzz8&=@Eq#*1 zbLyd!1ch`u#_6tbr(dp^>lF=xKJpi^J`!Nwv)z%gGEK%tgj1f4v-n3 z3rns3EuAT*41Gw1Ol5;EROB4G)|+;J005V7a(rhiJtwOCJ_Wvn$50fIq#E18Ofgf7 zM?xo4jy>Oa2WEm%5?O?@A4qwFs*?dIl8nWLY0;a5L&7?u_$6d4%BGhA`;;!#h%F-H z;8s!q)lG2>FJkWMB+YDqzb=Ju=RJB7yrPH~P6JhK7+vL>5E5tsm)7Iy9S1bj%kB#B4@JIV1KHpnB5JwR z-lOZbp~C|!Kw+2oc-+-qa!QcW3tQYdkMnaTaCi z!cxTVY+-U$bPddz4v-P#FAK{wQxX8Z*C5CaAruD_ph=CN{AQD54+w_CGC98`iPAZK zcUQ0U?)QCjtmZM~7wxte6**CkU4m{2mCtxIb^F}cyx%mM@0|9sW2G+Ed#|dVDI;z1 zD4Mv+-@Idm=GUO?gvj2M>FxODK}y)Ute4%!US;XWyCqq#JE0k`(he${W(d9VXulfV z>&2Jw8M_|!qnU-{ct5gCbuc2^&sp#jP&|d3E+Y!i8FxT)YCtVybDodOU70_LWhep28?NtICyyEDC0rnIaO zO4cJLs?udU(rb`j=issN0lW(3aZ2n5{&zxKBNtrv5}%x`-|Csp!8uaT{7CP*L(91E z5^(A%b0DtCZjp|F{_~ZrR0fxJy>w)=(}WBo40$bi;)?^#F=nwJU-e}yA+VfQU*GuI z$mLlx|DSiY{;1Ngl;L}p_V6ZKF$y0r@soLVKh1}@%vdV)zXXdqUj#hw<_m=QicPl- zg~UWTh-LR}o|ufMockc{u#aPIuKR$?=<&Fjvg{C`V0ERcZzmLK zG3-@4`A&hf&NFW2*LQWECe`k=k(Tx`o&h+_Igh6TO3X_m5|vjF#QoT~L!y{2wvyj~)gRlCml!o#>`x9){{_@FRyIMM{ z=H+bX*elTZSnDB1uBo(#0Ul~g`p@8+@I{D64(*vftjJ&6sp0>_(ei{7y@iVyag6u2 zlPbhhiI_T~^OGueyR7wCy7GGUr4Dh%TQM*+{^$FiQR=AT7N5DF5N^cADNCbd!Gye~ zk^_EzC)rt8L((w|WM^-GYP5%uJ-$JPWxaHlh^LgU|CH=y_T!7{ayQhUKj1e+?%i=3 zoMChS(qMW$&Y>OCPp9$HMD(9VgF_v?W>5c6bLm)92!9;gW|>HjObZDfDSHK}qX||- zzUALI8TB{LRBl-)J{djH=u#OoNb^5n90Oz=N}!l(TTzMuoqKE7l6TZGWOF+TtiJYWaLj7$ z(`9<0sx$Vvc#dhrXBhYBS|4k7b@ittGi(^!8J;xT59eZ~{QgHj2QzB&n&VXe;*Hb@N3~XSo{M6Rd6QoF^ycE|{m3-&f&ci8_mEp8S?dUS6Y|6#h$|AMiFXl3tB zK%<@WNu7HbUbQEoOIlR2emf)YAw0hWNwnDR`c#LTSdv@^;F2j+oNTayyQ;woip)8eWj2z|V znWSQ*%$afVb6wB$W|T7o;m!&=$E3K_-I(X>Md%&RRMknMOFNuFu%-)=l|@{GZJchY zI@*e`EiNNGTxi?OhAs5Nr>6XEbFFyus}a{tUwu2*ytx{l{1}n-rz%Z(gO-1Bi>Py$ z-7@*)Ka&wiXx2vSvRCiH5_Vt7cU0t1De Date: Thu, 3 Dec 2026 22:23:20 +0100 Subject: [PATCH 2/8] Strip Eve/Idunn/compat residue from muninn-contracts and sleipnir-daemon; move SleipnirInputMappingRecord into muninn-contracts --- crates/muninn-contracts/src/lib.rs | 112 +-- crates/muninn-contracts/src/records.rs | 160 +--- crates/sleipnir-daemon/src/main.rs | 1070 ++---------------------- 3 files changed, 98 insertions(+), 1244 deletions(-) diff --git a/crates/muninn-contracts/src/lib.rs b/crates/muninn-contracts/src/lib.rs index e111ae5..ac2f4ec 100644 --- a/crates/muninn-contracts/src/lib.rs +++ b/crates/muninn-contracts/src/lib.rs @@ -7,9 +7,6 @@ pub use records::*; cultmesh_rs::cultmesh_documents!(MuninnRecords { MuninnTelemetrySurfaceRecord => MUNINN_TELEMETRY_SURFACE_SCHEMA, - MuninnCaptureStreamRecord => MUNINN_CAPTURE_STREAM_SCHEMA, - MuninnCaptureStreamCommandRecord => MUNINN_CAPTURE_STREAM_COMMAND_SCHEMA, - MuninnObsStreamCatalogRecord => MUNINN_OBS_STREAM_CATALOG_SCHEMA, MuninnMoveMarkerCandidateRecord => MUNINN_MOVE_MARKER_CANDIDATE_SCHEMA, MuninnMoveControllerStateRecord => MUNINN_MOVE_CONTROLLER_STATE_SCHEMA, MuninnHidControllerStateRecord => MUNINN_HID_CONTROLLER_STATE_SCHEMA, @@ -19,8 +16,7 @@ cultmesh_rs::cultmesh_documents!(MuninnRecords { MuninnMoveTrackerHealthRecord => MUNINN_MOVE_TRACKER_HEALTH_SCHEMA, MuninnMoveEvidenceTransportHealthRecord => MUNINN_MOVE_EVIDENCE_TRANSPORT_HEALTH_SCHEMA, MuninnQuestAccessRecord => MUNINN_QUEST_ACCESS_SCHEMA, - MuninnCommandBoundaryCompatRecord => MUNINN_COMMAND_BOUNDARY_SCHEMA, - MuninnTransportProfileCompatRecord => MUNINN_TRANSPORT_PROFILE_SCHEMA, + SleipnirInputMappingRecord => SLEIPNIR_INPUT_MAPPING_SCHEMA, }); #[cfg(test)] @@ -45,9 +41,6 @@ mod tests { } vec![ row!(MuninnTelemetrySurfaceRecord, MUNINN_TELEMETRY_SURFACE_SCHEMA), - row!(MuninnCaptureStreamRecord, MUNINN_CAPTURE_STREAM_SCHEMA), - row!(MuninnCaptureStreamCommandRecord, MUNINN_CAPTURE_STREAM_COMMAND_SCHEMA), - row!(MuninnObsStreamCatalogRecord, MUNINN_OBS_STREAM_CATALOG_SCHEMA), row!(MuninnMoveMarkerCandidateRecord, MUNINN_MOVE_MARKER_CANDIDATE_SCHEMA), row!(MuninnMoveControllerStateRecord, MUNINN_MOVE_CONTROLLER_STATE_SCHEMA), row!(MuninnHidControllerStateRecord, MUNINN_HID_CONTROLLER_STATE_SCHEMA), @@ -60,8 +53,7 @@ mod tests { MUNINN_MOVE_EVIDENCE_TRANSPORT_HEALTH_SCHEMA ), row!(MuninnQuestAccessRecord, MUNINN_QUEST_ACCESS_SCHEMA), - row!(MuninnCommandBoundaryCompatRecord, MUNINN_COMMAND_BOUNDARY_SCHEMA), - row!(MuninnTransportProfileCompatRecord, MUNINN_TRANSPORT_PROFILE_SCHEMA), + row!(SleipnirInputMappingRecord, SLEIPNIR_INPUT_MAPPING_SCHEMA), ] } @@ -69,9 +61,6 @@ mod tests { fn record_names_are_the_published_schema_ids() { let expected = [ ("muninn.telemetry_surface", "muninn.telemetry_surface.v1"), - ("muninn.capture_stream", "muninn.capture_stream.v1"), - ("muninn.capture_stream_command", "muninn.capture_stream_command.v1"), - ("muninn.obs_stream_catalog", "muninn.obs_stream_catalog.v1"), ("muninn.move_marker_candidate", "muninn.move_marker_candidate.v1"), ("muninn.move_controller_state", "muninn.move_controller_state.v1"), ("muninn.hid_controller_state", "muninn.hid_controller_state.v1"), @@ -84,8 +73,7 @@ mod tests { "muninn.move_evidence_transport_health.v1", ), ("muninn.quest_access", "muninn.quest_access.v1"), - ("muninn.command_boundary", "muninn.command_boundary.v1"), - ("muninn.transport_profile", "muninn.transport_profile.v1"), + ("sleipnir.input_mapping", "sleipnir.input_mapping.v1"), ]; let actual: Vec<_> = contract() .into_iter() @@ -191,75 +179,6 @@ mod tests { Some(9), "dc0015a773757266616365a4686f7374a46c69766591a373726391a361666691a3616374a461757468a664657461696ca174a470736964a6706c6162656ca3636d64a36d7468cd0fa1cd04b0cd1f402891a376696491a4766c616291a361696491a4616c6162", ), - pin( - "MuninnCaptureStreamRecord", - MuninnCaptureStreamRecord { - stream_id: text("stream"), - host_id: text("host"), - state: text("live"), - video_source: text("vsrc"), - audio_source: text("asrc"), - transport: text("rudp"), - targets: texts(&["tgt"]), - command_witness: text("wit"), - supervisor_pid: None, - mux_pid: Some(77), - restart_count: 3, - detail: text("detail"), - updated_at: text("t"), - }, - None, - "9da673747265616da4686f7374a46c697665a476737263a461737263a47275647091a3746774a3776974c04d03a664657461696ca174", - ), - pin( - "MuninnCaptureStreamCommandRecord", - MuninnCaptureStreamCommandRecord { - command_id: text("cmd"), - host_id: text("host"), - stream_id: text("stream"), - state: text("live"), - action: text("start"), - target_host: text("tgt"), - port: 4001, - obs_target_host: Some(text("obs")), - obs_port: 4002, - media_transport: text("rudp"), - media_packet_bytes: 1200, - requested_by: text("who"), - detail: text("detail"), - updated_at: text("t"), - rudp_video_bitrate_kbps: 8000, - rudp_latency_budget_ms: 40, - video_source_id: text("vid"), - audio_source_id: text("aid"), - }, - Some(14), - "dc0012a3636d64a4686f7374a673747265616da46c697665a57374617274a3746774cd0fa1a36f6273cd0fa2a472756470cd04b0a377686fa664657461696ca174cd1f4028a3766964a3616964", - ), - pin( - "MuninnObsStreamCatalogRecord", - MuninnObsStreamCatalogRecord { - catalog_id: text("catalog"), - host_id: text("host"), - stream_ids: texts(&["sid"]), - labels: texts(&["lab"]), - urls: texts(&["url"]), - states: texts(&["st"]), - updated_at: text("t"), - command_rudp_target: text("cmd"), - media_target_host: text("mth"), - media_port: 4001, - media_packet_bytes: 1200, - rudp_video_bitrate_kbps: 8000, - rudp_latency_budget_ms: 40, - video_source_ids: texts(&["vid"]), - video_source_labels: texts(&["vlab"]), - audio_source_ids: texts(&["aid"]), - audio_source_labels: texts(&["alab"]), - }, - Some(7), - "dc0011a7636174616c6f67a4686f737491a373696491a36c616291a375726c91a27374a174a3636d64a36d7468cd0fa1cd04b0cd1f402891a376696491a4766c616291a361696491a4616c6162", - ), pin( "MuninnMoveMarkerCandidateRecord", MuninnMoveMarkerCandidateRecord { @@ -442,20 +361,21 @@ mod tests { "9fa6616363657373a4686f7374a673657269616ca4636f6e6ea770726f64756374a56d6f64656ca6646576696365a3746964a5696e707574a4706f7365a5766964656faa767472616e73706f7274a46c697665a664657461696ca174", ), pin( - "MuninnCommandBoundaryCompatRecord", - MuninnCommandBoundaryCompatRecord { - value: serde_json::json!({ "daemon_id": "muninn" }), + "SleipnirInputMappingRecord", + SleipnirInputMappingRecord { + provider_id: text("prov"), + enabled: true, + device_filter: text("dev"), + stream_id: text("stream"), + presentation: text("xbox360"), + axis_map: serde_json::json!({ "leftX": 0 }), + button_map: serde_json::json!({ "cross": "a" }), + pending_learn: serde_json::json!({ "target": "b" }), + updated_at: text("t"), + source: text("src"), }, None, - "9181a96461656d6f6e5f6964a66d756e696e6e", - ), - pin( - "MuninnTransportProfileCompatRecord", - MuninnTransportProfileCompatRecord { - value: serde_json::json!({ "state": "live" }), - }, - None, - "9181a57374617465a46c697665", + "9aa470726f76c3a3646576a673747265616da778626f7833363081a56c656674580081a563726f7373a16181a6746172676574a162a174a3737263", ), ] } diff --git a/crates/muninn-contracts/src/records.rs b/crates/muninn-contracts/src/records.rs index 7742843..2d96f6f 100644 --- a/crates/muninn-contracts/src/records.rs +++ b/crates/muninn-contracts/src/records.rs @@ -2,9 +2,6 @@ use cultcache_rs::DatabaseEntry; use serde_json::Value; pub const MUNINN_TELEMETRY_SURFACE_SCHEMA: &str = "muninn.telemetry_surface.v1"; -pub const MUNINN_CAPTURE_STREAM_SCHEMA: &str = "muninn.capture_stream.v1"; -pub const MUNINN_CAPTURE_STREAM_COMMAND_SCHEMA: &str = "muninn.capture_stream_command.v1"; -pub const MUNINN_OBS_STREAM_CATALOG_SCHEMA: &str = "muninn.obs_stream_catalog.v1"; pub const MUNINN_MOVE_MARKER_CANDIDATE_SCHEMA: &str = "muninn.move_marker_candidate.v1"; pub const MUNINN_MOVE_CONTROLLER_STATE_SCHEMA: &str = "muninn.move_controller_state.v1"; pub const MUNINN_HID_CONTROLLER_STATE_SCHEMA: &str = "muninn.hid_controller_state.v1"; @@ -15,83 +12,7 @@ pub const MUNINN_MOVE_TRACKER_HEALTH_SCHEMA: &str = "muninn.move_tracker_health. pub const MUNINN_MOVE_EVIDENCE_TRANSPORT_HEALTH_SCHEMA: &str = "muninn.move_evidence_transport_health.v1"; pub const MUNINN_QUEST_ACCESS_SCHEMA: &str = "muninn.quest_access.v1"; -pub const MUNINN_COMMAND_BOUNDARY_SCHEMA: &str = "muninn.command_boundary.v1"; -pub const MUNINN_TRANSPORT_PROFILE_SCHEMA: &str = "muninn.transport_profile.v1"; - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "muninn.capture_stream", schema = "muninn.capture_stream.v1")] -pub struct MuninnCaptureStreamRecord { - #[cultcache(key = 0)] - pub stream_id: String, - #[cultcache(key = 1)] - pub host_id: String, - #[cultcache(key = 2)] - pub state: String, - #[cultcache(key = 3)] - pub video_source: String, - #[cultcache(key = 4)] - pub audio_source: String, - #[cultcache(key = 5)] - pub transport: String, - #[cultcache(key = 6)] - pub targets: Vec, - #[cultcache(key = 7)] - pub command_witness: String, - #[cultcache(key = 8)] - pub supervisor_pid: Option, - #[cultcache(key = 9)] - pub mux_pid: Option, - #[cultcache(key = 10)] - pub restart_count: u32, - #[cultcache(key = 11)] - pub detail: String, - #[cultcache(key = 12)] - pub updated_at: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "muninn.capture_stream_command", - schema = "muninn.capture_stream_command.v1" -)] -pub struct MuninnCaptureStreamCommandRecord { - #[cultcache(key = 0)] - pub command_id: String, - #[cultcache(key = 1)] - pub host_id: String, - #[cultcache(key = 2)] - pub stream_id: String, - #[cultcache(key = 3)] - pub state: String, - #[cultcache(key = 4)] - pub action: String, - #[cultcache(key = 5)] - pub target_host: String, - #[cultcache(key = 6)] - pub port: u16, - #[cultcache(key = 7)] - pub obs_target_host: Option, - #[cultcache(key = 8)] - pub obs_port: u16, - #[cultcache(key = 9)] - pub media_transport: String, - #[cultcache(key = 10)] - pub media_packet_bytes: u32, - #[cultcache(key = 11)] - pub requested_by: String, - #[cultcache(key = 12)] - pub detail: String, - #[cultcache(key = 13)] - pub updated_at: String, - #[cultcache(key = 14, default)] - pub rudp_video_bitrate_kbps: u32, - #[cultcache(key = 15, default)] - pub rudp_latency_budget_ms: u32, - #[cultcache(key = 16, default)] - pub video_source_id: String, - #[cultcache(key = 17, default)] - pub audio_source_id: String, -} +pub const SLEIPNIR_INPUT_MAPPING_SCHEMA: &str = "sleipnir.input_mapping.v1"; #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( @@ -143,48 +64,6 @@ pub struct MuninnTelemetrySurfaceRecord { pub audio_source_labels: Vec, } -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "muninn.obs_stream_catalog", - schema = "muninn.obs_stream_catalog.v1" -)] -pub struct MuninnObsStreamCatalogRecord { - #[cultcache(key = 0)] - pub catalog_id: String, - #[cultcache(key = 1)] - pub host_id: String, - #[cultcache(key = 2)] - pub stream_ids: Vec, - #[cultcache(key = 3)] - pub labels: Vec, - #[cultcache(key = 4)] - pub urls: Vec, - #[cultcache(key = 5)] - pub states: Vec, - #[cultcache(key = 6)] - pub updated_at: String, - #[cultcache(key = 7, default)] - pub command_rudp_target: String, - #[cultcache(key = 8, default)] - pub media_target_host: String, - #[cultcache(key = 9, default)] - pub media_port: u16, - #[cultcache(key = 10, default)] - pub media_packet_bytes: u32, - #[cultcache(key = 11, default)] - pub rudp_video_bitrate_kbps: u32, - #[cultcache(key = 12, default)] - pub rudp_latency_budget_ms: u32, - #[cultcache(key = 13, default)] - pub video_source_ids: Vec, - #[cultcache(key = 14, default)] - pub video_source_labels: Vec, - #[cultcache(key = 15, default)] - pub audio_source_ids: Vec, - #[cultcache(key = 16, default)] - pub audio_source_labels: Vec, -} - #[derive(Clone, Debug, PartialEq, DatabaseEntry)] #[cultcache( type = "muninn.move_marker_candidate", @@ -488,21 +367,26 @@ pub struct MuninnQuestAccessRecord { } #[derive(Clone, Debug, PartialEq, DatabaseEntry)] -#[cultcache( - type = "muninn.command_boundary", - schema = "muninn.command_boundary.v1" -)] -pub struct MuninnCommandBoundaryCompatRecord { +#[cultcache(type = "sleipnir.input_mapping", schema = "sleipnir.input_mapping.v1")] +pub struct SleipnirInputMappingRecord { #[cultcache(key = 0)] - pub value: Value, -} - -#[derive(Clone, Debug, PartialEq, DatabaseEntry)] -#[cultcache( - type = "muninn.transport_profile", - schema = "muninn.transport_profile.v1" -)] -pub struct MuninnTransportProfileCompatRecord { - #[cultcache(key = 0)] - pub value: Value, + pub provider_id: String, + #[cultcache(key = 1)] + pub enabled: bool, + #[cultcache(key = 2)] + pub device_filter: String, + #[cultcache(key = 3)] + pub stream_id: String, + #[cultcache(key = 4)] + pub presentation: String, + #[cultcache(key = 5)] + pub axis_map: Value, + #[cultcache(key = 6)] + pub button_map: Value, + #[cultcache(key = 7)] + pub pending_learn: Value, + #[cultcache(key = 8)] + pub updated_at: String, + #[cultcache(key = 9)] + pub source: String, } diff --git a/crates/sleipnir-daemon/src/main.rs b/crates/sleipnir-daemon/src/main.rs index 43675ce..204a0d7 100644 --- a/crates/sleipnir-daemon/src/main.rs +++ b/crates/sleipnir-daemon/src/main.rs @@ -1,16 +1,14 @@ use anyhow::{Context, Result, anyhow}; -use cultmesh_rs::{ - CultMesh, CultMeshNodeOptions, CultMeshRudpDocumentPublishOptions, CultMeshRudpSnapshotOptions, -}; +use cultmesh_rs::{CultMesh, CultMeshNodeOptions, CultMeshRudpSnapshotOptions}; use cultnet_rs::{ - CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding, CultNetRudpSocketMode, - CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, CultNetWireContract, - encode_cultnet_message_to_vec, + CultNetRudpSocketMode, CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, +}; +use muninn_contracts::{ + MUNINN_HID_CONTROLLER_STATE_SCHEMA, MuninnHidControllerStateRecord, MuninnRecords, + SLEIPNIR_INPUT_MAPPING_SCHEMA, SleipnirInputMappingRecord, }; -use muninn_contracts::{MUNINN_HID_CONTROLLER_STATE_SCHEMA, MuninnHidControllerStateRecord}; use odin_core::{ - EVE_PROVIDER_ADVERTISEMENT_SCHEMA, EveProviderAdvertisementRecord, - IdunnDaemonHealthRecord, OdinDocuments, OdinEndpointQuery, SleipnirInputMappingRecord, + EVE_PROVIDER_ADVERTISEMENT_SCHEMA, EveProviderAdvertisementRecord, OdinEndpointQuery, discover_provider_endpoints, }; use std::collections::HashMap; @@ -22,15 +20,36 @@ use std::thread; use std::time::{Duration, Instant}; const SLEIPNIR_HID_RUDP_CONNECTION_ID: u32 = 0x6d75_0005; -const SLEIPNIR_COMMAND_ROUTE: &str = "cultmesh://odin/command/sleipnir/input_mapping"; -const SLEIPNIR_INPUT_MAPPING_SCHEMA: &str = "sleipnir.input_mapping.v1"; -const IDUNN_HEALTH_RUDP_CONNECTION_ID: u32 = 0x1d0d_0001; -const CULTNET_RUDP_PROTOCOL_ID: &str = "cultnet.transport.rudp.v0"; const INPUT_STALE_NEUTRAL_AFTER: Duration = Duration::from_millis(1_500); const INPUT_STREAM_RECONNECT_AFTER: Duration = Duration::from_secs(3); const DEFAULT_STICK_DEADZONE: f32 = 0.12; const HID_RUDP_MAX_FRAGMENT_BYTES: u32 = 1_200; +/// Sleipnir's Muninn contracts plus Odin's external provider advertisement schema for discovery. +#[derive(Clone, Copy, Debug, Default)] +struct SleipnirDocuments; + +impl cultmesh_rs::CultMeshDocumentSet for SleipnirDocuments { + fn register_cache(&self, cache: &mut cultcache_rs::CultCache) -> Result<()> { + MuninnRecords.register_cache(cache)?; + cache.register_entry_type::()?; + Ok(()) + } + + fn register_documents(&self, registry: &mut cultnet_rs::CultNetDocumentRegistry) -> Result<()> { + MuninnRecords.register_documents(registry)?; + registry.register( + cultnet_rs::CultNetDocumentBinding::for_entry_with_schema_id::< + EveProviderAdvertisementRecord, + >( + "gamecult.eve.provider_advertisement".to_string(), + EVE_PROVIDER_ADVERTISEMENT_SCHEMA.to_string(), + ), + ); + Ok(()) + } +} + #[derive(Clone, Debug, PartialEq, Eq)] struct Options { store_path: PathBuf, @@ -41,20 +60,11 @@ struct Options { interval_ms: u64, odin_cultmesh_uri: Option, rudp_bind: Option, - command_route: String, - idunn_rudp_health: Option, once: bool, dry_run: bool, trace: bool, } -#[derive(Clone, Debug, PartialEq, Eq)] -struct IdunnRudpHealthOptions { - endpoint: SocketAddr, - daemon_id: String, - health_contract: String, -} - struct ActiveRudpStream { transport: CultNetRudpSocketTransportConnection, target: Option, @@ -72,41 +82,6 @@ struct HidControllerRudpSubscription { stream_id: Option, } -#[derive(Clone, Debug)] -struct SleipnirRuntimeState { - provider_id: String, - selected_muninn_endpoint: Option, - selected_device_filter: Option, - presentation: String, - virtual_backend: String, - stream_state: String, - last_device_id: Option, - last_device_kind: Option, - last_sequence: Option, - last_frame_age_ms: Option, - last_input_latency: Option, - ignored_stream_frames: u64, - available_devices: Vec, - axis_map: HashMap, - button_map: HashMap, - pending_learn: Option, - updated_at: String, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct SleipnirInputLatencySnapshot { - device_id: String, - sequence: u64, - source_to_arrival_ms: Option, - arrival_to_buffer_ms: u128, - buffer_to_axis_ms: u128, - axis_to_hid_ms: u128, - source_to_hid_ms: Option, - total_observed_ms: u128, - axis_summary: Vec, - emitted: bool, -} - #[derive(Clone, Debug, PartialEq)] struct SleipnirDesiredMapping { enabled: bool, @@ -152,19 +127,6 @@ struct VirtualPadState { right_trigger: u8, } -#[derive(Clone, Debug)] -struct TimedHidRecord { - record: MuninnHidControllerStateRecord, - timing: HidRecordTiming, -} - -#[derive(Clone, Debug)] -struct HidRecordTiming { - frame_received_at: Instant, - frame_received_unix_ns: i64, - buffer_ready_at: Instant, -} - impl Default for VirtualPadState { fn default() -> Self { Self { @@ -267,7 +229,7 @@ fn main() -> Result<()> { let options = Options::parse(env::args().skip(1))?; let mut node = CultMesh::create_node( &options.store_path, - OdinDocuments, + SleipnirDocuments, CultMeshNodeOptions { runtime_id: "sleipnir-daemon".to_string(), pull_on_start: true, @@ -279,7 +241,7 @@ fn main() -> Result<()> { Some( CultMesh::create_node( discovery_store_path, - OdinDocuments, + SleipnirDocuments, CultMeshNodeOptions { runtime_id: "sleipnir-discovery".to_string(), pull_on_start: true, @@ -317,7 +279,7 @@ fn main() -> Result<()> { }; if options.trace { if !desired_mapping.enabled { - eprintln!("Sleipnir input consumption is disabled; publishing control surface only"); + eprintln!("Sleipnir input consumption is disabled; waiting for mapping activation"); } else { match discovered_endpoint.as_deref() { Some(endpoint) => eprintln!("Sleipnir selected Muninn HID endpoint {endpoint}"), @@ -328,29 +290,9 @@ fn main() -> Result<()> { let mut rudp_stream = create_rudp_stream(options.rudp_bind, discovered_endpoint, options.trace)?; let mut last_rudp_discovery_attempt_at = Instant::now(); - let initial_state = { - let discovery_ref = discovery_node.as_ref().unwrap_or(&node); - SleipnirRuntimeState::from_runtime( - &options, - current_device_filter.as_deref(), - discovery_ref, - rudp_stream.as_ref(), - None, - 0, - &desired_mapping, - None, - ) - }; - publish_sleipnir_provider(&mut node, &options, &initial_state, true)?; - let mut last_idunn_health_attempt_at = Instant::now() - Duration::from_secs(60); - publish_idunn_health_if_configured(&options, &initial_state, &mut last_idunn_health_attempt_at); let mut last_sequence_by_device = HashMap::::new(); - let mut ignored_stream_frames = 0u64; - let mut last_surface_publish_at = Instant::now() - Duration::from_secs(60); let mut last_odin_catalog_pull_at = Instant::now() - Duration::from_secs(60); - let mut recent_applied_record: Option = None; - let mut recent_input_latency: Option = None; let mut output_is_neutral = true; let mut last_output_frame_at: Option = None; let mut last_output_source_timestamp_ns: Option = None; @@ -394,7 +336,6 @@ fn main() -> Result<()> { create_rudp_stream(options.rudp_bind, rediscovered_endpoint, options.trace)?; last_sequence_by_device.clear(); } - let mut last_applied_record: Option = None; if let Some(stream) = rudp_stream.as_mut() { if ensure_rudp_connected(stream, options.trace)? { if !output_is_neutral { @@ -431,9 +372,7 @@ fn main() -> Result<()> { options.trace, )?; let records = receive_rudp_records(stream, options.trace)?; - for timed_record in records { - let record = timed_record.record; - let timing = timed_record.timing; + for record in records { if record_matches_filter(&record, current_device_filter.as_deref()) { stream.last_frame_at = Some(Instant::now()); stream.last_stale_log_at = None; @@ -452,7 +391,6 @@ fn main() -> Result<()> { .is_none_or(|last| record.source_timestamp_ns > last); if has_new_sequence && has_new_source_timestamp { let state = map_record_to_virtual_pad(&record, &desired_mapping); - let axis_classified_at = Instant::now(); let output_frame_at = Instant::now(); if options.trace { let source_age_ms = unix_nanos_i64() @@ -472,49 +410,27 @@ fn main() -> Result<()> { } match backend.update(&state) { Ok(()) => { - let hid_emitted_at = Instant::now(); - recent_input_latency = Some(input_latency_snapshot( - &record, - &timing, - axis_classified_at, - hid_emitted_at, - &desired_mapping, - true, - )); output_is_neutral = state == VirtualPadState::default(); last_output_frame_at = Some(output_frame_at); last_output_source_timestamp_ns = Some(record.source_timestamp_ns); - last_applied_record = Some(record); } Err(error) => { eprintln!( "Sleipnir virtual pad update failed for device={} seq={}: {error:#}", record.device_id, record.sequence ); - recent_input_latency = Some(input_latency_snapshot( - &record, - &timing, - axis_classified_at, - Instant::now(), - &desired_mapping, - false, - )); - last_applied_record = Some(record); } } } } else if options.trace { - ignored_stream_frames = ignored_stream_frames.saturating_add(1); - if ignored_stream_frames <= 5 || ignored_stream_frames % 120 == 0 { - eprintln!( - "Sleipnir ignored fast HID frame device={} kind={} stream={} filter={:?}", - record.device_id, - record.device_kind, - record.stream_id, - options.device_filter - ); - } + eprintln!( + "Sleipnir ignored fast HID frame device={} kind={} stream={} filter={:?}", + record.device_id, + record.device_kind, + record.stream_id, + options.device_filter + ); } } if desired_mapping.enabled @@ -549,67 +465,11 @@ fn main() -> Result<()> { drop(rudp_stream.take()); rudp_stream = create_rudp_stream(options.rudp_bind, rediscovered_endpoint, options.trace)?; - let runtime_state = { - let discovery_ref = discovery_node.as_ref().unwrap_or(&node); - SleipnirRuntimeState::from_runtime( - &options, - current_device_filter.as_deref(), - discovery_ref, - rudp_stream.as_ref(), - recent_applied_record.as_ref(), - ignored_stream_frames, - &desired_mapping, - recent_input_latency.as_ref(), - ) - }; - publish_sleipnir_provider(&mut node, &options, &runtime_state, true)?; - publish_idunn_health_if_configured( - &options, - &runtime_state, - &mut last_idunn_health_attempt_at, - ); } else if options.trace && desired_mapping.enabled { eprintln!("Sleipnir still has no Odin-discovered Muninn HID endpoint"); } last_rudp_discovery_attempt_at = Instant::now(); } - let surface_age = last_surface_publish_at.elapsed(); - let has_new_applied_record = last_applied_record.is_some(); - let missing_input_target = rudp_stream - .as_ref() - .is_none_or(|stream| stream.target.is_none()); - if let Some(record) = last_applied_record.as_ref() { - recent_applied_record = Some(record.clone()); - } - if (has_new_applied_record && surface_age >= Duration::from_secs(1)) - || (missing_input_target && surface_age >= Duration::from_secs(5)) - { - let runtime_state = { - let discovery_ref = discovery_node.as_ref().unwrap_or(&node); - SleipnirRuntimeState::from_runtime( - &options, - current_device_filter.as_deref(), - discovery_ref, - rudp_stream.as_ref(), - recent_applied_record.as_ref(), - ignored_stream_frames, - &desired_mapping, - recent_input_latency.as_ref(), - ) - }; - publish_sleipnir_provider( - &mut node, - &options, - &runtime_state, - has_new_applied_record, - )?; - publish_idunn_health_if_configured( - &options, - &runtime_state, - &mut last_idunn_health_attempt_at, - ); - last_surface_publish_at = Instant::now(); - } if options.once { break; } @@ -618,268 +478,6 @@ fn main() -> Result<()> { Ok(()) } -impl SleipnirRuntimeState { - fn from_runtime( - options: &Options, - selected_device_filter: Option<&str>, - discovery_node: &cultmesh_rs::CultMeshNode, - stream: Option<&ActiveRudpStream>, - last_record: Option<&MuninnHidControllerStateRecord>, - ignored_stream_frames: u64, - desired_mapping: &SleipnirDesiredMapping, - last_input_latency: Option<&SleipnirInputLatencySnapshot>, - ) -> Self { - let has_recent_frame = stream - .and_then(|stream| stream.last_frame_at) - .is_some_and(|last_frame| last_frame.elapsed() < Duration::from_secs(3)); - let stream_state = match stream { - _ if !desired_mapping.enabled => "idle", - Some(_) if has_recent_frame => "connected", - Some(stream) if stream.transport.connected() => "connected", - Some(stream) if stream.target.is_some() => "connecting", - Some(_) => "listening", - None => "discovering", - } - .to_string(); - let selected_muninn_endpoint = stream - .and_then(|stream| stream.target) - .map(|target| target.to_string()); - let mut available_devices = discover_available_hid_devices(discovery_node); - if let (Some(record), Some(endpoint)) = (last_record, selected_muninn_endpoint.as_deref()) { - upsert_available_hid_device( - &mut available_devices, - AvailableHidDevice { - device_id: record.device_id.clone(), - device_kind: record.device_kind.clone(), - source_path: record.source_path.clone(), - stream_id: record.stream_id.clone(), - host_id: record.host_id.clone(), - endpoint: endpoint.to_string(), - }, - ); - } - Self { - provider_id: sleipnir_provider_id(options), - selected_muninn_endpoint, - selected_device_filter: selected_device_filter.map(ToString::to_string), - presentation: default_presentation(), - virtual_backend: if options.dry_run { - "logging.dry-run" - } else if cfg!(windows) { - "vigem.xbox360" - } else { - "unavailable" - } - .to_string(), - stream_state, - last_device_id: last_record.map(|record| record.device_id.clone()), - last_device_kind: last_record.map(|record| record.device_kind.clone()), - last_sequence: last_record.map(|record| record.sequence), - last_frame_age_ms: stream - .and_then(|stream| stream.last_frame_at) - .map(|last_frame| last_frame.elapsed().as_millis()), - last_input_latency: last_input_latency.cloned(), - ignored_stream_frames, - available_devices, - axis_map: desired_mapping.axis_map.clone(), - button_map: desired_mapping.button_map.clone(), - pending_learn: desired_mapping.pending_learn.clone(), - updated_at: timestamp(), - } - } -} - -fn publish_sleipnir_provider( - node: &mut cultmesh_rs::CultMeshNode, - options: &Options, - state: &SleipnirRuntimeState, - publish_remote: bool, -) -> Result<()> { - let mut advertisement = EveProviderAdvertisementRecord { - value: serde_json::json!({ - "schema": "gamecult.eve.provider_advertisement.v1", - "providerId": state.provider_id, - "daemonId": sleipnir_daemon_id(options), - "title": sleipnir_provider_title(options), - "description": "Sleipnir mirrors Muninn-discovered input streams into a local virtual HID backend.", - "canonicalService": "asgard.sleipnir", - "locatedService": format!("asgard.{}.sleipnir", options.host_id), - "verseId": format!("{}.local", options.host_id), - "cultMeshAddress": format!("asgard.{}.sleipnir/input-mirror", options.host_id), - "status": state.stream_state, - "mode": "daemon-live", - "updatedAt": state.updated_at, - "stateStore": options.store_path.display().to_string(), - "surfaceId": state.provider_id, - "capabilities": [ - "muninn.input.discovery", - "cultmesh.input.stream.consumer", - "virtual-hid.xinput" - ], - "endpoints": [ - { - "transport": "cultcache-store", - "address": options.store_path.display().to_string() - } - ], - "routes": [ - { - "transport": "cultcache-store", - "address": options.store_path.display().to_string() - } - ] - }), - }; - if let Some(routes) = advertisement - .value - .get_mut("routes") - .and_then(|value| value.as_array_mut()) - { - routes.push(serde_json::json!({ - "transport": "cultnet.transport.rudp.v0", - "address": options.command_route, - "resolver": "odin-cultmesh", - "schema": SLEIPNIR_INPUT_MAPPING_SCHEMA, - "role": "sleipnir.input_mapping.command", - "channel": "schema" - })); - } - node.put(&state.provider_id, &advertisement)?; - if publish_remote && let Some(target) = resolve_odin_cultmesh_uri(options) { - if let Err(error) = node.publish_document_to_rudp_catalog( - &state.provider_id, - &advertisement, - CultMeshRudpDocumentPublishOptions { - target, - runtime_id: sleipnir_daemon_id(options), - source_role: Some("sleipnir.input-mirror-provider".to_string()), - tags: vec!["sleipnir".to_string(), "odin-verse-discovery".to_string()], - ..CultMeshRudpDocumentPublishOptions::default() - }, - ) { - if options.trace { - eprintln!("Sleipnir could not publish provider advertisement to Odin: {error:#}"); - } - } - } - Ok(()) -} - -fn publish_idunn_health_if_configured( - options: &Options, - state: &SleipnirRuntimeState, - last_attempt_at: &mut Instant, -) { - let Some(idunn) = options.idunn_rudp_health.as_ref() else { - return; - }; - if last_attempt_at.elapsed() < Duration::from_secs(5) { - return; - } - *last_attempt_at = Instant::now(); - let health_state = if state.stream_state == "connected" || state.stream_state == "idle" { - "active" - } else { - "degraded" - }; - let detail = format!( - "Sleipnir {}: endpoint={} device={} sequence={} age_ms={}", - state.stream_state, - state - .selected_muninn_endpoint - .as_deref() - .unwrap_or("discovering"), - state - .selected_device_filter - .as_deref() - .unwrap_or("unselected"), - state - .last_sequence - .map(|sequence| sequence.to_string()) - .unwrap_or_else(|| "none".to_string()), - state - .last_frame_age_ms - .map(|age| age.to_string()) - .unwrap_or_else(|| "none".to_string()) - ); - if let Err(error) = publish_idunn_rudp_health(idunn, health_state, &detail, &state.updated_at) { - if options.trace { - eprintln!( - "Sleipnir could not publish Idunn RUDP health for {} at {}: {error:#}", - idunn.daemon_id, state.updated_at - ); - } - } -} - -fn publish_idunn_rudp_health( - options: &IdunnRudpHealthOptions, - state: &str, - detail: &str, - observed_at: &str, -) -> Result<()> { - let health = IdunnDaemonHealthRecord { - daemon_id: options.daemon_id.clone(), - state: state.to_string(), - detail: detail.to_string(), - observed_at: observed_at.to_string(), - health_contract: options.health_contract.clone(), - publication_source: "daemon-published".to_string(), - transport: CULTNET_RUDP_PROTOCOL_ID.to_string(), - }; - let message = CultNetMessage::DocumentPutRaw { - message_id: format!( - "sleipnir-health:{}:{}", - options.daemon_id, - observed_at.replace(':', "-") - ), - document: CultNetRawDocumentRecord { - schema_id: "idunn.daemon_health".to_string(), - record_key: options.daemon_id.clone(), - stored_at: observed_at.to_string(), - payload_encoding: CultNetRawPayloadEncoding::Messagepack, - payload: rmp_serde::to_vec(&health).context("encoding Idunn daemon health")?, - source_runtime_id: Some("sleipnir-daemon".to_string()), - source_agent_id: None, - source_role: Some("daemon-health-publisher".to_string()), - tags: Some(vec![CULTNET_RUDP_PROTOCOL_ID.to_string()]), - }, - }; - let bind_address = if options.endpoint.is_ipv4() { - "0.0.0.0:0" - } else { - "[::]:0" - }; - let socket = UdpSocket::bind(bind_address) - .with_context(|| format!("binding Sleipnir Idunn RUDP sender at {bind_address}"))?; - socket.set_read_timeout(Some(Duration::from_millis(100)))?; - let mut transport = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions::client( - "sleipnir-daemon", - socket, - options.endpoint, - IDUNN_HEALTH_RUDP_CONNECTION_ID, - ))?; - transport.connect(Vec::new())?; - let deadline = Instant::now() + Duration::from_millis(300); - while !transport.connected() { - let _ = transport.receive_once()?; - transport.poll_resends()?; - if Instant::now() >= deadline { - return Err(anyhow!( - "timed out connecting Sleipnir RUDP sender to {}", - options.endpoint - )); - } - } - let payload = encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0) - .context("encoding Idunn health CultNet message")?; - transport - .send("schema", payload) - .with_context(|| format!("sending Sleipnir Idunn health to {}", options.endpoint))?; - Ok(()) -} - fn resolve_odin_cultmesh_uri(options: &Options) -> Option { let uri = options.odin_cultmesh_uri.as_deref()?.trim(); if uri.is_empty() { @@ -994,6 +592,7 @@ fn hid_state_host_id_from_value(value: &serde_json::Value) -> Option { string_field(payload, &["host_id", "hostId"]) } +#[cfg(test)] fn read_desired_mapping( node: &mut cultmesh_rs::CultMeshNode, options: &Options, @@ -1375,128 +974,6 @@ fn effective_device_filter( .or_else(|| options.device_filter.clone()) } -fn discover_available_hid_devices(node: &cultmesh_rs::CultMeshNode) -> Vec { - let mut devices = Vec::new(); - for record in node - .cache() - .get_all::() - .ok() - .into_iter() - .flatten() - { - upsert_available_hid_device( - &mut devices, - available_hid_device_from_record( - node, - &record, - discover_muninn_hid_endpoint( - node, - Some(record.device_id.as_str()), - Some(record.stream_id.as_str()), - false, - ), - ), - ); - } - for provider in node - .cache() - .get_all::() - .ok() - .into_iter() - .flatten() - { - for device in available_hid_devices_from_value(&provider.value) { - upsert_available_hid_device(&mut devices, device); - } - } - for envelope in node.cache().snapshot() { - if envelope.schema_id.as_deref() == Some(MUNINN_HID_CONTROLLER_STATE_SCHEMA) - || envelope.r#type == "muninn.hid_controller_state" - { - if let Ok(value) = rmp_serde::from_slice::(&envelope.payload) { - if let Some(device) = available_hid_device_from_hid_value(node, &value) { - upsert_available_hid_device(&mut devices, device); - } - } - continue; - } - if envelope.schema_id.as_deref() == Some(EVE_PROVIDER_ADVERTISEMENT_SCHEMA) - || envelope.r#type == "gamecult.eve.provider_advertisement" - { - if let Ok(value) = rmp_serde::from_slice::(&envelope.payload) { - for device in available_hid_devices_from_value(&value) { - upsert_available_hid_device(&mut devices, device); - } - } - continue; - } - } - devices.retain(|device| endpoint_looks_like_socket(&device.endpoint)); - devices.sort_by(|left, right| { - (&left.host_id, &left.device_id, &left.endpoint).cmp(&( - &right.host_id, - &right.device_id, - &right.endpoint, - )) - }); - devices - .dedup_by(|left, right| left.host_id == right.host_id && left.device_id == right.device_id); - devices -} - -fn available_hid_device_from_hid_value( - node: &cultmesh_rs::CultMeshNode, - value: &serde_json::Value, -) -> Option { - let payload = value - .as_array() - .and_then(|items| { - (items.len() == 1) - .then(|| items.first()) - .flatten() - .filter(|item| item.is_object() || item.is_array()) - }) - .unwrap_or(value); - let (stream_id, host_id, device_id, device_kind, source_path) = - if let Some(items) = payload.as_array() { - ( - items.first()?.as_str()?.to_string(), - items.get(1)?.as_str()?.to_string(), - items.get(2)?.as_str()?.to_string(), - items.get(3)?.as_str()?.to_string(), - items - .get(10) - .and_then(|item| item.as_str()) - .unwrap_or("unknown") - .to_string(), - ) - } else { - ( - string_field(payload, &["stream_id", "streamId"])?, - string_field(payload, &["host_id", "hostId"])?, - string_field(payload, &["device_id", "deviceId"])?, - string_field(payload, &["device_kind", "deviceKind"])?, - string_field(payload, &["source_path", "sourcePath"]) - .unwrap_or_else(|| "unknown".to_string()), - ) - }; - let endpoint = discover_muninn_hid_endpoint( - node, - Some(device_id.as_str()), - Some(stream_id.as_str()), - false, - ) - .unwrap_or_else(|| "discovering".to_string()); - Some(AvailableHidDevice { - device_id, - device_kind, - source_path, - stream_id, - host_id, - endpoint, - }) -} - fn string_field(value: &serde_json::Value, names: &[&str]) -> Option { names .iter() @@ -1504,71 +981,6 @@ fn string_field(value: &serde_json::Value, names: &[&str]) -> Option { .map(ToString::to_string) } -fn available_hid_device_from_record( - node: &cultmesh_rs::CultMeshNode, - record: &MuninnHidControllerStateRecord, - endpoint: Option, -) -> AvailableHidDevice { - AvailableHidDevice { - device_id: record.device_id.clone(), - device_kind: record.device_kind.clone(), - source_path: record.source_path.clone(), - stream_id: record.stream_id.clone(), - host_id: record.host_id.clone(), - endpoint: endpoint.unwrap_or_else(|| { - discover_muninn_hid_endpoint( - node, - Some(record.device_id.as_str()), - Some(record.stream_id.as_str()), - false, - ) - .unwrap_or_else(|| "discovering".to_string()) - }), - } -} - -fn upsert_available_hid_device(devices: &mut Vec, device: AvailableHidDevice) { - if let Some(existing) = devices.iter_mut().find(|existing| { - existing.host_id == device.host_id && existing.device_id == device.device_id - }) { - if should_replace_available_hid_device(existing, &device) { - *existing = device; - } - } else { - devices.push(device); - } - devices.sort_by(|left, right| { - (&left.host_id, &left.device_id, &left.endpoint).cmp(&( - &right.host_id, - &right.device_id, - &right.endpoint, - )) - }); -} - -fn should_replace_available_hid_device( - existing: &AvailableHidDevice, - candidate: &AvailableHidDevice, -) -> bool { - let existing_score = available_hid_device_discovery_score(existing); - let candidate_score = available_hid_device_discovery_score(candidate); - candidate_score >= existing_score -} - -fn available_hid_device_discovery_score(device: &AvailableHidDevice) -> u8 { - let mut score = 0; - if device.endpoint != "discovering" { - score += 4; - } - if device.stream_id.contains(&device.device_id) { - score += 2; - } - if !device.source_path.trim().is_empty() && device.source_path != "unknown" { - score += 1; - } - score -} - fn available_hid_devices_from_value(value: &serde_json::Value) -> Vec { let mut devices = Vec::new(); let Some(streams) = value @@ -1663,32 +1075,10 @@ fn endpoint_looks_like_socket(endpoint: &str) -> bool { .is_ok_and(|parsed_port| parsed_port != 0) } -fn stable_id(value: &str) -> String { - let normalized = value - .chars() - .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '-' }) - .collect::() - .trim_matches('-') - .to_ascii_lowercase(); - if normalized.is_empty() { - "device".to_string() - } else { - normalized - } -} - fn sleipnir_provider_id(options: &Options) -> String { format!("sleipnir.input-mirror.{}", options.host_id) } -fn sleipnir_daemon_id(options: &Options) -> String { - format!("{}-sleipnir", options.host_id) -} - -fn sleipnir_provider_title(options: &Options) -> String { - format!("Sleipnir {} Input Mirror", title_case(&options.host_id)) -} - fn timestamp() -> String { use std::time::{SystemTime, UNIX_EPOCH}; match SystemTime::now().duration_since(UNIX_EPOCH) { @@ -1697,6 +1087,7 @@ fn timestamp() -> String { } } +#[cfg(test)] fn unix_millis_i64() -> i64 { use std::time::{SystemTime, UNIX_EPOCH}; SystemTime::now() @@ -1713,14 +1104,6 @@ fn unix_nanos_i64() -> i64 { .unwrap_or_default() } -fn title_case(value: &str) -> String { - let mut chars = value.chars(); - match chars.next() { - Some(first) => first.to_uppercase().collect::() + chars.as_str(), - None => String::new(), - } -} - fn create_rudp_stream( bind: Option, connect_endpoint: Option, @@ -2012,15 +1395,16 @@ fn stream_host_hint(stream_id: Option<&str>) -> Option { (!normalized.is_empty()).then_some(normalized) } -fn receive_rudp_records(stream: &mut ActiveRudpStream, trace: bool) -> Result> { +fn receive_rudp_records( + stream: &mut ActiveRudpStream, + trace: bool, +) -> Result> { let mut records = Vec::new(); let mut empty_polls = 0usize; for _ in 0..64 { match stream.transport.receive_once() { Ok(Some(frame)) if frame.channel_id == "latest" || frame.channel_id == "hid" => { empty_polls = 0; - let frame_received_at = Instant::now(); - let frame_received_unix_ns = unix_nanos_i64(); if trace { eprintln!( "Sleipnir received fast HID frame channel={} bytes={}", @@ -2028,15 +1412,10 @@ fn receive_rudp_records(stream: &mut ActiveRudpStream, trace: bool) -> Result { empty_polls = 0; @@ -2067,36 +1446,7 @@ fn receive_rudp_records(stream: &mut ActiveRudpStream, trace: bool) -> Result, -) -> Vec { - let mut latest_by_device = HashMap::::new(); - for (index, record) in records.into_iter().enumerate() { - latest_by_device - .entry(record.record.device_id.clone()) - .and_modify(|(latest_index, latest_record)| { - if record.record.source_timestamp_ns > latest_record.record.source_timestamp_ns - || (record.record.source_timestamp_ns - == latest_record.record.source_timestamp_ns - && record.record.sequence > latest_record.record.sequence) - { - *latest_index = index; - *latest_record = record.clone(); - } - }) - .or_insert((index, record)); - } - let mut latest = latest_by_device.into_values().collect::>(); - latest.sort_by_key(|(index, _)| *index); - latest.into_iter().map(|(_, record)| record).collect() + Ok(coalesce_latest_hid_records_by_device(records)) } fn coalesce_latest_hid_records_by_device( @@ -2146,69 +1496,6 @@ fn record_matches_filter( }) } -fn input_latency_snapshot( - record: &MuninnHidControllerStateRecord, - timing: &HidRecordTiming, - axis_classified_at: Instant, - hid_emitted_at: Instant, - mapping: &SleipnirDesiredMapping, - emitted: bool, -) -> SleipnirInputLatencySnapshot { - let source_to_arrival_ms = (record.source_timestamp_ns > 0).then(|| { - timing - .frame_received_unix_ns - .saturating_sub(record.source_timestamp_ns) - / 1_000_000 - }); - let source_to_hid_ms = (record.source_timestamp_ns > 0) - .then(|| unix_nanos_i64().saturating_sub(record.source_timestamp_ns) / 1_000_000); - SleipnirInputLatencySnapshot { - device_id: record.device_id.clone(), - sequence: record.sequence, - source_to_arrival_ms, - arrival_to_buffer_ms: timing - .buffer_ready_at - .saturating_duration_since(timing.frame_received_at) - .as_millis(), - buffer_to_axis_ms: axis_classified_at - .saturating_duration_since(timing.buffer_ready_at) - .as_millis(), - axis_to_hid_ms: hid_emitted_at - .saturating_duration_since(axis_classified_at) - .as_millis(), - source_to_hid_ms, - total_observed_ms: hid_emitted_at - .saturating_duration_since(timing.frame_received_at) - .as_millis(), - axis_summary: axis_classification_summary(record, mapping), - emitted, - } -} - -fn axis_classification_summary( - record: &MuninnHidControllerStateRecord, - mapping: &SleipnirDesiredMapping, -) -> Vec { - let mut axes = mapping - .axis_map - .iter() - .map(|(target, binding)| { - let value = record.axes.get(binding.source).copied(); - format!( - "{}<-axis{}{}{}", - target, - binding.source, - if binding.invert { " inverted" } else { "" }, - value - .map(|value| format!(" value={:.3}", value)) - .unwrap_or_else(|| " missing".to_string()) - ) - }) - .collect::>(); - axes.sort(); - axes -} - fn map_record_to_virtual_pad( record: &MuninnHidControllerStateRecord, mapping: &SleipnirDesiredMapping, @@ -2326,17 +1613,12 @@ impl Options { interval_ms: 8, odin_cultmesh_uri: Some("cultmesh://odin/rendezvous/provider-catalog".to_string()), rudp_bind: None, - command_route: SLEIPNIR_COMMAND_ROUTE.to_string(), - idunn_rudp_health: None, once: false, dry_run: false, trace: env::var("SLEIPNIR_TRACE") .ok() .is_some_and(|value| value != "0" && !value.eq_ignore_ascii_case("false")), }; - let mut idunn_rudp_health_endpoint = None; - let mut idunn_daemon_id = None; - let mut idunn_health_contract = None; let mut args = args.peekable(); while let Some(arg) = args.next() { match arg.as_str() { @@ -2362,42 +1644,9 @@ impl Options { .context("--rudp-bind must be a socket address")?, ) } - "--command-rudp-bind" => { - let _ = next_value(&mut args, "--command-rudp-bind")?; - return Err(anyhow!( - "--command-rudp-bind has been removed; Sleipnir reads input mapping commands from Odin/CultMesh discovery" - )); - } - "--command-route" => { - options.command_route = next_value(&mut args, "--command-route")? - } - "--command-rudp-advertise" => { - return Err(anyhow!( - "--command-rudp-advertise has been removed; use --command-route with a cultmesh:// Odin command route" - )); - } - "--odin-cultmesh-rudp" => { - let _ = next_value(&mut args, "--odin-cultmesh-rudp")?; - return Err(anyhow!( - "--odin-cultmesh-rudp has been removed; use --odin-cultmesh-uri cultmesh://odin/rendezvous/provider-catalog and let CultMesh resolve Odin's transport" - )); - } "--odin-cultmesh-uri" => { options.odin_cultmesh_uri = Some(next_value(&mut args, "--odin-cultmesh-uri")?) } - "--idunn-rudp-health" => { - idunn_rudp_health_endpoint = Some( - next_value(&mut args, "--idunn-rudp-health")? - .parse() - .context("--idunn-rudp-health must be a socket address")?, - ) - } - "--idunn-daemon" => { - idunn_daemon_id = Some(next_value(&mut args, "--idunn-daemon")?) - } - "--idunn-health-contract" => { - idunn_health_contract = Some(next_value(&mut args, "--idunn-health-contract")?) - } "--once" => options.once = true, "--dry-run" => options.dry_run = true, "--trace" => options.trace = true, @@ -2408,25 +1657,6 @@ impl Options { other => return Err(anyhow!("unrecognized argument {other}\n{}", usage())), } } - options.idunn_rudp_health = match ( - idunn_rudp_health_endpoint, - idunn_daemon_id, - idunn_health_contract, - ) { - (None, None, None) => None, - (Some(endpoint), Some(daemon_id), Some(health_contract)) => { - Some(IdunnRudpHealthOptions { - endpoint, - daemon_id, - health_contract, - }) - } - _ => { - return Err(anyhow!( - "--idunn-rudp-health, --idunn-daemon, and --idunn-health-contract must be provided together" - )); - } - }; Ok(options) } } @@ -2438,7 +1668,7 @@ fn next_value(args: &mut impl Iterator, flag: &str) -> Result &'static str { - "usage: sleipnir [--store PATH] [--discovery-store PATH] [--mapping-path LEGACY_PATH] [--host HOST] [--device DEVICE_OR_KIND] [--odin-cultmesh-uri cultmesh://...] [--rudp-bind ADDR] [--command-route cultmesh://...] [--idunn-rudp-health ADDR --idunn-daemon ID --idunn-health-contract CONTRACT] [--interval-ms N] [--trace] [--dry-run] [--once]" + "usage: sleipnir [--store PATH] [--discovery-store PATH] [--mapping-path LEGACY_PATH] [--host HOST] [--device DEVICE_OR_KIND] [--odin-cultmesh-uri cultmesh://...] [--rudp-bind ADDR] [--interval-ms N] [--trace] [--dry-run] [--once]" } #[cfg(test)] @@ -2480,7 +1710,7 @@ mod tests { std::env::temp_dir().join(format!("sleipnir-{name}-{}.cc", unix_millis_i64())); let node = CultMesh::create_node( &store_path, - OdinDocuments, + SleipnirDocuments, CultMeshNodeOptions { runtime_id: format!("sleipnir-test-{name}"), pull_on_start: true, @@ -2625,31 +1855,11 @@ mod tests { } #[test] - fn runtime_state_prefers_recent_frames_over_handshake_churn() { - let (node, store_path) = test_node("runtime-fresh-frame"); - let options = Options::parse( - ["--store", store_path.to_str().unwrap(), "--dry-run"] - .into_iter() - .map(String::from), - ) - .unwrap(); - let mut mapping = default_mapping(); - mapping.enabled = true; - let stream = create_rudp_stream(None, Some("127.0.0.1:9".to_string()), false).unwrap(); - - let state = SleipnirRuntimeState::from_runtime( - &options, - Some("nav"), - &node, - stream.as_ref(), - None, - 0, - &mapping, - None, - ); - - assert_eq!(state.stream_state, "connected"); - let _ = fs::remove_file(store_path); + fn ensure_rudp_connected_does_not_mark_fresh_stream_stale() { + let mut stream = create_rudp_stream(None, Some("127.0.0.1:9".to_string()), false) + .unwrap() + .unwrap(); + assert!(!ensure_rudp_connected(&mut stream, false).unwrap()); } #[test] @@ -2740,140 +1950,6 @@ mod tests { let _ = fs::remove_file(store_path); } - #[test] - fn discovers_available_hid_devices_from_typed_muninn_state_records() { - let (mut node, store_path) = test_node("hid-record-discovery"); - node.put( - "muninn.telemetry.starfire", - &EveProviderAdvertisementRecord { - value: json!({ - "providerId": "muninn.telemetry.starfire", - "endpoints": [{ - "address": "198.51.100.66:17888", - "schema": "muninn.hid_controller_state.v1", - "transport": "cultnet.transport.rudp.v0" - }] - }), - }, - ) - .unwrap(); - node.put( - "starfire:nav-windows-psnav-0:hid-controller-state", - &MuninnHidControllerStateRecord { - stream_id: "starfire:nav-windows-psnav-0:hid-controller-state".to_string(), - host_id: "starfire".to_string(), - device_id: "nav-windows-psnav-0".to_string(), - device_kind: "ps3-navigation".to_string(), - sequence: 1, - source_timestamp_ns: 0, - axes: vec![0.0, 0.0, 0.0], - buttons: Vec::new(), - battery01: f32::NAN, - observed_at: "unix:0".to_string(), - source_path: "windows-psmove://nav".to_string(), - }, - ) - .unwrap(); - - let devices = discover_available_hid_devices(&node); - - assert_eq!(devices.len(), 1); - assert_eq!(devices[0].device_id, "nav-windows-psnav-0"); - assert_eq!(devices[0].host_id, "starfire"); - assert_eq!( - devices[0].stream_id, - "starfire:nav-windows-psnav-0:hid-controller-state" - ); - assert_eq!(devices[0].endpoint, "198.51.100.66:17888"); - let _ = fs::remove_file(store_path); - } - - #[test] - fn normalizes_tuple_shaped_hid_state_payloads_for_discovery() { - let (mut node, store_path) = test_node("hid-tuple-discovery"); - node.put( - "muninn.telemetry.raven", - &EveProviderAdvertisementRecord { - value: json!({ - "providerId": "muninn.telemetry.raven", - "endpoints": [{ - "address": "198.51.100.84:17888", - "schema": "muninn.hid_controller_state.v1", - "transport": "cultnet.transport.rudp.v0" - }] - }), - }, - ) - .unwrap(); - let device = available_hid_device_from_hid_value( - &node, - &json!([ - "raven:xbox-raven:hid-controller-state", - "raven", - "xbox-raven", - "xbox-controller", - 42, - 0, - [], - [], - null, - "unix:0", - "xinput://raven/xbox" - ]), - ) - .unwrap(); - - assert_eq!(device.device_id, "xbox-raven"); - assert_eq!(device.host_id, "raven"); - assert_eq!(device.endpoint, "198.51.100.84:17888"); - let _ = fs::remove_file(store_path); - } - - #[test] - fn available_hid_device_upsert_deduplicates_endpoint_variants() { - let mut devices = Vec::new(); - upsert_available_hid_device( - &mut devices, - AvailableHidDevice { - device_id: "nav-windows-psnav-0".to_string(), - device_kind: "ps3-navigation".to_string(), - source_path: "windows-psmove://nav".to_string(), - stream_id: "starfire:nav-windows-psnav-0:hid-controller-state".to_string(), - host_id: "starfire".to_string(), - endpoint: "discovering".to_string(), - }, - ); - upsert_available_hid_device( - &mut devices, - AvailableHidDevice { - device_id: "nav-windows-psnav-0".to_string(), - device_kind: "ps3-navigation".to_string(), - source_path: "windows-psmove://nav".to_string(), - stream_id: "starfire:nav-windows-psnav-0:hid-controller-state".to_string(), - host_id: "starfire".to_string(), - endpoint: "198.51.100.66:17888".to_string(), - }, - ); - upsert_available_hid_device( - &mut devices, - AvailableHidDevice { - device_id: "nav-windows-psnav-0".to_string(), - device_kind: "ps3-navigation".to_string(), - source_path: "windows-psmove://nav".to_string(), - stream_id: "muninn:starfire:hid-controller-state".to_string(), - host_id: "starfire".to_string(), - endpoint: "198.51.100.66:17888".to_string(), - }, - ); - - assert_eq!(devices.len(), 1); - assert_eq!(devices[0].endpoint, "198.51.100.66:17888"); - assert_eq!( - devices[0].stream_id, - "starfire:nav-windows-psnav-0:hid-controller-state" - ); - } - #[test] fn stream_id_host_hint_filters_provider_routes() { let (mut node, store_path) = test_node("hid-host-hint"); @@ -3055,19 +2131,6 @@ mod tests { let _ = fs::remove_file(discovery_store_path); } - #[test] - fn rejects_removed_command_rudp_bind() { - let error = Options::parse( - ["--command-rudp-bind", "127.0.0.1:17889"] - .into_iter() - .map(String::from), - ) - .unwrap_err() - .to_string(); - - assert!(error.contains("--command-rudp-bind has been removed")); - } - #[test] fn accepts_odin_cultmesh_uri() { let options = Options::parse( @@ -3086,19 +2149,6 @@ mod tests { ); } - #[test] - fn rejects_removed_odin_cultmesh_rudp() { - let error = Options::parse( - ["--odin-cultmesh-rudp", "127.0.0.1:17871"] - .into_iter() - .map(String::from), - ) - .unwrap_err() - .to_string(); - - assert!(error.contains("--odin-cultmesh-rudp has been removed")); - } - #[cfg(windows)] #[test] fn xbox_face_button_names_stay_distinct() { -- 2.47.3 From 3081fb848069e405819f4ff6fcef41306d69d46c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 22:24:54 +0100 Subject: [PATCH 3/8] Remove streaming docs, dead scripts, media deployment bindings, and update README/deprecation notes --- README.md | 73 +- deployment/idunn/raven-muninn.toml | 33 +- docs/muninn-media-streaming.md | 376 ---- docs/realtime-robustness-cut.md | 2145 ---------------------- docs/streaming-deprecation.md | 50 +- scripts/activate-muninn-raven-av-srt.cmd | 2 - scripts/activate-muninn-raven-media.ps1 | 1 - scripts/health-muninn.cmd | 3 - scripts/health-muninn.ps1 | 4 +- scripts/health-nightwing-muninn.cmd | 3 - scripts/health-starfire-muninn.cmd | 3 - scripts/restart-nightwing-muninn.ps1 | 5 +- scripts/wasapi-loopback-capture.ps1 | 469 ----- 13 files changed, 54 insertions(+), 3113 deletions(-) delete mode 100644 docs/muninn-media-streaming.md delete mode 100644 docs/realtime-robustness-cut.md delete mode 100644 scripts/activate-muninn-raven-av-srt.cmd delete mode 100644 scripts/activate-muninn-raven-media.ps1 delete mode 100644 scripts/health-muninn.cmd delete mode 100644 scripts/health-nightwing-muninn.cmd delete mode 100644 scripts/health-starfire-muninn.cmd delete mode 100644 scripts/wasapi-loopback-capture.ps1 diff --git a/README.md b/README.md index c894b34..5dd23d0 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,46 @@ # Muninn -> **Deprecation notice (Meta, 2026-11-06).** Muninn's *streaming* role (screen and audio -> capture, the media sender, and the OBS media receiver at -> [github.com/GameCult/Ratatoskr](https://github.com/GameCult/Ratatoskr), not the forge chat -> client of the same name) is superseded in the streaming space. Do not build new work on it. -> Nothing is deleted yet; what depends on it and what looks removable is in -> [docs/streaming-deprecation.md](docs/streaming-deprecation.md). The non-streaming roles -> (sensors, PS Move, input for Sleipnir) are not covered by this notice. +> **Streaming stack removed (2026-12-03).** Muninn's deprecated A/V streaming +> role (screen and loopback-audio capture, the media sender, and Ratatoskr OBS +> receiver wiring) has been removed from `main` and archived at tag +> `parked/muninn-media-streaming-2026-12-03` (see +> [docs/streaming-deprecation.md](docs/streaming-deprecation.md)). The +> non-streaming roles (PS Move, Quest, HID/XInput forwarding to Sleipnir, and +> Idunn presence) are live. -**Local capture broker for the GameCult swarm.** +**Local sensor and HID broker for the GameCult swarm.** -Muninn resolves what data streams a host can offer, advertises them, and serves -them to CultMesh peers on request. Screen and loopback audio, cameras, PS Move -controllers and their optical markers, HID and XInput gamepads, Quest access. +Muninn reads PS Move controllers and optical markers, HID and XInput gamepads, +and Quest state, and serves typed records and low-latency RUDP HID streams to +CultMesh peers such as Sleipnir and Mimir. -Muninn running does not mean Muninn is broadcasting. Each feed it can reach is -*available* for another service to request. Mimir asks for sensors. Sleipnir asks -for input. A stream asks for screen and audio. Muninn does not decide what any of -them are for. - -**Naming note.** Muninn's docs say "Ratatoskr" for the OBS media receiver, which lives at -[github.com/GameCult/Ratatoskr](https://github.com/GameCult/Ratatoskr) (forge mirror: +**Naming note.** Older docs say "Ratatoskr" for the archived OBS media receiver, +which lives at [github.com/GameCult/Ratatoskr](https://github.com/GameCult/Ratatoskr) +(forge mirror: [GameCult/Ratatoskr-receiver](https://eureka.gamecult.org/forge/GameCult/Ratatoskr-receiver)). The forge repo `GameCult/Ratatoskr` is an unrelated project, Void's Cinny-based chat client. -Extracted from [Odin](https://github.com/GameCult/Odin) with its full history. -Muninn had lived as three crates inside the repository of the service that -discovers it, with its document schemas owned by `odin-core` — an inversion of -the ownership it needs to hold. Same shape as the -[Idunn](https://github.com/GameCult/Idunn) extraction of 2026-09-05, and done -deliberately after it. +Extracted from [Odin](https://github.com/GameCult/Odin) with its full history; +Muninn's own record contracts live in `muninn-contracts`. --- ## Status -**This repository does not build yet.** It is a faithful history extraction, not -a finished cut. `muninn-daemon` still depends on `odin-core` by path for the -twenty record types and schema constants it uses, and that dependency is one of -the things being removed. - -See [docs/teardown-map.md](docs/teardown-map.md) for the working map: current -body, the authorities currently fused into one 14,567-line `main.rs`, schema -decomposition, extraction blast radius, and the measured diagnosis of the audio -decay that prompted the rebuild. +`muninn-contracts`, `muninn-daemon` (`Move`, `Quest`, HID, and +`idunn_presence.rs`), `muninn-move-tracker`, `muninn-psmoveapi-tracker`, and +`sleipnir-daemon` build and test on the workspace. `sleipnir-daemon` still +reads `odin-core` strictly for Odin's external provider-advertisement discovery +records; `muninn-daemon` has no `odin-core` dependency. ## Authority -- **Owner:** Muninn owns local source enumeration, capability advertisement, - per-consumer stream grants, and transport of granted streams. -- **Input:** locally reachable devices; typed capture stream commands from - requesting peers. -- **Output:** CultMesh Media Streams and typed sensor records. -- **Not Muninn's:** the media protocol itself (a general CultMesh contract, owned - by CultLib), discovery and rendezvous (Odin), deployment and continuity - (Idunn), the hue programs that decide what colour a Move should be (Mimir), - and any consumer's lowering — OBS, browser, or otherwise. - -Muninn is one producer of a general contract. It is not the contract. +- **Owner:** Muninn owns local source enumeration, HID RUDP serving, Quest + state publishing, and Move tracking/hue-program state. +- **Input:** locally reachable controllers, optical trackers, and Quest state. +- **Output:** low-latency RUDP HID frames and typed CultMesh/CultCache sensor + and Move records. +- **Not Muninn's:** discovery and rendezvous (Odin), deployment and runtime + presence policy (Idunn), the hue programs that decide what colour a Move + should be (Mimir), and Sleipnir's virtual HID output. diff --git a/deployment/idunn/raven-muninn.toml b/deployment/idunn/raven-muninn.toml index c440494..dc1024d 100644 --- a/deployment/idunn/raven-muninn.toml +++ b/deployment/idunn/raven-muninn.toml @@ -29,52 +29,26 @@ source = "target/release/muninn.exe" destination = "muninn.exe" executable = true -[[artifacts]] -id = "wasapi-loopback-capture" -source_kind = "worktree-tree" -source = "scripts/wasapi-loopback-capture.ps1" -destination = "wasapi-loopback-capture.ps1" - # The launch contract. Host-specific values come from the operator binding's -# argument bindings; everything Raven-independent is literal. The loopback -# script is named relative to the installed release, which is the working -# directory the actuator starts serve in. +# argument bindings; everything Raven-independent is literal. [service] executable_artifact = "muninn" arguments = [ { kind = "literal", value = "serve" }, { kind = "literal", value = "--store" }, { kind = "binding", name = "store_path" }, - { kind = "literal", value = "--activate-store" }, - { kind = "binding", name = "activate_store_path" }, { kind = "literal", value = "--log-root" }, { kind = "binding", name = "log_root" }, { kind = "literal", value = "--host" }, { kind = "literal", value = "raven" }, - { kind = "literal", value = "--stream" }, - { kind = "literal", value = "muninn.raven.av.rudp" }, - { kind = "literal", value = "--target-host" }, - { kind = "binding", name = "media_target_uri" }, - { kind = "literal", value = "--media-transport" }, - { kind = "literal", value = "rudp" }, { kind = "literal", value = "--odin-cultmesh-uri" }, { kind = "literal", value = "cultmesh://odin/rendezvous/provider-catalog" }, { kind = "literal", value = "--hid-controller-rudp-bind" }, { kind = "literal", value = "0.0.0.0:17887" }, { kind = "literal", value = "--hid-controller-rudp-advertise" }, { kind = "binding", name = "hid_controller_rudp_advertise" }, - { kind = "literal", value = "--media-rudp-bind" }, - { kind = "literal", value = "0.0.0.0:5220" }, - { kind = "literal", value = "--media-rudp-advertise" }, - { kind = "binding", name = "media_rudp_advertise" }, { kind = "literal", value = "--move-state" }, { kind = "literal", value = "xbox-raven=xinput://0" }, - { kind = "literal", value = "--audio-device" }, - { kind = "literal", value = "Realtek" }, - { kind = "literal", value = "--ffmpeg" }, - { kind = "binding", name = "ffmpeg_path" }, - { kind = "literal", value = "--loopback-script" }, - { kind = "literal", value = "wasapi-loopback-capture.ps1" }, { kind = "literal", value = "--interval-seconds" }, { kind = "literal", value = "15" }, ] @@ -90,10 +64,7 @@ required_environment = [ [service.health] contract = "muninn.runtime-health.v1" -[[provides]] -capability = "muninn.media-producer" -schema = "gamecult.media_stream_advertisement.v1" -compatibility = "v1" + # raven-muninn publishes to Odin over CultMesh RUDP (--odin-cultmesh-uri), and # it has no route, so it declares the Odin dependency: Idunn admits it as Ready diff --git a/docs/muninn-media-streaming.md b/docs/muninn-media-streaming.md deleted file mode 100644 index e5689c6..0000000 --- a/docs/muninn-media-streaming.md +++ /dev/null @@ -1,376 +0,0 @@ -# Muninn Media Streaming - -Muninn live A/V is the stress organ for CultMesh transport. The goal is not -"make OBS show something once." The goal is encoded game video and audio moving -between nearby PCs at LAN speed with bounded latency, observable ownership, and -transport behavior that teaches CultMesh how to carry hot media. - -## Objective - -Raven Muninn captures screen video and Realtek loopback audio, encodes them with -hardware-first low-latency settings, publishes them through CultNet/CultMesh -media streams, and lets the Muninn OBS plugin render the stream without owning -capture, daemon lifecycle, or transport truth. - -## Current Mechanism - -The current Raven A/V path is a compatibility path: - -1. OBS reads Raven's `muninn.obs_stream_catalog` from the synced CultCache - store. -2. The OBS plugin sends a typed `muninn.capture_stream_command` to Raven's - Muninn daemon over CultNet RUDP. -3. Raven Muninn `serve` owns command acceptance and spawns a daemon-owned - activation child for the requested stream. -4. The activation child starts WASAPI loopback capture and FFmpeg. -5. FFmpeg muxes encoded video and audio into MPEG-TS on stdout. -6. Muninn slices that byte stream into fixed-size chunks and sends those chunks - over the RUDP `media` channel. -7. The OBS plugin forwards received bytes into a local FFmpeg source. - -That path proved activation, capture, hardware encode, and cross-machine -delivery. It is not the final media architecture. MPEG-TS byte chunks over an -unordered lossy hot path give CultMesh no frame identity, no deadline, no media -dependency graph, and no clean way to choose between retransmit, conceal, -discard, keyframe request, or audio/video resync. - -## Invariants - -- Muninn owns local capture and stream activation for the machine body where - the sensors live. -- OBS and Mimir are consumers. They may request a stream and report receiver - health, but they do not start capture by implication and do not own Raven - daemon state. -- Idunn owns daemon supervision and health pressure. It does not infer that - liveness means screen/audio capture should be burning. -- CultMesh owns live media stream semantics: stream identity, frame identity, - timestamps, deadlines, dependencies, channel policy, and receiver feedback. -- CultCache records are receipts, catalog entries, and operator/debug state. - They are not the hot media lane. -- Audio and video have separate clocks and recovery policy. They may share a - session, but they must not be hidden inside an opaque transport byte soup. -- Transport reliability is deadline-bound. Late media is damage, not treasure. - -## Intended Change - -Replace "MPEG-TS stdout sliced into RUDP packets" with "codec access units and -audio packets published as typed CultMesh media frames." - -The stream owner should emit media documents shaped around decisions the -transport and decoder actually need: - -```text -muninn.media_video_access_unit.v1 - stream_id - session_id - frame_id - codec - pts_ticks - duration_ticks - timebase_num - timebase_den - keyframe - dependency_frame_id - deadline_ticks - chunk_index - chunk_count - payload - -muninn.media_audio_packet.v1 - stream_id - session_id - packet_id - codec - pts_ticks - duration_ticks - timebase_num - timebase_den - deadline_ticks - payload - -muninn.media_receiver_feedback.v1 - stream_id - session_id - receiver_id - highest_decodable_frame_id - missing_frame_ids - missing_video_chunk_keys - late_frame_ids - requested_keyframe - jitter_us - decode_queue_us -``` - -The exact schema names can move when promoted into the shared document catalog, -but the ownership shape should not: frame/access-unit identity is load-bearing. - -## Authority Map - -- Owner: Muninn capture runtime owns source capture, encode configuration, and - emission of video access units plus audio packets for a requested stream. -- Inputs: explicit `muninn.capture_stream_command`, local capture devices, - encoder capabilities, receiver feedback, stream policy, and Idunn-supervised - daemon runtime state. -- Outputs: typed active stream receipts in CultCache, CultMesh media frames over - CultNet RUDP, and typed receiver/transport health receipts. -- Derived state: OBS catalog entries are discovery hints; local FFmpeg bridge - URLs are compatibility lowering details; packet counters and logs are - observability only. -- Forbidden writers: OBS source settings, local UDP bridge behavior, scheduled - task wrappers, health scripts, and replayed command receipts must not decide - capture state, stream identity, frame order, or media repair policy. -- Shared paths: direct operator requests, OBS plugin requests, future Mimir - requests, restart recovery, and reconnect recovery must all publish the same - typed capture command and consume the same active stream receipts. -- Deletion line: delete the hot-path assumption that a media stream is an - MPEG-TS byte stream. Keep it only as a named compatibility lowering until the - OBS receiver can consume typed media frames directly. - -## Boring Stream Discovery Contract - -The desired operator experience is boring: OBS asks the Verse for Muninns, the -plugin shows live sources, and a selected source either activates or reports the -specific owner that refused it. No local plugin fallback may invent Raven -devices. A fake `display:0` or Realtek loopback row is worse than an empty list -because it makes stale state look selectable. - -Live ownership: - -- Owner: Muninn `serve` owns source inventory for the body where the devices - exist. It publishes video and audio source ids, labels, command boundary, - media profile, and current active sessions. -- Inputs: local display/audio enumeration, explicit configured source hints, - daemon health, and accepted stream commands. -- Outputs: `muninn.telemetry_surface.v1`, `gamecult.eve.provider_advertisement.v1`, - `muninn.command_boundary.v1`, `muninn.transport_profile.v1`, active - `muninn.capture_stream.v1` receipts, and the temporary - `muninn.obs_stream_catalog.v1` compatibility record. -- Derived state: the OBS dropdown is a lowering of discovered Muninn state. It - is not an inventory owner, activation owner, or health owner. -- Forbidden writers: OBS defaults, local hard-coded device names, synced stale - CultCache mirrors, scheduled-task launchers, and previous activation receipts - must not create selectable devices or active streams. -- Shared paths: initial OBS load, refresh button, periodic refresh, source - selection, reconnect, and OBS restart must all read the same live-discovered - source list and issue the same typed capture command when activation is - needed. -- Deletion line: the plugin may display `discovery missing`, but it must not - synthesize `Display 1` or `Realtek loopback` as if Raven advertised them. - Until Odin/Verse discovery is the direct plugin input, the OBS catalog remains - a compatibility projection of Muninn-owned live state, not its own truth. - Compatibility store fallback is allowed only as availability fallback: the - plugin must use the first current store that yields Muninn telemetry and must - not merge stale stores into a more attractive fake inventory. - A store older than the Muninn health freshness budget is not a discovery - source; it is an outage receipt. - -This contract also splits the media session truth: - -- Video session: selected video source id, encoder profile, bitrate, frame - timestamps, access-unit ids, keyframe policy, feedback pressure, and video - receiver queue. -- Audio session: selected audio source id, sample format, packet timestamps, - reorder budget, continuity/drop policy, and OBS audio output cadence. -- Combined OBS source: a convenience lowering that may request one video session - and one audio session together. It does not merge their clocks or transport - state into one opaque "A/V target". - -## Known-Good Checkpoint (2026-06-23) - -The current system is in a usable compatibility state worth preserving before -the next transport experiment. - -What is working: - -- Raven Muninn runs continuously as the capture owner and accepts stream - activation over CultNet RUDP. -- OBS on Starfire shows the live-discovered Muninn source inventory instead of - synthesizing fake devices from stale local defaults. -- Video and audio sessions activate separately through the combined OBS source - lowering and the stream comes up cleanly again after reconnect. -- The OBS plugin currently receives the temporary live - `muninn.obs_stream_catalog.v1` projection over UDP `17874` and uses it as the - live discovery source before any CultCache fallback. - -Current compatibility details: - -- Raven command ingress is currently bound to `0.0.0.0:17883`. -- Starfire OBS listens for the temporary live OBS catalog on UDP `17874`. -- The daemon `serve` loop must continue publishing the OBS catalog while idle; - otherwise OBS falls back to stale store state and reports `discovery-missing` - or shows dead inventory. -- The current OBS plugin is still a compatibility client. It does not yet host - the Rust CultMesh runtime directly and it is not yet consuming Odin/Verse - discovery as a first-class Verse client. - -Known debt that remains intentionally visible: - -- Idunn health publication can still time out independently of the media path. - That is operational debt, not proof that Muninn discovery or streaming is - down. -- The OBS catalog is still a temporary projection. The boring end state is live - Verse discovery with no plugin-owned catalog receiver and no stale store - merge behavior. - -## Codec Direction - -Use vendor hardware encode before inventing a codec. NVIDIA's practical answer -in this space is NVENC/NVDEC, low-latency encode presets, high LAN bitrate, -short GOP or intra-refresh, no B-frames, no lookahead, and application-level -transport that understands frame deadlines. - -Shipping order: - -1. H.264 NVENC low-latency as the compatibility baseline for broad decoder - support, simple failure analysis, and OBS bridge stability. -2. HEVC NVENC low-latency when Raven encode and OBS decode both prove the - target latency budget. -3. AV1 NVENC only after the exact Raven-to-OBS path proves encode, decode, and - queue latency inside budget. AV1 can be the quality/bandwidth winner, but it - must earn the low-latency lane on our hardware instead of getting promoted by - codec fashion. - -The codec should produce elementary video access units, not a muxed MPEG-TS -program. Audio should use Opus low-delay packets unless the OBS lowering needs -a temporary PCM/AAC compatibility bridge. - -Recommended first LAN profile: - -- Profile id: `muninn.rudp.low_latency_h264_lan.v1`. -- Video: H.264 NVENC, `p5` (`main.rs:9504`), ultra-low-latency tune, CBR high enough that LAN - bandwidth is not the constraint, no B-frames, no lookahead, short GOP or - intra-refresh, keyframe actuation on feedback pressure (not built: keyframe requests are only - counted and logged today; Cut 6 builds it). -- VBV: derive `bufsize` from roughly one frame of bitrate - (`bitrate_kbps / framerate`) instead of a large fixed encoder reservoir. - The point is bounded latency, not hoarding compressed video in a nicer hat. -- Audio: Opus low-delay when OBS lowering can consume it directly; otherwise a - temporary PCM/AAC bridge with separate packet identity and clock. -- Transport: payload elementary access units as typed media records, never a - muxed container as the unit of truth. -- Packet size: default typed media chunks are `848` bytes (`main.rs:81`). That leaves headroom - for CultNet/MessagePack/RUDP headers inside a normal Ethernet MTU so the OBS - bridge does not depend on IP fragmentation or private RUDP fragment - reassembly. The sender also sets CultNet RUDP `max_fragment_bytes` to `1431` - bytes (`1472` byte IPv4 UDP payload budget minus `36` RUDP fixed header bytes - minus the five-byte `media` channel id), so oversized typed records fragment - in CultNet deliberately instead of falling through to accidental IP - fragmentation. -- Resend cadence: sender RUDP media resends are scheduled every `30` ms (`main.rs:94`) while - the packet is still inside its expiry, which is the request's latency budget (a request that names none gets `250` ms, `main.rs:98`, and the advertisement offers the same as `default_latency_budget_ms`). -- Send queue: `media_send.rs` owns it. The unit is a group, one access unit with its parity or one audio packet, stamped `produced_at + latency budget` when the packetizer emits it. A request's latency budget is clamped to 1..=2000 ms. The send loop moves one payload per step and picks it afresh each time: audio, then repairs, then video, so audio never waits behind more than the payload in progress, full socket or not. The group deadline is checked before every payload; a group that outlives it mid-send is abandoned and counted `groups_cut_short`. Queues are capped per kind (audio 256, video 512 groups) and drop the oldest group, counted as `groups_dropped_audio` and `groups_dropped_video`. Every access unit the sender drops (queue cap, expiry, packetizer overflow) has already consumed its frame id, so the receiver sees a gap; an overflow also discards the dropped frame's remaining slices instead of emitting them as a frame. A repair keeps the deadline of the frame it repairs, goes only to the receiver that asked, and is not sent after that deadline. -- Control: sender may adapt bitrate, keyframe cadence, chunk size, and playout - budget from receiver feedback; the receiver must not silently stretch latency - to preserve visual perfection. -- Receiver URL policy: RUDP stream URLs carry `profile`, - `sender_resend_delay_ms`, `reliable_expire_after_ms`, - `assembly_deadline_ms`, and `gap_wait_ms` so the OBS bridge receives timing - budget from Muninn's stream profile instead of hard-coding receiver policy - privately. - -### Motion Vectors And Reconstruction - -Do not make CultMesh a bespoke game-streaming codec in the first shipping path. -The motion-vector/delta idea is real, but it belongs as an augmentation around -the hardware codec, not as the primary authority. - -NVIDIA's relevant public pattern is: - -- NVENC/NVDEC for hardware video encode and decode. -- Low-latency encode tuning, high refresh rate, adaptive bitrate, and explicit - network/frame timing for cloud gaming. -- Foveated streaming for bandwidth reduction when a trusted focus region exists. -- Optical Flow / motion estimation hardware for interpolation, extrapolation, - analysis, or concealment experiments. - -For Muninn, that means: - -- If we only have desktop capture pixels, trust NVENC for motion estimation and - compression. Do not compute our own patch stream before the codec has failed a - measured requirement. -- If a game or renderer we control can expose motion vectors, depth, regions of - interest, or dirty rectangles, publish them as optional sideband media hints. - They may guide encoder ROI, decoder concealment, frame extrapolation, or - foveated quality allocation. They do not replace the encoded video access - unit unless a separate research path proves that decoder under the same OBS - latency budget. -- Stochastic reconstruction is allowed only inside a bounded playout budget. - When the deadline expires, the receiver displays the best available frame, - conceals damage, or requests a keyframe. It must not preserve dead packets by - growing latency. - -Useful references for this direction: - -- NVIDIA Video Codec SDK presets describe low-latency and ultra-low-latency - tuning plus preset tradeoffs for encoder tools such as GOP structure, - B-frames, and lookahead: - -- NVIDIA CloudXR publicly frames low-latency spatial streaming around NVENC, - adaptive bitrate, foveated streaming, diagnostics, and bidirectional data - channels: - -- NVIDIA's Optical Flow SDK exposes hardware motion vectors for real-time - interpolation/extrapolation and related video processing: - - -## CultNet RUDP Media Policy - -The RUDP `media` channel should become a media-aware lane, not merely a reliable -unordered byte lane. - -Required behavior: - -- Frame-level fragmentation and reassembly keyed by `(stream_id, session_id, - frame_id)`. -- Deadline-aware retransmission: resend while useful, drop when the playout - budget is gone. -- Receiver feedback that can NACK missing chunks, request a keyframe, and - report jitter/decode queue pressure. -- Small playout buffer chosen by policy, for example 8-20 ms on a wired LAN. -- Optional FEC/parity for video chunks where one repair packet beats a resend. -- Separate audio policy that favors continuity and bounded drift over perfect - packet recovery. - -## OBS Lowering - -The OBS plugin should lower typed media frames into OBS-friendly video/audio. -The clean target is direct decode from elementary streams using libavcodec or -NVDEC where available, then hand decoded video frames and audio packets to OBS. - -Temporary bridge allowed: - -- Reconstruct an elementary stream from typed video access units. -- Feed the local FFmpeg source only as a compatibility decoder. -- Keep audio as a separate OBS audio path so audio sync is explicit instead of - being hidden inside a damaged MPEG-TS stream. - -The compatibility bridge must not own stream truth. It is a lowering target, -not the protocol. - -## Cut Plan - -1. Promote media-frame schemas in Odin/CultLib and add unit tests for - encode/decode round trips. -2. Teach Muninn activation to emit video access units and audio packets instead - of arbitrary MPEG-TS byte chunks. -3. Teach CultNet RUDP media receive to reassemble by frame and deadline, with - explicit NACK/keyframe feedback. -4. Teach the OBS plugin to consume typed media frames and feed OBS through a - direct decoder or a narrowly named compatibility elementary-stream bridge. -5. Remove the MPEG-TS byte-chunk hot path once the typed receiver is stable. - -## Verification - -The rebuild is not proven by "OBS shows video once." Minimum proof: - -- Raven `serve` remains idle until an explicit capture command arrives. -- OBS request activates Raven without manual Raven terminals. -- Sender logs and receiver telemetry agree on stream id, session id, frame id, - codec, PTS, deadlines, drops, NACKs, and keyframe requests. -- A forced packet drop causes bounded damage and recovery, not OBS freeze. -- Audio remains present as an OBS audio source and stays within the chosen - sync budget. -- Restarting OBS does not strand Raven capture or poison the next request with - stale command receipts. -- Restarting Raven Muninn restores catalog/health without starting capture - until requested. diff --git a/docs/realtime-robustness-cut.md b/docs/realtime-robustness-cut.md deleted file mode 100644 index 04ba0d6..0000000 --- a/docs/realtime-robustness-cut.md +++ /dev/null @@ -1,2145 +0,0 @@ -# Muninn realtime media robustness: cut map (v2) - -Imagination pass 2, 2026-09-30. **Draft, uncommitted.** Self places it over -`Muninn/docs/realtime-robustness-cut.md` on Muninn `main` (pass 1 is `e70db69`, -and the rulings are `eb332b0`). Name that branch in every brief. - -Campaign (operator, 2026-09-30): FEC, parity, receiver-requested IDR, bitrate -adaptation, and a loss-tolerant HID edge for remote play. - -## Status header - -| | | -|---|---| -| Map state | Imagination pass 3. Q1-Q10 are ruled (below). Pass 2 mapped Cut 6 in full (Q6 = a); pass 3 re-maps the HID cuts H0-H5 to Q9 (Sleipnir is a crate in Muninn's workspace) and Q10 (Muninn advertises an input-stream capability; the consumer requests it and dials). Three new forks are open: Q11 (who owns the input-stream records), Q12 (Move evidence rides the HID listener), Q13 (whether Raven's Sleipnir is live, which gates the H2/H4 merge). | -| In Hands | Cuts 0-1 on `hands/rr-cut0-1` (`2c120c9`, `f2a5db9`, `a189363`). This pass does not touch those sections. | -| Ready for Hands | Cut 2 (the latency default is settled by Q7); Cut 3 (Q2-Q4, Q8 settled); H1 (after H0, and after Q11); H3 (any time; behaviour-neutral); Cut 6a (after Cut 2) | -| Blocked | Cut 4 (on Cut 3's tag); Cut 5 (on the pin gate); Cut 6b (on Cut 2 and Cut 5); Cut 6c (on Idunn B3 and `route/b3-declare` merging, and on FFmpeg provisioning on Raven); H2 (on Q12); the H2+H4 merge to `main` (on Q13 and H5 readiness, because `raven-muninn` deploys `main`'s head); H5 (on Idunn B3) | -| Heads read | Muninn `origin/main` `eb332b0` (code identical to `cee7b9c`), `route/b3-declare` `2260853`; CultLib `069ecc3`; Ratatoskr `488b5b1`; Odin `main` `379b826`; donor Odin `80adfd3`; Odin tag `attic/claude-cultlib-pin-c2a9a6e` `3e96c6c`; Idunn `771138a`; gamecult-ops working tree (binding `idunn/yggdrasil/bindings/raven-muninn.toml.in`, `scripts/idunn/idunn-deployment-targets.ps1`) | - -The CultLib media plane is byte-identical between Muninn's pin `c2a9a6e` and -`main` `069ecc3`: `git diff c2a9a6e main` over `media_stream_contracts.rs`, -`media_stream_wire.rs`, `rudp.rs` and `transport.rs` is empty. Every CultLib -anchor below holds at both SHAs. `M` anchors are at `eb332b0` and equal -`cee7b9c` for code. `S` = Sleipnir at Odin `main` `379b826` -(`crates/sleipnir-daemon/src/main.rs`), `DS` = the donor's Sleipnir at `80adfd3`, -and `I` = Idunn `771138a`. - ---- - -## Rulings (operator, 2026-09-30) - -- **Q1: remote play.** A viewer's controller drives a game on another host over LAN or mesh, so quick - taps must survive loss. The HID edge record is born in Muninn after named cut 1, and delivery uses - CultLib's profile-owned channels. Imagination maps the HID cuts next; nothing is specified yet. -- **Q2 (a): a pinned side-commit for now.** A single-purpose Odin commit bumps `odin-core` to Cut 3's - CultLib, and a `pins/` tag keeps it alive rather than `attic/`. Severing Muninn from `odin-core` - continues as Muninn's own cuts. Every CultLib bump repays this debt. -- **Q3: depend on `reed-solomon-erasure` 6, without simd.** A known-answer test pins the wire bytes, so - the library can be replaced without changing the wire. -- **Q4: delete the reliable `audio` channel.** Audio goes lossy with parity on `media`. This reverses the - 2026-09-10 decision. -- **Q5: audio parity comes after Opus.** Video parity ships in Cut 5. Audio stays on the reliable channel - until the Opus cut, then moves. -- **Q6 (a), against the recommendation: port the native encoder.** This is the libavdevice/NVENC child, - with an Idunn recipe step on Raven. Cut 6 gives IDR on request and bitrate adaptation, and it is the - campaign's one new native target. -- **Q7: 250 ms default, owned by the request.** It goes in the advertisement, and both ends derive from - the request. -- **Q8: fixed parity first.** Video uses `k ≤ 16`, `m = max(2, ⌈0.25k⌉)`; audio uses 4+2. The rate is - carried per record. Adaptive parity is a later cut. - - -**Pass-2 consequences of the rulings.** Every section below is rewritten to -the ruled design. The earlier options survive only in git (`e70db69`). -- Q2 names the `pins/` mechanism. The first `pins/` commit is **not** needed - for HID: `3e96c6c` already pins CultLib `c2a9a6e`, which is Muninn's current - pin. Retag it `pins/odin-core-cultlib-c2a9a6e` now, keep the `attic/` tag - until nothing references it, and cut the next `pins/` commit only at Cut 3's - CultLib tag. -- Q6 = (a) makes Cut 6 a real cut (6a-6c below). -**HID rulings, 2026-09-30.** -- **Q9: Sleipnir becomes a crate in Muninn's workspace.** It does not get its own repo, and it does not - stay in Odin. Odin's copy is deleted after the StreamPixels ship. -- **Q10: the consumer asks Muninn, and Muninn advertises the capability.** This is the opposite of the map's - viewer-dials recommendation. Operator: "Ratatoskr is asking Muninn to open a video stream, Sleipnir asks - Muninn to open an input stream. Both should be Muninn capabilities which it chooses to broadcast via - CultMesh." So Muninn publishes an input-stream capability through CultMesh beside its media capability, - and Sleipnir requests it the way Ratatoskr requests video. Both consumers dial the producing Muninn. - Pass 3 re-mapped H0-H5 to this shape. - -**Rulings, 2026-09-30 (operator), pass 3 forks:** -- **Q11 (a): the input-stream records live in `muninn-contracts` as `muninn.input_stream_*`.** The input track - needs no CultLib change. Promote them to CultLib if a second producer appears. -- **Q12 (a): Mimir's Move proof is in use.** Move evidence becomes a channel on the input-stream session, and a - small Mimir cut switches over. H2 waits for that Mimir cut. -- **Q13 (c): no live Sleipnir, so accept the gap.** H2 and H4 may merge independently. The operator said - (2026-09-30): "If Sleipnir is running, feel free to take it down; we're certainly not using it". - - Checked read-only on Raven the same day: no Sleipnir process is running. - - Only an on-demand scheduled task, `\Codex-Sleipnir-LAN-Proof`, remains. It last ran on 2026-07-17. - - Raven runs `muninn.exe` alone. - -**Cut 2 Soul pass, 2026-09-30: fix first.** The queues, caps and budget ownership hold. Findings: -- Audio waits behind a whole video group send. -- The deadline is checked only when the socket blocks. -- Whole-frame drops leave the receiver no trace. -- A packetizer overflow can emit a corrupt access unit. -- The budget has no upper clamp. - -**Ruling (Self, 2026-09-30): the receiver owns loss signalling.** A frame lost whole on the network looks the -same as one the sender dropped, so there is one owner for both: -- Ratatoskr requests a keyframe on a `frame_id` gap. This is a Cut 4 requirement. -- Cut 2 makes every sender-side drop (queue cap, expiry, packetizer overflow) consume a `frame_id`, so the gap - is visible. -- The latency budget is clamped to 2000 ms. - -## Target: ends and invariants - -**End.** A Muninn stream that loses packets degrades by what each signal class -permits, and recovers inside one latency budget without a human. Loss is -repaired by parity first, then by selective retransmit, then by a keyframe. The -sender never holds more than it can send in time, and every figure it reports -comes from observation. - -Invariants. Each one must be falsifiable by a test or a probe. - -1. **One latency budget, owned by the request.** `latency_budget_ms` on - `gamecult.media_stream_request.v1` is the only deadline source. The sender's - queue age, repair eligibility and parity grouping, and the receiver's - assembly age, all derive from it. Nothing else mints a deadline. Two - constants disagree today (finding B6). -2. **No unbounded buffers on the media path.** Every queue between the encoder - and the socket has a count bound and a time bound. Crossing the bound drops - **whole frame groups** (chunks together with their parity), oldest first. It - never returns an error that restarts the stream, and it never sends a partial - frame whose parity is then useless. -3. **Deterministic parity.** Parity bytes are a pure function of the data - shards, `(k, m)` and the scheme id. They involve no clock, no randomness and - no per-process state. A known-answer vector pins the scheme, so a library - upgrade that changes its matrix fails a test. -4. **MDS recovery guarantee.** Any `≤ m` erasures in a `k+m` block recover the - data exactly. Any `> m` erasures report failure and never produce wrong - bytes. This is proved exhaustively for every shipped `(k, m)`. -5. **One codec, both ends.** The encoder and decoder of the erasure code live in - one place, CultLib, with the record that carries it. A producer and a - consumer that disagree on the math cannot both compile against the same pin. - This is the split that stranded audio recovery in Mimir's C++ (teardown-map - L241-247). -6. **Each media payload fits one datagram, parity included.** Encoded wire size - is `≤ MUNINN_RUDP_MEDIA_MAX_FRAGMENT_BYTES` (1431; `main.rs:82-86`) for - data and parity shards alike. The fragment amplification `1-(1-p)^n` - (teardown-map L417-419) must not return through parity. -7. **Health is observed, never configured** (teardown-map L210-211). Parity - recovered, parity failed, repairs sent, IDRs requested and bitrate changes - are counted where they happen, per leg. -8. **A keyframe request is an edge, not a level.** One decode-chain - invalidation produces at most one IDR per cooldown. A recoverable missing - chunk never forces an IDR. That is already true on the receiver side: - Ratatoskr `feedback.rs:92` and CultLib `4160ab5`. -9. **The transport stays semantics-free.** CultNet RUDP gains no media-, HID- - or producer-named channel behaviour beyond what it has. The donor's - `"hid.edge"` / `"hid.edge.assist"` arms in a vendored `rudp.rs` (`9af2edb`, - `80adfd3`) are the pattern this forbids. - - -10. **One commit primitive per virtual pad.** Snapshot axes, ordered edges, - epoch baselines and staleness neutralisation all reach ViGEm through one - Sleipnir function. Within an epoch, button visibility is owned **only** by - the edge stream. The snapshot's `buttons` field is a baseline at epoch start - and nothing else. The donor overwrote snapshot buttons with the previous - record's (`DS main.rs:573-578`); that split is forbidden. -11. **A tap survives loss without transport retransmission.** A press and - release captured between two transport ticks reach the pad, in order, under - the Cut 3b profiles up to `loss-5pct` and `burst-8`. The mechanism is - redundancy: every unacknowledged edge rides every frame until it is - acknowledged. No reliable channel carries input, so there is no - retransmit debt and no head-of-line blocking. -12. **Input memory is bounded on both ends.** - - The sender keeps at most 256 unacknowledged edges **per (subscriber - session, device) window**, and rotates that window's epoch on overflow - (donor rule, `D main.rs:5846-5854`). One lossy subscriber never forces - another to rebaseline. - - A frame carries at most `MAX_EDGES_PER_FRAME` (32, or less if H1's - worst-case encode test says 32 does not fit one datagram). - - The receiver buffers nothing beyond the window it was sent. - - Stale epochs are fenced by monotonic comparison, not by a growing set - (the donor's `retired_epochs: HashSet`, `DS main.rs:210`, grows forever). -13. **Input latency is bounded, and the bound is owned by the request.** A - queued edge is held visible for 24 ms (`DS main.rs:32-35`, one 60 Hz game - sample plus margin) **unless** it is older than `input_budget_ms`. Then it - is actuated without the hold. A tap is compressed, never dropped. The - budget is Q7's shape applied to input: the advertisement carries the - default (100 ms), the request carries the value, and both ends derive from - the request. -14. **No JSON on a live wire.** Muninn↔Sleipnir today speaks JSON both ways - (B14), and the donor did too (`D main.rs:6117,6141`, `DS main.rs:693-699`). - Every HID and encoder-control message becomes a typed CultCache record in - a CultNet message. -15. **Encoder commands are typed and fire-and-forget; their effect is - observed.** Muninn writes `muninn.video_encoder_command.v1` records to the - encoder's stdin as CultNet frames. Whether an IDR happened is read from the - Annex B stream (keyframe access units). Whether a bitrate took is read from - measured bytes per second. Neither is read from what was asked (invariant 7). -16. **One video encoder path.** When Cut 6b lands, the ffmpeg CLI video child is - deleted. A missing encoder binary fails the request with a typed `detail`. - There is no fallback, because the donor's - `video_encoder_path.is_some()` switch (`D main.rs:1942`) kept two paths - alive. - -Explicitly **not** in scope: -- Mimir's `Mimir.CultMeshMedia`: a separate MPEG-TS-over-documents relay, - `mimir.cultmesh_media_frame`, `Program.cs:11`. It is not a - `gamecult.media_*` consumer. -- The retired C++ OBS receiver. It is "deliberately no longer understood" - (teardown-map L672-674). -- Opus itself, which is Muninn's own named cut. It is sequenced here, not - mapped here. - ---- - -## Probed mechanism claims - -These were run, not inferred from names. - -| Claim | How it was established | Result | -|---|---|---| -| What Muninn's sender emits | Read `media_packetizer.rs` @`cee7b9c`; Yggdrasil `cargo test -p muninn-daemon --bin muninn -- media parity repair rudp` | 78 pass. Video: data chunks plus XOR stripe parity (`gamecult.media_video_parity_shard.v2`) on `media`, unreliable. Audio: `pcm-f32le-interleaved`, 3,840-byte packets, on `audio`, **reliable**. **No audio parity.** | -| Receiver recovery present | Read Ratatoskr @`488b5b1` | Video: XOR stripe recovery, one chunk per stripe (`video.rs:224-269`). Audio: **none**; it passes straight through (`receiver.rs:320-323`). Keyframe request: yes, edge-triggered with a cooldown (`feedback.rs:92,130`). `cargo test -p ratatoskr-core` on Yggdrasil: 31 + 2 pass, including `parity_gives_back_one_lost_chunk_per_stripe` and `two_losses_in_one_stripe_are_beyond_repair`. | -| Donor GF(256) tested | Yggdrasil `cargo test -p muninn-daemon --bin muninn -- fec parity gf audio_fec video_wire` @`80adfd3` | 9 pass. Audio 4+2: exhaustive over every 1- and 2-erasure pattern (`donor media_packetizer.rs:4919`). **Video 8+4 Cauchy: only one single-erasure recovery, done by hand inside the test (`:2957`). There is no Rust multi-erasure video decoder** (it lived in Mimir's C++). **There is no known-answer vector for `gf256_mul`/0x11d**: a consistent wrong polynomial passes every round-trip. | -| An established codec fits | Scratch crate `rs-probe` on Yggdrasil, `--release` | `reed-solomon-erasure` 6 (GF(2^8)): any shard length (849 OK), exhaustive `≤m` recovery true for 4+2 and 8+4, `m+1` erasures fail cleanly. It costs 13.5 µs to encode and 11 µs to decode an 8+4 block of 850 bytes, and 2.6 µs / 3.4 µs for 4+2 at 864 bytes. `reed-solomon-simd` 3: **refuses odd shard sizes** (`InvalidShardSize{849}`), decode about 230 µs per block. | -| Current XOR vs RS at equal overhead | iid model, `python` (arithmetic, not a harness) | For a 200-chunk keyframe at 3% loss, XOR16 fails the frame **63%** of the time at 8% overhead, and RS 8+4 fails 4e-4 at 50%. For frames of `n ≤ 16` chunks, XOR16 is **duplication**: each stripe holds one chunk, so the overhead is 100%. | - -| Muninn↔Sleipnir HID wire today | Read `M main.rs` and `S main.rs` | **JSON both ways.** Subscription: `S :2303-2310` → `M :6216-6217`. State: `M :6298-6300` (ingress server) and `M :6835-6836` (outbound client) → `S :2485-2498`. Sleipnir coalesces "latest wins" per device (`S :2543-2590`), so a tap between two received frames never reaches ViGEm. | -| CultLib channel delivery | Read `C rudp.rs:2339-2410` | Only `media` takes its delivery from the profile, plus `audio` hardcoded Reliable. `schema`, `latest` and `_` are fixed by name. `latest` is Unreliable and **Sequenced per channel** (`:2384-2390`, `:185-191`), so a late older packet is dropped. The window-per-frame design fits this exactly, because each frame supersedes the last. **No CultLib change is needed for HID.** | -| Idunn host-native runner for the encoder | Read `I src/host.rs:934-960`, `I src/deployment.rs:55-110`, the binding | The Raven runner's `allowed_programs = ["cargo"]`. **Host-native materialisation refuses `external_inputs`** (`I host.rs:953-956`), so a sha-pinned FFmpeg download cannot be a recipe input on Raven. Runner environment comes from the binding (`[runners.rust-host.environment]`, precedent `CARGO_NET_GIT_FETCH_WITH_CLI`). `[service] required_adjacent_artifacts` exists (`I deployment.rs:113`). Recipe phases include `acceptance` (`:71-77`). | -| Donor encoder shape | `git show 80adfd3:native/muninn-video-encoder/*` | 265 lines of C++20, CMake with `FFMPEG_ROOT`. lavfi `ddagrab` → decoder → `h264_nvenc`. A `std::getline` stdin thread parses `IDR` / `BITRATE n` / `QUIT`. `fail()` calls `exit(1)`. Bitrate is reconfigured by mutating `AVCodecContext` before `send_frame`, and IDR by `pict_type = I` with `forced-idr=1`. The build script links the OBS deps snapshot at an `E:\Projects\Mimir` path that no longer exists. | ---- - -## Body findings - -`M` = Muninn `cee7b9c`, `C` = CultLib `069ecc3`, `R` = Ratatoskr `488b5b1`, -`D` = donor Odin `80adfd3`, `O` = Odin `main` `379b826`. - -**B1. Audio has no parity and rides a reliable channel.** -- `M media_packetizer.rs:1055-1063` sends audio on `MUNINN_AUDIO_RUDP_CHANNEL`. -- `C rudp.rs:2218-2228` profiles `"audio"` as `Reliable` whatever the options - say. Only `media` is configurable (`C rudp.rs:2208-2211`). -- `C media_stream_contracts.rs:34-41` says outright that audio has no parity - record. -- The `audio` channel exists only so that audio could be reliable - (`C media_stream_wire.rs:41-44`). Once audio is lossy with parity, it has no - reason to exist. - -**B2. PCM packets fragment.** 480 ticks × 2 ch × 4 B = 3,840 B -(`M main.rs:2455-2470`) against a 1,431-byte fragment limit (`M main.rs:82-86`). -So every audio packet is 3 datagrams. Parity over PCM protects 3-fragment -shards (roughly 3p shard loss) and costs 1.5 Mbps at 4+2. Opus at about 183 kbps -(teardown-map L475) fits one datagram. - -**B3. Video parity is XOR stripes, per frame.** -- `M media_packetizer.rs:625` sets `STRIPES = 16`. -- `:627-724` builds the stripes and `:726-754` writes data and then parity. -- The recovery guarantee is one loss per stripe. See the probe table for what - that costs on keyframes and small frames. -- The v2 record carries only stripe geometry (`C media_stream_contracts.rs:466-517`). - It cannot describe an RS block. - -**B4. A keyframe request is counted and ignored.** -- `M main.rs:3036-3048` `record_receiver_keyframe_pressure` logs "continuing - current low-latency encoder session until explicit encoder control exists". -- teardown-map L666-668 claims "the sender turns every new keyframe request into - an IDR". **That is false.** -- Recovery today is the fixed all-IDR GOP: `framerate/4` - (`M main.rs:10309-10311`) with `-g`, `-keyint_min` and `-forced-idr 1` - (`:10405-10410`). A lost reference therefore freezes for up to 250 ms. Ratatoskr - shows nothing until the next keyframe (`R video.rs` test - `nothing_is_delivered_between_a_loss_and_the_next_keyframe`, `:720`). - -**B5. No bitrate adaptation.** -- Bitrate is fixed per command (`M main.rs:1481-1487`, `:10399-10404`). -- What adapts is the **repair** rate (`MuninnRudpRepairBudget`, - `M main.rs:2744-2827`), not the encode rate. -- The ffmpeg CLI child (`:10343-10421`) has no live control surface. A change - of bitrate is a restart (`:1475`). - -**B6. The latency budget has two owners.** -- Producer: an empty request budget becomes - `MUNINN_RUDP_MEDIA_RECEIVER_ASSEMBLY_DEADLINE_MS = 2_000` - (`M main.rs:95,1489-1495`). That default drives the sender queue deadline, - audio expiry and the advertisement default (`:10286-10291`, `:1159`). -- Consumer: Ratatoskr sends 0, so it gets the 2 s default - (`R catalog.rs:174,198`), but it ages frames at its own **250 ms** - (`R video.rs:99-101`). -- So the sender will queue video for up to 2 s that the receiver has already - given up on. - -**B7. The sender's buffers are unbounded in count.** -- `M main.rs:2427` is `mpsc::channel` (unbounded), and - `PendingMuninnMediaSendQueues` (`:2701-2731`) is two unbounded `VecDeque`s. -- Payloads expire **individually** by age (`:2505-2532`). Half a frame can be - sent after its other half expired, which spends bandwidth on an undecodable - frame and its useless parity. -- The Annex B reader errors the whole stream when `pending > max_pending_bytes` - (`M media_packetizer.rs:296-306`) instead of dropping. -- Backpressure spins with `thread::sleep(1 ms)` (`M main.rs:2981`). - -**B8. Repairs renew their own send deadline.** -`poll_rudp_media_receiver_feedback` passes `Instant::now()` as `queued_at` for -every repair (`M main.rs:3125-3132`). A repair's age budget therefore starts -when it is asked for, not at the frame's deadline. This breaks invariant 1 -(donor doctrine: "a repair cache must not mint a new deadline", -`D docs/realtime-delivery-authority.md`). - -**B9. Receiver residue is still in the producer.** -- `AudioPacketBuffer` (`M media_packetizer.rs:847-987`) is a receiver jitter - buffer. -- The whole-stream helpers `packetize_video_annex_b_stream` (`:756-805`), - `encode_video_annex_b_stream_wire_records` (`:1017-1029`), - `video_annex_b_stream_send_payloads` (`:1031-1036`) and - `encode_record_payload`/`decode_record_payload` (`:1080-1090`) are called - only from tests. The tests are `media_packetizer.rs` `#[test]`s at - 1533/1570/1602/1820-1930/1992/2033/2078/2467, and `main.rs:12353,12395`. -- teardown-map L463-465 ("Muninn now holds only the producer half") is false. - -**B10. The mux loop has no seam.** `run_rudp_mux_once` (`M main.rs:2292-~2680`) -fuses process spawning, hub opening, catalog publishing, queueing, feedback, -repair and progress logging. No test can drive the send path without -PowerShell, ffmpeg and WASAPI. That is why "not exercised live" only ever meant -exercised on Raven. - -**B11. The CultLib pin is welded to an attic tag.** -- Muninn builds `odin-core` from Odin `3e96c6c` (`M Cargo.toml:25`). That - commit is on **no Odin branch**. Only the tag - `refs/tags/attic/claude-cultlib-pin-c2a9a6e` holds it - (`git ls-remote origin`). -- Odin `main` itself pins CultLib `a8aedda` (`O crates/odin-core/Cargo.toml:14-17`), - which is **older** than Muninn's `c2a9a6e`. -- odin-core's types are `DatabaseEntry`. Any CultLib bump in Muninn therefore - reopens the two-`cultcache-rs` diamond (teardown-map L616-619) unless odin-core - moves too. -- Muninn uses 21 odin-core symbols (`M main.rs:27-37`). Four are Odin's: - `EveProviderAdvertisementRecord`, `EveSurfaceStateRecord`, - `IdunnDaemonHealthRecord` and `OdinDocuments`. teardown-map L621-626 says 23 - and 7; `discover_provider_endpoints` and `OdinEndpointQuery` are no longer - imported. - -**B12. The donor's shape.** 29 commits, `2796884..80adfd3`, 2026-07-12..17. It -predates Muninn's extraction (teardown-map L628-629), the CultLib media -contract (`a250ec6` onward), and the consumer-dials-producer inversion. -- Its records are `muninn.*` in odin-core: video parity **v4**, audio parity - v1 (`D odin-core documents.rs`). -- Its transport is a single dialled client (`CultNetRudpSocketTransportConnection`, - `D main.rs:684`), not the hub. -- Its encoder control is a native C++ child, - `native/muninn-video-encoder/main.cpp` (265 lines, libavdevice with - `h264_nvenc`, stdin `IDR` / `BITRATE `). -- Its doc and code disagree on bitrate recovery: the doc says 5% every 2 s, - the code does `max/50` every 10 s (`D main.rs:2502-2507`). -- Its bitrate ceiling is **half** the configured rate, because "Block FEC can - roughly double the encoder payload" (`D main.rs:2454-2458`). -- Its "dispersed video parity" (`e58e0a7`) is not cross-frame: it was - bookending, then superseded by a within-frame round-robin over blocks - (`4e2abee`; `D media_packetizer.rs:1295-1360`). - -**B13. The donor's HID edge rewrites the transport.** -- `9af2edb` and `80adfd3` hardcode `"hid.edge"`, `"hid.edge.ack"`, - `"hid.subscribe"` and `"hid.edge.assist"` into a vendored `rudp.rs`, plus an - ACK-state change. -- The consumer, `sleipnir-daemon`, is in **Odin** (`O crates/sleipnir-daemon`, - 3,658 lines). The record is `MuninnHidControllerStateRecord` in odin-core - (latest-state snapshot, `buttons: Vec`; `3e96c6c documents.rs:1524-1547`). -- Today Muninn sends snapshots only (`M main.rs:6172-6200, 6758-6800`), so a tap - shorter than one sample, or lost with its packet, never happens. - -**B14. The HID wire is JSON, and a tap dies at two places.** -- The wire: `M main.rs:6137-6142, 6216-6217, 6298-6300, 6835-6836`; - `S main.rs:2303-2310, 2497-2498`. The 2026-09 repo census flagged the same - lines (`gamecult-ops/docs/repo-census-2026-09/repos/Odin.md:48`). -- **Muninn reads a source once per transport tick** - (`read_hid_controller_state_for_stream`, `M :6286`, `:6370`). A press and - release inside one tick never exist as data. -- **Sleipnir keeps only the latest record per device** (`S :2543-2590`), so a - tap that survived capture dies again at the sink. - -**B15. Muninn has two HID transport paths, and so does Sleipnir.** -`M` here is Muninn `main` `c3520d1`; HID lines moved +7 to +9 since `eb332b0`. -- Muninn listens: `--hid-controller-rudp-bind`, `M :6151-6340`. This is the one - Raven runs (recipe `raven-muninn.toml:62-65`, advertised `10.77.0.4:17887`), - and Starfire's legacy script can run it too - (`restart-starfire-muninn.ps1:14-15, 74-79`). -- Muninn dials: `--hid-controller-rudp-target`, `M :6724-6863`, parsed at - `:10899-10904`. -- Sleipnir mirrors both: it dials a discovered endpoint, or listens on - `--rudp-bind` (`S :2191-2281`, server branch `:2244-2281`). -- **Q10 settles it:** the consumer dials the producer's advertised endpoint, - exactly as Ratatoskr dials Muninn for video. The surviving direction is - "Muninn listens, Sleipnir dials". Muninn's outbound client and Sleipnir's - listening mode are the losing paths; H2 and H4 delete them. - -**B16. Sleipnir is welded into Odin's pin.** -- `S` is a member of Odin's workspace. It takes `odin-core` by path - (`Odin crates/sleipnir-daemon/Cargo.toml`) and CultLib at `a8aedda`, which is - Odin `main`'s pin, the one StreamPixels ships on. -- It imports 10 odin-core symbols (`S :10-14`). One is Muninn's HID record, - and one is its own `SleipnirInputMappingRecord`. -- Any Sleipnir change that consumes a Muninn-owned record at Muninn's CultLib - (`c2a9a6e`) reopens the two-`cultcache-rs` diamond **inside Odin's - workspace**, and that can only be closed by moving Odin `main`'s pin. -- Its deployment target is the legacy script-driven `raven-sleipnir` - (`gamecult-ops/scripts/idunn/idunn-deployment-targets.ps1:126-138`, - `Repo = "Odin"`, scheduled task plus SSH). It has no Idunn recipe. **Whether - it runs on Raven today is unverified.** - -**B17. The sink already has the seam a harness needs.** -`trait VirtualPadBackend { fn update(&mut self, state: &VirtualPadState) }` -(`S :179-181`) has a `LoggingBackend` (`:183`) beside the ViGEm one -(`:200-240`, `cfg(windows)`). A recording backend gives a pad timeline on Linux. - -**B18. Raven cannot fetch the encoder's FFmpeg through Idunn.** -Host-native materialisation refuses `external_inputs` (`I host.rs:953-956`), and -the runner may execute only `cargo`. So the FFmpeg development root must be: -- pre-provisioned on Raven (operator action, recorded in gamecult-ops with its - sha256); -- named by the binding's runner environment; -- compiled against by `build.rs`, through the `cc` crate for the C++ and link - directives for FFmpeg. No CMake step and no new allowed program. - -`ffmpeg_path` today points at a WinGet static `ffmpeg.exe` (binding -`raven-muninn.toml.in`, `ffmpeg_path`), which has no headers or import -libraries. - -**B19. The recipe is mid-edit by another campaign.** `route/b3-declare` -(`2260853`, unmerged) adds `[[dependencies]] odin.verse-rendezvous` to -`deployment/idunn/raven-muninn.toml`. Cut 6c edits the same file and must build -on it after it merges. - -**B20. Move evidence rides the HID listener, and Mimir consumes it.** -- `serve` gets the Move-evidence sender back from - `start_hid_controller_rudp_ingress` (`M :429-437`), and the ingress thread - sends it on channel `move-evidence` over the HID connection id - (`M :6271-6283`). -- It sends only while an HID subscription is selected (`M :6258-6269`), so a - consumer that wants Move evidence must speak the JSON `hid.subscribe`. -- Mimir does exactly that: `MimirOdinMoveProofEvidenceRingProvider.cs:223` - (Mimir `d88f2e6`) sends `{"streamId": ...}` on `hid.subscribe`. It discovers - the endpoint from the JSON `inputStreams` in Muninn's Eve provider - advertisement (`M :3713-3722`), channel `move-evidence`. -- The local ring is switched on by the absence of the HID bind - (`local_ring_enabled: options.hid_controller_rudp_bind.is_none()`, - `M :4238`). -- So deleting the JSON subscription (H2) silently stops Move evidence reaching - Mimir. The pass-2 map did not know this second consumer existed. Q12. - -**B21. HID discovery is JSON scraped out of Eve advertisements.** -- Muninn writes its HID endpoint and devices as JSON into three places in - `publish_runtime_boundary_records`: the transport profile's `input_streams` - (`M :3674-3699`, key at `:3856`), the provider advertisement's - `inputStreams` (`M :3701-3727`, key at `:3885`) and its `endpoints` - (`M :3729-3750`), in two casings. -- Sleipnir recovers it by pulling `muninn.hid_controller_state.v1` records to - learn host ids (`S :978-1003`), then pulling those hosts' provider - advertisements (`S :950-975`), then parsing JSON in either casing and in - tuple shape (`S :1845-2131`, `:2370-2478`), with Odin's generic - `discover_provider_endpoints` as a fallback (`S :2380-2398`). -- The video capability has none of this: one typed advertisement, one typed - request (`R catalog.rs:64-145`, `M :971-1166`). That typed path is what Q10 - orders input to mirror. -- The Odin-facing `publish_hid_controller_state_to_odin` (`M :6865-6875`, a - store `put` keyed by stream id) has **one reader**: Sleipnir's discovery. - Nothing else in Odin, Mimir, Ratatoskr, StreamPixels, Eve, VoidBot, Heimdall - or Idunn names the schema (`git grep`, 2026-09-30). - -**B22. Two readers own the same HID devices.** -- The serve tick reads every source to build receipts - (`publish_move_controller_states`, `M :4976-5134`). -- The ingress thread reads the same sources again at its own tick - (`read_hid_controller_state_for_stream`, `M :6377-6528`). -- The collision is fenced, not removed: on Windows the tick skips PS Move - sources whenever the HID bind is set (`M :5081-5086`), because the report - reader thread would otherwise have two consumers. -- Neither reader samples fast enough for a tap. The ingress loop sleeps 8 ms - (`M :6338`), and Sleipnir's default interval is 8 ms (`S :2791`). The - pass-2 map's "2 ms at the current poll (`HID_CONTROLLER_RUDP_POLL_INTERVAL`)" - is the **donor's** constant (`D main.rs:5879`). It does not exist at `c3520d1`. - -**B23. A producer restart orphans every running request.** -- `sync_media_stream_requests` admits only requests in state `pending` - (`M :1004`). The "already answered" memory is process-local - (`answered_requests`, `M :463`). -- So after a Muninn restart, every request it had answered `running` stays - `running` on Odin and is never admitted again. The consumer must notice and - publish a fresh request. -- Whether Ratatoskr re-requests is **unverified** (the redial lives in - `R receiver.rs`, and the request lives in the OBS plugin's C). -- H2 does not copy this. An input request is admitted as **demand**, by - `action`, and its `state` is only the producer's answer. The same change for - media belongs to Muninn's media owner and is recorded, not made, here. - ---- - -## Donor ledger: port, rewrite, drop - -| Donor piece | Verdict | Why | -|---|---|---| -| `gf256_mul`/`gf256_inv`, `recover_audio_fec_data`, `video_fec_coefficient` (`D media_packetizer.rs:1177-1180, 1525-1612`) | **Drop; replace with `reed-solomon-erasure`** (Q3) | No video decoder, no KAT, and it solves a matrix per byte for audio. The probed crate is MDS-exhaustive at the shipped sizes and fast enough by 3 orders of magnitude. Owned math is a liability we need not carry. | -| 4+2 audio block and 8+4 video block sizing | **Port as defaults**, parameterised as `(k, m)` in the record | Field-chosen numbers, but carried by the record so a decoder needs no config. | -| Within-frame round-robin send order over blocks (`D :1295-1360`) | **Port** (rewrite against CultLib types) | Turns a burst into one loss per block. It is policy, not math. | -| `pad_audio_codec_frame` 2-byte BE length prefix (`D media_packetizer.rs:674-686`) | **Port** into the Opus cut's framing (`opus-padded-v1`) | Constant shard size for variable codec frames. Matches the `aac-adts-padded-v1` precedent (teardown-map L477-479). | -| Datagram-fit tests (`D :3065`, `production_aac_audio_fec_shards_fit_one_rudp_datagram`) | **Port as behavioural tests** at the CultLib codec and in Muninn | They pin invariant 6. | -| Exhaustive erasure test (`D :4919`) | **Port**, generalised to every shipped `(k, m)` | Pins invariant 4. | -| `MuninnKeyframeRequestGate` (`D main.rs:2864-2884`, cooldown 500 ms at `:102`) | **Port** (Cut 6) | Small and correct: an edge with a cooldown. | -| `MuninnVideoBitrateController` (`D :2439-2512`) | **Rewrite** (Cut 6b) | Its ceiling halving assumes 50% FEC overhead, and its doc and code disagree. The rewrite keys the ceiling on the ruled parity rate and aggregates across hub receivers, which the donor predates. | -| `native/muninn-video-encoder/main.cpp` (265 lines) | **Port** the capture and encode loop (Cut 6a). **Rewrite** its shell. | Kept: the lavfi → decode → encode loop, NVENC options, `pict_type = I` and `AVCodecContext` bitrate mutation. Deleted: `main`, `parse_options`, the `std::getline` text command thread, `fail()`/`exit`, and `fwrite` to stdout. They become a C ABI (`muninn_encoder_run` with poll and write callbacks) under a Rust `main` that decodes typed command records (invariant 15). | -| `CMakeLists.txt`, `scripts/build-muninn-video-encoder.ps1` | **Drop** | `build.rs` with the `cc` crate compiles the C++. The Idunn runner may run only `cargo` (B18). The script's FFmpeg path no longer exists. | -| `capture_button_edges`, `ActiveHidControllerRudpSource` edge fields, overflow epoch rotation (`D main.rs:5732-5856`) | **Rewrite** as two pieces in `muninn-contracts::hid` (H1): `EdgeDetector` (diffs samples; runs on the capture thread, H2) and `EdgeWindow` (per subscriber session and device; owns epoch, pending bound and acks; runs on the input transport tick, H2). | The rotation and bound rules are right. The donor ran detection at transport-tick time, which loses sub-tick taps (B14); it kept one window per source, which cannot serve two subscribers; it cloned `epoch` needlessly; and it sent JSON. | -| Donor's `hid.edge` (reliable) + `hid.edge.assist` (unreliable resend) channels and the `hid.subscribe`/`hid.edge.ack` JSON | **Drop** | Two mechanisms for one job, plus four transport name arms (invariant 9). Replaced by one frame on the profile-declared `latest` channel that carries state and the unacknowledged window (invariant 11). | -| `HidSemanticCursor` (`DS main.rs:204-256`) | **Port** into `muninn-contracts::hid::EdgeCursor` (H1), with the `retired_epochs` set **replaced** by a monotonic epoch fence | The ordering, dedupe and gap bound (256) are right. The unbounded set is not (invariant 12). | -| `INPUT_EDGE_MINIMUM_VISIBILITY` 24 ms and the actuation queue (`DS main.rs:32-35, 655-700`) | **Port** into Sleipnir (H4), with the budget override added | Invariant 13. The donor queue has no latency ceiling. | -| Snapshot-buttons overwrite (`DS main.rs:573-578`) | **Drop** | Split button ownership (invariant 10). | -| Donor capture-thread split (`fb4f331`), 1 ms XInput sampling (`D main.rs:5881, 6880-6940`) | **Port** (H2) | This is where a tap first exists as data. | -| `crates/sleipnir-daemon/examples/xinput_edge_observer.rs` (`80adfd3`, 127 lines) | **Port** as Sleipnir's live probe (H5) | It reads the virtual pad through XInput, as the game does. That is the layer where a lost tap is visible (SKILL: instrument the layer the user sees). | -| Bounded `sync_channel` plus per-frame groups, capacities 256/512 (`D main.rs:85-87, 2023-2028, 2356-2369`) | **Port the shape**, rewrite against the hub loop (Cut 2) | Exactly invariant 2. | -| `cultnet-impair` (696 lines, seeded loss/burst/jitter/reorder/dup/stall, CSV) | **Port to CultLib** `packages/cultnet-rs/examples/` (Cut 3b) | It is a CultNet transport tool. `media_delivery_probe.rs` already sits there and expects it (its header, `C examples/media_delivery_probe.rs:5`). | -| Vendored `rudp.rs` ACK changes (`9af2edb` `direct_ack_state`, ACK reliable duplicates) | **Drop** | CultLib evolved separately (`75c1807` acknowledges retransmits across horizons; `47b9fc4` changes reader semantics). Anything still missing is a CultLib finding with its own proof, not a port. | -| `muninn.*` v4/v1 parity schemas | **Drop** | Superseded by `gamecult.*` in CultLib. No live reader. | - -Recommend Self tags the donor `parked/muninn-bounded-realtime-send` at `80adfd3` -before anything cites it again. This is the parked-not-dead pattern: the branch -is untracked per the morning file item 11. - ---- - -## Where FEC lives: owner decision - -**Owner: CultLib `cultnet-rs`, a new `media_fec.rs` module beside -`media_stream_wire.rs`.** It holds pure functions and no I/O. - -- **Not Muninn.** The receiver needs the decoder, so a codec in Muninn is either - duplicated in Ratatoskr or missing there. The first reproduces the Mimir split - (invariant 5). The second reproduces today's audio situation. -- **Not CultNet RUDP (transport FEC).** - - Transport FEC would group datagrams by send time, not by frame and - deadline. A block spanning two frames delays the first frame's recovery - past its deadline. - - It would also sit beside the frame-level NACK repair that Muninn and - Ratatoskr already run through `gamecult.media_receiver_feedback`, giving - two recovery authorities for one loss. - - The media plane's rule "a media payload fits one datagram" (invariant 6) - removes the one advantage transport FEC would have, which is protecting - fragments. - - The transport stays semantics-free (invariant 9). -- **Not CultMesh.** CultMesh carries state and discovery documents through Odin, - the advertisement and the request. Media records are CultNet wire records on a - live session and are never stored. FEC has no document to live in. -- **Not a new crate.** Authority separation does not buy a package. The media - plane is two files in `cultnet-rs` today, and every consumer (Muninn, - Ratatoskr, StreamPixels' vendored copy) already links it. - -What the module owns: -- the scheme id; -- `protect(frame_records, policy) -> send-ordered wire records` for video; -- `protect_audio(block) -> parity records`; -- `recover(block shards) -> Result`. - -What it does **not** own: -- the `(k, m)` choice, which is policy and belongs to the producer (Q8); -- when to give up, which is the receiver's deadline (invariant 1); -- sockets. - ---- - -## Identity, lifecycle and authority (0b) - -| Kind | What names it | What happens to it over time | Who decides | -|---|---|---|---| -| Video parity shard `gamecult.media_video_parity_shard.v3` | `(stream_id, session_id, frame_id, block_index, parity_index)`; the key extends today's (`C media_stream_wire.rs:92-110`) | Emitted with its frame's group, and dropped with the group at the deadline. Never repaired, never cached for repair. v2 is **deleted**, not kept beside it. | Producer emits. CultLib codec defines the bytes. Receiver consumes until the frame deadline. | -| Audio parity shard `gamecult.media_audio_parity_shard.v1` | `(stream_id, session_id, base_packet_id, parity_index)` | Emitted after its k-th data packet. It expires with the block's latest deadline. Lands only after Opus (Q5). | Same. | -| FEC scheme id (`rs-gf256-v1`) | A string on each parity record | Changes only with a new schema version. A KAT pins it. | CultLib. | -| `(k, m)` policy | Carried per parity record (`block_data_count`, `parity_count`) | Fixed (Q8): video `k ≤ 16`, `m = max(2, ⌈k/4⌉)`; audio 4+2. | Producer (Muninn). | -| Latency budget | `gamecult.media_stream_request.v1.latency_budget_ms` (key 11) | Fixed for a request. Default 250 ms in the advertisement (Q7). A new request restarts the child (teardown-map L533). | **Consumer** asks; producer honours it. | -| Keyframe request | `requested_keyframe` on feedback | Counted per receiver. It is an edge: at most one IDR per 500 ms cooldown per stream. | Receiver asserts. Muninn's gate decides (6b). | -| Encoder command `muninn.video_encoder_command.v1` | `(encoder process, command_sequence)`. The sequence is monotonic from 1 per spawned encoder process. | Lives only on the stdin pipe. Never stored. It dies with the process; a respawn restarts the sequence at 1. | Muninn's `EncoderControl` writes. The encoder applies at the next frame. **Effect is observed from the bitstream**, not acknowledged. | -| Live encode bitrate | Observed bytes per second over a 1 s window | Moves within `[floor, ceiling]` from the request's `video_bitrate_kbps` and the parity rate | Muninn's bitrate controller (6b) | -| Input-stream advertisement `muninn.input_stream_advertisement.v1` (Q11) | `stream_id` (`muninn..input`) | Republished on the same cadence and at the same site as the media advertisement. State `available` / `streaming` / `unavailable`. | Muninn (producer). | -| Input-stream request `muninn.input_stream_request.v1` (Q11) | `input_stream_request_key(stream_id, receiver_id)` | The consumer publishes `start` or `stop`. The producer admits it **as demand**, by `action`, not by `state` (B23), and writes its answer (`running` / `stopped` / `failed` with `detail`) onto the same key. A new request supersedes the old one under the key. | **Consumer** asks (Sleipnir); producer answers. | -| Input session | The hub session whose connect payload is the request's `receiver_id` (the Ratatoskr rule, `R receiver.rs:40-42`) | Lives while the consumer is attached. A session with no admitted request is served nothing. | Consumer dials; Muninn's input hub admits. | -| HID epoch | `(session, device_id, epoch: u64)`. The epoch is the window's monotonic creation time in ns, and `+1` on overflow rotation. | New per window (session attach, device change, process start) and per overflow. The receiver fences any epoch below its current one. | Muninn's `EdgeWindow`. Sleipnir only fences. | -| HID state sequence | `(session, device_id, epoch, state_sequence)` | Monotonic per epoch. Each frame supersedes the last (the `latest` channel is sequenced per session). | Muninn. | -| HID edge | `(session, device_id, epoch, edge_sequence)`, contiguous from 1 per epoch | Detected once, at sample time, on the capture thread. Pending per window until acknowledged. Resent in every frame while pending, at most `MAX_EDGES_PER_FRAME` per frame and 256 held. Overflow rotates that window's epoch and drops its history. | Muninn detects (capture) and delivers (window). Sleipnir applies in order and acknowledges cumulatively. | -| HID edge ack `muninn.hid_edge_ack.v1` | `(device_id, epoch, applied_through)` on the consumer's session | Cumulative and idempotent. Resent each Sleipnir tick while nonzero. | Sleipnir. | - ---- - -## Cut 0: correct the Muninn maps against git (docs only) - -**Status: in Hands on `hands/rr-cut0-1` (`2c120c9`, `f2a5db9`, `a189363`). Unchanged by pass 2.** - -Repo Muninn, `main`. Hands, doc-only. Nothing is deleted from history. Superseded -claims are marked as history in place and not left as two live designs. - -Corrections to `docs/teardown-map.md` @`cee7b9c`: - -| Line | Says | Git says | -|---|---|---| -| 1-3 | "(pre-rebuild)", dated 09-09, body at `Odin\crates\muninn-daemon` | Live repo `GameCult/Muninn`. `main.rs` is 15,134 lines and `media_packetizer.rs` 2,633. | -| 24 | CultLib pin `c13b6ba0` | `c2a9a6e` (`Cargo.toml:21-23`) | -| 50, 65 | "19 muninn.* schemas… in odin-core", "20 symbols" | The four media schemas moved to CultLib (`gamecult.*`). 21 odin-core symbols (`main.rs:27-37`). | -| 450 | Ratatoskr "Pinned to CultLib `d1a9eda`" | `c2a9a6e` (Ratatoskr `Cargo.toml:16-18`) | -| 463-465 | "Muninn now holds only the producer half" | `AudioPacketBuffer` and the whole-stream helpers remain (B9). Cut 1 makes the sentence true. | -| 611 | CultLib `main` `05e0925` | Contract unchanged since `c2a9a6e`. `main` is `069ecc3`. | -| 615-642 | "The one thing blocking a clean Muninn build… uncommitted `[patch]`… `Cargo.lock` untracked" | Resolved (L684-686). `Cargo.lock` is tracked (`60ed6b2`). Mark as history. **Add:** odin-core comes from `3e96c6c`, which is reachable only through the attic tag (B11). | -| 621-626 | 23 symbols, 7 Odin's | 21 symbols, 4 Odin's (B11) | -| 656-659 | "Not yet exercised live: Raven runs a pre-b679fc2 Muninn" | Contradicted by L536-603. Both legs were proven 2026-09-10/11 on `bc43e1b`+. | -| 666-668 | "the sender turns every new keyframe request into an IDR" | False. `main.rs:3036-3048` logs only (B4). | - -Corrections to `docs/muninn-media-streaming.md` @`cee7b9c`: - -| Line | Says | Code says | -|---|---|---| -| 240 | preset `p1` | `p5` (`main.rs:10279`) | -| 249 | chunks `480` bytes | `848` (`main.rs:81`) | -| 258-259 | resend `5` ms inside a `75` ms expiry | `30` ms (`main.rs:94`). Expiry is the latency budget, default 2,000 ms (`main.rs:95`). | - -Verification: `git diff --stat` shows only the two docs. Soul checks each row -against `git show cee7b9c:`. Ledger: ±0 code. - ---- - -## Cut 1: subtract the receiver residue from the producer - -**Status: in Hands on `hands/rr-cut0-1` (`2c120c9`, `f2a5db9`, `a189363`). Unchanged by pass 2.** - -Repo Muninn, `main`. This is a subtraction cut, kept separate from behaviour -cuts. No pin change. - -**Deletes first** (`media_packetizer.rs` @`cee7b9c`): -- `AudioPacketBuffer` plus its impl, `:847-987`, and its 5 tests - (`audio_packet_buffer_*`, around `:1820-1935`); -- `VideoAnnexBStreamPacketizeOptions` `:162-173`, - `VideoAnnexBStreamWireOptions` `:175-180`, `packetize_video_annex_b_stream` - `:756-805`, `encode_video_annex_b_stream_wire_records` `:1017-1029` and - `video_annex_b_stream_send_payloads` `:1031-1036`; -- `encode_record_payload` / `decode_record_payload` `:1080-1090`; -- empty-line runs left by earlier cuts (`:230-240`, `:403-406`, `:552-556`, - `:1091-1099`). - -**Keeps and moves.** These tests prove real packetizer behaviour and are -**re-homed onto `VideoAnnexBStreamSendState`**, not deleted: -- `packetizes_annex_b_stream_into_timed_video_records` (`:1533`); -- `packetizes_non_reference_h264_p_frames_without_dependency` (`:1570`); -- `rejects_negative_annex_b_stream_deadline_delay` (`:1602`); -- `media_wire_batches_annex_b_video_records` / `media_wire_encodes_annex_b_stream_for_sender` / `media_send_payloads_pin_video_to_media_channel` (`:1992, 2033, 2078`); -- `main.rs:12340-12420`, the two fragment-limit tests. - -`feedback_payload_decodes_legacy_record_without_chunk_keys` (`:2467`) proves a -CultLib `default` key. Delete it here if `C tests/media_stream_contracts.rs` -already pins key 10's default. Otherwise move it there. Hands checks which -applies and reports. - -**Adds:** none. - -**Verification:** -- `cargo build --release -p muninn-daemon` and - `cargo test -p muninn-daemon --bin muninn` on Yggdrasil via ygg-verify. -- A negative grep: `rg "AudioPacketBuffer|packetize_video_annex_b_stream\b|decode_record_payload" crates/` - returns nothing. -- `cargo mutants --in-diff` scoped to `media_packetizer.rs`. - -**Ledger:** about −330 lines, no new surface. - ---- - -## Cut 2: bounded sender, one deadline owner, and a drivable seam - -Repo Muninn, `main`. No pin change. Cut 5's parity rides on it. - -Q7 ruled: the default is 250 ms, owned by the request. It goes in the advertisement, and Ratatoskr derives its `max_frame_age` from its request (Cut 4). - -**Authority map.** -- **Owner:** a new `MediaSendCore` in Muninn. It holds the queues, the hub, the - feedback intake, the repair cache and budget, and the progress stats. -- **Inputs:** `Read` sources for encoded video and audio, a `MediaSendPolicy` - derived **only** from the request (`latency_budget_ms`, `video_bitrate_kbps`, - `media_packet_bytes`), a `CultNetRudpServerHub`, and a clock. -- **Outputs:** payloads on the hub, repairs to the asking receiver, stats. -- **Derived state:** - - the queue deadline, repair eligibility and audio expiry derive from - `policy.latency_budget`; - - `MUNINN_RUDP_MEDIA_RECEIVER_ASSEMBLY_DEADLINE_MS` is **no longer an owner**. - It dies, and the advertisement's `default_latency_budget_ms` takes the - 250 ms constant (Q7). -- **Forbidden writers:** - - `Instant::now()` as a repair's `queued_at` (`main.rs:3129`). A repair - inherits its frame's deadline. - - Per-payload expiry. Expiry is per group. - - `VideoAnnexBStreamSendState` erroring on overflow - (`media_packetizer.rs:296-306`). Overflow drops the oldest complete access - unit and counts it. -- **Shared paths:** live sends, repairs and the harness all go through - `MediaSendCore`. `run_rudp_mux_once` keeps process spawning and publishing, - and nothing else. -- **Deletion line:** `mpsc::channel` at `main.rs:2427`, the unbounded - `PendingMuninnMediaSendQueues` (`:2701-2731`), per-payload expiry (`:2505-2532`), - and the 1 ms sleep spin (`:2981`), which becomes a bounded poll of resends - that stops at the group deadline. - -**Adds (types and rules only):** -- `QueuedMediaGroup { kind, deadline: Instant, payloads }`. One access unit with - its parity, or one audio packet. -- `mpsc::sync_channel` with a small bound, as in the donor (`capacity 1` of - groups). -- Per-kind group caps: audio 256, video 512 in the donor. Cap them in **groups**, - and name the byte ceiling they imply. -- Drop-oldest-group on cap, counted as `groups_dropped_{audio,video}`. -- Audio before video, as today (`:2705-2716`). - -**Harness seam (the reason B10 matters).** A `#[cfg(test)]` driver feeds -`MediaSendCore` from a committed Annex B fixture. It needs: -- a short H.264 clip, generated once and committed with its ffmpeg command - recorded beside it (provenance); -- a PCM ramp. - -It serves over a loopback hub, through a seeded **drop relay thread** (a UDP -relay between two sockets that drops by a seeded schedule), to an in-test -`CultNetRudpSocketTransportConnection` client. The client counts received and -expired groups. It needs no ffmpeg, PowerShell or GPU, so it runs on Yggdrasil. - -**Verification (rules each test pins):** -- Push faster than the hub drains: resident queue memory stays `≤` the stated - ceiling, and the stream is not restarted. This kills a mutant that removes - the cap or turns it into `usize::MAX`. -- Expire mid-frame: either every payload of a frame group is sent or none is. - Assert on the relay's captured datagrams, not on stats. The observation sits - at the wire (invariant 2). -- A repair asked for after its frame's deadline is not sent. A repair asked - for before it is sent. Probe at `deadline − ε` and `deadline + ε`, with ε - under 5 ms, so that a mutant that re-derives the deadline from `now` is - caught. **At least one mutant must be a function of the budget**, a clamp or - an offset (SKILL: "weakest thing that would still pass"). -- The request's `latency_budget_ms` reaches the queue deadline exactly. Use a - dev-only seam that records the computed `Duration` and assert exact equality - at two budget values. Both must differ from the default, and both must be - unequal to each other. -- `cargo mutants --in-diff`. Survivors are triaged by name. - -**Only live proves:** that dropping whole groups under Raven's CPU pressure (93%, -teardown-map L603) keeps the stream watchable. That needs a Raven run after -Idunn B3 (see Sequencing). - -**Ledger:** roughly −150 in `run_rudp_mux_once` and +250 for `MediaSendCore` -plus the harness. About +100 net. It buys invariant 2 and the only test path -into the sender. - ---- - -## Cut 3: the CultLib media FEC codec and records - -Repo CultLib, a branch from `main`. Tag and publish per CultLib's release -rules. A release is a cut: Soul passes before the tag (SKILL step 5). Q3, Q4 -and Q8 are ruled. Consumption waits on the pin gate (Q2, Sequencing step 11). - -**3a. Deletes first:** -- `GameCultMediaVideoParityShardRecord` v2 (`C media_stream_contracts.rs:466-517`), - its schema const (`:46`), `validate_video_parity_record` - (`C media_stream_wire.rs:323-388`), the `VideoParity` wire arm's v2 decode - (`:98-103`, `:183-186`), and the v2 tests in `tests/media_stream_wire.rs` - and `tests/media_stream_contracts.rs`. -- Per Q4: `GAMECULT_MEDIA_AUDIO_CHANNEL` (`C media_stream_wire.rs:41-44`), - the `"audio"` channel profile (`C rudp.rs:2218-2228`), `"audio"` in the - `channel_send_options` arm (`:2394`), and the test rows - (`tests/cultnet.rs:436, 3023-3030`). - -**Adds:** -- `gamecult.media_video_parity_shard.v3`. It carries the frame framing fields as - v2 does, plus `fec_scheme: String`, `block_index`, `block_count`, - `block_data_start`, `block_data_count` (k), `parity_index`, `parity_count` - (m), `shard_payload_bytes`, `last_chunk_payload_bytes` and `payload` (bin). - The donor's v4 field list (`B12`) plus the scheme id is the right shape. -- `gamecult.media_audio_parity_shard.v1`. Fields: `fec_scheme`, - `base_packet_id`, `base_pts_ticks`, `packet_duration_ticks`, `timebase_*`, - `deadline_ticks` (the maximum in the block), `data_shard_count`, - `parity_index`, `parity_shard_count`, `shard_payload_bytes` and `payload`. - This is the donor's v1 shape plus the scheme id. -- `GameCultMediaWireRecord::AudioParity`, with its validation, record key - (`B` identity table) and decode arm. -- `media_fec.rs`: - - `MediaFecPolicy`, fixed per Q8. Video frames split into `⌈n/16⌉` near-equal - blocks (`k ≤ 16`), with `m = max(2, ⌈k/4⌉)`. Audio is 4+2. The rate is - carried per record. - - `protect_video_frame(&[VideoAccessUnitRecord], &policy) -> Vec` - in **send order**, round-robin over blocks (donor `4e2abee`); - - `protect_audio_block(&[AudioPacketRecord; k]) -> Vec`; - - `recover_video_block` / `recover_audio_block(present) -> Result, BeyondRepair>`. - - Backing: `reed-solomon-erasure = "6"` (Q3), default features, no - `simd-accel`. The KAT pins the wire, so the library is replaceable. -- Update the module doc `C media_stream_contracts.rs:34-41`: audio now has - parity. - -**Rules that must die under their own mutation:** -- Every `≤ m` erasure pattern recovers exactly, for **every** shipped `(k, m)`: - `k = 1..16` with its ruled `m`, and 4+2. This is exhaustive. The largest is - `k = 16, m = 4`, about 6,200 patterns, which the probe shows is cheap. -- `m+1` erasures return `BeyondRepair`. They never return `Ok` with wrong bytes. -- KAT: fixed 4×37-byte input, then the exact parity bytes, committed as hex. - This kills any change of matrix, polynomial or shard order. -- Every data and parity wire record at the policy's maximum shard size is - `≤ 1431` bytes encoded (invariant 6). The bound is a named constant, not a - literal copied from Muninn. -- Blocks never span frames. A `protect_video_frame` call with mixed `frame_id` - errors. -- Send order: within any window of `block_count` consecutive records, no two - come from one block. That is the burst property. Assert it on the output - sequence, not on a helper. -- Parity carries its frame's `deadline_ticks` unchanged. - -**3b. Port `cultnet-impair`** from the donor -(`D crates/cultnet-impair/src/main.rs`, 696 lines, and -`tests/realtime-impairment/*.toml`) to -`packages/cultnet-rs/examples/cultnet_impair.rs` plus profiles under -`packages/cultnet-rs/tests/impairment/`. This is a separate commit. -- Keep the donor's six deterministic policy tests. -- Drop anything that imports the donor's vendored transport. -- Add a **seeded loss matrix** as a codec test, with no sockets: data plus - parity through a seeded iid/burst erasure schedule, then `recover`, then a - recovered-frame ratio per cell. `clean`, `loss-1/3/5pct`, `burst-4/8` are the - donor's profiles. Commit the table the test prints as the evidence record. - Assert only the guarantee (for example, `burst-4` against round-robin - `k=8, m=4`: every block with ≤ m losses recovers), not a tuned ratio. - -**Runtime parity.** The media plane is Rust-only today. `grep` finds no -`media_video_parity_shard` outside `packages/cultnet-rs`. Record that the scheme -id names the construction, so a future C# or TypeScript decoder has a KAT to -meet. `reed-solomon-erasure` states it is compatible with Backblaze JavaReedSolomon -and klauspost/reedsolomon. **This claim is not probed**; the KAT is the contract, -not the claim. - -**Verification:** -- `cd packages/cultnet-rs && cargo test` -- `cargo mutants --in-diff` on Yggdrasil. -- Negative grep: `rg "media_video_parity_shard.v2|GAMECULT_MEDIA_AUDIO_CHANNEL" packages/` - is empty. -- A **StreamPixels check**: its vendored CultLib carries `media_stream_*` - (`StreamPixels/vendor/CultLib/...`). Confirm that StreamPixels compiles - nothing that names the deleted symbols before the tag. StreamPixels is on the - ship path, so this is read-only; do not bump it. - -**Ledger:** -- deletes: about −180 (v2 record, validator, tests, audio channel); -- adds: +140 (records and validation), +200 (`media_fec.rs` with tests), - +700 (impair port, an example rather than library surface); -- one new dependency, `reed-solomon-erasure`, which pulls `lru 0.7` and - `parking_lot 0.11` (seen in the probe build). - -Net library surface is about +160. The impair tool is tooling. - ---- - -## Cut 4: Ratatoskr decodes with the CultLib codec - -Repo Ratatoskr, `main`. It lands **before** Cut 5, so that the receiver -understands v3 before the producer emits it. - -**Deletes first:** -- the XOR stripe recovery: `ParityShard` (`R video.rs:180-186`), `repair()` - `:224-269`, the stripe doc `:1-8`, and the stripe tests `:638-683`; -- the `insert_parity` v2 path `:346-374`. - -**Keeps:** the assembler's lifecycle: admit, expire, evict, repair cadence, and -the keyframe wait. - -**Adds:** -- `insert_parity` for v3. It calls `recover_video_block` when a block has - `≥ k` shards. -- An audio hole recoverer: - - hold a missing packet only until its block can recover **or** its deadline - passes, whichever comes first, bounded by the request's budget - (invariant 1); - - then recover, or report a hole; - - "Stamp live audio with the receive clock" (`d11f533`) stays the playout - owner. -- Stats counted from observation: `parity_recovered_chunks`, - `parity_beyond_repair_blocks`, `audio_recovered_packets` and `audio_holes`. - -**Rules:** -- A v3 block missing `≤ m` shards completes without a repair request. Assert - that no feedback record names its chunks. -- A block missing `m+1` shards falls through to the repair path and names only - the unrecovered chunks. -- An audio packet recovered by parity is delivered once, with its original - `packet_id` and `pts`. -- An audio hole past its deadline is reported and never delivered late. -- `max_frame_age` derives from the request's `latency_budget_ms`, not - `Duration::from_millis(250)` (`R video.rs:101`). The same two-value exact - check as Cut 2. - -**Verification:** -- Bump the CultLib pin to Cut 3's tag. -- `cargo test -p ratatoskr-core` and the C checks per Ratatoskr's README on - Yggdrasil. -- `cargo mutants --in-diff`. - -**Only live proves:** that OBS renders through recovered frames, and that audio -recovery does not add audible delay. That needs the plugin on Starfire, which -is operator-installed. - -**Ledger:** −90 XOR, +150 (v3 intake and audio recoverer). About +60. - ---- - -## Cut 5: Muninn emits CultLib parity, and audio goes lossy - -Repo Muninn, `main`. It is gated by the pin gate (Q2, Sequencing step 11). -Per Q5, **video parity ships here, and the audio half waits for Opus**: audio -stays on the reliable `audio` channel until then. - -**Deletes first:** -- `MUNINN_VIDEO_PARITY_STRIPES`, `build_video_parity_shards` and - `video_wire_records_with_parity` (`M media_packetizer.rs:625-754`), and - their tests; -- `audio_packet_send_payload`'s audio-channel pin (`:1055-1063`) and - `MUNINN_AUDIO_RUDP_CHANNEL` (`:15-16`), per Q4, in the audio half after Opus; -- the `media_send_payload_pins_audio_to_media_channel` test's assertion - (`:2252-2280`), which is rewritten to its new truth. - -**Adds:** -- The video send state calls `cultnet_rs::protect_video_frame(records, &policy)`. - Each output becomes one `QueuedMediaGroup` (Cut 2). -- The audio send state accumulates `k` packets and emits parity after the - k-th. This is the donor's `fec_block` pattern (`D media_packetizer.rs:618-632`, `:812-826`), - against CultLib types. -- A partial block at stream end or restart is emitted without parity and - counted. It is not padded with invented packets. -- Audio on the `media` channel, lossy. -- The advertisement names the FEC scheme it emits, only if Ratatoskr needs to - know before the first record arrives. The default is not to add a field: - parity is self-describing. -- `MUNINN_RUDP_MEDIA_PROFILE_ID` (`main.rs:76`) bumps to `…lan.v2`, because the - profile's wire behaviour changed. - -**Rules:** -- End to end through Cut 2's drop relay, with the `loss-3pct` seed: - - every frame whose blocks each lost `≤ m` shards is decodable at the client - with **zero** repair requests; - - audio packets lost `≤ m` per block are delivered. - - The in-test client decodes with CultLib's `recover_*`, so this does not need - Ratatoskr as a dependency. -- The wire contains no `v2` parity and no `audio`-channel frames. Assert on the - relay's captured datagrams. - -**Harness run on Yggdrasil (the loss-injection acceptance):** -- Cut 2's test driver with the Cut 3b profiles matrix: - `clean`, `loss-1pct`, `loss-3pct`, `loss-5pct`, `burst-4`, `burst-8`, - `reorder`, `duplicate`. -- Report per cell: - - frames complete without repair; - - frames complete via repair; - - frames expired; - - audio recovered and holes; - - wire overhead, measured as bytes on the relay divided by encoded payload - bytes. -- Run it once at Muninn `cee7b9c`-equivalent behaviour (XOR, reliable audio) - and once after, and commit both tables. **The before-and-after table is the - evidence that the campaign bought something.** - -**Only live proves:** -- that NVENC's real frame-size distribution, including IDR spikes of hundreds of - chunks, fits the chosen `(k, m)` without the overhead pushing past the link; -- that the Raven → Starfire LAN and the mesh-hairpin path (28 Mbps, - teardown-map L292) both hold. - -Protocol: the operator runs the stream for N minutes on each path with the -receive probe's stats captured. Parity overhead against the 28 Mbps hairpin is -the number that decides whether the later adaptive-parity cut (Q8) is needed. - -**Ledger:** −130 XOR, +60 of calls into CultLib. **Net about −70.** - ---- - -## Cut 6: native encoder, IDR on request and bitrate adaptation (Q6 = a) - -The ruling was against Imagination's recommendation, which was to decide on -harness evidence. This map carries out the ruling. The one cost to name: this is -the campaign's only new native target, and its Windows build is proven nowhere -but Raven. - -Three parts, each with its own verification: -- **6a** builds the encoder and needs no GPU; -- **6b** wires Muninn to it; -- **6c** deploys it and accepts it on Raven. - -Build hosts and target platforms are named separately throughout, per the -global Build budget rule. - -### 6a: the `muninn-video-encoder` package (Muninn repo) - -**Why a package.** -- **Owner:** Muninn. -- **Live consumer:** Muninn's activation child, which spawns it. -- **Protected invariants:** invariant 15 (typed commands, observed effect) and - invariant 16 (one encoder path). -- **Why the existing owner cannot serve:** FFmpeg's C API must be linked. Linking - libav into `muninn-daemon` would make every Muninn build, on Nightwing, - Starfire and in CI, need an FFmpeg development root. A separate package - confines that to one target. -- **What it replaces:** the ffmpeg CLI video child (6b deletes it). -- **Build fan-out:** add `muninn-video-encoder` to the workspace `members`, and - **not** to `default-members`, so that a plain `cargo build` or `cargo test` - never needs FFmpeg. - -**Layout.** -- `crates/muninn-video-encoder/Cargo.toml`: `[[bin]] muninn-video-encoder`. - Dependencies: `muninn-contracts` (the command record, H0/H1), - `cultnet-rs` (framing and message envelope), `anyhow`. Build-dependencies: - `cc`, plus `pkg-config` for the Linux path only. -- `native/encoder_core.cpp`: the donor loop, **ported**, with these changes: - - `main`, `parse_options`, the `command_reader` thread and `fail()` are - deleted. Errors return a code and a message into a caller buffer. - - Its only entry point is: - ```c - int muninn_encoder_run(const muninn_encoder_options*, - int (*poll)(void* ctx, muninn_encoder_control* out), - int (*write)(void* ctx, const uint8_t* data, size_t len), - void* ctx, char* error, size_t error_len); - ``` - `poll` is called once per captured frame. It returns - `{force_idr, bitrate_kbps (0 = unchanged), stop}`. - - The encoder name is an option. `h264_nvenc` (with the donor's option - dictionary) is for production. `libx264` (`preset=ultrafast`, - `tune=zerolatency`) is only for the Linux verification build. The capture - input is an option too: `ddagrab=...` in production, `testsrc2=...` in - verification. -- `build.rs`: - - On Windows, read `MUNINN_FFMPEG_ROOT` (required), compile - `encoder_core.cpp` with `cc` (MSVC, `/std:c++20`), emit - `cargo:rustc-link-search` for `lib/`, and link `avcodec avdevice avfilter - avformat avutil`. - - Refuse to build unless `include/libavcodec/version_major.h` has the pinned - `LIBAVCODEC_VERSION_MAJOR`. The pin is a named constant in `build.rs`; the - operator's provisioned build sets it. - - Emit `cargo:rerun-if-env-changed=MUNINN_FFMPEG_ROOT`. - - On Linux, find the same libraries through `pkg-config`. -- `src/main.rs`: - - parses argv: `--input`, `--encoder`, `--framerate`, `--bitrate-kbps`, - `--gop-frames`, `--frames N` (verification bound); - - runs a stdin reader thread: `cultnet_rs::LengthPrefixedMessageFramer`, - then `decode_cultnet_message_from_slice`, then `MuninnVideoEncoderCommandRecord`, - then validation, then a **bounded** `sync_channel(16)`; - - implements `poll` by draining that channel into one control value: - - any IDR sets `force_idr`; - - the **last** bitrate wins, so coalescing matches the donor's atomic - exchange; - - `stop` ends the run; - - implements `write` to stdout; - - guards the framer with a maximum frame length of 4 KiB. The framer buffers - whatever arrives, so a garbage length prefix must not grow memory - (invariant 2's spirit). - -**The command record** `muninn.video_encoder_command.v1`, in `muninn-contracts`. -It is Muninn-owned and process-local, and published to no store. - -| key | field | rule | -|---|---|---| -| 0 | `command_sequence: u64` | starts at 1 per encoder process and increases by exactly 1. A gap or repeat is refused and counted, which exposes a writer bug. | -| 1 | `kind: String` | `idr`, `bitrate` or `stop`. Anything else is refused and counted. | -| 2 | `bitrate_kbps: u32` | nonzero only for `bitrate`, within `[250, 100_000]` (the donor's bounds, from its command thread) | -| 3 | `cause: String` | for example `keyframe-request` or `receiver-pressure`. Telemetry only. | -| 4 | `issued_at: String` | telemetry only | - -**Verification on Yggdrasil.** Build host Linux x86_64. Target platform Linux, -**not** the Windows shipping target. -- Image: the rust verify image plus - `apt-get install -y libavdevice-dev libavfilter-dev libavformat-dev libavcodec-dev libx264-dev pkg-config`. - This runs inside the job's command. A dedicated image is a later optimisation - if the apt time hurts. -- Unit tests, `cargo test -p muninn-video-encoder`: - - the record round-trips; - - a stream of framed commands split at every byte boundary decodes - identically; - - `bitrate_kbps` of 249 and 100_001 is refused, and 250 and 100_000 are - accepted. At least one tested value must sit where a clamp would change - it; per SKILL, a clamp is the mutant to beat; - - a sequence gap or repeat is refused; - - many bitrate commands between two polls yield the last one; - - an IDR and a bitrate in one poll yield both. -- Integration test, spawning the built binary with `--input testsrc2=size=320x240:rate=30`, - `--encoder libx264`, `--gop-frames 1000` and `--frames 120`: - - Parse stdout with Muninn's `h264_annex_b_access_units`. The test - lives in `muninn-daemon`'s test module so it can reach the parser. - - After the 20th access unit, write an `idr` command. **Exactly one** keyframe - access unit appears in AUs 21-23. There is none elsewhere except AU 0, - because the GOP is 1000. - - After the 60th AU, write `bitrate 150` (down from 1500). The mean non-key - AU size over 90-120 is at most half the mean over 30-60. - - If libx264's in-session reconfigure does not honour this, the test must - say so, and fall back to asserting that the core received the value - (a dev-only counter on the C ABI). That fallback is recorded as **not yet - reached** for Linux, never as unreachable. -- `cargo mutants` on the Rust shell's diff. The C++ core has no mutation tool, - so it is defended behaviourally by the integration scenario (SKILL). - -### 6b: Muninn drives the encoder (Muninn repo) - -Depends on: -- Cut 2's `MediaSendCore` seam; -- Cut 5's parity policy, for the ceiling. - -**Deletes first:** -- `record_receiver_keyframe_pressure` (`M main.rs:3036-3048`) and its two call - sites in `run_rudp_mux_once`. -- The ffmpeg CLI video child: - - `rudp_video_ffmpeg_args` (`M :10343-10421`); - - `muninn_rudp_video_bitrate_arg`, `muninn_rudp_video_vbv_buffer_arg` and - `muninn_rudp_video_gop_frames` (`:10296-10311`), which move into encoder - options; - - the video `Command::new(&options.ffmpeg_path)` spawn in `run_rudp_mux_once`; - - `ffmpeg_args`; - - the CLI-argument tests (around `:12180-12335`), re-homed as encoder-options - tests where they pin a rule: GOP equals a quarter of the frame rate, and - the explicit bitrate. -- The `MuninnRudpMediaProfile` fields that fed only the CLI (`video_preset`, - `video_tune`, `video_b_frames`, `video_rc_lookahead`, `:10279-10285`). The - runtime-boundary JSON at `:3830-3847` loses them, and its `"recovery"` string - changes to what is now true. -- `ffmpeg_path` stays for the **audio** child until the Opus cut. - -**Adds:** -- `trait EncoderControl { fn request_idr(&mut self, cause: &str); fn set_bitrate(&mut self, kbps: u32, cause: &str); }` - as a port in `MediaSendCore`. - - The production implementation owns the encoder's `ChildStdin` on a - **writer thread** behind `sync_channel(8)`. - - **Rule: a control write never blocks the send loop.** When the channel is - full, a pending bitrate command is replaced by the newer one, and an IDR is - kept. - - The test implementation records the commands. -- `KeyframeRequestGate`, ported from `D main.rs:2864-2884` with the 500 ms - cooldown (`D :102`). It is fed the aggregate `requested_keyframes` counter - across hub receivers. Any receiver's new edge counts. -- `BitrateController`, rewritten from `D :2439-2512`: - - ceiling `= request.video_bitrate_kbps / (1 + r)`, where `r` is the video - parity overhead from Cut 5's policy, measured as parity bytes over data - bytes in the last second, not assumed; - - floor `= max(ceiling / 4, 1_000)`; - - start at the ceiling; - - each 500 ms sample, **back off** to ×0.85 on damage. Damage is new late - frames, a new keyframe request, new deferred repairs, new - `groups_dropped_video` (Cut 2), or jitter plus decode queue at or above 75% - of the request's budget; - - otherwise, **step up** by `ceiling / 50` after 10 s stable. These are the - donor code's values (`D :2502-2507`); its doc disagreed, and the Cut 5 - harness may retune the named constants; - - known limit, recorded: with many viewers, the worst receiver sets the - rate. -- Spawn: - - `--video-encoder ` resolves relative to the release directory, like - the loopback script; - - `--video-encoder-runtime-dir ` is prepended to the child's `PATH`, so - that the FFmpeg DLLs resolve; - - the child runs at the existing video priority class - (`media_child_priority`). - - A missing or failing encoder fails the request with a typed `detail` - (invariant 16). -- Observation (invariant 15): - - `idr_commands`, and `idr_observed` (a keyframe access unit from - `VideoAnnexBStreamSendState` within 3 frames of a command); - - `bitrate_commanded_kbps`, and `bitrate_observed_kbps` (encoded bytes per - second, 1 s window); - - all four in the progress line and the telemetry surface. - -**Rules (each pinned by a test on `MediaSendCore` with the recording -`EncoderControl`):** -- One keyframe-request edge gives exactly one `idr`. A second edge inside - 500 ms gives none. One edge at `cooldown + ε` gives one. The cooldown is - probed on both sides. -- A recoverable missing chunk (a feedback record with - `missing_video_chunk_keys` and `requested_keyframe = false`) gives no `idr` - (invariant 8). -- Damage in one sample gives exactly one ×0.85. It never goes below the floor. -- Stable for 10 s gives exactly one step. It never goes above the ceiling. -- The ceiling is **derived from the request**: test two request bitrates and - two parity ratios, with exact equality through a dev-only seam that records - the computed ceiling. Kill a clamp mutant. -- A stalled encoder stdin (the test writer never drains) does not stall - `MediaSendCore`. Assert the send loop's tick count keeps advancing. -- The Cut 2 harness, driven by a fake encoder that honours `idr` (a - file-backed Annex B source that emits a keyframe on command): under - `loss-3pct`, the receiver's frozen interval after a lost reference is - ≤ RTT + 2 frames, not the 250 ms GOP. - -**Verification:** Yggdrasil, `cargo test -p muninn-daemon` and -`cargo mutants --in-diff`. No GPU is needed. - -**Ledger:** about −220 (CLI child, args, tests and the log-only keyframe -handler) and +260 (port, gate, controller, spawn and observation). 6a adds -roughly +400: 230 of ported C++ and 170 of Rust shell and tests. - -### 6c: recipe, binding and Raven acceptance - -Build host **Raven** (Windows 11, MSVC, the NVIDIA driver). Target platform -**Raven**. Builder: Idunn's host actuator, `rust-host` runner, `cargo` only. - -**Prerequisites (not Hands):** -- Idunn B3 and `route/b3-declare` merged to Muninn `main` (B19). -- **Operator provisioning on Raven**, a one-time step like the firewall rule: - - unpack a pinned FFmpeg **shared** build with NVENC enabled (headers, import - libraries, DLLs) to `C:\GameCult\deps\ffmpeg--shared\`; - - record its URL and sha256 in `gamecult-ops/inventory.md` under Raven. - - Nothing in the deploy path can fetch it (B18). This gap is recorded for - Idunn (Substrate missing). - -**Recipe** (`Muninn/deployment/idunn/raven-muninn.toml`, on top of `2260853`): - - [[steps]] - id = "build-muninn-video-encoder" - phase = "build" - runner = "rust-host" - required_environment = ["MUNINN_FFMPEG_ROOT"] - argv = ["cargo", "build", "--locked", "--release", - "-p", "muninn-video-encoder", "--bin", "muninn-video-encoder"] - - [[steps]] - id = "accept-nvenc-control" - phase = "acceptance" - runner = "rust-host" - required_environment = ["MUNINN_FFMPEG_ROOT"] - argv = ["cargo", "test", "--locked", "--release", - "-p", "muninn-video-encoder", "--features", "nvenc-acceptance", - "--", "--exact", "nvenc_honours_idr_and_bitrate_commands"] - - [[artifacts]] - id = "muninn-video-encoder" - source_kind = "runner-output" - runner = "rust-host" - source = "target/release/muninn-video-encoder.exe" - destination = "muninn-video-encoder.exe" - executable = true - -In `[service]`: -- `required_adjacent_artifacts = ["muninn-video-encoder", "wasapi-loopback-capture"]`; -- the arguments gain `--video-encoder` → literal `muninn-video-encoder.exe`, and - `--video-encoder-runtime-dir` → binding `ffmpeg_runtime_dir`. - -The acceptance test sits behind a feature so that CI and Yggdrasil never select -it. It is the 6a integration scenario with `--encoder h264_nvenc` and -`--input testsrc2`, hardware encode from system-memory frames (no desktop -needed). So **the deploy itself refuses a Raven where NVENC cannot honour a -typed IDR or bitrate command**. Hands confirms that host-native `acceptance` -steps run before promotion (`I src/deployment.rs:71-77` declares the phase). -If they do not, this becomes a build-phase step, and that is recorded. - -**Binding** (`gamecult-ops/idunn/yggdrasil/bindings/raven-muninn.toml.in`, -gamecult-ops owns it, an operator-approved ops change): - - [runners.rust-host.environment] - MUNINN_FFMPEG_ROOT = 'C:\GameCult\deps\ffmpeg--shared' - [workload.argument_bindings] - ffmpeg_runtime_dir = 'C:\GameCult\deps\ffmpeg--shared\bin' - -Both are open maps. The binding vocabulary does not grow, so the actuator needs -no rebuild (`Idunn docs/host-actuator.md:112`). Hands verifies this against the -actuator's binding parser before sealing. - -**Deploy:** `sudo idunn up raven-muninn` from yggdrasil, per -`gamecult-ops/runbooks/idunn-host-raven.md`. It is the operator's action; Raven -is a human-used workstation (teardown-map L268-271). - -**What only Raven proves, live, with the operator present:** -- `ddagrab` with `h264_nvenc`: a receiver-requested IDR is **observed at - Ratatoskr** as a keyframe within one RTT plus one frame, while a game is - running (Raven at 93% CPU is the known condition). -- NVENC in-session reconfigure under a game. The donor recorded 12 → 6 Mbps at - frame 35 on 2026-07-17, on a pre-extraction body. -- `bitrate_observed_kbps` follows commands on the mesh-hairpin path (28 Mbps) - and backs off under it. -- DLL resolution from the release directory under the actuator's launch. -- **The payoff step.** Lengthening the scheduled GOP beyond a quarter second is - what IDR-on-request buys. Do it only after this acceptance, as a one-constant - change measured against the Cut 5 table and the live run. Until then the - 250 ms GOP stays as the fallback ceiling. - -**Ledger 6c:** recipe +25 lines, binding +4. - ---- - -## HID edge for remote play: cuts H0-H5 (Q1, Q9, Q10 ruled) - -**What it is for** (Q1, 2026-09-30): a viewer's controller drives a game on -another host, over LAN or mesh, so quick taps must survive loss. -- The **producer** is Muninn on the viewer's host, capturing the pad. -- The **consumer** is Sleipnir on the game host, which drives ViGEm. -- Today the consumer is `raven-sleipnir`, Raven being the game host (B16). - -**Anchors in this section.** -- `M` = Muninn `main` `c3520d1`. -- `S` = Sleipnir at Odin `main` `379b826`, `crates/sleipnir-daemon/src/main.rs`. - H3 moves that file verbatim, so after H3 the same line numbers hold at - `Muninn/crates/sleipnir-daemon/src/main.rs` until H4 edits it. -- `R` = Ratatoskr `488b5b1`. -- `C` = CultLib `c2a9a6e`, Muninn's pin. -- `Mi` = Mimir `d88f2e6`. -- `Ops` = gamecult-ops `8554e60`. - -### The capability mechanism, verified: video today, input mirrored - -Q10 orders input to be requested the way Ratatoskr requests video. This is -that request path, read at the SHAs above. - -| Step | Video today | Input after H2/H4 | -|---|---|---| -| Producer advertises through CultMesh | Muninn builds `gamecult.media_stream_advertisement.v1` (`M :1122-1166`). It stores it and publishes it to Odin's catalog under its `stream_id`, with role `media-stream-producer` (`M :4146-4166`). | Muninn builds `muninn.input_stream_advertisement.v1` in `input_stream.rs`, and publishes it at the same site with role `input-stream-producer`. | -| Advertised endpoint | `media_endpoint` is explicit (`--media-rudp-advertise`), or derived, **never guessed** (`advertised_media_endpoint`, `M :1173-1196`). `media_connection_id` is `MUNINN_MEDIA_RUDP_CONNECTION_ID`. | `input_endpoint` comes from the same function, parameterised (`advertised_endpoint(explicit, bind)`). `input_connection_id` is `0x6d75_0005`, today's HID id (`M :74`, `S :23`). | -| Recipe declares the capability | `[[provides]] capability = "muninn.media-producer"` (`raven-muninn.toml:93-96`) | `[[provides]] capability = "muninn.input-producer"`, schema `muninn.input_stream_advertisement.v1` | -| Consumer discovers | Ratatoskr pulls the advertisement schema from Odin (`R catalog.rs:64-91`) | Sleipnir pulls the input advertisement schema and its own mapping schema: one pull, typed, with no JSON scraping (B21). | -| Consumer asks | Ratatoskr publishes a request under `media_stream_request_key(stream, receiver)`, role `media-stream-consumer` (`R catalog.rs:95-122`). The request names the sources, and the latency budget defaults from the advertisement (`R :151-179`). | Sleipnir publishes `muninn.input_stream_request.v1` under `input_stream_request_key(stream, receiver)`, role `input-stream-consumer`. It names `device_id`, and `input_budget_ms` defaults from the advertisement. | -| Producer admits and answers | Muninn pulls request documents from Odin each tick (`M :971-1034`), turns them into `MuninnCaptureStreamCommandRecord`s, and writes the answer onto the request key (`M :1038-1117`). | The **same pull** takes both request schemas in one snapshot. Input requests go to the input organ as demand (B23), with **no** detour through a command record, and are answered on the same key. | -| Who dials | The consumer dials the advertised endpoint (`R receiver.rs:4-7`). Its connect payload is its `receiver_id` (`R receiver.rs:40-42`). Muninn listens on a `CultNetRudpServerHub` (`M :3192-3213`). | The consumer (Sleipnir, on the game host) dials the viewer's Muninn. Muninn listens on a `CultNetRudpServerHub` and serves a session only the device its request names. | - -**One rule for both streams:** the consumer dials the Muninn that produces the -stream, and that Muninn listens. For video, the producing Muninn is on the game -host. For input, it is on the viewer's machine, because the controller is -there. Every host whose Muninn produces a stream admits inbound UDP on that -stream's port. Raven already does this for video. H5 adds the same rule on each -viewer that produces input. - -**Two deliberate differences from the video path**, each protecting a named -invariant: -- **Admission as demand, not as `state == pending`** (B23). A restarted - producer resumes serving every live consumer without a re-request. The video - path should adopt this too, under its own owner. -- **No command-record detour.** `MuninnCaptureStreamCommandRecord` exists for - the media child's lifecycle and for legacy readers (teardown-map, item 2 of - "Next unblocked work"). Input has neither, so it does not grow a second - command vocabulary. - -### Ownership - -| Organ | Owns | Does not own | -|---|---|---| -| Muninn capture thread, one per source (H2) | The **only** device reader (B22); sampling (XInput 1 ms, Windows HID every report, joystick events as they arrive); `EdgeDetector`; the latest-state slot; the per-source edge queue | Sessions, windows, epochs, frames | -| Muninn input organ, `crates/muninn-daemon/src/input_stream.rs` (H2) | The advertisement; admission of input requests as demand, and their answers; the input hub and its sessions; one `EdgeWindow` per (session, device); frame emission on `latest`; applying acks | Device reads; mapping; deciding that an edge was applied | -| `muninn-contracts` (H0, H1) | The input records and their key and validation; the HID wire records and their CultNet envelope; `EdgeDetector`, `EdgeWindow` and `EdgeCursor` as pure code | Sockets, threads, devices, Odin | -| Sleipnir (`crates/sleipnir-daemon`, Muninn workspace, H3/H4) | Choosing the device from typed advertisements plus its mapping record; publishing the request; dialling; the `EdgeCursor`; **the single `commit_pad` primitive** (invariant 10); the hold and the request-owned budget (invariant 13); acks; neutralising on staleness | Edge creation, epochs, capture, discovery JSON | -| CultLib | The `latest` channel: Unreliable and Sequenced, fixed by name (`C rudp.rs:2189-2192, 2384-2390`); `CultNetRudpServerHub` with per-session send (`C rudp.rs:1384, 1464, 1475`) | Anything HID-named (invariant 9). **No CultLib change** (under Q11's recommendation). | -| Odin | Catalog storage for the advertisement and request documents. It is schema-agnostic: `odin-daemon` names no media schema either (`git grep`, Odin `379b826`). | Anything input-specific. **No Odin change.** | - -**Why one frame on `latest`, and not the donor's reliable `hid.edge` channel.** -- A frame carries the current state **and** every unacknowledged edge of that - session's window, up to `MAX_EDGES_PER_FRAME`. -- Each frame therefore supersedes the last, which is exactly what a sequenced - channel delivers: an older frame arriving late is dropped, and nothing is - lost by that. -- Loss costs one transport tick. H2 sets that tick to 2 ms. Today it is 8 ms - (B22). -- There is no retransmit timer, no reliable window to stall, and no second - "assist" path. -- The ruling's "profile-owned channels" is met by using a channel the profile - already declares, with the delivery it declares. - -**How Odin `main`'s pin stays untouched while StreamPixels ships.** -- Nothing in H0-H5 commits to Odin `main`. -- Sleipnir moves into Muninn's workspace (Q9) at Muninn's pins: CultLib - `c2a9a6e`, and odin-core from Odin `3e96c6c`. That is the commit Odin made - for exactly this ("CultLib pin a8aedda -> c2a9a6e so a consumer can build - odin-core without a path override"). It already bumps `sleipnir-daemon`'s - own manifest to `c2a9a6e`, and its odin-core API equals Odin `main`'s: - `git diff 3e96c6c 379b826 -- crates/odin-core` touches only `Cargo.toml` and - two examples. -- From H3 on, Odin `main`'s `crates/sleipnir-daemon` is a **forbidden writer**. -- After StreamPixels ships, **one** Odin commit deletes the crate from Odin's - workspace. It is a deletion, with no pin change and no other edit. -- Until then two copies of the source exist, and only Muninn's is built and - deployed from H5 on. Recorded as debt, with its deletion line. - -### H0: shape of Muninn's named cut 1 (a constraint, not a new cut) - -Named cut 1 moves Muninn's 16 records out of odin-core. For H, it must place -them in a **library** crate in Muninn's workspace, `crates/muninn-contracts` -(`crate-type = rlib`), not in `muninn-daemon`'s binary. - -- **Owner:** Muninn. -- **Live consumers:** - - `muninn-daemon`; - - `sleipnir-daemon`, a workspace member from H3. It imports - `MuninnHidControllerStateRecord` today (`S :12`), until H4. - - `muninn-video-encoder` (6a). -- **Protected invariant:** each Muninn wire record has one definition, and - every crate that links it resolves one `cultcache-rs`. With Sleipnir in the - workspace that is structural: one `Cargo.lock`, a path dependency, and no - git pin to drift. The pass-2 guard test for a cross-repo pin is **not** - written. -- **Why the existing owner cannot serve:** a binary crate cannot be a - dependency, and two binaries (`muninn`, `sleipnir`) share these records. -- **What it replaces:** Muninn records defined in Odin's odin-core. - -Its dependencies are `cultcache-rs`, `cultnet-rs`, `serde` and `anyhow`, taken -from `[workspace.dependencies]` (H3 hoists the pins there). - -**Ordering against H3.** Neither waits for the other. If H3 lands first, -Sleipnir keeps importing the HID record from odin-core. Named cut 1 then -switches both importers in one commit, which is the practical gain of Q9. - -### H1: input-stream records, HID wire records and protocol state machines (`muninn-contracts`) - -Location per Q11 (recommended): `crates/muninn-contracts/src/input_stream.rs` -(the capability records) and `crates/muninn-contracts/src/hid.rs` (the wire -records and state machines). If Q11 rules CultLib, the same types go to -`CultLib packages/cultnet-rs/src/input_stream_contracts.rs` under `gamecult.*` -ids, and H1 waits for Cut 3's CultLib tag and the pin gate. - -**Adds, the capability pair** (types and rules; bodies are Hands'). It is -modelled field-for-field on `C media_stream_contracts.rs:71-183`. -- `muninn.input_stream_advertisement.v1`: - - `stream_id`, `producer_id`, `label`; - - `state`, one of `available`, `streaming`, `unavailable`; - - `device_ids`, `device_labels`, `device_kinds`: parallel, equal length; - - `default_input_budget_ms`: the default, 100; - - `input_endpoint`, `input_connection_id`; - - `updated_at`. -- `muninn.input_stream_request.v1`: - - `request_id`, `stream_id`, `producer_id`, `receiver_id`; - - `action`, one of `start` or `stop`; - - `state`, one of `pending`, `running`, `stopped`, `failed`; - - `device_id`, `input_budget_ms`, `detail`, `updated_at`. -- `input_stream_request_key(stream_id, receiver_id)`, with the same shape as - `media_stream_request_key` (`C media_stream_contracts.rs:180`). -- `validate_input_stream_advertisement` and `validate_input_stream_request`. - They mirror `C :184-290`. Validation refuses: - - unequal device arrays; - - `start` without a `device_id`; - - an `input_budget_ms` of 0 on a `start`, because the consumer fills in the - advertised default, as Ratatoskr does (`R catalog.rs:174`); - - an unknown action or state. - -**Adds, the wire:** -- `muninn.hid_input_frame.v1`: - - `device_id`, `stream_id`; - - `epoch: u64`, never 0; - - `state_sequence: u64`; - - `source_timestamp_ns: i64`, telemetry only; - - `axes: Vec`; - - `buttons: Vec`, the held set **after** the last edge in this - frame's window; - - `edge_first_sequence: u64`; - - `edge_buttons: Vec`, `edge_pressed: Vec`, - `edge_captured_ns: Vec`: parallel arrays, equal length, at most - `MAX_EDGES_PER_FRAME`, contiguous from `edge_first_sequence`. - - Hands may use a nested record list instead of parallel arrays if the - `cultcache-rs` derive supports it at the pin. The rule, not the spelling, is - the contract. -- `muninn.hid_edge_ack.v1`: `device_id`, `epoch`, `applied_through: u64`. -- `MuninnHidWireRecord { Frame, Ack }` with `encode`/`decode` through the - CultNet message envelope. This is the pattern of CultLib's - `encode_media_wire_record` (`C media_stream_wire.rs:134-190`), with - validation on both encode and decode. -- **Deleted from the design:** pass 2's `muninn.hid_subscription.v1`. Device - selection is the request's `device_id`, and the subscriber's identity is the - session's connect payload. There is no in-session subscription message. - -**Adds, the state machines:** -- `EdgeDetector` (runs on the capture thread): - - `sample(buttons_now, captured_ns) -> impl Iterator` diffs against the - previous sample: releases first, then presses (the donor order); - - edges carry no sequence and no epoch. Those belong to a window. -- `EdgeWindow` (one per session and device, on the input tick): - - `new(epoch_ns)`; - - `push(edge)` appends, with a sequence contiguous from 1; - - `frame_edges() -> ≤ MAX_EDGES_PER_FRAME oldest pending`; - - `ack(epoch, applied_through)`; - - `rebaseline()`. Past 256 pending it sets the epoch to `+1`, - `state_sequence` to 0, clears pending, and reports the rotation to the - caller, which counts it. -- `EdgeCursor` (receiver): - - `accept_frame(epoch, state_sequence, first_seq, edges) -> Admission`; - - an epoch below the current one: fenced (a monotonic comparison, with no - set); - - a new, higher epoch: take `buttons` as the baseline, set - `applied_through = first_seq + len - 1`, and return no edges. Taps inside - the first frame of an epoch are carried by the baseline, not replayed. - **This is recorded as a deliberate loss at epoch start only.** - - the same epoch: return the edges with sequence above `applied_through`, in - order. Duplicates are dropped by sequence, and a gap past 256 is refused. - -**Rules that must die under their own mutation.** A property-style test drives -`EdgeDetector` → two `EdgeWindow`s (two subscribers, independent drop seeds) → -frames → a seeded drop, reorder or duplicate → one `EdgeCursor` per -subscriber. -- Every edge captured is delivered **exactly once, in capture order, to each - subscriber**, under every Cut 3b profile. Use the **same seed tables** as the - media harness, so one impairment vocabulary serves both. -- One subscriber at `burst-8` never rotates the other subscriber's epoch. -- A press and release captured in one sampling interval arrive as two edges, - press then release. -- The window in a frame never exceeds `MAX_EDGES_PER_FRAME`. Pending is never - above 256. At 257 the epoch rotates, and the next frame's epoch is exactly - one more. -- An ack for a stale epoch changes nothing. An ack for `n` trims exactly - through `n`. -- The cursor rejects a frame from any epoch below its current one, including - `current − 1`. Kill the off-by-one comparison mutant. -- **Fit.** A frame with a full window, the longest button names, 16 axes and - a full held set encodes to ≤ 1,200 bytes (`HID_CONTROLLER_RUDP_MAX_FRAGMENT_BYTES`, - `M :6140`), so it never fragments (invariant 6's rule, applied to input). - - A rough count puts 32 edges with 16-character names at about 1,270 bytes. - **The test sets the constant.** Start at 32, and lower it until the worst - case fits. - - Never raise the fragment limit to make it fit. -- The frame round-trips. A frame with unequal parallel arrays, or a - non-contiguous window, is refused on decode. -- The request and advertisement round-trip. Each refusal listed above has a - test. - -**Verification:** `cargo test -p muninn-contracts` and `cargo mutants --in-diff` -on Yggdrasil, one job. - -**Build budget:** one library crate that already exists from named cut 1. -It gains no dependencies and no new target. - -**Ledger:** about +550 (the capability pair ~100, the wire and three state -machines ~250, tests ~200). It retires the donor's ~350 HID lines, which never -land. - -### H2: Muninn serves input streams (Muninn repo) - -Depends on H1 and Q12. It is developed on the same Hands branch as H4 and -merged with it (see Sequencing). - -**Authority map.** -- **Owner:** - - edges: `EdgeDetector` on each source's capture thread; - - delivery: the input organ in `input_stream.rs`, one `EdgeWindow` per - (session, device). -- **Inputs:** - - device samples, capture only; - - admitted input requests, from the serve tick's single Odin pull; - - hub sessions and their connect payloads; - - `hid_edge_ack` frames. -- **Outputs:** - - `hid_input_frame` per session on `latest`; - - the advertisement; - - answers on request keys; - - counters (frames, rotations, acks, sessions). -- **Derived state:** - - `muninn.hid_controller_state.v1` receipts become **observation-only**, - projected from the capture slot. They are no longer read from the device, - and they are no longer a discovery source. - - The Eve provider advertisement lists no input streams. -- **Forbidden writers:** - - the transport tick deciding edges; - - the serve tick reading a device that a capture thread owns; - - wall-clock time deciding freshness (telemetry only; donor doctrine, - `D docs/realtime-delivery-authority.md`); - - JSON anywhere on this path; - - an in-session subscription message. -- **Shared paths:** live capture, reconnect, restart (demand re-admission) and - tests all go through `EdgeDetector` → `EdgeWindow`. A reattaching session - gets a new window, a new epoch, and a baseline. - -**Deletes first** (`M`): -1. **The losing path per Q10: Muninn's outbound client.** - - `ActiveHidControllerStream` (`:6077-6086`); - - `create_hid_controller_stream` (`:6724-6763`); - - `publish_hid_controller_state_to_stream` (`:6765-6778`) and `_inner` - (`:6780-6863`); - - in `serve`: `let mut hid_controller_stream` (`:418`) and its argument - (`:506`); - - the `hid_controller_stream` parameter of `publish_move_controller_states` - (`:4982`), and its three calls (`:5026-5029`, `:5073-5076`, - `:5112-5115`); - - the option field (`:229`), its default (`:10628`) and its parse arm - `--hid-controller-rudp-target` | `--hid-controller-udp-target` - (`:10899-10904`). -2. **The JSON listener body.** Its direction survives; its body does not. - - `HidControllerRudpSubscription` (`:6143-6149`); - - `start_hid_controller_rudp_ingress` (`:6151-6177`); - - `run_hid_controller_rudp_ingress` (`:6179-6340`); - - `hid_controller_source_matches_subscription` (`:6342-6360`); - - `hid_controller_record_matches_subscription` (`:6362-6375`); - - `sanitize_hid_controller_record` (`:6710-6722`); - - the `serve` wiring at `:429-437`, per Q12. -3. **The per-tick reader as the place where HID state is made.** - - `read_hid_controller_state_for_stream` (`:6377-6528`), - `emit_hid_controller_record_if_due` (`:6530-6554`), - `hid_controller_stream_heartbeat_due` (`:6556-6560`) and - `hid_controller_axes_changed` (`:6562-6570`). - - The device-read bodies inside them move to the capture thread; they are - not rewritten. The emit-if-due throttling dies, because the window - decides what to send. - - `ActiveHidControllerRudpSource`, `active_hid_controller_rudp_source` and - `sync_hid_controller_rudp_sources` (`:6088-6129`) become the capture-set - reconciler. The hot-plug test `rudp_sources_reconcile_hotplugged_physical_identity` - (`:14620-14636`) is kept and retargeted. -4. **The double-read fence** (`:5081-5086`), because the capture thread is - now the only reader (B22). -5. **The JSON discovery surface** (B21). - - `hid_controller_endpoint` (`:3626-3631`); - - the device JSON (`:3653-3672`); - - `transport_input_streams` and `provider_input_streams` (`:3673-3727`); - - the provider `endpoints` pushes (`:3729-3750`); - - the `"input_streams"` key (`:3856`) and the `"inputStreams"` key - (`:3885`). - - The test `runtime_boundary_advertises_hid_and_move_evidence_streams` - (`:14072-14172`) is rewritten against the typed advertisement. -6. **The discovery write** `publish_hid_controller_state_to_odin` - (`:6865-6875`) and its three calls (`:5030`, `:5077`, `:5116`). Its only - reader is Sleipnir's discovery, which H4 deletes (B21). Receipts through - `put_hid_controller_state_receipt` (`:5970`) stay. -7. **Rename, not keep beside.** The options `hid_controller_rudp_bind` and - `_advertise` (`:230-231`, parse `:10906-10916`) become - `--input-rudp-bind` and `--input-rudp-advertise`. The old spellings are - refused with a message naming the new ones (the house pattern, - `M :10890-10894`). `local_ring_enabled` (`:4238`) follows Q12. - -**Adds:** -- `crates/muninn-daemon/src/input_stream.rs`, so `main.rs` shrinks. It holds: - - `input_stream_advertisement(options, live_sources)`, published at `:4146` - beside the media advertisement, with role `input-stream-producer` and tag - `muninn.input-stream-advertisement`; - - `InputDemand`: the admitted requests, keyed by `receiver_id`. It is - written by the serve tick and read by the input thread (a latest-wins - `Arc>`); - - `run_input_hub`: a `CultNetRudpServerHub` on `--input-rudp-bind`, open for - the life of `serve` when configured (`muninn_input_rudp_hub_options`, on - the model of `M :3232-3241`). On a 2 ms tick it: - - drains each source's edge queue into the windows of every session that - requested that device; - - sends one frame per (session, device) on `latest`, with a 50 ms - heartbeat when a window holds nothing new - (`HID_CONTROLLER_RUDP_HEARTBEAT_AFTER`, `:6138`); - - applies acks; - - drops sessions after timeout, as the media hub does (`M :3090-3096`). -- **Request intake: one owner for both capabilities.** - - `sync_media_stream_requests` (`M :971-1034`) becomes - `sync_stream_requests`. It makes **one** `pull_rudp_catalog_snapshot` with - `schema_ids = [media request, input request]`. - - Media requests continue exactly as today. - - Input requests addressed to `options.host_id` are admitted by `action` - (B23). An unknown `device_id` is answered `failed` with a typed `detail`. - A `stop`, or a newer request under the same key, withdraws the demand. - - `answer_media_stream_request` (`M :1069-1117`) gets an input twin with - the same keying and dedupe (`answered`). A generic helper is not - introduced for two call sites. -- `advertised_media_endpoint` (`M :1173-1196`) is parameterised as - `advertised_endpoint(explicit, bind, command_advertise)`. Media and input - call the one function, so input inherits "explicit or derived, never - guessed". -- `MuninnDocuments` (`M :10503-10542`) registers the two input records. -- **A capture thread per source**, ported from `fb4f331`: - - XInput sampled every 1 ms (`D main.rs:5881`); - - Windows HID through the existing report reader - (`start_windows_hid_report_reader_if_supported`, `M :8813`), every report; - - joystick events as they arrive. - - Each sample goes through `EdgeDetector` **on the capture thread**. The - edges go to a bounded per-source queue (256; overflow rebaselines every - window on that device), and the latest state goes to a slot. - - The serve tick's HID receipts (`M :5016-5025`, `:5064-5072`, - `:5102-5111`) read the slot, not the device. -- `raven-muninn.toml`: - - the argument pair `:62-65` becomes `--input-rudp-bind 0.0.0.0:17887` and - `--input-rudp-advertise` (binding `input_rudp_advertise`); - - a second `[[provides]]` block: `muninn.input-producer`, - `muninn.input_stream_advertisement.v1`, `v1`. - - The binding rename lands in gamecult-ops with H5. - - This edits the file `route/b3-declare` also edits, in a different block. - Rebase onto it if it has merged. - -**Rules:** -- A tap shorter than one transport tick, from a scripted fake XInput source, - becomes two edges in the next frame. -- Two sessions requesting one device each receive every edge once. Dropping - all frames to one session for 600 ms rotates only that session's epoch. -- A session whose `receiver_id` has no admitted request receives no frame. - So does a session whose request names another device. -- After a simulated restart, with fresh `InputDemand` and an Odin fixture - still holding the request at `running`, the session is served again with no - new request (B23). -- The frame stream from a fake source through a seeded drop relay matches - H1's property on the wire. Assert on captured datagrams. -- The serve tick never opens a device that a capture thread owns: a dev-only - per-device open counter reads 1. -- `rg serde_json crates/muninn-daemon/src/input_stream.rs` is empty, and no HID - path in `main.rs` calls `serde_json`. -- The typed advertisement round-trips through a local CultMesh node fixture, - as `R tests/catalog.rs:162-180` does for media. - -**Verification:** Yggdrasil, `cargo test -p muninn-daemon`, one job. The -XInput and Windows HID readers are `cfg(windows)`, so the scenario uses a -scripted source behind the same capture trait. -- **Starfire:** one Windows compile check of `muninn-daemon`. It is batched - with H4's, one job and no burners (load budget). -- **Only live proves:** real XInput sampling jitter on the viewer's host (H5). - -**Build budget:** `muninn-daemon` only. One new module, no new target and no -new dependency. - -**Ledger:** about −750 (the outbound client ~150, the JSON listener and match -functions ~235, the per-tick reader and emit ~195 (its read bodies relocate), -the JSON advertisement ~105, the discovery write and fence ~20, the rewritten -test ~60 net) and about +450 (the organ ~300, capture threads ~100, -intake/answer twin ~50). **Net about −300.** - -### H3: Sleipnir moves into Muninn's workspace (Q9); behaviour-neutral - -**Source:** Odin `379b826` `crates/sleipnir-daemon/{Cargo.toml, src/main.rs}`, -3,658 lines. That is 8 commits by path, the oldest through `4ad8bdb`, and -`--follow` finds no earlier rename. - -**How history moves.** This is the Muninn extraction precedent: Muninn's own -history came out of Odin whole (316 commits, root `2d88408`). -- In a scratch clone of Odin, run - `git filter-repo --path crates/sleipnir-daemon`. -- In Muninn, `git merge --allow-unrelated-histories` that result. It lands at - the same path, `crates/sleipnir-daemon/`. -- `git log -- crates/sleipnir-daemon` then works in Muninn. Odin keeps its own - copy of the history after its deletion commit. - -**Per-file changes, all in Muninn:** -- `Cargo.toml` (workspace): - - add `crates/sleipnir-daemon` to `members`; - - add a `[workspace.dependencies]` table holding the one CultLib rev - (`c2a9a6e526390808ef195759056fda0b9a55d8a3`) for `cultcache-rs`, - `cultmesh-rs` and `cultnet-rs`, plus `odin-core` at Odin `3e96c6c`. -- `crates/muninn-daemon/Cargo.toml:18-20, 24`: the four git pins become - `{ workspace = true }`. From here, "pins move in lockstep" is one line, not - a discipline. -- `crates/sleipnir-daemon/Cargo.toml`: - - the CultLib pins become `{ workspace = true }`. They were `a8aedda` in - Odin: the pin moves from Odin `main`'s to Muninn's; - - `odin-core = { path = "../odin-core" }` becomes `{ workspace = true }`; - - `edition`, `license` and `publish` already read `.workspace`, and - Muninn's workspace defines all three. -- `crates/sleipnir-daemon/src/main.rs`: **no edit**. The pin move from - `a8aedda` to `c2a9a6e` is the only behavioural exposure. Odin made the - same move for this crate in `3e96c6c`. -- `Cargo.lock`: regenerated. It gains `vigem-client` for Windows only, and - Muninn's recipe keeps building `-p muninn-daemon --bin muninn` (`:14-22`), - so Raven's Muninn build is unchanged. - -**Deletes:** none in Muninn. Odin `main`'s copy becomes a forbidden writer, -and its removal is the post-ship Odin commit. - -**Verification:** -- `cargo test -p sleipnir-daemon` on Yggdrasil (Linux, `LoggingBackend`). The - existing 22 tests (`S :2959-3660`) pass unchanged at the new pin. -- `cargo test -p muninn-daemon` passes unchanged. The workspace-dependency - hoist is proved by an unchanged `cargo tree -d -p muninn-daemon` for - `cultcache-rs`: exactly one. -- Starfire: one Windows `cargo check -p sleipnir-daemon`, because - `vigem-client` is `cfg(windows)`. -- `SleipnirInputMappingRecord` keeps coming from odin-core (`S :13`). Moving - it into Sleipnir is a later subtraction, not this cut. - -**Build budget:** one binary target, `sleipnir`, joins the workspace. It -leaves Odin's workspace at the post-ship commit, so the estate's target count -is unchanged. - -**Ledger:** 0 (a move) plus about −10 manifest lines (the pins hoisted). - -### H4: Sleipnir requests input and applies edges (Muninn repo) - -Developed with H2 on one Hands branch, and merged with it. - -**Authority map.** -- **Owner:** `commit_pad(state)` is the only caller of - `VirtualPadBackend::update`. Today there are five direct calls: `S :387`, - `:400`, `:472`, `:525`, and the `LoggingBackend` path. -- **Inputs:** - - typed input advertisements; - - the mapping record; - - the answered request; - - frames on its own session. -- **Outputs:** the request, acks, the pad timeline, and the Eve surface. -- **Derived state:** - - "available devices" is derived from advertisements; - - the selected endpoint is derived from the chosen advertisement; - - neither is discovered from JSON. -- **Forbidden writers:** - - any `backend.update` outside `commit_pad`; - - a snapshot writing `buttons` inside an epoch; - - JSON; - - `discover_provider_endpoints`. -- **Shared paths:** frames, epoch baselines, staleness neutralisation, mapping - change and reconnect all reach the pad through `commit_pad`. - -**Deletes first** (`S`, identical lines after H3): -1. **The losing path per Q10: Sleipnir's listening mode.** - - `Options.rudp_bind` (`:42`); - - the `--rudp-bind` | `--udp-bind` arm (`:2823-2829`); - - the server branch of `create_rudp_stream` (`:2244-2281`); - - `[--rudp-bind ADDR]` in `usage` (`:2906`). -2. **The JSON subscription.** - - `HidControllerRudpSubscription` (`:68-72`); - - `ActiveRudpStream.last_subscription*` (`:64-65`); - - `send_hid_subscription_if_due` (`:2283-2321`) and its call (`:426-431`). -3. **The JSON decode and the button coalescing.** - - `receive_rudp_records` (`:2480-2541`) is rewritten to decode - `MuninnHidWireRecord`; - - `coalesce_latest_timed_hid_records_by_device` (`:2543-2565`) and - `coalesce_latest_hid_records_by_device` (`:2567-2588`) are deleted, - with their tests (`:2959-2996`). Axes stay latest-wins, because the - frame carries only current axes. -4. **JSON and Odin-generic discovery** (B21). - - The second, provider-key pull in `pull_odin_catalog_snapshot` - (`:950-975`). The first pull's schema list becomes - `[muninn.input_stream_advertisement.v1, sleipnir.input_mapping.v1]`, - plus the request schema for the answer. - - `muninn_provider_keys_for_discovered_hid_hosts` (`:978-1003`) and - `hid_state_host_id_from_value` (`:1005-1019`). - - `effective_muninn_hid_endpoint` (`:1826-1833`). - - `discover_available_hid_devices` through `endpoint_looks_like_socket` - (`:1845-2131`). - - `resolve_socket_addr` stays. `discover_muninn_hid_endpoint` through - `stream_host_hint` (`:2370-2478`) goes. - - The eight discovery tests (`:3164-3513`) are replaced by three tests over - typed advertisements. - - Imports go: `EVE_PROVIDER_ADVERTISEMENT_SCHEMA` (used only at `:957`, - `:1890` and `:2420`), `MUNINN_HID_CONTROLLER_STATE_SCHEMA`, - `MuninnHidControllerStateRecord`, `OdinEndpointQuery` and - `discover_provider_endpoints` (`:10-14`). Sleipnir's odin-core symbols - fall from 10 to 4: the Eve advertisement and surface records, - `OdinDocuments`, and `SleipnirInputMappingRecord`. Pass 1 of H5 takes - `IdunnDaemonHealthRecord` too. -5. **Direct pad writes:** the five `backend.update` sites listed above. -6. **Removed-flag stubs that only reject old spellings:** - `--command-rudp-bind`, `--command-rudp-advertise` and - `--odin-cultmesh-rudp` (`:2830-2849`), with their tests (`:3605-3647`). - They are older than a Muninn-workspace body, and nothing passes them now - (`Ops idunn-deployment-targets.ps1:131`: `sleipnir --host raven`). - -**Adds:** -- `SleipnirDocuments`: `OdinDocuments` plus the two input records, on the - model of `MuninnDocuments` (`M :10503-10542`). It replaces `OdinDocuments` - at `S :269, 281`. -- `select_input_device(advertisements, mapping) -> Option<(advertisement, device_id)>`. - This is **one** function. It matches `mapping.stream_id` against the - advertisement's `stream_id`, and `mapping.device_filter` against - `device_ids` and `device_kinds`. The rules of `record_matches_filter` - (`S :2602-2612`) are kept. - - Persisted mapping records hold the old stream-id format - (`host:move_id:hid-controller-state`). They fall through to - `device_filter` and are rewritten on the next Eve mapping command. No - migration shim. -- **The request lifecycle,** the Ratatoskr pattern (`R catalog.rs:95-179`): - - publish `start` on selection, with `receiver_id = sleipnir.` and - `input_budget_ms` from the advertisement's default; - - publish `stop` on deselection, on mapping disable, and on clean exit; - - publish a **new** `start` (a fresh `request_id`) when the session is lost - or silent for `INPUT_STREAM_RECONNECT_AFTER` (`S :29`). A restarted - producer re-admits by demand anyway (B23); this covers the Odin document - being lost. -- **Dial:** the client branch of `create_rudp_stream` (`S :2196-2243`), with - `connect(receiver_id bytes)` in place of `connect(Vec::new())` - (`S :2232`, `:2365`), because the hub binds the session to the request by - its connect payload. -- `EdgeCursor` per selected device. -- An actuation queue drained by `commit_pad`. Frame axes, cursor edges, epoch - baselines, staleness neutralisation (`INPUT_STALE_NEUTRAL_AFTER`, `S :28`) - and a mapping change all go through it (invariant 10). -- The 24 ms visibility hold, overridden at the **request's** - `input_budget_ms`: an edge older than the budget is committed without the - hold (invariant 13). -- `hid_edge_ack` for `applied_through` after each commit, and every tick while - nonzero, on `latest`. -- `map_record_to_virtual_pad` (`S :2677-2696`), `apply_pending_learn` - (`S :1714-1754`) and `input_latency_snapshot` (`S :2614-2651`) take the - cursor's pad input (axes plus held buttons plus the frame's timestamps) - instead of `MuninnHidControllerStateRecord`. The mapping logic is unchanged. -- The loop's sleep uses a 2 ms default for `--interval-ms` (`S :2791` - today: 8). - -**Rules** (on a recording backend, asserting the pad timeline, which is the -layer the game samples): -- A quick tap under `loss-5pct` and `burst-8`: the timeline shows press, then - release; the press is held ≥ 24 ms; nothing is doubled. -- Reordered and duplicated frames produce the same timeline as clean. -- A burst of 20 taps: every one appears. The last is committed no later than - `input_budget_ms` plus one tick after capture. Kill a mutant that removes the - budget override. Probe at `budget ± ε`, with the budget taken from a request - of 60 ms and one of 100 ms. The hold follows the request, not a constant. -- A frame from epoch `current − 1` after a rotation is ignored, and the pad - shows the new baseline. -- Silence for 1.5 s neutralises through `commit_pad`. Assert that the backend - was called only from that function (a dev-only call-site counter). -- Selection: - - a mapping naming a device kind picks the right advertisement among two - hosts; - - a mapping naming an absent device publishes no request; - - a `failed` answer surfaces its `detail` on the Eve surface. -- **End to end on Yggdrasil**, now inside one workspace: - - H2's `run_input_hub` with a scripted source, through a seeded drop relay - (the Cut 3b tool's relay and profiles), to Sleipnir's session loop with a - recording backend; - - an in-process CultMesh node stands in for Odin, holding the advertisement - and request. - - The test lives in `crates/sleipnir-daemon/tests/`, with `muninn-daemon`'s - organ reached as a dev-dependency only if Hands can make it a lib target - cheaply. Otherwise the test drives the hub from `muninn-contracts`'s state - machines plus a thin test driver, as in pass 2. - -**Verification:** `cargo test -p sleipnir-daemon` and `cargo mutants --in-diff` -on Yggdrasil, one job batched with H2's. One Starfire Windows check covers both -crates. - -**Build budget:** `sleipnir-daemon` only. It gains the `muninn-contracts` path -dependency and drops `serde_json` if nothing else in `main.rs` still needs it. -The Eve surface builds JSON (`S :1021-1455`), so it probably stays. - -**Ledger:** about −1,050 (listening mode ~45, JSON subscription ~50, -JSON decode and coalesce ~110, discovery ~420, removed-flag stubs ~20, their -tests ~450) and about +350 (selection and request ~120, cursor, queue and -commit ~130, tests ~250 minus the retired). **Net about −600.** - -### H5: deploy, and the viewer's side - -**Preflight (Q13):** establish whether `raven-sleipnir` runs today (B16 says -unverified). On Raven, read: -- the scheduled task the legacy target keeps alive - (`Ops idunn-deployment-targets.ps1:126-138`); -- Sleipnir's published health `sleipnir.cultnet-rudp-input-mirror-health` on - Odin. - -If it runs, Raven's local pad mirror is live. It dials Raven's Muninn at -`10.77.0.4:17887` with JSON, and it breaks the moment Idunn deploys a -`main` that contains H2 (`raven-muninn` admits `refs/heads/main` by -`ref-head`, binding `raven-muninn.toml.in:7-9`). - -**Steps:** -- **Sleipnir recipe** `deployment/idunn/raven-sleipnir.toml` in **Muninn's** - repo, beside `raven-muninn.toml`: - - a `rust-host` build step, `cargo build --locked --release -p sleipnir-daemon - --bin sleipnir`, which builds `vigem-client` on Windows; - - `[[dependencies]] odin.verse-rendezvous`, per Idunn's B3 ruling ("the - recipe declares readiness"), because Sleipnir publishes its Eve surface - and its requests to Odin; - - its presence contract. -- **Presence:** `M src/idunn_presence.rs` (229 lines; Muninn-specific only in - one doc line and one error string, `:14`, `:146`) moves **verbatim** into - `muninn-contracts` as `idunn_presence`. Both daemons call it. - - Delete Sleipnir's legacy `publish_idunn_health_if_configured` and - `publish_idunn_rudp_health` (`S :792-905`), their three flags - (`S :2853-2867`), and the `IdunnDaemonHealthRecord` import. That leaves - three odin-core symbols. - - Presence's rightful owner is CultLib, because every Idunn-launched daemon - needs it. Recorded under "Substrate missing"; not moved here. -- **Binding** `idunn/yggdrasil/bindings/raven-sleipnir.toml.in` in - gamecult-ops, modelled on `raven-muninn.toml.in`, with the same repository - (`GameCult/Muninn`) and a different `recipe_path`. - - In the same change, `raven-muninn.toml.in`'s argument binding - `hid_controller_rudp_advertise` (`:38`) becomes `input_rudp_advertise`. -- **Retire** the legacy `raven-sleipnir` script target - (`Ops idunn-deployment-targets.ps1:126-138`, `Repo = "Odin"`) and - `scripts/deploy-raven-sleipnir.ps1` / `restart-raven-sleipnir.ps1`, in the - same gamecult-ops change. gamecult-ops owns them. -- **The viewer's Muninn.** - - Starfire's is the legacy `starfire-muninn` script target - (`Ops :74-86`). `restart-starfire-muninn.ps1:14-15, 74-79` already passes - an optional HID bind and advertise; these become `--input-rudp-bind` and - `--input-rudp-advertise`, with Starfire's mesh address advertised. - - Rebinding `starfire-muninn` to an Idunn recipe is its own ops item, not - this cut. - - A viewer outside GameCult's hosts runs Muninn by hand. That limit is - recorded, not solved here. -- **Firewall:** a host whose Muninn produces input admits inbound UDP on its - input port (17887) from the game host, as a video producer does on its media port. Starfire needs one - Windows Firewall rule. It is scoped to the mesh interface where possible, - and recorded in gamecult-ops inventory beside Raven's 5220/17887. Raven - keeps 17887 open only while it also produces input for its own local - mirror. -- **What only live proves.** Raven with a game, the operator present, and the - ported `xinput_edge_observer` example (`80adfd3`, 127 lines, into - `crates/sleipnir-daemon/examples/`) reading the ViGEm pad as the game does: - - Sleipnir on Raven finds Starfire's advertisement, requests, dials, and the - request is answered `running`; - - taps from Starfire's pad reach the game over LAN and over the mesh - hairpin; - - the observer shows every tap at ≥ 24 ms visibility; - - end-to-end input latency, from `edge_captured_ns` to the observer; - - a `serve` restart on Starfire resumes input with no operator action (B23). - -**Ledger (repo code only):** about −115 (legacy health) and +40 (presence -wiring). The recipe and binding are declarations. - ---- - -## Sequencing - -Two tracks, media and input. From H3 on they share one repository, Muninn, -and `muninn-daemon/src/main.rs`, so their Hands run **serially in Muninn**, -and in parallel only across repositories and worktrees. - -**Now:** -1. **Cuts 0-1** (merged to `main` at `c3520d1`). -2. **Retag `3e96c6c` as `pins/odin-core-cultlib-c2a9a6e`** (Q2 note). This is a - tag only; Odin `main` is untouched. -3. **Muninn named cut 3** (retire `--idunn-rudp-health`). It removes one of - Muninn's four Odin symbols. It runs serially with the next item. -4. **Cut 2** (bounded sender and seam; Q7's 250 ms default). Muninn. -5. **Muninn named cut 1 in H0's shape** (`muninn-contracts`). Muninn, serially - after Cut 2 or before it; never in parallel on `main.rs`. -6. **In parallel, other repos:** Cut 3 (CultLib worktree; Soul passes before - the tag). - -**Input track:** -7. **H3** (Sleipnir into Muninn's workspace). Behaviour-neutral and - independent of named cut 1. It touches only manifests, the lock and the - imported crate, so it may run beside Cut 2 without touching `main.rs`. -8. **H1** (`muninn-contracts`), after step 5 and Q11. If Q11 rules CultLib, H1 - joins Cut 3's CultLib work and the input track waits for the pin gate - (step 12). -9. **H2 and H4** on one Hands branch, after Q12. Soul verifies each cut - separately. They **merge to `main` together, and only when H5 is ready to - deploy in the same window**, or with `raven-muninn`'s deployment brake - engaged, because `raven-muninn` deploys `main`'s head and a new-wire - Muninn breaks the legacy Sleipnir (Q13). -10. **H5**, after Idunn B3 (the recipe declares its Odin dependency), and the - Q13 preflight. This is operator deployment. - -**Media track:** -11. **Pin gate:** a single-purpose Odin commit bumps odin-core to Cut 3's - CultLib tag, parented on `3e96c6c`, tagged - `pins/odin-core-cultlib-`. Muninn's `[workspace.dependencies]` (H3) - moves once, which moves Muninn and Sleipnir together by construction. - Ratatoskr moves in lockstep. -12. **Cut 4** (Ratatoskr), then **Cut 5** (Muninn video parity). -13. **Cut 6a** (after Cut 2; independent of Cut 5), then **6b** (after Cut 5, - for the ceiling), then **6c** (after `route/b3-declare` merges, Idunn B3, - and FFmpeg provisioning on Raven). -14. **Opus** (Muninn named cut 2), then **Cut 5's audio half** (Q5) and the - `audio` channel deletion taking effect (Q4). -15. **GOP lengthening:** the payoff of 6c, a single-constant change after live - acceptance. - -**StreamPixels ship:** -- no Odin `main` commits; -- no Odin pin change; -- no Idunn edits; -- no StreamPixels CultLib bump. - -After the ship: the Odin commit that deletes `crates/sleipnir-daemon`, and -optionally Odin's own CultLib bump, which is the Odin Stability session's call. - -**Recipe contention.** 6c and H2 both edit `raven-muninn.toml`, in different -blocks (H2: the input arguments `:62-65` and a `[[provides]]`; 6c: the encoder), -and both sit on top of `2260853` after it merges. Whichever lands second -rebases. H5 creates `raven-sleipnir.toml` beside it. - -**Yggdrasil load.** One job at a time for this campaign while StreamPixels' -verification runs. 6a's apt install makes its jobs longer, so batch its unit -and integration runs into one job. H2 and H4 run as one job. - ---- - -## Operator questions - -Q1-Q10 are ruled; see the Rulings block. Three forks are open. None blocks the -media track. - -**Q11. Who owns the input-stream capability records?** -- Context: - - The video capability's pair is CultLib's producer-agnostic - `gamecult.media_stream_*` (`C media_stream_contracts.rs:71-183`). Muninn, - Ratatoskr and StreamPixels' vendored copy share it across three repos. - - Input has one producer (Muninn) and one consumer (Sleipnir), and after Q9 - they share one workspace. - - Any CultLib change moves Muninn off `c2a9a6e`, and only the pin gate - closes the odin-core diamond that reopens (B11). -- Options: - - (a) **`muninn-contracts`, as `muninn.input_stream_*`.** H1 needs no CultLib - change and runs before Cut 3's tag. When a second producer or consumer - appears, the records move to CultLib under `gamecult.*`. They are live - documents republished every tick, not stored truth, so that move is a - schema rename with no migration. - - (b) **CultLib, as `gamecult.input_stream_*`,** beside the media pair. This - is the general-library shape a reasonable CultLib consumer would expect, - and it is the exact mirror. H1 joins Cut 3's CultLib tag, and the whole - input track waits for the pin gate (step 12), behind Cuts 3 and 4. -- Recommendation: **(a)**. The mechanism is mirrored exactly; only the - schema's owner differs, and it differs because the capability has one - implementation today. -- What depends on it: H1's location and ids; whether the input track waits - for the pin gate; `MuninnDocuments` and `SleipnirDocuments` registrations. - -**Q12. Move evidence rides the HID listener. What happens to it?** (B20) -- Context: - - Muninn sends Move-evidence frames (MessagePack - `mimir.muninn_move_evidence_stream_frame.v1`) on channel `move-evidence` - of the HID connection, only to a session that sent the JSON - `hid.subscribe`. - - Mimir's runtime does that (`Mi MimirOdinMoveProofEvidenceRingProvider.cs:223`), - after finding the endpoint in the JSON `inputStreams` H2 deletes. - - Mimir's provider was last changed on 2026-07-14 (`345c46b`). Raven's - recipe sets no `--move-evidence-stream`. Nightwing and Starfire configure - it. -- Options: - - (a) **Fold Move evidence into the input-stream capability.** Muninn - advertises a second `muninn.input_stream_advertisement.v1` per host, with - a `payload_schema` field distinguishing HID frames from Move-evidence - frames. Mimir requests it by document and dials with its `receiver_id`. - This needs a Mimir (C#) cut, "H2m", landing with H2. - - (b) **Keep a Move-evidence-only JSON `hid.subscribe` arm** on the new hub - until Mimir moves. This keeps JSON on a live wire (invariant 14) and a - second admission path (Q10), so it needs a named deletion line. - - (c) **Drop the remote Move-evidence transport**, if Mimir's move proof is - dormant. Delete the RUDP hand-off (`M :4267-4275`), `rudp_sender`, and the - bind coupling of `local_ring_enabled` (`:4238`). Mimir re-enters through - (a) when it next needs the stream. -- Recommendation: **(a) if anyone runs Mimir's move proof today, else (c).** - (b) only as a bounded bridge under (a). -- What depends on it: H2's deletion list items 2 and 7; whether a Mimir cut - joins the input track. - -**Q13. Is Raven's legacy Sleipnir live, and may its local mirror go dark -between the H2/H4 merge and H5?** -- Context: - - B16 left "whether it runs on Raven today" unverified. - - `raven-muninn` deploys `main`'s head. The moment `main` holds H2, Raven's - Muninn speaks the new wire, and a legacy JSON Sleipnir on Raven stops - receiving input. -- Options: - - (a) **Hold the H2/H4 merge until H5 deploys in the same window.** No dark - interval; the merge waits on Idunn B3. - - (b) **Merge when Soul passes, with `raven-muninn`'s deployment brake - engaged** until H5. Raven's Muninn stays on the previous release, and - media Cuts behind it wait too. - - (c) **Accept a dark interval** for Raven's local mirror, if the preflight - shows it is not in use. -- Recommendation: run H5's preflight first. If the mirror is live, choose - **(a)**. If not, choose **(c)**. (b) blocks the media track and is the - worst trade. -- What depends on it: when H2 and H4 may merge; whether H5 waits on B3 before - any of the input track lands on `main`. - ---- - -## Substrate missing (record, do not wait on it) - -- **No typed verify transaction.** Every probe went through the ygg-verify - stopgap, and one run queued behind 5 busy slots. This is Idunn's verify - campaign. -- **No machine-readable media-path map.** The ownership facts are spread across - `teardown-map.md` (with 10+ stale rows), a memory file (`media-path-ownership.md`) - and three repos. The staleness this pass found (B4, B9, L656) is the cost. -- **No synthetic media source anywhere on the path.** Every earlier - measurement needed Raven, a GPU and a game. Cut 2's seam is the first harness - that runs off Raven. -- **Idunn host-native targets cannot fetch pinned inputs.** - `external_inputs` are refused on host-native materialisation (`I host.rs:953-956`). - So Raven's FFmpeg development root is hand-provisioned and verified only by - `build.rs`'s version pin and the inventory's sha256. Every future Windows-host - native dependency hits this. The requirement belongs to Idunn: materialise a - sha-pinned archive on a host-native runner. -- **No C++ CultNet runtime.** The encoder's typed command channel needs a Rust - shell around the C++ core (6a). Every native child with a control channel - will pay this, and the alternative (hand-decoding MessagePack in C++) is the - Mimir receiver scar. The Rust-shell-over-C-ABI pattern (Ratatoskr's FFI, - `muninn-move-tracker`'s staticlib) is the house answer until a need justifies - a C++ runtime. - -## Appendix A: probe logs - -In this session's scratchpad: -- `donor-fec-tests.log` (9 pass); -- `muninn-media-tests.log` (78 pass); -- `rs-probe.log` and `rs-probe/` (the scratch crate, commit `656865b`); -- `ratatoskr-tests.log` (31 + 2 pass at `488b5b1`). - -Pass 2 ran no new builds. Its claims are source reads at the named SHAs. The -6a, H1 and H4 harnesses are the first executions of those designs. diff --git a/docs/streaming-deprecation.md b/docs/streaming-deprecation.md index 8f4085a..6e24964 100644 --- a/docs/streaming-deprecation.md +++ b/docs/streaming-deprecation.md @@ -1,37 +1,29 @@ -# Streaming deprecation (Meta, 2026-11-06) +# Streaming deprecation & removal (Meta, 2026-11-06; removed 2026-12-03) -Muninn's streaming role and the OBS media receiver are superseded in the streaming -space. Scope: screen and loopback-audio capture, the media sender, and the receiver at -github.com/GameCult/Ratatoskr (forge mirror `GameCult/Ratatoskr-receiver`; the forge repo -`GameCult/Ratatoskr` is an unrelated chat client and is not covered). Nothing has been -deleted. The lists below come from file names and docs, not from a consumer audit; -confirm each consumer before cutting. +Muninn's streaming role and the OBS media receiver were superseded in the streaming +space (screen and loopback-audio capture, the media sender, and the receiver at +github.com/GameCult/Ratatoskr; forge mirror `GameCult/Ratatoskr-receiver`, distinct +from the unrelated `GameCult/Ratatoskr` chat client). -## What depends on the streaming role +On 2026-12-03 (`kiko-body:ruling:strip-deprecated-streaming-pipe`), the streaming +stack was removed from the active tree and archived at git tag +`parked/muninn-media-streaming-2026-12-03`. -- Nothing in StreamPixels on main. StreamPixels `tools/showcheck` (PR #2) read Muninn's - activation log and the receiver's OBS log until it was rescoped on 2026-11-06 (a762f69) - to server, overlay and OBS only; the Muninn and Ratatoskr hops are gone from it and - survive only on its parked branch `kiko/showcheck-muninn-chain`. -- Docs here that describe it: `docs/muninn-media-streaming.md`, - `docs/realtime-robustness-cut.md`, and the receiver sections of `docs/teardown-map.md`. -- Operations: `scripts/activate-muninn-raven-*`, `scripts/health-*`, - `scripts/restart-*`, and `deployment/idunn` (the health and restart scripts also serve - the non-streaming daemon, so they stay). -- The receiver repo's README names Muninn in prose. - -## Removal candidates (streaming only; verify consumers first) +## Removed surfaces (archived at `parked/muninn-media-streaming-2026-12-03`) - `crates/muninn-daemon/src/media_send.rs`, `media_send/tests.rs`, - `media_packetizer.rs`, and the media wiring in `main.rs`. -- Media-related records in `crates/muninn-contracts` (`records.rs`, `lib.rs`), if no - non-streaming consumer reads them. -- `scripts/activate-muninn-raven-av-srt.cmd`, `scripts/activate-muninn-raven-media.ps1`, - `scripts/wasapi-loopback-capture.ps1`. -- `docs/muninn-media-streaming.md` (move to history rather than delete if it is cited). + `media_packetizer.rs`, test fixtures (`clip.h264`), and media capture/mux/catalog + wiring in `crates/muninn-daemon/src/main.rs`. +- Streaming-only records (`MuninnCaptureStreamRecord`, + `MuninnCaptureStreamCommandRecord`, `MuninnObsStreamCatalogRecord`, + `MuninnCommandBoundaryCompatRecord`, `MuninnTransportProfileCompatRecord`) in + `crates/muninn-contracts`. +- `scripts/wasapi-loopback-capture.ps1`, `scripts/activate-muninn-raven-av-srt.cmd`, + `scripts/activate-muninn-raven-media.ps1`, dead `.cmd` health stubs, and + `docs/muninn-media-streaming.md` / `docs/realtime-robustness-cut.md`. +- `muninn.media-producer` and streaming arguments in `deployment/idunn/raven-muninn.toml`. -## Keep +## Kept Sensor serving, PS Move tracking (`muninn-move-tracker`, `muninn-psmoveapi-tracker`, -`native/`), and `sleipnir-daemon` input are outside this notice. Do not remove them under -it. `idunn_presence.rs` matched a media search term only; it is presence, not streaming. +`native/`), `Quest`, `idunn_presence.rs`, and `sleipnir-daemon` remain active. diff --git a/scripts/activate-muninn-raven-av-srt.cmd b/scripts/activate-muninn-raven-av-srt.cmd deleted file mode 100644 index 279d605..0000000 --- a/scripts/activate-muninn-raven-av-srt.cmd +++ /dev/null @@ -1,2 +0,0 @@ -@echo off -powershell.exe -NoProfile -ExecutionPolicy Bypass -File %~dp0activate-muninn-raven-av-srt.ps1 diff --git a/scripts/activate-muninn-raven-media.ps1 b/scripts/activate-muninn-raven-media.ps1 deleted file mode 100644 index 64021dc..0000000 --- a/scripts/activate-muninn-raven-media.ps1 +++ /dev/null @@ -1 +0,0 @@ -throw "activate-muninn-raven-media.ps1 archived: Muninn media activation is daemon-owned and target resolution is through Odin/CultMesh. Redeploy Muninn through Idunn and publish a typed muninn.capture_stream_command with a cultmesh:// media target URI." diff --git a/scripts/health-muninn.cmd b/scripts/health-muninn.cmd deleted file mode 100644 index e2ddbe7..0000000 --- a/scripts/health-muninn.cmd +++ /dev/null @@ -1,3 +0,0 @@ -@echo off -echo health-muninn.cmd archived: Raven Muninn has no daemon-published health. Run health-muninn.ps1 as an explicit witness inspection (scheduled-task actions, serve process, store freshness); it is not Idunn health truth. -exit /b 2 diff --git a/scripts/health-muninn.ps1 b/scripts/health-muninn.ps1 index 407b89e..1359d31 100644 --- a/scripts/health-muninn.ps1 +++ b/scripts/health-muninn.ps1 @@ -2,7 +2,6 @@ param( [string] $RavenHost = "raven-local", [string] $MuninnExe = "C:\Meta\Odin\Muninn\muninn.exe", [string] $StorePath = "C:\Meta\Odin\state\muninn.telemetry.cc", - [string] $ActivateStorePath = "C:\Meta\Odin\state\muninn.activate.cc", [string] $LogRoot = "C:\Meta\Odin\logs\muninn", [int] $MaxStoreAgeSeconds = 180, [int] $ConnectTimeoutSeconds = 10, @@ -171,8 +170,7 @@ if (`$null -eq `$process) { throw "Muninn serve process is not running" } foreach (`$pattern in @( - "--host raven", - "--activate-store $ActivateStorePath" + "--host raven" )) { if (`$process.CommandLine -notlike "*`$pattern*") { throw "Muninn serve process is missing expected command-line segment `${pattern}: `$(`$process.CommandLine)" diff --git a/scripts/health-nightwing-muninn.cmd b/scripts/health-nightwing-muninn.cmd deleted file mode 100644 index eede45d..0000000 --- a/scripts/health-nightwing-muninn.cmd +++ /dev/null @@ -1,3 +0,0 @@ -@echo off -echo health-nightwing-muninn.cmd archived: Nightwing Muninn has no daemon-published health. Run health-nightwing-muninn.ps1 as an explicit witness inspection (serve process, store freshness, PID file); it is not Idunn health truth. -exit /b 2 diff --git a/scripts/health-starfire-muninn.cmd b/scripts/health-starfire-muninn.cmd deleted file mode 100644 index db26de6..0000000 --- a/scripts/health-starfire-muninn.cmd +++ /dev/null @@ -1,3 +0,0 @@ -@echo off -echo health-starfire-muninn.cmd archived: Starfire Muninn has no daemon-published health. Run health-starfire-muninn.ps1 as an explicit witness inspection (serve process, store freshness, PID file); it is not Idunn health truth. -exit /b 2 diff --git a/scripts/restart-nightwing-muninn.ps1 b/scripts/restart-nightwing-muninn.ps1 index 58fa1b1..48c41b0 100644 --- a/scripts/restart-nightwing-muninn.ps1 +++ b/scripts/restart-nightwing-muninn.ps1 @@ -20,8 +20,7 @@ param( [string] $OdinCultMeshUri = $(if ($env:ODIN_CULTMESH_URI) { $env:ODIN_CULTMESH_URI } else { "cultmesh://odin/rendezvous/provider-catalog" }), [string] $OdinCultMeshRudpEndpoint = $(if ($env:CULTMESH_URI_ODIN_RUDP) { $env:CULTMESH_URI_ODIN_RUDP } else { "10.77.0.2:17871" }), [string] $HidControllerRudpBind = "0.0.0.0:17888", - [string] $HidControllerRudpAdvertise = $(if ($env:MUNINN_HID_CONTROLLER_RUDP_ADVERTISE) { $env:MUNINN_HID_CONTROLLER_RUDP_ADVERTISE } else { "10.77.0.3:17888" }), - [string] $CommandRudpAdvertise = "10.77.0.3:17889" + [string] $HidControllerRudpAdvertise = $(if ($env:MUNINN_HID_CONTROLLER_RUDP_ADVERTISE) { $env:MUNINN_HID_CONTROLLER_RUDP_ADVERTISE } else { "10.77.0.3:17888" }) ) $ErrorActionPreference = "Stop" @@ -125,7 +124,6 @@ if (-not [string]::IsNullOrWhiteSpace($HidControllerRudpAdvertise)) { $hidControllerRudpSetLines += "set -- ""`$@"" --hid-controller-rudp-advertise $(Quote-ShSingle $HidControllerRudpAdvertise)" } $hidControllerRudpSetBlock = ($hidControllerRudpSetLines -join "`n") -$commandRudpSetBlock = "set -- ""`$@"" --command-rudp-advertise $(Quote-ShSingle $CommandRudpAdvertise)" $remoteScript = @" set -eu mkdir -p '$LogRoot' @@ -155,7 +153,6 @@ set -- "`$@" \ --interval-seconds '$IntervalSeconds' $odinCultMeshUriSetBlock $hidControllerRudpSetBlock -$commandRudpSetBlock CULTNET_RUDP_TRACE=1 CULTMESH_URI_ODIN_RUDP='$OdinCultMeshRudpEndpoint' nohup '$MuninnExe' "`$@" \ > '$LogRoot/muninn-serve.out.log' \ 2> '$LogRoot/muninn-serve.err.log' \ diff --git a/scripts/wasapi-loopback-capture.ps1 b/scripts/wasapi-loopback-capture.ps1 deleted file mode 100644 index c8fd2a1..0000000 --- a/scripts/wasapi-loopback-capture.ps1 +++ /dev/null @@ -1,469 +0,0 @@ -param( - [string]$Output = "-", - [string]$Device = "", - [double]$Seconds = 0, - [int]$SampleRate = 48000, - [int]$Channels = 2, - [ValidateSet("Render", "Capture")] - [string]$DataFlow = "Render", - [switch]$Loopback, - [ValidateSet("Console", "Multimedia", "Communications")] - [string]$Role = "Console" -) - -$ErrorActionPreference = "Stop" - -$source = @" -using System; -using System.IO; -using System.Runtime.InteropServices; -using System.Threading; - -namespace Mimir { - public static class WasapiLoopbackCapture { - const int eRender = 0; - const int eCapture = 1; - const int eConsole = 0; - const int eMultimedia = 1; - const int eCommunications = 2; - const int CLSCTX_ALL = 23; - const uint DEVICE_STATE_ACTIVE = 0x00000001; - const uint AUDCLNT_SHAREMODE_SHARED = 0; - const uint AUDCLNT_STREAMFLAGS_LOOPBACK = 0x00020000; - const int AUDCLNT_BUFFERFLAGS_SILENT = 0x2; - static readonly Guid IID_IAudioClient = new Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"); - static readonly Guid IID_IAudioCaptureClient = new Guid("C8ADBD64-E71E-48a0-A4DE-185C395CD317"); - static readonly Guid PcmSubformat = new Guid("00000001-0000-0010-8000-00aa00389b71"); - static readonly Guid FloatSubformat = new Guid("00000003-0000-0010-8000-00aa00389b71"); - static readonly PROPERTYKEY DeviceFriendlyNameKey = new PROPERTYKEY( - new Guid("A45C254E-DF1C-4EFD-8020-67D146A850E0"), - 14); - - [StructLayout(LayoutKind.Sequential, Pack = 2)] - struct WAVEFORMATEX { - public ushort wFormatTag; - public ushort nChannels; - public uint nSamplesPerSec; - public uint nAvgBytesPerSec; - public ushort nBlockAlign; - public ushort wBitsPerSample; - public ushort cbSize; - } - - [StructLayout(LayoutKind.Sequential, Pack = 2)] - struct WAVEFORMATEXTENSIBLE { - public WAVEFORMATEX Format; - public ushort wValidBitsPerSample; - public uint dwChannelMask; - public Guid SubFormat; - } - - [StructLayout(LayoutKind.Sequential)] - struct PROPERTYKEY { - public Guid fmtid; - public uint pid; - - public PROPERTYKEY(Guid formatId, uint propertyId) { - fmtid = formatId; - pid = propertyId; - } - } - - [StructLayout(LayoutKind.Sequential)] - struct PROPVARIANT { - public ushort vt; - public ushort wReserved1; - public ushort wReserved2; - public ushort wReserved3; - public IntPtr pointerValue; - public int intValue; - } - - [ComImport] - [Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] - class MMDeviceEnumerator { } - - [ComImport] - [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IMMDeviceEnumerator { - [PreserveSig] - int EnumAudioEndpoints(int dataFlow, uint stateMask, out IMMDeviceCollection devices); - [PreserveSig] - int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint); - } - - [ComImport] - [Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IMMDeviceCollection { - [PreserveSig] - int GetCount(out uint count); - [PreserveSig] - int Item(uint index, out IMMDevice device); - } - - [ComImport] - [Guid("D666063F-1587-4E43-81F1-B948E807363F")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IMMDevice { - [PreserveSig] - int Activate(ref Guid iid, int dwClsCtx, IntPtr pActivationParams, out IAudioClient audioClient); - [PreserveSig] - int OpenPropertyStore(uint access, out IPropertyStore properties); - } - - [ComImport] - [Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IPropertyStore { - [PreserveSig] - int GetCount(out uint propertyCount); - [PreserveSig] - int GetAt(uint propertyIndex, out PROPERTYKEY key); - [PreserveSig] - int GetValue(ref PROPERTYKEY key, out PROPVARIANT value); - [PreserveSig] - int SetValue(ref PROPERTYKEY key, ref PROPVARIANT value); - [PreserveSig] - int Commit(); - } - - [ComImport] - [Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IAudioClient { - [PreserveSig] - int Initialize(uint shareMode, uint streamFlags, long hnsBufferDuration, long hnsPeriodicity, IntPtr pFormat, IntPtr audioSessionGuid); - [PreserveSig] - int GetBufferSize(out uint bufferSize); - [PreserveSig] - int GetStreamLatency(out long latency); - [PreserveSig] - int GetCurrentPadding(out uint currentPadding); - [PreserveSig] - int IsFormatSupported(uint shareMode, IntPtr pFormat, out IntPtr closestMatch); - [PreserveSig] - int GetMixFormat(out IntPtr deviceFormat); - [PreserveSig] - int GetDevicePeriod(out long defaultDevicePeriod, out long minimumDevicePeriod); - [PreserveSig] - int Start(); - [PreserveSig] - int Stop(); - [PreserveSig] - int Reset(); - [PreserveSig] - int SetEventHandle(IntPtr eventHandle); - [PreserveSig] - int GetService(ref Guid iid, out IAudioCaptureClient captureClient); - } - - [ComImport] - [Guid("C8ADBD64-E71E-48a0-A4DE-185C395CD317")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IAudioCaptureClient { - [PreserveSig] - int GetBuffer(out IntPtr data, out uint frames, out uint flags, out ulong devicePosition, out ulong qpcPosition); - [PreserveSig] - int ReleaseBuffer(uint frames); - [PreserveSig] - int GetNextPacketSize(out uint frames); - } - - [DllImport("ole32.dll")] - static extern int PropVariantClear(ref PROPVARIANT variant); - - public static void Capture(string outputPath, string deviceSubstring, double seconds, int targetRate, int targetChannels, string dataFlowName, bool loopback, string roleName) { - Stream output = IsStdoutPath(outputPath) ? Console.OpenStandardOutput() : new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read); - try { - IMMDeviceEnumerator enumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator()); - int dataFlow = DataFlowFromName(dataFlowName); - uint streamFlags = loopback ? AUDCLNT_STREAMFLAGS_LOOPBACK : 0u; - IMMDevice device = ResolveDevice(enumerator, dataFlow, roleName, deviceSubstring); - try { - IAudioClient audioClient; - Guid audioClientId = IID_IAudioClient; - Check(device.Activate(ref audioClientId, CLSCTX_ALL, IntPtr.Zero, out audioClient), "Activate IAudioClient"); - IntPtr mixFormatPtr; - Check(audioClient.GetMixFormat(out mixFormatPtr), "GetMixFormat"); - WAVEFORMATEX fmt = Marshal.PtrToStructure(mixFormatPtr); - Console.Error.WriteLine("MixFormat tag={0} channels={1} rate={2} bits={3} blockAlign={4} cbSize={5}", fmt.wFormatTag, fmt.nChannels, fmt.nSamplesPerSec, fmt.wBitsPerSample, fmt.nBlockAlign, fmt.cbSize); - IntPtr activeFormatPtr = mixFormatPtr; - IntPtr fallbackFormatPtr = IntPtr.Zero; - IntPtr closest = IntPtr.Zero; - int support = audioClient.IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, activeFormatPtr, out closest); - Console.Error.WriteLine("MixFormatSupport hr=0x{0:X8} closest={1}", support, closest != IntPtr.Zero); - if (support != 0 && closest != IntPtr.Zero) { - activeFormatPtr = closest; - fmt = Marshal.PtrToStructure(activeFormatPtr); - Console.Error.WriteLine("ClosestFormat tag={0} channels={1} rate={2} bits={3} blockAlign={4} cbSize={5}", fmt.wFormatTag, fmt.nChannels, fmt.nSamplesPerSec, fmt.wBitsPerSample, fmt.nBlockAlign, fmt.cbSize); - } - int init = audioClient.Initialize(AUDCLNT_SHAREMODE_SHARED, streamFlags, 0, 0, activeFormatPtr, IntPtr.Zero); - if (init < 0) { - fallbackFormatPtr = MakeWaveFormatPcm((ushort)targetChannels, (uint)targetRate, 16); - activeFormatPtr = fallbackFormatPtr; - fmt = Marshal.PtrToStructure(activeFormatPtr); - Console.Error.WriteLine("RetryFormat tag={0} channels={1} rate={2} bits={3} blockAlign={4} cbSize={5}", fmt.wFormatTag, fmt.nChannels, fmt.nSamplesPerSec, fmt.wBitsPerSample, fmt.nBlockAlign, fmt.cbSize); - IntPtr retryClosest = IntPtr.Zero; - int retrySupport = audioClient.IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, activeFormatPtr, out retryClosest); - Console.Error.WriteLine("RetryFormatSupport hr=0x{0:X8} closest={1}", retrySupport, retryClosest != IntPtr.Zero); - if (retrySupport != 0 && retryClosest != IntPtr.Zero) { - Marshal.FreeHGlobal(fallbackFormatPtr); - fallbackFormatPtr = IntPtr.Zero; - activeFormatPtr = retryClosest; - fmt = Marshal.PtrToStructure(activeFormatPtr); - Console.Error.WriteLine("RetryClosestFormat tag={0} channels={1} rate={2} bits={3} blockAlign={4} cbSize={5}", fmt.wFormatTag, fmt.nChannels, fmt.nSamplesPerSec, fmt.wBitsPerSample, fmt.nBlockAlign, fmt.cbSize); - } - init = audioClient.Initialize(AUDCLNT_SHAREMODE_SHARED, streamFlags, 0, 0, activeFormatPtr, IntPtr.Zero); - } - Check(init, loopback ? "Initialize loopback" : "Initialize capture"); - IAudioCaptureClient captureClient; - Guid captureClientId = IID_IAudioCaptureClient; - Check(audioClient.GetService(ref captureClientId, out captureClient), "GetService IAudioCaptureClient"); - Check(audioClient.Start(), "Start"); - DateTime end = seconds > 0 ? DateTime.UtcNow.AddSeconds(seconds) : DateTime.MaxValue; - byte[] pcm = new byte[8192]; - byte[] silence = new byte[0]; - int sourceRate = Math.Max(1, (int)fmt.nSamplesPerSec); - double sourceFramesPerTargetFrame = sourceRate / (double)Math.Max(1, targetRate); - long sourceFramesSeen = 0; - double nextOutputSourceFrame = 0.0; - float[] previousFrame = new float[Math.Max(1, targetChannels)]; - bool hasPreviousFrame = false; - int idleFramesPerChunk = Math.Max(1, (int)Math.Round(Math.Max(1, targetRate) * 0.005)); - int idleBytes = checked(idleFramesPerChunk * Math.Max(1, targetChannels) * 4); - try { - while (DateTime.UtcNow < end) { - uint packetFrames; - Check(captureClient.GetNextPacketSize(out packetFrames), "GetNextPacketSize"); - if (packetFrames == 0) { - Thread.Sleep(5); - continue; - } - IntPtr data; - uint frames; - uint flags; - ulong devicePosition; - ulong qpcPosition; - Check(captureClient.GetBuffer(out data, out frames, out flags, out devicePosition, out qpcPosition), "GetBuffer"); - try { - int sourceChannels = Math.Max(1, (int)fmt.nChannels); - int sourceBytesPerFrame = (int)fmt.nBlockAlign; - int sourceBits = (int)fmt.wBitsPerSample; - int sourceBytesPerSample = Math.Max(1, sourceBits / 8); - int frameBytes = targetChannels * 4; - long packetStart = sourceFramesSeen; - long packetEnd = packetStart + frames; - int outputFrames = 0; - double countCursor = nextOutputSourceFrame; - while (countCursor < packetEnd) { - outputFrames++; - countCursor += sourceFramesPerTargetFrame; - } - int needed = checked(outputFrames * frameBytes); - if (pcm.Length < needed) pcm = new byte[needed]; - int dst = 0; - float[] left = new float[targetChannels]; - float[] right = new float[targetChannels]; - while (nextOutputSourceFrame < packetEnd) { - long leftAbsolute = (long)Math.Floor(nextOutputSourceFrame); - long rightAbsolute = Math.Min(packetEnd - 1, leftAbsolute + 1); - double fraction = nextOutputSourceFrame - leftAbsolute; - ReadFrame(leftAbsolute, packetStart, data, flags, sourceChannels, sourceBytesPerFrame, sourceBytesPerSample, sourceBits, fmt.wFormatTag, activeFormatPtr, previousFrame, hasPreviousFrame, left); - ReadFrame(rightAbsolute, packetStart, data, flags, sourceChannels, sourceBytesPerFrame, sourceBytesPerSample, sourceBits, fmt.wFormatTag, activeFormatPtr, previousFrame, hasPreviousFrame, right); - for (int ch = 0; ch < targetChannels; ch++) { - float sample = (float)(left[ch] + (right[ch] - left[ch]) * fraction); - byte[] bytes = BitConverter.GetBytes(sample); - Buffer.BlockCopy(bytes, 0, pcm, dst, 4); - dst += 4; - } - nextOutputSourceFrame += sourceFramesPerTargetFrame; - } - if (frames > 0) { - ReadFrame(packetEnd - 1, packetStart, data, flags, sourceChannels, sourceBytesPerFrame, sourceBytesPerSample, sourceBits, fmt.wFormatTag, activeFormatPtr, previousFrame, false, previousFrame); - hasPreviousFrame = true; - } - output.Write(pcm, 0, needed); - output.Flush(); - sourceFramesSeen = packetEnd; - } - finally { - Check(captureClient.ReleaseBuffer(frames), "ReleaseBuffer"); - } - } - } - finally { - audioClient.Stop(); - Marshal.FreeCoTaskMem(mixFormatPtr); - if (fallbackFormatPtr != IntPtr.Zero) Marshal.FreeHGlobal(fallbackFormatPtr); - if (closest != IntPtr.Zero) Marshal.FreeCoTaskMem(closest); - Marshal.ReleaseComObject(captureClient); - Marshal.ReleaseComObject(audioClient); - } - } - finally { - Marshal.ReleaseComObject(device); - Marshal.ReleaseComObject(enumerator); - } - } - finally { - if (!IsStdoutPath(outputPath)) output.Dispose(); - } - } - - static IMMDevice ResolveDevice(IMMDeviceEnumerator enumerator, int dataFlow, string roleName, string deviceSubstring) { - if (String.IsNullOrWhiteSpace(deviceSubstring)) { - IMMDevice defaultDevice; - Check(enumerator.GetDefaultAudioEndpoint(dataFlow, RoleFromName(roleName), out defaultDevice), "GetDefaultAudioEndpoint"); - Console.Error.WriteLine("SelectedAudioDevice dataFlow={0} default role={1} name=\"{2}\"", dataFlow == eCapture ? "capture" : "render", roleName, DeviceFriendlyName(defaultDevice)); - return defaultDevice; - } - - IMMDeviceCollection devices; - Check(enumerator.EnumAudioEndpoints(dataFlow, DEVICE_STATE_ACTIVE, out devices), "EnumAudioEndpoints"); - try { - uint count; - Check(devices.GetCount(out count), "GetCount"); - for (uint index = 0; index < count; index++) { - IMMDevice device; - Check(devices.Item(index, out device), "Item"); - string friendlyName = ""; - try { - friendlyName = DeviceFriendlyName(device); - if (friendlyName.IndexOf(deviceSubstring, StringComparison.OrdinalIgnoreCase) >= 0) { - Console.Error.WriteLine("SelectedAudioDevice dataFlow={0} match=\"{1}\" name=\"{2}\"", dataFlow == eCapture ? "capture" : "render", deviceSubstring, friendlyName); - return device; - } - } - catch { - Marshal.ReleaseComObject(device); - throw; - } - Marshal.ReleaseComObject(device); - } - } - finally { - Marshal.ReleaseComObject(devices); - } - - throw new InvalidOperationException("No active " + (dataFlow == eCapture ? "capture" : "render") + " endpoint matched --device \"" + deviceSubstring + "\""); - } - - static string DeviceFriendlyName(IMMDevice device) { - IPropertyStore store; - Check(device.OpenPropertyStore(0, out store), "OpenPropertyStore"); - try { - PROPERTYKEY key = DeviceFriendlyNameKey; - PROPVARIANT value; - Check(store.GetValue(ref key, out value), "GetValue FriendlyName"); - try { - if (value.vt == 31 && value.pointerValue != IntPtr.Zero) { - return Marshal.PtrToStringUni(value.pointerValue) ?? ""; - } - return ""; - } - finally { - PropVariantClear(ref value); - } - } - finally { - Marshal.ReleaseComObject(store); - } - } - - static bool IsStdoutPath(string outputPath) { - return String.Equals(outputPath, "-", StringComparison.Ordinal) || - String.Equals(outputPath, "stdout", StringComparison.OrdinalIgnoreCase); - } - - static void ReadFrame(long absoluteFrame, long packetStart, IntPtr data, uint flags, int sourceChannels, int sourceBytesPerFrame, int sourceBytesPerSample, int sourceBits, ushort tag, IntPtr formatPtr, float[] previousFrame, bool hasPreviousFrame, float[] target) { - if (absoluteFrame < packetStart) { - for (int ch = 0; ch < target.Length; ch++) target[ch] = hasPreviousFrame ? previousFrame[ch] : 0f; - return; - } - - int packetFrame = checked((int)(absoluteFrame - packetStart)); - for (int ch = 0; ch < target.Length; ch++) { - float sample = 0f; - if ((flags & AUDCLNT_BUFFERFLAGS_SILENT) == 0) { - int srcCh = Math.Min(ch, sourceChannels - 1); - IntPtr src = IntPtr.Add(data, packetFrame * sourceBytesPerFrame + srcCh * sourceBytesPerSample); - sample = ReadSample(src, sourceBits, tag, formatPtr); - } - target[ch] = sample; - } - } - - static void Check(int hr, string stage) { - if (hr < 0) { - Exception inner = Marshal.GetExceptionForHR(hr); - throw new InvalidOperationException(stage + " failed: 0x" + hr.ToString("X8") + " " + (inner == null ? "" : inner.Message), inner); - } - } - - static int RoleFromName(string roleName) { - if (String.Equals(roleName, "Multimedia", StringComparison.OrdinalIgnoreCase)) return eMultimedia; - if (String.Equals(roleName, "Communications", StringComparison.OrdinalIgnoreCase)) return eCommunications; - return eConsole; - } - - static int DataFlowFromName(string dataFlowName) { - if (String.Equals(dataFlowName, "Capture", StringComparison.OrdinalIgnoreCase)) return eCapture; - return eRender; - } - - static IntPtr MakeWaveFormatPcm(ushort channels, uint sampleRate, ushort bits) { - WAVEFORMATEX fmt = new WAVEFORMATEX(); - fmt.wFormatTag = 1; - fmt.nChannels = channels; - fmt.nSamplesPerSec = sampleRate; - fmt.wBitsPerSample = bits; - fmt.nBlockAlign = (ushort)(channels * bits / 8); - fmt.nAvgBytesPerSec = sampleRate * fmt.nBlockAlign; - fmt.cbSize = 0; - IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WAVEFORMATEX))); - Marshal.StructureToPtr(fmt, ptr, false); - return ptr; - } - - static float ReadSample(IntPtr source, int bits, ushort tag, IntPtr formatPtr) { - bool isFloat = tag == 3; - if (tag == 65534) { - WAVEFORMATEXTENSIBLE ext = Marshal.PtrToStructure(formatPtr); - isFloat = ext.SubFormat == FloatSubformat; - } - if (isFloat && bits == 32) { - return Math.Max(-1f, Math.Min(1f, (float)Marshal.PtrToStructure(source, typeof(float)))); - } - if (bits == 16) { - return Marshal.ReadInt16(source) / 32768f; - } - if (bits == 24) { - int b0 = Marshal.ReadByte(source, 0); - int b1 = Marshal.ReadByte(source, 1); - int b2 = Marshal.ReadByte(source, 2); - int value = b0 | (b1 << 8) | (b2 << 16); - if ((value & 0x800000) != 0) value |= unchecked((int)0xff000000); - return Math.Max(-1f, Math.Min(1f, value / 8388608f)); - } - if (bits == 32) { - if (tag == 65534) { - WAVEFORMATEXTENSIBLE ext = Marshal.PtrToStructure(formatPtr); - if (ext.SubFormat == PcmSubformat && ext.wValidBitsPerSample > 0 && ext.wValidBitsPerSample < 32) { - int value = Marshal.ReadInt32(source); - int shifted = value >> (32 - ext.wValidBitsPerSample); - return Math.Max(-1f, Math.Min(1f, shifted / (float)(1 << (ext.wValidBitsPerSample - 1)))); - } - } - return Math.Max(-1f, Math.Min(1f, Marshal.ReadInt32(source) / 2147483648f)); - } - return 0f; - } - } -} -"@ - -Add-Type -TypeDefinition $source -$effectiveOutput = if ($Output -eq "stdout") { "-" } else { $Output } -[Mimir.WasapiLoopbackCapture]::Capture($effectiveOutput, $Device, $Seconds, $SampleRate, $Channels, $DataFlow, $Loopback, $Role) -- 2.47.3 From ea13174acaf6cf47523cebcc8c52c0d2b4fb435b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 22:27:34 +0100 Subject: [PATCH 4/8] Eliminate Linux compiler warnings in muninn-daemon --- crates/muninn-daemon/src/main.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/muninn-daemon/src/main.rs b/crates/muninn-daemon/src/main.rs index 806753b..ac6f8f4 100644 --- a/crates/muninn-daemon/src/main.rs +++ b/crates/muninn-daemon/src/main.rs @@ -11,11 +11,10 @@ use cultnet_rs::{ GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, GameCultRuntimePresenceHealthRecord, }; use muninn_contracts::{ - MUNINN_MOVE_HUE_PROGRAM_SCHEMA, MuninnHidControllerStateRecord, - MuninnMoveControllerStateRecord, MuninnMoveEvidenceTransportHealthRecord, - MuninnMoveHueProgramRecord, MuninnMoveIdentityRecord, MuninnMoveLightCommandRecord, - MuninnMoveMarkerCandidateRecord, MuninnQuestAccessRecord, MuninnRecords, - MuninnTelemetrySurfaceRecord, + MuninnHidControllerStateRecord, MuninnMoveControllerStateRecord, + MuninnMoveEvidenceTransportHealthRecord, MuninnMoveHueProgramRecord, + MuninnMoveIdentityRecord, MuninnMoveLightCommandRecord, MuninnMoveMarkerCandidateRecord, + MuninnQuestAccessRecord, MuninnRecords, MuninnTelemetrySurfaceRecord, }; #[cfg(feature = "psmoveapi-tracker")] use muninn_contracts::MuninnMoveTrackerHealthRecord; @@ -2877,6 +2876,7 @@ struct ActiveHidControllerRudpSource { sequence: u64, joystick_axes: [i16; 16], joystick_buttons: [bool; 32], + #[cfg(windows)] latest_report: Option, last_emitted_axes: Option>, last_emitted_buttons: Option>, @@ -2890,11 +2890,12 @@ fn active_hid_controller_rudp_source(source: MoveStateSource) -> ActiveHidContro ActiveHidControllerRudpSource { #[cfg(windows)] report_rx: start_windows_hid_report_reader_if_supported(&source.hidraw_path), + #[cfg(windows)] + latest_report: None, source, sequence: 0, joystick_axes: [0; 16], joystick_buttons: [false; 32], - latest_report: None, last_emitted_axes: None, last_emitted_buttons: None, last_emitted_at: None, @@ -2915,6 +2916,7 @@ fn sync_hid_controller_rudp_sources( } } +#[cfg(windows)] #[derive(Clone, Debug)] struct LatestHidReport { bytes: Vec, @@ -2925,6 +2927,7 @@ struct LatestHidReport { const HID_CONTROLLER_RUDP_HEARTBEAT_AFTER: Duration = Duration::from_millis(50); const HID_CONTROLLER_RUDP_AXIS_EPSILON: f32 = 0.01; const HID_CONTROLLER_RUDP_MAX_FRAGMENT_BYTES: u32 = 1_200; +#[cfg(windows)] const HID_CONTROLLER_RUDP_MAX_REPORT_DRAIN: usize = 256; #[derive(Clone, Debug, Deserialize)] @@ -3346,6 +3349,7 @@ fn emit_hid_controller_record_if_due( Some(record) } +#[cfg(windows)] fn hid_controller_stream_heartbeat_due(active: &ActiveHidControllerRudpSource) -> bool { active .last_emitted_at @@ -4264,11 +4268,13 @@ fn push_unique_light_target( } } +#[cfg(test)] fn default_move_color_for_identity(identity: &str) -> (u8, u8, u8) { let hue = (stable_u64_hash(identity) % 360) as f64; hsv_to_rgb(hue, 0.82, 1.0) } +#[cfg(test)] fn golden_move_color_for_roster(identity: &str, roster: &[String]) -> (u8, u8, u8) { const GOLDEN_RATIO_CONJUGATE: f64 = 0.618_033_988_749_894_9; let Some(index) = roster.iter().position(|candidate| candidate == identity) else { @@ -4278,6 +4284,7 @@ fn golden_move_color_for_roster(identity: &str, roster: &[String]) -> (u8, u8, u hsv_to_rgb(hue, 1.0, 1.0) } +#[cfg(test)] fn scheduled_golden_move_color( identity: &str, roster: &[String], -- 2.47.3 From 83384d549549a96b17bdc347c1f1bcf3dfc8ccc4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 22:42:22 +0100 Subject: [PATCH 5/8] Restore Odin EveProviderAdvertisementRecord lease in muninn-daemon and update docs/muninn.md --- README.md | 8 +- crates/muninn-daemon/Cargo.toml | 1 + crates/muninn-daemon/src/main.rs | 259 ++++++++++++++++++++++++++++++- docs/muninn.md | 74 ++++----- 4 files changed, 290 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 5dd23d0..9c101f5 100644 --- a/README.md +++ b/README.md @@ -30,9 +30,11 @@ Muninn's own record contracts live in `muninn-contracts`. `muninn-contracts`, `muninn-daemon` (`Move`, `Quest`, HID, and `idunn_presence.rs`), `muninn-move-tracker`, `muninn-psmoveapi-tracker`, and -`sleipnir-daemon` build and test on the workspace. `sleipnir-daemon` still -reads `odin-core` strictly for Odin's external provider-advertisement discovery -records; `muninn-daemon` has no `odin-core` dependency. +`sleipnir-daemon` build and test on the workspace. Both `muninn-daemon` and +`sleipnir-daemon` read `odin-core` strictly for Odin's external +`EveProviderAdvertisementRecord` discovery surface (`muninn-daemon` publishes +its advertised HID RUDP endpoint lease via `EveProviderAdvertisementRecord`, and +`sleipnir-daemon` resolves it via `odin_core::discover_provider_endpoints`). ## Authority diff --git a/crates/muninn-daemon/Cargo.toml b/crates/muninn-daemon/Cargo.toml index 88c36e2..9e3b3f5 100644 --- a/crates/muninn-daemon/Cargo.toml +++ b/crates/muninn-daemon/Cargo.toml @@ -22,6 +22,7 @@ libc = "0.2" muninn-contracts = { path = "../muninn-contracts" } muninn-move-tracker = { path = "../muninn-move-tracker" } muninn-psmoveapi-tracker = { path = "../muninn-psmoveapi-tracker", optional = true } +odin-core = { workspace = true } rmp-serde = "1.3" serde = { version = "1", features = ["derive"] } serde_bytes = "0.11" diff --git a/crates/muninn-daemon/src/main.rs b/crates/muninn-daemon/src/main.rs index ac6f8f4..aa82f4b 100644 --- a/crates/muninn-daemon/src/main.rs +++ b/crates/muninn-daemon/src/main.rs @@ -18,6 +18,7 @@ use muninn_contracts::{ }; #[cfg(feature = "psmoveapi-tracker")] use muninn_contracts::MuninnMoveTrackerHealthRecord; +use odin_core::{EVE_PROVIDER_ADVERTISEMENT_SCHEMA, EveProviderAdvertisementRecord}; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use std::env; @@ -57,6 +58,8 @@ use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::UI::Input::XboxController::{XINPUT_GAMEPAD, XINPUT_STATE, XInputGetState}; const MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID: u32 = 0x6d75_0005; +const CULTNET_RUDP_PROTOCOL_ID: &str = "cultnet.transport.rudp.v0"; +const MUNINN_ODIN_PROVIDER_LEASE_REFRESH_SECONDS: u64 = 30; const PS_MOVE_LED_REPORT_LEN: usize = 49; const WINDOWS_XINPUT_SOURCE_PREFIX: &str = "xinput://"; const XINPUT_GAMEPAD_DPAD_UP_MASK: u16 = 0x0001; @@ -253,6 +256,7 @@ fn serve(options: Options) -> Result<()> { let mut active_move_states = active_move_state_sources(serve_move_state_sources(&options, move_runtime_enabled)); start_idunn_presence_worker(&options); + start_odin_provider_lease_worker(&options); let mut active_move_marker_cameras = active_move_marker_camera_sources(&options, Arc::clone(&move_hue_program)); let move_evidence_rudp_sender = start_hid_controller_rudp_ingress( @@ -338,7 +342,7 @@ fn serve(options: Options) -> Result<()> { move_evidence_transport_health.as_ref(), )?; publish_quest_access_if_requested(&mut node, &options)?; - publish_surface(&mut node, &options, "idle", &[])?; + publish_surface(&mut node, &options, "idle", &[], &live_move_sources)?; Ok(()) })(); if let Err(error) = tick { @@ -916,7 +920,9 @@ fn publish_surface( options: &Options, state: &str, active_streams: &[String], + live_move_sources: &[MoveStateSource], ) -> Result<()> { + let updated_at = timestamp()?; let record = MuninnTelemetrySurfaceRecord { surface_id: options.surface_id.clone(), host_id: options.host_id.clone(), @@ -932,7 +938,7 @@ fn publish_surface( active_streams: active_streams.to_vec(), activation_authority: "muninn.serve.telemetry".to_string(), detail: "Muninn telemetry surface is live.".to_string(), - updated_at: timestamp()?, + updated_at: updated_at.clone(), primary_stream_id: String::new(), primary_stream_label: String::new(), command_rudp_target: String::new(), @@ -948,9 +954,197 @@ fn publish_surface( }; node.put("latest", &record)?; node.put(&record.surface_id, &record)?; + publish_odin_provider_advertisement(node, options, live_move_sources, &updated_at)?; Ok(()) } +fn publish_odin_provider_advertisement( + node: &mut cultmesh_rs::CultMeshNode, + options: &Options, + live_move_sources: &[MoveStateSource], + updated_at: &str, +) -> Result<()> { + let provider_id = muninn_provider_id(options); + let hid_controller_endpoint = options.hid_controller_rudp_bind.map(|bind| { + options + .hid_controller_rudp_advertise + .clone() + .unwrap_or_else(|| bind.to_string()) + }); + let hid_controller_devices_camel = live_move_sources + .iter() + .map(|source| { + serde_json::json!({ + "deviceId": source.move_id, + "deviceKind": hid_controller_kind_from_source(source), + "sourcePath": source.hidraw_path + }) + }) + .collect::>(); + let input_stream_id = format!("muninn:{}:hid-controller-state", options.host_id); + let provider_input_streams = hid_controller_endpoint + .as_ref() + .map(|endpoint| { + let mut streams = vec![serde_json::json!({ + "streamId": input_stream_id, + "schema": "muninn.hid_controller_state.v1", + "transport": CULTNET_RUDP_PROTOCOL_ID, + "address": endpoint, + "connectionId": MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID, + "channel": "latest", + "devices": hid_controller_devices_camel + })]; + if let Some(stream_id) = options.move_evidence_stream_id.as_ref() { + streams.push(serde_json::json!({ + "streamId": stream_id, + "schema": "mimir.muninn_move_evidence_stream_frame.v1", + "transport": CULTNET_RUDP_PROTOCOL_ID, + "address": endpoint, + "connectionId": MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID, + "channel": "move-evidence" + })); + } + serde_json::json!(streams) + }) + .unwrap_or_else(|| serde_json::json!([])); + let mut provider_endpoints = vec![serde_json::json!({ + "transport": "cultcache-store", + "address": options.store_path.display().to_string() + })]; + if let Some(endpoint) = hid_controller_endpoint.as_ref() { + provider_endpoints.push(serde_json::json!({ + "transport": CULTNET_RUDP_PROTOCOL_ID, + "role": "muninn.hid_controller_state", + "schema": "muninn.hid_controller_state.v1", + "address": endpoint, + "connectionId": MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID, + "channel": "latest" + })); + if options.move_evidence_stream_id.is_some() { + provider_endpoints.push(serde_json::json!({ + "transport": CULTNET_RUDP_PROTOCOL_ID, + "role": "muninn.move_evidence_stream", + "schema": "mimir.muninn_move_evidence_stream_frame.v1", + "address": endpoint, + "connectionId": MUNINN_HID_CONTROLLER_RUDP_CONNECTION_ID, + "channel": "move-evidence" + })); + } + } + let provider_advertisement = EveProviderAdvertisementRecord { + value: serde_json::json!({ + "schema": EVE_PROVIDER_ADVERTISEMENT_SCHEMA, + "providerId": provider_id, + "daemonId": muninn_daemon_id(options), + "title": format!("Muninn {} Telemetry", title_case_host(&options.host_id)), + "canonicalService": "asgard.muninn", + "locatedService": format!("asgard.{}.muninn", options.host_id), + "verseId": format!("{}.local", options.host_id), + "cultMeshAddress": format!("asgard.{}.muninn/telemetry", options.host_id), + "status": "active", + "mode": "daemon-live", + "updatedAt": updated_at, + "stateStore": options.store_path.display().to_string(), + "surfaceId": options.surface_id, + "capabilities": muninn_capabilities(options), + "endpoints": provider_endpoints, + "inputStreams": provider_input_streams, + "routes": [{ + "transport": "cultcache-store", + "address": options.store_path.display().to_string() + }] + }), + }; + node.put(&provider_id, &provider_advertisement)?; + Ok(()) +} + +fn start_odin_provider_lease_worker(options: &Options) { + if resolve_odin_cultmesh_uri(options).is_none() { + return; + } + + let options = options.clone(); + thread::spawn(move || { + let mut has_published = false; + loop { + let result = open_node(&options, "muninn-odin-provider-lease") + .and_then(|node| publish_odin_provider_lease(&node, &options)); + match result { + Ok(()) => { + has_published = true; + thread::sleep(Duration::from_secs( + MUNINN_ODIN_PROVIDER_LEASE_REFRESH_SECONDS, + )); + } + Err(error) => { + eprintln!("Muninn could not renew its Odin provider lease: {error:#}"); + thread::sleep(if has_published { + Duration::from_secs(MUNINN_ODIN_PROVIDER_LEASE_REFRESH_SECONDS) + } else { + Duration::from_secs(1) + }); + } + } + } + }); +} + +fn publish_odin_provider_lease(node: &cultmesh_rs::CultMeshNode, options: &Options) -> Result<()> { + let Some(target) = resolve_odin_cultmesh_uri(options) else { + return Ok(()); + }; + let provider_id = muninn_provider_id(options); + let provider = node.get_required::(&provider_id)?; + node.publish_document_to_rudp_catalog( + &provider_id, + &provider, + CultMeshRudpDocumentPublishOptions { + target, + runtime_id: muninn_daemon_id(options), + source_role: Some("muninn.telemetry-provider".to_string()), + tags: vec![ + "provider-lease".to_string(), + "odin-verse-discovery".to_string(), + ], + ..CultMeshRudpDocumentPublishOptions::default() + }, + ) +} + +fn muninn_provider_id(options: &Options) -> String { + format!("muninn.telemetry.{}", options.host_id) +} + +fn muninn_daemon_id(options: &Options) -> String { + match options.host_id.as_str() { + "raven" => "muninn".to_string(), + "starfire" => "starfire-muninn".to_string(), + "nightwing" => "nightwing-muninn".to_string(), + _ => format!("muninn-{}", options.host_id), + } +} + +fn title_case_host(host_id: &str) -> String { + let mut chars = host_id.chars(); + match chars.next() { + Some(first) => first.to_uppercase().collect::() + chars.as_str(), + None => "Unknown".to_string(), + } +} + +fn muninn_capabilities(options: &Options) -> Vec { + let mut capabilities = vec!["muninn.telemetry_surface".to_string()]; + if options.quest_adb { + capabilities.push("quest.usb.access".to_string()); + } + if !options.move_state_sources.is_empty() || options.hid_controller_rudp_bind.is_some() { + capabilities.push("psmove.controller.state".to_string()); + capabilities.push("muninn.move_evidence_stream".to_string()); + } + capabilities +} + fn available_sources(options: &Options) -> Vec { let mut sources = Vec::new(); for source in &options.move_state_sources { @@ -6665,7 +6859,7 @@ fn ensure_state_dirs(options: &Options) -> Result<()> { Ok(()) } -/// Muninn's typed records plus Idunn runtime presence health. +/// Muninn's typed records, Idunn runtime presence health, and Odin's external provider advertisement. #[derive(Clone, Copy, Debug, Default)] struct MuninnDocuments; @@ -6673,6 +6867,7 @@ impl cultmesh_rs::CultMeshDocumentSet for MuninnDocuments { fn register_cache(&self, cache: &mut cultcache_rs::CultCache) -> Result<()> { MuninnRecords.register_cache(cache)?; cache.register_entry_type::()?; + cache.register_entry_type::()?; Ok(()) } @@ -6686,6 +6881,14 @@ impl cultmesh_rs::CultMeshDocumentSet for MuninnDocuments { GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.to_string(), ), ); + registry.register( + cultnet_rs::CultNetDocumentBinding::for_entry_with_schema_id::< + EveProviderAdvertisementRecord, + >( + "gamecult.eve.provider_advertisement".to_string(), + EVE_PROVIDER_ADVERTISEMENT_SCHEMA.to_string(), + ), + ); Ok(()) } } @@ -8944,4 +9147,54 @@ Device 00:07:04:A8:00:D0 (public) assert!((record.trigger_value - (128.0 / 255.0)).abs() < f32::EPSILON); assert!((record.battery01 - 0.8).abs() < f32::EPSILON); } + + #[test] + fn provider_advertisement_resolves_hid_rudp_endpoint_through_odin_discovery() { + let store_path = temp_store_path("provider-hid-discovery"); + let options = Options::parse( + [ + "serve", + "--store", + store_path.to_str().unwrap(), + "--host", + "nightwing", + "--hid-controller-rudp-bind", + "0.0.0.0:17888", + "--hid-controller-rudp-advertise", + "10.77.0.3:17888", + "--move-state", + "xbox-nightwing=xinput://0", + ] + .into_iter() + .map(String::from), + ) + .unwrap(); + let mut node = open_node(&options, "muninn-provider-test").unwrap(); + + publish_surface( + &mut node, + &options, + "idle", + &[], + &options.move_state_sources, + ) + .unwrap(); + + let matches = odin_core::discover_provider_endpoints( + &node, + odin_core::OdinEndpointQuery { + schema: Some("muninn.hid_controller_state.v1"), + transport_contains: Some("rudp"), + host_hint: Some("nightwing"), + device_filter: Some("xbox-nightwing"), + }, + ); + assert_eq!(matches.len(), 1); + assert_eq!(matches[0].address, "10.77.0.3:17888"); + assert_eq!( + matches[0].stream_id.as_deref(), + Some("muninn:nightwing:hid-controller-state") + ); + let _ = fs::remove_file(store_path); + } } diff --git a/docs/muninn.md b/docs/muninn.md index b262640..019dc65 100644 --- a/docs/muninn.md +++ b/docs/muninn.md @@ -3,20 +3,25 @@ Muninn is Odin's portable local telemetry Verse assembler. It runs on a device body and publishes a typed CultMesh/CultCache surface for -what that body can sense or expose locally: screen capture, loopback audio, -microphones, cameras, and future sensors. +what that body exposes locally: PS Move controllers and optical marker evidence, +HID/XInput gamepads, and Quest USB access. + +> The deprecated A/V streaming stack (screen capture, WASAPI loopback audio, +> FFmpeg muxing, `muninn.capture_stream.v1`, `muninn.obs_stream_catalog.v1`, +> `request-stream`, and `wasapi-loopback-capture.ps1`) was removed on +> 2026-12-03 and archived at git tag `parked/muninn-media-streaming-2026-12-03`. ## Authority -- Owner: Muninn owns local telemetry discovery, stream affordance publication, - and explicit activation of requested local streams. -- Inputs: cheap local probes, operator or Verse activation requests, and local - capture tools such as FFmpeg or WASAPI helpers. -- Outputs: `muninn.telemetry_surface.v1`, active `muninn.capture_stream.v1`, +- Owner: Muninn owns local telemetry discovery, HID RUDP endpoint + serving/advertisement, Quest USB probing, and local Move evidence/light state. +- Inputs: cheap local HID/USB/camera probes and typed Move commands (`muninn.move_light_command.v1`, `muninn.move_hue_program.v1`). +- Outputs: `muninn.telemetry_surface.v1`, `gamecult.eve.provider_advertisement.v1` + (carrying HID RUDP endpoints for Sleipnir), `muninn.hid_controller_state.v1`, Quest access records, Move receipt records, and a CultMesh bytes stream carrying live Move evidence frames for Mimir. -- Forbidden writers: daemon startup, Idunn keepalive, Mimir ingest, OBS, Odin, - Gjallar, and renderer bodies must not start capture by implication. +- Forbidden writers: daemon startup, Idunn keepalive, Mimir ingest, Odin, and + renderer bodies must not hijack Muninn's local device state. ## Runtime @@ -26,33 +31,21 @@ muninn serve --store C:\Meta\Odin\state\muninn.telemetry.cc --interval-seconds 1 muninn --health --store C:\Meta\Odin\state\muninn.telemetry.cc ``` -`serve` is cheap and idle. It publishes affordances, consumes addressed pending -`muninn.move_light_command.v1` records, and keeps the local Verse surface fresh -without starting FFmpeg, screen capture, microphone capture, or loopback -capture. +`serve` publishes `muninn.telemetry_surface.v1` and Odin's +`gamecult.eve.provider_advertisement.v1` lease (including +`--hid-controller-rudp-advertise` when HID RUDP serving is enabled), consumes +addressed pending `muninn.move_light_command.v1` records, syncs +`muninn.move_hue_program.v1`, and keeps the local telemetry surface fresh. -Muninn writes its stream affordance catalog as typed CultCache state inside: +Muninn writes its telemetry surface and local state as typed CultCache state inside: ```text C:\Meta\Odin\state\muninn.telemetry.cc ``` -The record is type `muninn.obs_stream_catalog` with schema -`muninn.obs_stream_catalog.v1` at key `obs`. Consumers discover the catalog -through Odin/CultMesh; Muninn does not publish a parallel OBS RUDP catalog. - -Activation is explicit typed state: - -```powershell -muninn request-stream --target-host cultmesh://odin/media/muninn-raven-av --media-transport rudp -``` - -`target_host` in the legacy command record field is a CultMesh URI, not a host -or IP. The activation child resolves `muninn.media.rudp.v1` endpoints from -Odin's provider catalog before opening the CultNet RUDP media lane. SRT, OBS -target flags, and standalone Raven activation scripts are archived; Mimir, -OBS, and other renderers are consumers of Odin/CultMesh discovery, not transport -owners. +Peers such as Sleipnir discover Muninn's HID RUDP endpoint from Odin's +`gamecult.eve.provider_advertisement.v1` catalog rather than passing static +port bindings out of band. ## Quest Access And Unity Return Video @@ -93,8 +86,8 @@ For Starfire's local Quest-attached daemon, Idunn supervises the `starfire-muninn` target through: ```powershell -E:\Projects\Odin\scripts\restart-starfire-muninn.cmd -E:\Projects\Odin\scripts\health-starfire-muninn.cmd +scripts/restart-starfire-muninn.ps1 +scripts/health-starfire-muninn.ps1 ``` The restart script launches Muninn hidden with `--host starfire --quest-adb`. @@ -103,17 +96,6 @@ fails MessagePack decode on boot, the restart path archives the corrupt file, clears the stale `.lock`, and relaunches the daemon instead of leaving the lane dead. -The deployed loopback helper must accept Muninn's command contract: - -```powershell -wasapi-loopback-capture.ps1 -Output stdout -Device Realtek -SampleRate 48000 -Channels 2 -``` - -`stdout` is an alias for binary standard output, and `Device` is the requested -render-device hint. Current helper builds may ignore the hint and use the -default render endpoint, but they must accept the argument so Muninn's generated -mux command remains executable. - ## Move Marker Candidates `crates/muninn-move-tracker` is Muninn's native/Rust PS Move optical candidate @@ -197,9 +179,9 @@ missing or the Quest is unavailable, Muninn publishes `muninn.quest_access` as ## Host Deployments Raven is deployed by Idunn since 2026-09-11. `deployment/idunn/raven-muninn.toml` -is the target declaration: the build step, the two artifacts (`muninn.exe` -and the loopback capture script) and the launch contract. Raven's paths and -advertised endpoints are argument bindings in the yggdrasil operator binding +is the target declaration: the build step, the `muninn.exe` artifact, and the +launch contract. Raven's paths and advertised endpoints are argument bindings in +the yggdrasil operator binding (`gamecult-ops/idunn/yggdrasil/bindings/raven-muninn.toml.in`). The host actuator (`idunn-host`, from the Idunn repo) runs in Raven's user session, builds the exact frozen revision with Raven's own cargo, installs the sealed -- 2.47.3 From 0bec81d1e5f92734f809e906c2b3a554d5cc814e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 22:43:31 +0100 Subject: [PATCH 6/8] Use std::env::temp_dir() in provider discovery test --- crates/muninn-daemon/src/main.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/muninn-daemon/src/main.rs b/crates/muninn-daemon/src/main.rs index aa82f4b..ca68c46 100644 --- a/crates/muninn-daemon/src/main.rs +++ b/crates/muninn-daemon/src/main.rs @@ -9150,7 +9150,10 @@ Device 00:07:04:A8:00:D0 (public) #[test] fn provider_advertisement_resolves_hid_rudp_endpoint_through_odin_discovery() { - let store_path = temp_store_path("provider-hid-discovery"); + let store_path = std::env::temp_dir().join(format!( + "muninn-provider-hid-discovery-{}.cc", + timestamp_ns().unwrap() + )); let options = Options::parse( [ "serve", -- 2.47.3 From 5095044f175321016515ed51e1606ad9cb8a61d4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 22:44:08 +0100 Subject: [PATCH 7/8] Assert all discovered HID endpoint matches resolve to advertised address --- crates/muninn-daemon/src/main.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/muninn-daemon/src/main.rs b/crates/muninn-daemon/src/main.rs index ca68c46..f25b756 100644 --- a/crates/muninn-daemon/src/main.rs +++ b/crates/muninn-daemon/src/main.rs @@ -9192,8 +9192,10 @@ Device 00:07:04:A8:00:D0 (public) device_filter: Some("xbox-nightwing"), }, ); - assert_eq!(matches.len(), 1); - assert_eq!(matches[0].address, "10.77.0.3:17888"); + assert!(!matches.is_empty()); + assert!(matches + .iter() + .all(|endpoint_match| endpoint_match.address == "10.77.0.3:17888")); assert_eq!( matches[0].stream_id.as_deref(), Some("muninn:nightwing:hid-controller-state") -- 2.47.3 From c475c2d77a04b4c2f9a6eb274de9dcf17bc652ce Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 22:45:08 +0100 Subject: [PATCH 8/8] Check discovered endpoint matches without relying on dedupe ordering --- crates/muninn-daemon/src/main.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/muninn-daemon/src/main.rs b/crates/muninn-daemon/src/main.rs index f25b756..78accbb 100644 --- a/crates/muninn-daemon/src/main.rs +++ b/crates/muninn-daemon/src/main.rs @@ -9196,10 +9196,9 @@ Device 00:07:04:A8:00:D0 (public) assert!(matches .iter() .all(|endpoint_match| endpoint_match.address == "10.77.0.3:17888")); - assert_eq!( - matches[0].stream_id.as_deref(), - Some("muninn:nightwing:hid-controller-state") - ); + assert!(matches.iter().any(|endpoint_match| { + endpoint_match.stream_id.as_deref() == Some("muninn:nightwing:hid-controller-state") + })); let _ = fs::remove_file(store_path); } } -- 2.47.3