diff --git a/README.md b/README.md index d0b4578..2fdffa4 100644 --- a/README.md +++ b/README.md @@ -75,10 +75,12 @@ Odin endpoint, pull every `gamecult.media_stream_advertisement` Odin holds, and offer each stream's video sources, audio sources and codecs from the advertisement itself, plus bitrate and latency budget (zero means the producer's default). Selecting and activating publishes a -`gamecult.media_stream_request` naming this receiver's endpoint; the producer -dials it with the advertised connection id and answers on the same request -key. Nothing in the properties comes from configuration or from Muninn: the -picker shows whatever advertises. +`gamecult.media_stream_request`; the producer answers on the same request +key, and the source dials the `media_endpoint` the advertisement named, +repeating the dial until the producer answers. The consumer never listens: +the machine running OBS admits nothing inbound and needs no firewall rule or +port forward. Nothing in the properties comes from configuration or from +Muninn: the picker shows whatever advertises. Video reaches OBS the way the previous plugin proved in the field: the core relays each whole access unit as a raw byte stream to a loopback UDP port and @@ -144,9 +146,9 @@ is how the last receiver and sender drifted apart without either noticing. What is not here yet: - **A live frame.** No stream has crossed Raven → Starfire through this path. - It needs Muninn on Raven running a build that advertises and answers - (`b679fc2` or later) and Starfire admitting inbound UDP on the receiver's - port. + It needs Muninn on Raven running a build that advertises a media + endpoint, listens on it, and answers requests; Raven's firewall admits + that one UDP port. Starfire admits nothing. - **Opus.** The request carries `audio_codec`; the only producer today emits `pcm-f32le-interleaved`. When Opus lands, the audio path here grows a decoder or a second `ffmpeg_source` child. diff --git a/crates/ratatoskr-core/Cargo.toml b/crates/ratatoskr-core/Cargo.toml index 1bd22d0..9b544dd 100644 --- a/crates/ratatoskr-core/Cargo.toml +++ b/crates/ratatoskr-core/Cargo.toml @@ -13,9 +13,9 @@ crate-type = ["rlib", "cdylib", "staticlib"] [dependencies] anyhow = "1" chrono = "0.4" -cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "780e1a48cdf6ded6d3a6e3e72916817fb3768f05", package = "cultnet-rs" } -cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "780e1a48cdf6ded6d3a6e3e72916817fb3768f05", package = "cultmesh-rs" } -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "780e1a48cdf6ded6d3a6e3e72916817fb3768f05", package = "cultcache-rs" } +cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c84cb2e", package = "cultnet-rs" } +cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c84cb2e", package = "cultmesh-rs" } +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c84cb2e", package = "cultcache-rs" } [dev-dependencies] rmp-serde = "1.3" diff --git a/crates/ratatoskr-core/src/catalog.rs b/crates/ratatoskr-core/src/catalog.rs index fcff01b..966d4b7 100644 --- a/crates/ratatoskr-core/src/catalog.rs +++ b/crates/ratatoskr-core/src/catalog.rs @@ -2,9 +2,9 @@ //! //! Producers advertise `gamecult.media_stream_advertisement` through Odin; //! a consumer pulls those to build a picker and publishes a -//! `gamecult.media_stream_request` naming the stream, the sources, the codecs -//! and the endpoint the producer should dial. The producer answers on the -//! same request key. None of this touches the media channel, and none of it +//! `gamecult.media_stream_request` naming the stream, the sources and the +//! codecs. The producer answers on the same request key, and the consumer +//! dials the endpoint the advertisement named. None of this touches the media channel, and none of it //! names Muninn: the picker shows whatever advertises. //! //! Everything below is `cultmesh-rs`. A node here is a small local CultCache @@ -144,14 +144,13 @@ pub fn pull_request_state( node.get::(&key) } -/// A start request as the OBS source would issue it. `receiver_endpoint` is -/// where this consumer's media receiver listens; the producer dials it with -/// the advertised connection id. +/// A start request as the OBS source would issue it. It names no consumer +/// endpoint: the consumer dials the advertised `media_endpoint` and is known +/// to the producer by `receiver_id`. #[allow(clippy::too_many_arguments)] pub fn start_request( advertisement: &GameCultMediaStreamAdvertisementRecord, receiver_id: &str, - receiver_endpoint: SocketAddr, video_source_id: &str, audio_source_id: &str, video_codec: &str, @@ -165,7 +164,6 @@ pub fn start_request( stream_id: advertisement.stream_id.clone(), producer_id: advertisement.producer_id.clone(), receiver_id: receiver_id.to_string(), - receiver_endpoint: receiver_endpoint.to_string(), action: "start".to_string(), state: "pending".to_string(), video_source_id: video_source_id.to_string(), @@ -190,7 +188,6 @@ pub fn stop_request( stream_id: advertisement.stream_id.clone(), producer_id: advertisement.producer_id.clone(), receiver_id: receiver_id.to_string(), - receiver_endpoint: String::new(), action: "stop".to_string(), state: "pending".to_string(), video_source_id: String::new(), diff --git a/crates/ratatoskr-core/src/ffi.rs b/crates/ratatoskr-core/src/ffi.rs index edc5990..2e9c0e6 100644 --- a/crates/ratatoskr-core/src/ffi.rs +++ b/crates/ratatoskr-core/src/ffi.rs @@ -21,9 +21,7 @@ use cultnet_rs::GameCultMediaStreamAdvertisementRecord; use crate::catalog::{CatalogOptions, pull_catalog, pull_request_state, publish_request, start_request, stop_request}; -use crate::feedback::FeedbackOptions; use crate::receiver::{MediaEvent, RatatoskrReceiver, ReceiverOptions}; -use crate::video::VideoAssemblerOptions; pub const RATATOSKR_OK: c_int = 0; pub const RATATOSKR_NONE: c_int = 1; @@ -64,23 +62,26 @@ fn pts_nanos(pts_ticks: i64, num: u32, den: u32) -> i64 { ((pts_ticks as i128 * num as i128 * 1_000_000_000) / den as i128) as i64 } +/// Dials the producer at `producer` (`host:port`, the advertisement's +/// `media_endpoint`) and keeps dialling until it answers. +/// /// # Safety -/// `bind` and `runtime_id` must be valid NUL-terminated UTF-8; `video_relay` +/// `producer` and `runtime_id` must be valid NUL-terminated UTF-8; `video_relay` /// may be NULL or a `host:port` to copy whole video access units to. /// `out_handle` must be a valid pointer to write one handle into. #[unsafe(no_mangle)] pub unsafe extern "C" fn ratatoskr_receiver_open( - bind: *const c_char, + producer: *const c_char, runtime_id: *const c_char, connection_id: c_uint, video_relay: *const c_char, out_handle: *mut *mut RatatoskrHandle, ) -> c_int { - if bind.is_null() || runtime_id.is_null() || out_handle.is_null() { + if producer.is_null() || runtime_id.is_null() || out_handle.is_null() { set_last_error("null argument"); return RATATOSKR_ERR_ARGUMENT; } - let (bind, runtime_id) = unsafe { (CStr::from_ptr(bind), CStr::from_ptr(runtime_id)) }; + let (producer, runtime_id) = unsafe { (CStr::from_ptr(producer), CStr::from_ptr(runtime_id)) }; let video_relay = if video_relay.is_null() { None } else { @@ -92,12 +93,12 @@ pub unsafe extern "C" fn ratatoskr_receiver_open( } } }; - let Ok(bind) = bind.to_str().map(str::to_owned) else { - set_last_error("bind address is not valid UTF-8"); + let Ok(producer) = producer.to_str().map(str::to_owned) else { + set_last_error("producer endpoint is not valid UTF-8"); return RATATOSKR_ERR_ARGUMENT; }; - let Ok(bind) = bind.parse::() else { - set_last_error(format!("bind address {bind} is not a socket address")); + let Some(producer) = resolve_endpoint(&producer) else { + set_last_error(format!("producer endpoint {producer} is not a host:port that resolves")); return RATATOSKR_ERR_ARGUMENT; }; let Ok(runtime_id) = runtime_id.to_str().map(str::to_owned) else { @@ -106,12 +107,8 @@ pub unsafe extern "C" fn ratatoskr_receiver_open( }; match RatatoskrReceiver::open(ReceiverOptions { - bind, - runtime_id, - connection_id: connection_id as u32, - video: VideoAssemblerOptions::default(), - feedback: FeedbackOptions::default(), video_relay, + ..ReceiverOptions::new(producer, runtime_id, connection_id as u32) }) { Ok(receiver) => { let handle = Box::new(RatatoskrHandle { @@ -234,17 +231,21 @@ pub unsafe extern "C" fn ratatoskr_receiver_undecodable(handle: *mut RatatoskrHa .unwrap_or(0) } -/// The port actually bound, which differs from the requested one when 0 was -/// passed. Returns 0 if unavailable. +/// 1 while the producer has answered the dial and not since gone quiet, else +/// 0. The receiver keeps dialling on its own either way. /// /// # Safety -/// `handle` must be live. +/// `handle` must be live or null. #[unsafe(no_mangle)] -pub unsafe extern "C" fn ratatoskr_receiver_local_port(handle: *mut RatatoskrHandle) -> u16 { - unsafe { handle.as_ref() } - .and_then(|handle| handle.receiver.local_addr().ok()) - .map(|addr| addr.port()) - .unwrap_or(0) +pub unsafe extern "C" fn ratatoskr_receiver_attached(handle: *mut RatatoskrHandle) -> c_int { + unsafe { handle.as_ref() }.is_some_and(|handle| handle.receiver.attached()) as c_int +} + +/// `host:port` to the first address it resolves to. A producer may advertise +/// a hostname. +fn resolve_endpoint(value: &str) -> Option { + use std::net::ToSocketAddrs; + value.to_socket_addrs().ok()?.next() } /// Payloads delivered and their total bytes, both observed rather than @@ -360,11 +361,13 @@ pub struct RatatoskrStreamInfo { pub default_video_bitrate_kbps: u32, pub default_latency_budget_ms: u32, pub media_packet_bytes: u32, + /// `host:port` the producer serves from; dial it with `media_connection_id`. + pub media_endpoint: *const c_char, pub media_connection_id: u32, } struct StreamStrings { - scalars: [CString; 4], + scalars: [CString; 5], /// Owns the bytes `list_pointers` point into; never read directly. _owned_lists: [Vec; 6], list_pointers: [Vec<*const c_char>; 6], @@ -455,6 +458,7 @@ pub unsafe extern "C" fn ratatoskr_catalog_pull( c_string(&stream.producer_id), c_string(&stream.label), c_string(&stream.state), + c_string(&stream.media_endpoint), ], _owned_lists: [a.0, b.0, c.0, d.0, e.0, f.0], list_pointers: [a.1, b.1, c.1, d.1, e.1, f.1], @@ -528,15 +532,17 @@ pub unsafe extern "C" fn ratatoskr_catalog_stream( default_video_bitrate_kbps: stream.default_video_bitrate_kbps, default_latency_budget_ms: stream.default_latency_budget_ms, media_packet_bytes: stream.media_packet_bytes, + media_endpoint: strings.scalars[4].as_ptr(), media_connection_id: stream.media_connection_id, }; unsafe { ptr::write(out, info) }; RATATOSKR_OK } -/// Asks the producer of stream `index` to start serving it to -/// `receiver_endpoint`. Empty source ids mean "none of that kind"; a zero -/// bitrate or latency means the producer's default. Blocks for the publish. +/// Asks the producer of stream `index` to start serving it; once it answers +/// `running`, dial its `media_endpoint` with `ratatoskr_receiver_open`. +/// Empty source ids mean "none of that kind"; a zero bitrate or latency +/// means the producer's default. Blocks for the publish. /// /// # Safety /// `catalog` must be live; strings must be valid NUL-terminated UTF-8. @@ -544,7 +550,6 @@ pub unsafe extern "C" fn ratatoskr_catalog_stream( pub unsafe extern "C" fn ratatoskr_request_start( catalog: *const RatatoskrCatalog, index: usize, - receiver_endpoint: *const c_char, video_source_id: *const c_char, audio_source_id: *const c_char, video_codec: *const c_char, @@ -560,8 +565,7 @@ pub unsafe extern "C" fn ratatoskr_request_start( set_last_error(format!("stream index {index} out of range")); return RATATOSKR_ERR_ARGUMENT; }; - let (Some(endpoint), Some(video_source), Some(audio_source), Some(video_codec), Some(audio_codec)) = ( - read_c_str(receiver_endpoint, "receiver endpoint"), + let (Some(video_source), Some(audio_source), Some(video_codec), Some(audio_codec)) = ( read_c_str(video_source_id, "video source id"), read_c_str(audio_source_id, "audio source id"), read_c_str(video_codec, "video codec"), @@ -569,15 +573,10 @@ pub unsafe extern "C" fn ratatoskr_request_start( ) else { return RATATOSKR_ERR_ARGUMENT; }; - let Ok(endpoint) = endpoint.parse::() else { - set_last_error(format!("receiver endpoint {endpoint} is not host:port")); - return RATATOSKR_ERR_ARGUMENT; - }; let observed_at = Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true); let request = start_request( stream, &catalog.options.runtime_id, - endpoint, video_source, audio_source, video_codec, @@ -709,7 +708,9 @@ mod tests { use std::ffi::CString; fn open() -> *mut RatatoskrHandle { - let bind = CString::new("127.0.0.1:0").expect("cstring"); + // An address nobody answers on; the dial is sent, not answered. + let dead = UdpSocket::bind("127.0.0.1:0").expect("binds").local_addr().expect("addr"); + let bind = CString::new(dead.to_string()).expect("cstring"); let id = CString::new("ratatoskr-ffi-test").expect("cstring"); let mut handle: *mut RatatoskrHandle = ptr::null_mut(); let rc = unsafe { @@ -723,7 +724,7 @@ mod tests { #[test] fn open_poll_close_round_trips() { let handle = open(); - assert!(unsafe { ratatoskr_receiver_local_port(handle) } != 0); + assert_eq!(unsafe { ratatoskr_receiver_attached(handle) }, 0, "nobody answered"); assert_eq!(unsafe { ratatoskr_receiver_poll(handle) }, 0); unsafe { ratatoskr_receiver_close(handle) }; } @@ -803,7 +804,7 @@ mod tests { unsafe { ratatoskr_receiver_poll(ptr::null_mut()) }, RATATOSKR_ERR_ARGUMENT ); - assert_eq!(unsafe { ratatoskr_receiver_local_port(ptr::null_mut()) }, 0); + assert_eq!(unsafe { ratatoskr_receiver_attached(ptr::null_mut()) }, 0); unsafe { ratatoskr_receiver_close(ptr::null_mut()) }; } diff --git a/crates/ratatoskr-core/src/receiver.rs b/crates/ratatoskr-core/src/receiver.rs index afe7d1f..e7105c6 100644 --- a/crates/ratatoskr-core/src/receiver.rs +++ b/crates/ratatoskr-core/src/receiver.rs @@ -1,18 +1,23 @@ -//! The subscription: bind, accept a producer, hand back media events, and -//! say back what was lost. +//! The subscription: dial the producer, hand back media events, and say back +//! what was lost. +//! +//! The consumer dials. A producer listens on the endpoint it advertises and +//! this receiver connects to it, so the machine running the renderer admits +//! nothing inbound: no firewall rule, no port forward. The producer is the +//! host doing the serving, and one open port there is the ordinary ask. //! //! Everything below the events is `cultnet-rs`. This file has no sequence //! numbers, no acknowledgement state and no retransmit timers, and it must not //! grow any — see the crate docs for why. use std::net::{SocketAddr, UdpSocket}; -use std::time::Instant; +use std::time::{Duration, Instant}; use anyhow::{Context, Result}; use chrono::{SecondsFormat, Utc}; use cultnet_rs::{ - CultNetRudpServerEvent, CultNetRudpServerHub, CultNetRudpServerHubOptions, - CultNetRudpServerSessionContext, CultNetTransportFrame, GameCultMediaAudioPacketRecord, + CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, CultNetTransportFrame, + GAMECULT_MEDIA_AUDIO_CHANNEL, GameCultMediaAudioPacketRecord, GameCultMediaReceiverFeedbackRecord, GameCultMediaWireRecord, MediaWireProvenance, decode_media_wire_record, encode_media_wire_record, }; @@ -27,11 +32,12 @@ pub const RATATOSKR_MEDIA_PRODUCER: &str = "ratatoskr"; #[derive(Clone, Debug)] pub struct ReceiverOptions { - /// Where to listen for the producer. - pub bind: SocketAddr, - /// Identifies this receiver to the producer and in CultNet logs. + /// The producer's advertised media endpoint, to dial. + pub producer: SocketAddr, + /// Identifies this receiver to the producer: it is the connect payload the + /// producer sees, the `receiver_id` on feedback, and the CultNet runtime id. pub runtime_id: String, - /// Must match the producer's media connection id. + /// Must match the producer's advertised media connection id. pub connection_id: u32, /// How incomplete video frames are waited for and given up on. pub video: VideoAssemblerOptions, @@ -41,13 +47,34 @@ pub struct ReceiverOptions { /// decoder that reads a raw H.264/H.265 byte stream from a local socket /// (OBS's own ffmpeg source does). `None` keeps frames in-process. pub video_relay: Option, + /// How long an unanswered dial is left before dialling afresh. A producer + /// is usually still spinning up when the first dial goes out. + pub redial_after: Duration, + /// How long an attached producer may be silent before it is presumed gone + /// and dialled afresh. The receiver pings at a third of this. + pub silence_timeout: Duration, +} + +impl ReceiverOptions { + pub fn new(producer: SocketAddr, runtime_id: impl Into, connection_id: u32) -> Self { + Self { + producer, + runtime_id: runtime_id.into(), + connection_id, + video: VideoAssemblerOptions::default(), + feedback: FeedbackOptions::default(), + video_relay: None, + redial_after: Duration::from_secs(1), + silence_timeout: Duration::from_secs(4), + } + } } /// What the renderer is given. Deliberately not the wire record: a renderer /// should not have to know how a frame was chunked to present it. #[derive(Clone, Debug, PartialEq, Eq)] pub enum MediaEvent { - /// A producer attached. + /// The producer answered the dial. ProducerAttached { remote: SocketAddr }, /// A whole video access unit, reassembled and, if needed, repaired. VideoFrame { frame: Box }, @@ -62,8 +89,8 @@ pub enum MediaEvent { Feedback { record: Box }, /// Feedback this receiver handed to the transport for the producer. FeedbackSent { record: Box }, - /// Feedback that could not be handed to the transport, usually because no - /// producer is attached to tell. + /// Feedback that could not be handed to the transport, usually because + /// the producer has not answered the dial yet. FeedbackNotSent { reason: String }, /// A media payload arrived but is not a media record this build understands. /// @@ -73,16 +100,24 @@ pub enum MediaEvent { Undecodable { bytes: Vec, reason: String }, /// A record decoded but contradicted the frame it belongs to. Rejected { reason: String }, - /// A producer detached, gracefully or otherwise. - ProducerDetached { remote: SocketAddr }, + /// The producer went away, by saying so or by silence. The receiver dials + /// again on its own; this is so a renderer can say why the picture froze. + ProducerDetached { remote: SocketAddr, reason: String }, } pub struct RatatoskrReceiver { - hub: CultNetRudpServerHub, + producer: SocketAddr, + runtime_id: String, + connection_id: u32, + redial_after: Duration, + silence_timeout: Duration, + transport: CultNetRudpSocketTransportConnection, + dialled_at: Instant, + pinged_at: Instant, + attached: bool, + redials: u64, relay: Option<(UdpSocket, SocketAddr)>, relayed_frames: u64, - runtime_id: String, - producer: Option, video: VideoAssembler, feedback: FeedbackComposer, payloads: u64, @@ -92,20 +127,11 @@ pub struct RatatoskrReceiver { } impl RatatoskrReceiver { + /// Dials the producer. Returns once the dial is sent, not once it is + /// answered: attachment is reported by [`MediaEvent::ProducerAttached`] + /// from [`poll`](Self::poll), and the dial is repeated until then. pub fn open(options: ReceiverOptions) -> Result { - let socket = UdpSocket::bind(options.bind) - .with_context(|| format!("binding Ratatoskr media receiver to {}", options.bind))?; - socket - .set_nonblocking(true) - .context("setting Ratatoskr media receiver nonblocking")?; - - let hub = CultNetRudpServerHub::new(CultNetRudpServerHubOptions::new( - options.runtime_id.clone(), - socket, - options.connection_id, - )) - .context("opening Ratatoskr CultNet RUDP receiver")?; - + let transport = dial(options.producer, &options.runtime_id, options.connection_id)?; let relay = match options.video_relay { Some(target) => { let socket = UdpSocket::bind("127.0.0.1:0").context("binding the video relay socket")?; @@ -113,14 +139,21 @@ impl RatatoskrReceiver { } None => None, }; - + let now = Instant::now(); Ok(Self { - hub, + producer: options.producer, + connection_id: options.connection_id, + redial_after: options.redial_after, + silence_timeout: options.silence_timeout, + transport, + dialled_at: now, + pinged_at: now, + attached: false, + redials: 0, relay, relayed_frames: 0, feedback: FeedbackComposer::new(options.runtime_id.clone(), options.feedback), runtime_id: options.runtime_id, - producer: None, video: VideoAssembler::new(options.video), payloads: 0, payload_bytes: 0, @@ -129,54 +162,47 @@ impl RatatoskrReceiver { }) } - pub fn local_addr(&self) -> Result { - self.hub.local_addr() + /// Where the dial goes. + pub fn producer(&self) -> SocketAddr { + self.producer } - /// Drains what has arrived, gives up on what is too old, and tells the - /// producer what is wanted. Never blocks; a caller drives this from its - /// own loop so the renderer keeps its own cadence. + /// Whether the producer has answered and not since gone quiet. + pub fn attached(&self) -> bool { + self.attached + } + + /// Dials made after the first, whether because nobody answered or because + /// an attached producer went away. + pub fn redials(&self) -> u64 { + self.redials + } + + /// Drains what has arrived, gives up on what is too old, tells the + /// producer what is wanted, and keeps the dial alive. Never blocks; a + /// caller drives this from its own loop so the renderer keeps its own + /// cadence. pub fn poll(&mut self) -> Result> { let now = Instant::now(); let mut events = Vec::new(); - while let Some(event) = self.hub.receive_event_once()? { - match event { - CultNetRudpServerEvent::Connected { session } => { - events.push(MediaEvent::ProducerAttached { - remote: session.remote_addr, - }); - self.producer = Some(session); - } - CultNetRudpServerEvent::Disconnected { session, .. } => { - events.push(MediaEvent::ProducerDetached { - remote: session.remote_addr, - }); - if self.producer.as_ref().is_some_and(|producer| { - producer.session_generation == session.session_generation - }) { - self.producer = None; + while let Some(frame) = self.transport.receive_once()? { + if let Some(payload) = media_payload(frame) { + self.payloads += 1; + self.payload_bytes += payload.len() as u64; + match decode_media_wire_record(&payload) { + Ok(record) => events.extend(self.admit(record, now)), + Err(error) => { + self.undecodable += 1; + events.push(MediaEvent::Undecodable { + bytes: payload, + reason: format!("{error:#}"), + }); } } - CultNetRudpServerEvent::Frame { frame, .. } => { - if let Some(payload) = media_payload(frame) { - self.payloads += 1; - self.payload_bytes += payload.len() as u64; - match decode_media_wire_record(&payload) { - Ok(record) => events.extend(self.admit(record, now)), - Err(error) => { - self.undecodable += 1; - events.push(MediaEvent::Undecodable { - bytes: payload, - reason: format!("{error:#}"), - }); - } - } - } - } - _ => {} } } - self.hub.poll_resends()?; + self.transport.poll_resends()?; + events.extend(self.keep_dialling(now)?); let repairs = self.video.due_repairs(now); let expired = self.video.expire(now); @@ -202,17 +228,57 @@ impl RatatoskrReceiver { Ok(events) } + /// The attach/detach state machine. The transport knows whether its + /// session is up; this decides what to do about it. + fn keep_dialling(&mut self, now: Instant) -> Result> { + if !self.attached { + if self.transport.connected() { + self.attached = true; + self.pinged_at = now; + return Ok(Some(MediaEvent::ProducerAttached { remote: self.producer })); + } + if now.duration_since(self.dialled_at) >= self.redial_after { + self.redial(now)?; + } + return Ok(None); + } + let reason = if let Some(reason) = self.transport.disconnect_reason() { + Some(format!("producer disconnected: {}", String::from_utf8_lossy(reason))) + } else if self.transport.check_timeout(self.silence_timeout.as_millis() as u64) { + Some(format!("silent for {:?}", self.silence_timeout)) + } else { + None + }; + if let Some(reason) = reason { + self.attached = false; + self.redial(now)?; + return Ok(Some(MediaEvent::ProducerDetached { remote: self.producer, reason })); + } + if now.duration_since(self.pinged_at) >= self.silence_timeout / 3 { + self.pinged_at = now; + self.transport.ping(Vec::new())?; + } + Ok(None) + } + + fn redial(&mut self, now: Instant) -> Result<()> { + self.transport = dial(self.producer, &self.runtime_id, self.connection_id)?; + self.dialled_at = now; + self.redials += 1; + Ok(()) + } + fn send_feedback( &mut self, record: GameCultMediaReceiverFeedbackRecord, stored_at: &str, ) -> MediaEvent { - let Some(producer) = self.producer.as_ref() else { + if !self.attached { self.feedback.record_not_sent(); return MediaEvent::FeedbackNotSent { - reason: "no producer is attached".to_string(), + reason: "the producer has not answered".to_string(), }; - }; + } let wire = GameCultMediaWireRecord::Feedback(record); let encoded = encode_media_wire_record( &wire, @@ -223,7 +289,7 @@ impl RatatoskrReceiver { producer: RATATOSKR_MEDIA_PRODUCER, }, ) - .and_then(|payload| self.hub.send(producer, MEDIA_CHANNEL, payload)); + .and_then(|payload| self.transport.send(MEDIA_CHANNEL, payload)); let GameCultMediaWireRecord::Feedback(record) = wire else { unreachable!("constructed above"); }; @@ -308,7 +374,7 @@ impl RatatoskrReceiver { (self.payloads, self.payload_bytes) } - /// Payloads that arrived on the media channel and did not decode. A + /// Payloads that arrived on the media channels and did not decode. A /// non-zero count here means the producer and this build disagree about the /// envelope, which is worth knowing loudly. pub fn undecodable(&self) -> u64 { @@ -331,32 +397,61 @@ impl RatatoskrReceiver { } } -/// Frames on other channels belong to other conversations. +/// A fresh client session towards the producer. A new socket each time: a +/// session that has been given up on takes its sequence state with it. +fn dial(producer: SocketAddr, runtime_id: &str, connection_id: u32) -> Result { + let bind = if producer.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" }; + let socket = UdpSocket::bind(bind).with_context(|| format!("binding a socket to dial {producer}"))?; + socket + .set_nonblocking(true) + .context("setting the Ratatoskr media socket nonblocking")?; + let mut transport = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions::client( + runtime_id, + socket, + producer, + connection_id, + )) + .context("opening the Ratatoskr CultNet RUDP media client")?; + transport + .connect(runtime_id.as_bytes().to_vec()) + .with_context(|| format!("dialling media producer {producer}"))?; + Ok(transport) +} + +/// Frames on other channels belong to other conversations. Video and feedback +/// ride the media channel; audio has its own so it can be reliable. fn media_payload(frame: CultNetTransportFrame) -> Option> { - (frame.channel_id == MEDIA_CHANNEL && !frame.payload.is_empty()).then_some(frame.payload) + let media = frame.channel_id == MEDIA_CHANNEL || frame.channel_id == GAMECULT_MEDIA_AUDIO_CHANNEL; + (media && !frame.payload.is_empty()).then_some(frame.payload) } #[cfg(test)] mod tests { use super::*; - use std::time::Duration; use cultnet_rs::{ - CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, + CultNetRudpServerEvent, CultNetRudpServerHub, CultNetRudpServerHubOptions, CultNetTransportDelivery, GameCultMediaVideoAccessUnitRecord, }; const CONNECTION: u32 = 0x0BE0_0001; - fn loopback() -> ReceiverOptions { - ReceiverOptions { - bind: "127.0.0.1:0".parse().expect("parses"), - runtime_id: "ratatoskr-test".to_string(), - connection_id: CONNECTION, - video: VideoAssemblerOptions::default(), - feedback: FeedbackOptions::default(), - video_relay: None, - } + /// An address nobody answers on. + fn dead_producer() -> SocketAddr { + let socket = UdpSocket::bind("127.0.0.1:0").expect("binds"); + socket.local_addr().expect("addr") + } + + fn towards(producer: SocketAddr) -> ReceiverOptions { + ReceiverOptions::new(producer, "ratatoskr-test", CONNECTION) + } + + fn producer_hub() -> CultNetRudpServerHub { + let socket = UdpSocket::bind("127.0.0.1:0").expect("binds"); + socket.set_nonblocking(true).expect("nonblocking"); + let mut options = CultNetRudpServerHubOptions::new("producer-test", socket, CONNECTION); + options.media_delivery = Some(CultNetTransportDelivery::Unreliable); + CultNetRudpServerHub::new(options).expect("hub") } fn chunk(frame_id: u64, index: u16, count: u16, payload: Vec) -> GameCultMediaWireRecord { @@ -379,15 +474,16 @@ mod tests { } #[test] - fn a_receiver_binds_and_reports_where() { - let receiver = RatatoskrReceiver::open(loopback()).expect("opens"); - let addr = receiver.local_addr().expect("has an address"); - assert_ne!(addr.port(), 0, "an ephemeral bind must resolve to a real port"); + fn a_receiver_dials_and_says_where() { + let producer = dead_producer(); + let receiver = RatatoskrReceiver::open(towards(producer)).expect("opens"); + assert_eq!(receiver.producer(), producer); + assert!(!receiver.attached(), "nobody has answered"); } #[test] - fn polling_an_idle_receiver_yields_nothing_and_does_not_block() { - let mut receiver = RatatoskrReceiver::open(loopback()).expect("opens"); + fn polling_an_unanswered_receiver_yields_nothing_and_does_not_block() { + let mut receiver = RatatoskrReceiver::open(towards(dead_producer())).expect("opens"); assert!(receiver.poll().expect("polls").is_empty()); assert_eq!(receiver.delivered(), (0, 0)); assert_eq!(receiver.video_stats(), VideoStats::default()); @@ -403,13 +499,16 @@ mod tests { }), None ); - assert_eq!( - media_payload(CultNetTransportFrame { - channel_id: MEDIA_CHANNEL.to_string(), - payload: vec![1, 2, 3], - }), - Some(vec![1, 2, 3]) - ); + for channel in [MEDIA_CHANNEL, GAMECULT_MEDIA_AUDIO_CHANNEL] { + assert_eq!( + media_payload(CultNetTransportFrame { + channel_id: channel.to_string(), + payload: vec![1, 2, 3], + }), + Some(vec![1, 2, 3]), + "{channel}" + ); + } } /// An empty payload is not a delivery. Counting it would inflate the one @@ -429,7 +528,7 @@ mod tests { /// chunking is the transport's business and stops here. #[test] fn video_records_become_frames_and_audio_stays_as_sent() { - let mut receiver = RatatoskrReceiver::open(loopback()).expect("opens"); + let mut receiver = RatatoskrReceiver::open(towards(dead_producer())).expect("opens"); let now = Instant::now(); assert_eq!(receiver.admit(chunk(1, 0, 2, vec![1, 2]), now), None); let Some(MediaEvent::VideoFrame { frame }) = receiver.admit(chunk(1, 1, 2, vec![3]), now) else { @@ -463,7 +562,7 @@ mod tests { listener.set_read_timeout(Some(Duration::from_secs(2))).expect("timeout"); let mut receiver = RatatoskrReceiver::open(ReceiverOptions { video_relay: Some(listener.local_addr().expect("addr")), - ..loopback() + ..towards(dead_producer()) }) .expect("opens"); let now = Instant::now(); @@ -483,23 +582,63 @@ mod tests { repair_first_wait: Duration::ZERO, ..Default::default() }, - ..loopback() + ..towards(dead_producer()) }) .expect("opens"); assert_eq!(receiver.admit(chunk(1, 0, 3, vec![1]), Instant::now()), None); let events = receiver.poll().expect("polls"); assert!( - matches!(events.as_slice(), [MediaEvent::FeedbackNotSent { reason }] if reason.contains("no producer")), + matches!(events.as_slice(), [MediaEvent::FeedbackNotSent { reason }] if reason.contains("not answered")), "got {events:?}" ); assert_eq!(receiver.feedback_stats().not_sent, 1); } - /// The whole return path over real sockets: a producer connects, loses a - /// chunk on the way, and is told which one — then, when the frame is given - /// up on, that it was late and that a keyframe is wanted. + /// A producer that is not up yet is dialled again, not given up on: the + /// request that spins it up and the dial that reaches it race by design. + #[test] + fn a_receiver_keeps_dialling_until_the_producer_answers() -> Result<()> { + let producer = dead_producer(); + let mut receiver = RatatoskrReceiver::open(ReceiverOptions { + redial_after: Duration::from_millis(30), + ..towards(producer) + })?; + std::thread::sleep(Duration::from_millis(100)); + assert!(receiver.poll()?.is_empty()); + assert!(receiver.redials() >= 1, "the unanswered dial was repeated"); + + let socket = UdpSocket::bind(producer).context("rebinding the producer's port")?; + socket.set_nonblocking(true)?; + let mut hub = CultNetRudpServerHub::new(CultNetRudpServerHubOptions::new("producer-test", socket, CONNECTION))?; + let deadline = Instant::now() + Duration::from_secs(3); + let mut connect_payload = None; + loop { + while let Some(event) = hub.receive_event_once()? { + if let CultNetRudpServerEvent::Connected { session } = event { + connect_payload = Some(session.connect_payload); + } + } + hub.poll_resends()?; + let events = receiver.poll()?; + if events.iter().any(|event| matches!(event, MediaEvent::ProducerAttached { remote } if *remote == producer)) { + break; + } + assert!(Instant::now() < deadline, "the producer never attached; redials={}", receiver.redials()); + std::thread::sleep(Duration::from_millis(2)); + } + assert!(receiver.attached()); + assert_eq!(connect_payload.as_deref(), Some(b"ratatoskr-test".as_slice()), "the producer learns who dialled"); + Ok(()) + } + + /// The whole return path over real sockets: the receiver dials a producer + /// hub, a chunk is lost on the way, and the producer is told which one — + /// then, when the frame is given up on, that it was late and that a + /// keyframe is wanted. #[test] fn a_producer_is_told_what_was_lost() -> Result<()> { + let mut hub = producer_hub(); + let producer = hub.local_addr()?; let mut receiver = RatatoskrReceiver::open(ReceiverOptions { video: VideoAssemblerOptions { max_frame_age: Duration::from_millis(150), @@ -508,53 +647,47 @@ mod tests { repair_max_requests: 3, ..Default::default() }, - ..loopback() + ..towards(producer) })?; - let receiver_addr = receiver.local_addr()?; - - let socket = UdpSocket::bind("127.0.0.1:0")?; - socket.set_nonblocking(true)?; - let mut options = CultNetRudpSocketTransportOptions::client("producer-test", socket, receiver_addr, CONNECTION); - options.media_delivery = Some(CultNetTransportDelivery::Unreliable); - let mut producer = CultNetRudpSocketTransportConnection::new(options)?; - producer.connect(b"test".to_vec())?; fn pump( receiver: &mut RatatoskrReceiver, - producer: &mut CultNetRudpSocketTransportConnection, + hub: &mut CultNetRudpServerHub, feedback: &mut Vec, ) -> Result> { - let events = receiver.poll()?; - producer.poll_resends()?; - while let Some(frame) = producer.receive_once()? { - if frame.channel_id == MEDIA_CHANNEL { - if let Ok(GameCultMediaWireRecord::Feedback(record)) = decode_media_wire_record(&frame.payload) { - feedback.push(record); + while let Some(event) = hub.receive_event_once()? { + if let CultNetRudpServerEvent::Frame { frame, .. } = event { + if frame.channel_id == MEDIA_CHANNEL { + if let Ok(GameCultMediaWireRecord::Feedback(record)) = decode_media_wire_record(&frame.payload) { + feedback.push(record); + } } } } - Ok(events) + hub.poll_resends()?; + receiver.poll() } let mut feedback = Vec::new(); let deadline = Instant::now() + Duration::from_secs(3); - while !producer.connected() { - pump(&mut receiver, &mut producer, &mut feedback)?; - assert!(Instant::now() < deadline, "producer never connected"); + while !receiver.attached() { + pump(&mut receiver, &mut hub, &mut feedback)?; + assert!(Instant::now() < deadline, "the producer never answered"); std::thread::sleep(Duration::from_millis(2)); } + let session = hub.sessions().into_iter().next().expect("the receiver is a session"); // Three chunks; the middle one never leaves. let provenance = MediaWireProvenance { stored_at: "t", runtime_id: "producer-test", role: "producer", producer: "test" }; for index in [0u16, 2] { let record = chunk(9, index, 3, vec![index as u8; 4]); - producer.send(MEDIA_CHANNEL, encode_media_wire_record(&record, provenance.clone())?)?; + hub.send(&session, MEDIA_CHANNEL, encode_media_wire_record(&record, provenance.clone())?)?; } let deadline = Instant::now() + Duration::from_secs(3); let mut expired = false; while Instant::now() < deadline { - for event in pump(&mut receiver, &mut producer, &mut feedback)? { + for event in pump(&mut receiver, &mut hub, &mut feedback)? { if let MediaEvent::VideoFrameExpired { frame } = event { assert_eq!(frame.key.frame_id, 9); expired = true; @@ -585,4 +718,65 @@ mod tests { assert_eq!(receiver.video_stats().expired, 1); Ok(()) } + + /// Audio on its own channel is media too, and a producer that goes silent + /// is noticed and dialled again rather than waited on forever. + #[test] + fn audio_arrives_on_its_channel_and_silence_is_a_detach() -> Result<()> { + let mut hub = producer_hub(); + let producer = hub.local_addr()?; + let mut receiver = RatatoskrReceiver::open(ReceiverOptions { + silence_timeout: Duration::from_millis(300), + redial_after: Duration::from_millis(50), + ..towards(producer) + })?; + let deadline = Instant::now() + Duration::from_secs(3); + while !receiver.attached() { + while hub.receive_event_once()?.is_some() {} + hub.poll_resends()?; + receiver.poll()?; + assert!(Instant::now() < deadline, "never attached"); + std::thread::sleep(Duration::from_millis(2)); + } + let session = hub.sessions().into_iter().next().expect("session"); + let audio = GameCultMediaWireRecord::Audio(GameCultMediaAudioPacketRecord { + stream_id: "s".into(), + session_id: "x".into(), + packet_id: 1, + codec: "pcm-f32le-interleaved".into(), + pts_ticks: 0, + duration_ticks: 480, + timebase_num: 1, + timebase_den: 48_000, + deadline_ticks: 480, + payload: vec![4; 16], + }); + let provenance = MediaWireProvenance { stored_at: "t", runtime_id: "producer-test", role: "producer", producer: "test" }; + hub.send(&session, GAMECULT_MEDIA_AUDIO_CHANNEL, encode_media_wire_record(&audio, provenance)?)?; + let deadline = Instant::now() + Duration::from_secs(3); + let mut heard = false; + while !heard { + while hub.receive_event_once()?.is_some() {} + hub.poll_resends()?; + heard = receiver.poll()?.iter().any(|event| matches!(event, MediaEvent::Audio { record } if record.payload == vec![4; 16])); + assert!(Instant::now() < deadline, "audio never arrived"); + std::thread::sleep(Duration::from_millis(2)); + } + + // The producer stops answering: no pumps, no pongs. + drop(hub); + let deadline = Instant::now() + Duration::from_secs(3); + loop { + let events = receiver.poll()?; + if let Some(MediaEvent::ProducerDetached { reason, .. }) = events.iter().find(|event| matches!(event, MediaEvent::ProducerDetached { .. })) { + assert!(reason.contains("silent"), "{reason}"); + break; + } + assert!(Instant::now() < deadline, "silence was never noticed"); + std::thread::sleep(Duration::from_millis(5)); + } + assert!(!receiver.attached()); + assert!(receiver.redials() >= 1, "and it dialled again"); + Ok(()) + } } diff --git a/crates/ratatoskr-core/tests/catalog.rs b/crates/ratatoskr-core/tests/catalog.rs index f0cc299..1fdab27 100644 --- a/crates/ratatoskr-core/tests/catalog.rs +++ b/crates/ratatoskr-core/tests/catalog.rs @@ -144,6 +144,7 @@ fn advertisement(stream_id: &str) -> GameCultMediaStreamAdvertisementRecord { default_video_bitrate_kbps: 12_000, default_latency_budget_ms: 250, media_packet_bytes: 848, + media_endpoint: "10.77.0.2:5220".into(), media_connection_id: 0x6d75_0001, updated_at: "2026-09-10T00:00:00Z".into(), } @@ -176,12 +177,12 @@ fn the_picker_sees_what_advertises_and_a_request_comes_back_answered() -> Result assert_eq!(pulled.rejected.len(), 1); assert_eq!(pulled.rejected[0].0, "broken"); assert_eq!(pulled.streams[0].audio_channels, 2); + assert_eq!(pulled.streams[0].media_endpoint, "10.77.0.2:5220", "where to dial comes from the advertisement"); // Ask for it, then read back what the mesh holds under the request key. let request = start_request( &pulled.streams[0], "starfire.obs", - "192.168.178.146:5204".parse()?, "display:0", "wasapi-loopback:Realtek", "h264", @@ -209,7 +210,7 @@ fn the_picker_sees_what_advertises_and_a_request_comes_back_answered() -> Result fn a_request_that_names_a_source_without_a_codec_is_refused_before_it_leaves() -> Result<()> { let odin = Odin::start()?; let options = options(&odin, "starfire.obs"); - let mut request = start_request(&advertisement("s"), "starfire.obs", "127.0.0.1:1".parse()?, "display:0", "", "h264", "", 0, 0, "t"); + let mut request = start_request(&advertisement("s"), "starfire.obs", "display:0", "", "h264", "", 0, 0, "t"); request.video_codec.clear(); let error = publish_request(&options, &request).unwrap_err(); assert!(error.to_string().contains("codec"), "{error}"); diff --git a/plugin/data/locale/en-US.ini b/plugin/data/locale/en-US.ini index 23cb3a4..311f223 100644 --- a/plugin/data/locale/en-US.ini +++ b/plugin/data/locale/en-US.ini @@ -1,7 +1,6 @@ RatatoskrSource="CultMesh Media Stream" Ratatoskr.Odin="Odin (rudp://host:port)" Ratatoskr.ReceiverId="Receiver id" -Ratatoskr.ReceiverHost="This host, as the producer reaches it" Ratatoskr.Stream="Stream" Ratatoskr.VideoSource="Video source" Ratatoskr.AudioSource="Audio source" diff --git a/plugin/include/ratatoskr.h b/plugin/include/ratatoskr.h index 02ef4a3..75b1e90 100644 --- a/plugin/include/ratatoskr.h +++ b/plugin/include/ratatoskr.h @@ -38,11 +38,14 @@ extern "C" { typedef struct RatatoskrHandle RatatoskrHandle; -/* Opens a media receiver. `video_relay` may be NULL, or a "host:port" that - * every whole video access unit is also copied to as a raw byte stream over - * UDP, for a local decoder that reads one (OBS's own ffmpeg source does). - * Release with ratatoskr_receiver_close exactly once. */ -int ratatoskr_receiver_open(const char *bind, +/* Dials the producer at `producer` ("host:port": the advertised media_endpoint) + * and keeps dialling until it answers, so it may be opened before the + * producer has started. This host admits nothing inbound. `video_relay` may + * be NULL, or a "host:port" that every whole video access unit is also + * copied to as a raw byte stream over UDP, for a local decoder that reads one + * (OBS's own ffmpeg source does). Release with ratatoskr_receiver_close + * exactly once. */ +int ratatoskr_receiver_open(const char *producer, const char *runtime_id, unsigned int connection_id, const char *video_relay, @@ -67,8 +70,8 @@ int ratatoskr_receiver_next_payload(RatatoskrHandle *handle, * the producer and this build disagree about the envelope. */ uint64_t ratatoskr_receiver_undecodable(RatatoskrHandle *handle); -/* The port actually bound; 0 if unavailable. */ -uint16_t ratatoskr_receiver_local_port(RatatoskrHandle *handle); +/* 1 while the producer has answered and not since gone quiet, else 0. */ +int ratatoskr_receiver_attached(RatatoskrHandle *handle); /* Payloads and bytes actually delivered, never what was requested. Either out * pointer may be NULL. */ @@ -124,7 +127,8 @@ typedef struct RatatoskrStreamInfo { uint32_t default_video_bitrate_kbps; uint32_t default_latency_budget_ms; uint32_t media_packet_bytes; - uint32_t media_connection_id; /* the producer dials the receiver with this */ + const char *media_endpoint; /* "host:port" the producer serves from */ + uint32_t media_connection_id; /* dial media_endpoint with this */ } RatatoskrStreamInfo; /* Pulls every advertised stream from Odin ("rudp://host:port" or "host:port"). @@ -144,13 +148,12 @@ int ratatoskr_catalog_stream(const RatatoskrCatalog *catalog, size_t index, RatatoskrStreamInfo *out_info); -/* Asks the producer of stream `index` to serve it to receiver_endpoint - * ("host:port" where this receiver listens, as the producer reaches it). +/* Asks the producer of stream `index` to serve it. This receiver is known to + * the producer by the catalog's runtime id; it dials media_endpoint itself. * Empty source ids mean none of that kind; zero bitrate or latency means the * producer's default. Blocks for the publish. */ int ratatoskr_request_start(const RatatoskrCatalog *catalog, size_t index, - const char *receiver_endpoint, const char *video_source_id, const char *audio_source_id, const char *video_codec, diff --git a/plugin/src/ratatoskr_source.c b/plugin/src/ratatoskr_source.c index af8cfa7..f9a005b 100644 --- a/plugin/src/ratatoskr_source.c +++ b/plugin/src/ratatoskr_source.c @@ -26,7 +26,6 @@ OBS_MODULE_USE_DEFAULT_LOCALE("ratatoskr", "en-US") #define SETTING_ODIN "odin" #define SETTING_RECEIVER_ID "receiver_id" -#define SETTING_RECEIVER_HOST "receiver_host" #define SETTING_STREAM "stream_id" #define SETTING_VIDEO_SOURCE "video_source_id" #define SETTING_AUDIO_SOURCE "audio_source_id" @@ -45,7 +44,6 @@ struct ratatoskr_source { /* settings as last applied */ char *odin; char *receiver_id; - char *receiver_host; char *stream_id; char *video_source_id; char *audio_source_id; @@ -261,35 +259,35 @@ static void start_stream(struct ratatoskr_source *ctx) ctx->audio_channels = info.audio_channels; ctx->relay_port = wants_video ? ratatoskr_free_udp_port() : 0; + /* Ask first, then dial: the request spins the producer up and the dial + * is repeated until it answers. Nothing here listens. */ + pthread_mutex_lock(&ctx->catalog_mutex); + int rc = ratatoskr_request_start(ctx->catalog, index, wants_video ? ctx->video_source_id : NONE_ID, + wants_audio ? ctx->audio_source_id : NONE_ID, ctx->video_codec, ctx->audio_codec, + ctx->bitrate_kbps, ctx->latency_ms); + pthread_mutex_unlock(&ctx->catalog_mutex); + if (rc != RATATOSKR_OK) { + log_last_error("start request failed"); + return; + } + blog(LOG_INFO, "[ratatoskr] asked %s for %s (video=%s audio=%s %s/%s %u kbps, %u ms); dialling %s", + info.producer_id, ctx->stream_id, wants_video ? ctx->video_source_id : "-", + wants_audio ? ctx->audio_source_id : "-", ctx->video_codec, ctx->audio_codec, ctx->bitrate_kbps, + ctx->latency_ms, info.media_endpoint); + char relay[64] = {0}; if (wants_video) snprintf(relay, sizeof(relay), "127.0.0.1:%u", (unsigned)ctx->relay_port); - int rc = ratatoskr_receiver_open("0.0.0.0:0", ctx->receiver_id, info.media_connection_id, - wants_video ? relay : NULL, &ctx->receiver); + rc = ratatoskr_receiver_open(info.media_endpoint, ctx->receiver_id, info.media_connection_id, + wants_video ? relay : NULL, &ctx->receiver); if (rc != RATATOSKR_OK) { log_last_error("receiver open failed"); + stop_stream(ctx); return; } if (wants_video) create_video_child(ctx); - char endpoint[512]; - snprintf(endpoint, sizeof(endpoint), "%s:%u", ctx->receiver_host, - (unsigned)ratatoskr_receiver_local_port(ctx->receiver)); - pthread_mutex_lock(&ctx->catalog_mutex); - rc = ratatoskr_request_start(ctx->catalog, index, endpoint, wants_video ? ctx->video_source_id : NONE_ID, - wants_audio ? ctx->audio_source_id : NONE_ID, ctx->video_codec, ctx->audio_codec, - ctx->bitrate_kbps, ctx->latency_ms); - pthread_mutex_unlock(&ctx->catalog_mutex); - if (rc != RATATOSKR_OK) { - log_last_error("start request failed"); - stop_stream(ctx); - return; - } - blog(LOG_INFO, "[ratatoskr] asked %s for %s -> %s (video=%s audio=%s %s/%s %u kbps, %u ms)", info.producer_id, - ctx->stream_id, endpoint, wants_video ? ctx->video_source_id : "-", wants_audio ? ctx->audio_source_id : "-", - ctx->video_codec, ctx->audio_codec, ctx->bitrate_kbps, ctx->latency_ms); - ctx->pump_running = true; if (pthread_create(&ctx->pump, NULL, pump_loop, ctx) != 0) { ctx->pump_running = false; @@ -310,7 +308,6 @@ static void ratatoskr_get_defaults(obs_data_t *settings) { obs_data_set_default_string(settings, SETTING_ODIN, DEFAULT_ODIN); obs_data_set_default_string(settings, SETTING_RECEIVER_ID, "obs"); - obs_data_set_default_string(settings, SETTING_RECEIVER_HOST, "127.0.0.1"); obs_data_set_default_string(settings, SETTING_VIDEO_CODEC, "h264"); obs_data_set_default_string(settings, SETTING_AUDIO_CODEC, "pcm-f32le-interleaved"); obs_data_set_default_int(settings, SETTING_BITRATE, 0); @@ -321,7 +318,6 @@ static void apply_settings(struct ratatoskr_source *ctx, obs_data_t *settings) { set_string(&ctx->odin, obs_data_get_string(settings, SETTING_ODIN)); set_string(&ctx->receiver_id, obs_data_get_string(settings, SETTING_RECEIVER_ID)); - set_string(&ctx->receiver_host, obs_data_get_string(settings, SETTING_RECEIVER_HOST)); set_string(&ctx->stream_id, obs_data_get_string(settings, SETTING_STREAM)); set_string(&ctx->video_source_id, obs_data_get_string(settings, SETTING_VIDEO_SOURCE)); set_string(&ctx->audio_source_id, obs_data_get_string(settings, SETTING_AUDIO_SOURCE)); @@ -351,7 +347,6 @@ static void ratatoskr_destroy(void *data) bfree(ctx->buffer); bfree(ctx->odin); bfree(ctx->receiver_id); - bfree(ctx->receiver_host); bfree(ctx->stream_id); bfree(ctx->video_source_id); bfree(ctx->audio_source_id); @@ -483,8 +478,6 @@ static obs_properties_t *ratatoskr_get_properties(void *data) obs_properties_add_text(props, SETTING_ODIN, obs_module_text("Ratatoskr.Odin"), OBS_TEXT_DEFAULT); obs_properties_add_text(props, SETTING_RECEIVER_ID, obs_module_text("Ratatoskr.ReceiverId"), OBS_TEXT_DEFAULT); - obs_properties_add_text(props, SETTING_RECEIVER_HOST, obs_module_text("Ratatoskr.ReceiverHost"), - OBS_TEXT_DEFAULT); obs_properties_add_button(props, "refresh", obs_module_text("Ratatoskr.Refresh"), on_refresh); obs_property_t *streams = obs_properties_add_list(props, SETTING_STREAM, obs_module_text("Ratatoskr.Stream"), diff --git a/plugin/tests/abi_smoke.c b/plugin/tests/abi_smoke.c index 1045f21..7cb88fe 100644 --- a/plugin/tests/abi_smoke.c +++ b/plugin/tests/abi_smoke.c @@ -19,7 +19,7 @@ static void check(int ok, const char *what) typedef int (*open_fn)(const char *, const char *, unsigned int, const char *, RatatoskrHandle **); typedef int (*poll_fn)(RatatoskrHandle *); typedef int (*next_fn)(RatatoskrHandle *, uint8_t *, size_t, size_t *, int *, int64_t *); -typedef uint16_t (*port_fn)(RatatoskrHandle *); +typedef int (*attached_fn)(RatatoskrHandle *); typedef void (*delivered_fn)(RatatoskrHandle *, uint64_t *, uint64_t *); typedef size_t (*err_fn)(char *, size_t); typedef void (*close_fn)(RatatoskrHandle *); @@ -35,19 +35,20 @@ int main(int argc, char **argv) open_fn r_open = (open_fn)(void *)GetProcAddress(lib, "ratatoskr_receiver_open"); poll_fn r_poll = (poll_fn)(void *)GetProcAddress(lib, "ratatoskr_receiver_poll"); next_fn r_next = (next_fn)(void *)GetProcAddress(lib, "ratatoskr_receiver_next_payload"); - port_fn r_port = (port_fn)(void *)GetProcAddress(lib, "ratatoskr_receiver_local_port"); + attached_fn r_attached = (attached_fn)(void *)GetProcAddress(lib, "ratatoskr_receiver_attached"); delivered_fn r_delivered = (delivered_fn)(void *)GetProcAddress(lib, "ratatoskr_receiver_delivered"); err_fn r_err = (err_fn)(void *)GetProcAddress(lib, "ratatoskr_last_error"); close_fn r_close = (close_fn)(void *)GetProcAddress(lib, "ratatoskr_receiver_close"); - check(r_open && r_poll && r_next && r_port && r_delivered && r_err && r_close, + check(r_open && r_poll && r_next && r_attached && r_delivered && r_err && r_close, "every documented symbol is exported"); if (failures) { printf("ABI SMOKE FAILED\n"); return 1; } RatatoskrHandle *handle = NULL; - check(r_open("127.0.0.1:0", "ratatoskr-abi-smoke", 0x0BE00001u, NULL, &handle) == RATATOSKR_OK, - "open returns OK"); + /* nobody listens on port 9; the dial is sent, not answered */ + check(r_open("127.0.0.1:9", "ratatoskr-abi-smoke", 0x0BE00001u, NULL, &handle) == RATATOSKR_OK, + "open returns OK without waiting for an answer"); check(handle != NULL, "open yields a handle"); - check(r_port(handle) != 0, "ephemeral bind resolves to a real port"); + check(r_attached(handle) == 0, "an unanswered dial is not attached"); check(r_poll(handle) == 0, "idle poll reports nothing waiting"); size_t out_len = 12345; @@ -70,14 +71,14 @@ int main(int argc, char **argv) handle = NULL; check(r_open("not-an-address", "x", 1, NULL, &handle) == RATATOSKR_ERR_ARGUMENT, - "a bad bind address is refused"); + "a bad producer endpoint is refused"); check(handle == NULL, "a refused open leaves no handle"); char message[256]; check(r_err(message, sizeof message) > 0, "a failure leaves a message"); check(strstr(message, "not-an-address") != NULL, "the message names the bad input"); - check(r_open("127.0.0.1:0", "x", 1, "not-a-relay", &handle) == RATATOSKR_ERR_ARGUMENT, + check(r_open("127.0.0.1:9", "x", 1, "not-a-relay", &handle) == RATATOSKR_ERR_ARGUMENT, "a bad video relay is refused"); free_port_fn r_free_port = (free_port_fn)(void *)GetProcAddress(lib, "ratatoskr_free_udp_port"); @@ -89,7 +90,7 @@ int main(int argc, char **argv) r_close(NULL); check(r_poll(NULL) == RATATOSKR_ERR_ARGUMENT, "null handle is refused"); - check(r_port(NULL) == 0, "null handle reports no port"); + check(r_attached(NULL) == 0, "null handle is not attached"); printf("%s\n", failures ? "ABI SMOKE FAILED" : "ABI SMOKE PASSED"); return failures ? 1 : 0;