rvoip_rtp_core/api/common/buffer/
mod.rs

1//! Common buffer functionality
2//!
3//! This module contains buffer management functionality shared between client and server.
4
5use std::sync::Arc;
6use std::time::Duration;
7use async_trait::async_trait;
8
9use crate::api::common::frame::MediaFrame;
10use crate::api::common::error::BufferError;
11
12mod media_buffer_impl;
13pub use media_buffer_impl::DefaultMediaBuffer;
14
15/// Media buffer configuration
16#[derive(Debug, Clone)]
17pub struct MediaBufferConfig {
18    /// Jitter buffer minimum delay in milliseconds
19    pub min_delay_ms: u32,
20    
21    /// Jitter buffer maximum delay in milliseconds
22    pub max_delay_ms: u32,
23    
24    /// Whether to use adaptive jitter buffer sizing
25    pub adaptive: bool,
26    
27    /// Target jitter buffer occupancy percentage (0-100)
28    pub target_occupancy: u8,
29    
30    /// Maximum number of packets that can be stored
31    pub max_packet_count: usize,
32    
33    /// Transmit buffer maximum latency in milliseconds
34    pub transmit_max_latency_ms: u32,
35    
36    /// Whether to prioritize I-frames for video
37    pub prioritize_keyframes: bool,
38}
39
40impl Default for MediaBufferConfig {
41    fn default() -> Self {
42        Self {
43            min_delay_ms: 20,
44            max_delay_ms: 120,
45            adaptive: true,
46            target_occupancy: 50,
47            max_packet_count: 1000,
48            transmit_max_latency_ms: 100,
49            prioritize_keyframes: true,
50        }
51    }
52}
53
54/// Buffer statistics
55#[derive(Debug, Clone)]
56pub struct BufferStats {
57    /// Current buffer delay in milliseconds
58    pub current_delay_ms: u32,
59    
60    /// Current number of packets in buffer
61    pub packet_count: usize,
62    
63    /// Maximum delay seen in the current session
64    pub max_delay_seen_ms: u32,
65    
66    /// Minimum delay seen in the current session
67    pub min_delay_seen_ms: u32,
68    
69    /// Number of late packets (arrived too late to be used)
70    pub late_packet_count: u64,
71    
72    /// Number of packets discarded due to buffer overflow
73    pub overflow_discard_count: u64,
74    
75    /// Average occupancy percentage
76    pub average_occupancy: f32,
77    
78    /// Number of buffer underruns
79    pub underrun_count: u64,
80}
81
82/// Media buffer interface for jitter buffering and transmit buffering
83#[async_trait]
84pub trait MediaBuffer: Send + Sync {
85    /// Put a media frame into the buffer
86    async fn put_frame(&self, frame: MediaFrame) -> Result<(), BufferError>;
87    
88    /// Get the next media frame from the buffer, waiting up to the specified timeout
89    async fn get_frame(&self, timeout: Duration) -> Result<MediaFrame, BufferError>;
90    
91    /// Get current buffer statistics
92    async fn get_stats(&self) -> BufferStats;
93    
94    /// Reset the buffer, discarding all frames
95    async fn reset(&self) -> Result<(), BufferError>;
96    
97    /// Flush the buffer, returning all frames in order
98    async fn flush(&self) -> Result<Vec<MediaFrame>, BufferError>;
99    
100    /// Update buffer configuration
101    async fn update_config(&self, config: MediaBufferConfig) -> Result<(), BufferError>;
102}
103
104/// Builder for MediaBufferConfig
105pub struct MediaBufferConfigBuilder {
106    config: MediaBufferConfig,
107}
108
109impl MediaBufferConfigBuilder {
110    /// Create a new builder with default configuration
111    pub fn new() -> Self {
112        Self {
113            config: MediaBufferConfig::default(),
114        }
115    }
116    
117    /// Apply a network preset
118    pub fn preset(mut self, preset: crate::api::common::config::NetworkPreset) -> Self {
119        use crate::api::common::config::NetworkPreset;
120        match preset {
121            NetworkPreset::LowLatency => {
122                self.config.min_delay_ms = 10;
123                self.config.max_delay_ms = 50;
124                self.config.adaptive = false;
125                self.config.target_occupancy = 30;
126            },
127            NetworkPreset::Balanced => {
128                // Default values are already balanced
129            },
130            NetworkPreset::Resilient => {
131                self.config.min_delay_ms = 50;
132                self.config.max_delay_ms = 200;
133                self.config.adaptive = true;
134                self.config.target_occupancy = 70;
135            },
136            NetworkPreset::HighProtection => {
137                self.config.min_delay_ms = 100;
138                self.config.max_delay_ms = 500;
139                self.config.adaptive = true;
140                self.config.target_occupancy = 80;
141            },
142        }
143        self
144    }
145    
146    /// Set audio specific preset
147    pub fn audio(mut self) -> Self {
148        // Audio typically needs less buffering but is more sensitive to jitter
149        self.config.min_delay_ms = 20;
150        self.config.max_delay_ms = 120;
151        self.config.target_occupancy = 50;
152        self
153    }
154    
155    /// Set video specific preset
156    pub fn video(mut self) -> Self {
157        // Video can tolerate more latency but needs more buffer space
158        self.config.min_delay_ms = 50;
159        self.config.max_delay_ms = 300;
160        self.config.target_occupancy = 60;
161        self.config.max_packet_count = 5000;
162        self.config.prioritize_keyframes = true;
163        self
164    }
165    
166    /// Set minimum delay in milliseconds
167    pub fn min_delay_ms(mut self, delay: u32) -> Self {
168        self.config.min_delay_ms = delay;
169        self
170    }
171    
172    /// Set maximum delay in milliseconds
173    pub fn max_delay_ms(mut self, delay: u32) -> Self {
174        self.config.max_delay_ms = delay;
175        self
176    }
177    
178    /// Set whether to use adaptive jitter buffer sizing
179    pub fn adaptive(mut self, adaptive: bool) -> Self {
180        self.config.adaptive = adaptive;
181        self
182    }
183    
184    /// Set target buffer occupancy percentage (0-100)
185    pub fn target_occupancy(mut self, occupancy: u8) -> Self {
186        self.config.target_occupancy = occupancy.min(100);
187        self
188    }
189    
190    /// Set maximum packet count
191    pub fn max_packet_count(mut self, count: usize) -> Self {
192        self.config.max_packet_count = count;
193        self
194    }
195    
196    /// Set transmit buffer maximum latency in milliseconds
197    pub fn transmit_max_latency_ms(mut self, latency: u32) -> Self {
198        self.config.transmit_max_latency_ms = latency;
199        self
200    }
201    
202    /// Set whether to prioritize keyframes for video
203    pub fn prioritize_keyframes(mut self, prioritize: bool) -> Self {
204        self.config.prioritize_keyframes = prioritize;
205        self
206    }
207    
208    /// Build the configuration
209    pub fn build(self) -> Result<MediaBufferConfig, BufferError> {
210        // Validate configuration
211        if self.config.min_delay_ms > self.config.max_delay_ms {
212            return Err(BufferError::ConfigurationError(
213                "Minimum delay must be less than or equal to maximum delay".to_string()
214            ));
215        }
216        
217        if self.config.max_packet_count == 0 {
218            return Err(BufferError::ConfigurationError(
219                "Maximum packet count must be greater than zero".to_string()
220            ));
221        }
222        
223        Ok(self.config)
224    }
225}
226
227/// Factory for creating MediaBuffer instances
228pub struct MediaBufferFactory;
229
230impl MediaBufferFactory {
231    /// Create a new MediaBuffer
232    pub fn create_buffer(
233        config: MediaBufferConfig,
234    ) -> Result<Arc<dyn MediaBuffer>, BufferError> {
235        let buffer = media_buffer_impl::DefaultMediaBuffer::new(config)?;
236        Ok(buffer as Arc<dyn MediaBuffer>)
237    }
238}