pub(crate) mod frame;
pub(crate) mod runner;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use fast_talker::options::{SocketOption, ThreadOption};
use parking_lot::Mutex;
use crate::gige::ControlPort;
use crate::gige::proto::bootstrap;
use crate::link::LinkCounters;
use crate::thread_util::ThreadHandle;
use crate::tuning::TuningReport;
pub use frame::{Frame, FrameStatus, PayloadKind};
#[cfg_attr(feature = "valuable", derive(valuable::Valuable))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum PacketSize {
#[default]
Auto,
Fixed(u16),
}
#[cfg_attr(feature = "valuable", derive(valuable::Valuable))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum ResendPolicy {
#[default]
Always,
Never,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StreamConfig {
pub channel: u16,
pub payload_size: Option<usize>,
pub n_buffers: usize,
pub packet_size: PacketSize,
pub packet_delay: Option<u32>,
pub resend: ResendPolicy,
pub initial_packet_timeout: Duration,
pub packet_timeout: Duration,
pub frame_retention: Duration,
pub packet_request_ratio: f64,
pub local_addr: Option<SocketAddr>,
pub thread: Vec<ThreadOption>,
pub stream_socket: Vec<SocketOption>,
}
pub const DEFAULT_STREAM_RECV_BUFFER: usize = 8 * 1024 * 1024;
impl Default for StreamConfig {
fn default() -> Self {
Self::new()
}
}
impl StreamConfig {
pub fn new() -> Self {
Self {
channel: 0,
payload_size: None,
n_buffers: 8,
packet_size: PacketSize::Auto,
packet_delay: None,
resend: ResendPolicy::Always,
initial_packet_timeout: Duration::from_millis(1),
packet_timeout: Duration::from_millis(20),
frame_retention: Duration::from_millis(100),
packet_request_ratio: 0.25,
local_addr: None,
thread: Vec::new(),
stream_socket: Vec::new(),
}
}
pub(crate) fn stream_socket_options(&self) -> Vec<SocketOption> {
let own_buffer = self
.stream_socket
.iter()
.any(|o| matches!(o, SocketOption::RecvBuffer(_)));
let default = (!own_buffer).then_some(SocketOption::RecvBuffer(DEFAULT_STREAM_RECV_BUFFER));
default
.into_iter()
.chain(self.stream_socket.iter().cloned())
.collect()
}
pub(crate) fn channel_base(&self) -> u32 {
u32::from(self.channel) * bootstrap::STREAM_CHANNEL_STRIDE
}
}
#[cfg_attr(feature = "valuable", derive(valuable::Valuable))]
#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "py", pyo3::pyclass(get_all, skip_from_py_object))]
pub struct StreamStats {
pub packets: u64,
pub bytes: u64,
pub completed_frames: u64,
pub failed_frames: u64,
pub timed_out_frames: u64,
pub aborted_frames: u64,
pub missing_frames: u64,
pub underruns: u64,
pub missing_packets: u64,
pub resend_requests: u64,
pub resent_packets: u64,
pub resend_ratio_reached: u64,
pub resend_disabled: u64,
pub duplicated_packets: u64,
pub error_packets: u64,
pub ignored_packets: u64,
pub unsupported_frames: u64,
pub size_mismatch_errors: u64,
pub frames_dropped: u64,
pub socket_drops: u64,
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "py", pyo3::pyclass(skip_from_py_object))]
pub struct FrameChannel {
rx: flume::Receiver<Arc<Frame>>,
}
impl FrameChannel {
pub(crate) fn new(rx: flume::Receiver<Arc<Frame>>) -> Self {
Self { rx }
}
pub fn wait_for(&self, timeout: Duration) -> Option<Arc<Frame>> {
self.rx.recv_timeout(timeout).ok()
}
pub fn try_recv(&self) -> Option<Arc<Frame>> {
self.rx.try_recv().ok()
}
pub fn recv_all(&self) -> Vec<Arc<Frame>> {
let mut out = Vec::new();
while let Ok(f) = self.rx.try_recv() {
out.push(f);
}
out
}
pub fn clear(&self) {
while self.rx.try_recv().is_ok() {}
}
pub fn is_disconnected(&self) -> bool {
self.rx.is_disconnected()
}
pub async fn recv_async(&self) -> Option<Arc<Frame>> {
self.rx.recv_async().await.ok()
}
}
pub(crate) struct StreamShared {
pub stats: Mutex<StreamStats>,
pub link: Arc<LinkCounters>,
}
pub struct StreamChannel {
pub(crate) to_worker: flume::Sender<runner::ToStreamWorker>,
pub(crate) thread: ThreadHandle,
pub(crate) shared: Arc<StreamShared>,
pub(crate) control: ControlPort,
pub(crate) channel_base: u32,
pub(crate) packet_size: u16,
pub(crate) local_addr: SocketAddr,
pub(crate) tuning: TuningReport,
}
impl std::fmt::Debug for StreamChannel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StreamChannel")
.field("local_addr", &self.local_addr)
.field("packet_size", &self.packet_size)
.finish()
}
}
impl StreamChannel {
pub fn subscribe(&self, capacity: usize) -> FrameChannel {
let (tx, rx) = flume::bounded(capacity);
let _ = self.to_worker.send(runner::ToStreamWorker::Subscribe(tx));
self.thread.wake().ok();
FrameChannel::new(rx)
}
pub fn stats(&self) -> StreamStats {
*self.shared.stats.lock()
}
pub fn packet_size(&self) -> u16 {
self.packet_size
}
pub fn local_addr(&self) -> SocketAddr {
self.local_addr
}
pub fn tuning_report(&self) -> &TuningReport {
&self.tuning
}
pub fn is_running(&self) -> bool {
self.thread.is_alive()
}
}
impl Drop for StreamChannel {
fn drop(&mut self) {
let _ = self
.control
.write_register(bootstrap::STREAM_CHANNEL_PORT + self.channel_base, 0)
.wait_timeout(self.control.budget());
let _ = self.to_worker.send(runner::ToStreamWorker::Shutdown);
self.thread.wake().ok();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_receive_buffer_is_added_to_other_options() {
let cfg = StreamConfig {
stream_socket: vec![SocketOption::LinuxBusyPoll(50)],
..StreamConfig::new()
};
assert_eq!(
cfg.stream_socket_options(),
[
SocketOption::RecvBuffer(DEFAULT_STREAM_RECV_BUFFER),
SocketOption::LinuxBusyPoll(50),
]
);
assert_eq!(
StreamConfig::new().stream_socket_options(),
[SocketOption::RecvBuffer(DEFAULT_STREAM_RECV_BUFFER)]
);
}
#[test]
fn own_receive_buffer_replaces_the_default() {
let cfg = StreamConfig {
stream_socket: vec![
SocketOption::LinuxBusyPoll(50),
SocketOption::RecvBuffer(1 << 20),
],
..StreamConfig::new()
};
assert_eq!(cfg.stream_socket_options(), cfg.stream_socket);
}
}