oximedia-net 0.1.5

Network streaming for OxiMedia
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! WebRTC Data Channel implementation.
//!
//! This module provides data channel functionality over SCTP/DTLS.

#![allow(dead_code)]
#![allow(clippy::too_many_arguments)]

use super::dtls::DtlsConnection;
use super::sctp::{Association, AssociationState};
use crate::error::{NetError, NetResult};
use bytes::Bytes;
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc;

/// Data channel state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DataChannelState {
    /// Connecting.
    Connecting,
    /// Open.
    Open,
    /// Closing.
    Closing,
    /// Closed.
    Closed,
}

/// Data channel configuration.
#[derive(Debug, Clone)]
pub struct DataChannelConfig {
    /// Channel label.
    pub label: String,
    /// Ordered delivery.
    pub ordered: bool,
    /// Max packet lifetime (ms).
    pub max_packet_lifetime: Option<u32>,
    /// Max retransmits.
    pub max_retransmits: Option<u32>,
    /// Protocol.
    pub protocol: String,
    /// Negotiated.
    pub negotiated: bool,
    /// Stream ID.
    pub id: Option<u16>,
}

impl Default for DataChannelConfig {
    fn default() -> Self {
        Self {
            label: String::new(),
            ordered: true,
            max_packet_lifetime: None,
            max_retransmits: None,
            protocol: String::new(),
            negotiated: false,
            id: None,
        }
    }
}

impl DataChannelConfig {
    /// Creates a new configuration.
    #[must_use]
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            ..Default::default()
        }
    }

    /// Sets ordered delivery.
    #[must_use]
    pub const fn ordered(mut self, ordered: bool) -> Self {
        self.ordered = ordered;
        self
    }

    /// Sets max packet lifetime.
    #[must_use]
    pub const fn max_packet_lifetime(mut self, lifetime: u32) -> Self {
        self.max_packet_lifetime = Some(lifetime);
        self
    }

    /// Sets max retransmits.
    #[must_use]
    pub const fn max_retransmits(mut self, retransmits: u32) -> Self {
        self.max_retransmits = Some(retransmits);
        self
    }

    /// Sets protocol.
    #[must_use]
    pub fn protocol(mut self, protocol: impl Into<String>) -> Self {
        self.protocol = protocol.into();
        self
    }

    /// Sets stream ID.
    #[must_use]
    pub const fn id(mut self, id: u16) -> Self {
        self.id = Some(id);
        self
    }
}

/// Data channel message type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MessageType {
    /// Text message.
    Text,
    /// Binary message.
    Binary,
}

/// Data channel message.
#[derive(Debug, Clone)]
pub struct Message {
    /// Message type.
    pub message_type: MessageType,
    /// Message data.
    pub data: Bytes,
}

impl Message {
    /// Creates a text message.
    #[must_use]
    pub fn text(data: impl Into<String>) -> Self {
        Self {
            message_type: MessageType::Text,
            data: Bytes::from(data.into()),
        }
    }

    /// Creates a binary message.
    #[must_use]
    pub fn binary(data: impl Into<Bytes>) -> Self {
        Self {
            message_type: MessageType::Binary,
            data: data.into(),
        }
    }

    /// Returns the message as a string (if text).
    #[must_use]
    pub fn as_text(&self) -> Option<String> {
        if self.message_type == MessageType::Text {
            String::from_utf8(self.data.to_vec()).ok()
        } else {
            None
        }
    }

    /// Returns the message data.
    #[must_use]
    pub fn as_bytes(&self) -> &Bytes {
        &self.data
    }
}

/// Data channel.
pub struct DataChannel {
    /// Configuration.
    config: DataChannelConfig,
    /// Stream ID.
    stream_id: u16,
    /// State.
    state: Arc<Mutex<DataChannelState>>,
    /// SCTP association.
    association: Arc<Association>,
    /// DTLS connection.
    dtls: Arc<DtlsConnection>,
    /// Message receiver.
    rx: Arc<Mutex<mpsc::UnboundedReceiver<Message>>>,
    /// Message sender.
    tx: mpsc::UnboundedSender<Message>,
}

impl DataChannel {
    /// Creates a new data channel.
    #[must_use]
    pub fn new(
        config: DataChannelConfig,
        stream_id: u16,
        association: Arc<Association>,
        dtls: Arc<DtlsConnection>,
    ) -> Self {
        let (tx, rx) = mpsc::unbounded_channel();

        Self {
            config,
            stream_id,
            state: Arc::new(Mutex::new(DataChannelState::Connecting)),
            association,
            dtls,
            rx: Arc::new(Mutex::new(rx)),
            tx,
        }
    }

    /// Opens the data channel.
    pub async fn open(&self) -> NetResult<()> {
        // Wait for SCTP association to be established
        while self.association.state() != AssociationState::Established {
            tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
        }

        *self.state.lock().unwrap_or_else(|e| e.into_inner()) = DataChannelState::Open;
        Ok(())
    }

    /// Sends a text message.
    pub async fn send_text(&self, text: impl AsRef<str>) -> NetResult<()> {
        self.send_message(Message::text(text.as_ref())).await
    }

    /// Sends a binary message.
    pub async fn send_binary(&self, data: impl Into<Bytes>) -> NetResult<()> {
        self.send_message(Message::binary(data)).await
    }

    /// Sends a message.
    pub async fn send_message(&self, message: Message) -> NetResult<()> {
        let state = *self.state.lock().unwrap_or_else(|e| e.into_inner());
        if state != DataChannelState::Open {
            return Err(NetError::invalid_state("Data channel not open"));
        }

        // Encode message with PPID
        let data = message.data;

        // Send via SCTP
        let packet = self.association.send_data(self.stream_id, data);
        let encoded = packet.encode();

        // Send via DTLS
        self.dtls.send(&encoded).await?;

        Ok(())
    }

    /// Receives a message.
    pub async fn recv_message(&self) -> NetResult<Message> {
        let mut rx = self.rx.lock().unwrap_or_else(|e| e.into_inner());
        rx.recv()
            .await
            .ok_or_else(|| NetError::connection("Channel closed"))
    }

    /// Polls for received data from SCTP.
    pub fn poll_recv(&self) -> Option<Message> {
        if let Some(data) = self.association.recv_data(self.stream_id) {
            // Determine message type (simplified - would check PPID)
            Some(Message::binary(data))
        } else {
            None
        }
    }

    /// Closes the data channel.
    ///
    /// Sends a zero-length data chunk on the stream to signal closure, then
    /// transitions to the Closed state.
    pub async fn close(&self) -> NetResult<()> {
        *self.state.lock().unwrap_or_else(|e| e.into_inner()) = DataChannelState::Closing;

        // Send a zero-length SCTP data chunk to signal stream closure to the peer.
        // The packet is routed through DTLS as with normal data messages.
        let close_packet = self
            .association
            .send_data(self.stream_id, bytes::Bytes::new());
        let encoded = close_packet.encode();
        // Send the close signal; ignore errors since we transition to Closed regardless.
        let _ = self.dtls.send(&encoded).await;

        *self.state.lock().unwrap_or_else(|e| e.into_inner()) = DataChannelState::Closed;
        Ok(())
    }

    /// Gets the channel state.
    #[must_use]
    pub fn state(&self) -> DataChannelState {
        *self.state.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Gets the channel label.
    #[must_use]
    pub fn label(&self) -> &str {
        &self.config.label
    }

    /// Gets the stream ID.
    #[must_use]
    pub const fn stream_id(&self) -> u16 {
        self.stream_id
    }

    /// Returns true if the channel is ordered.
    #[must_use]
    pub fn is_ordered(&self) -> bool {
        self.config.ordered
    }

    /// Gets the protocol.
    #[must_use]
    pub fn protocol(&self) -> &str {
        &self.config.protocol
    }
}

/// Data channel manager.
pub struct DataChannelManager {
    /// SCTP association.
    association: Arc<Association>,
    /// DTLS connection.
    dtls: Arc<DtlsConnection>,
    /// Data channels.
    channels: Arc<Mutex<Vec<Arc<DataChannel>>>>,
    /// Next stream ID.
    next_stream_id: Arc<Mutex<u16>>,
}

impl DataChannelManager {
    /// Creates a new manager.
    #[must_use]
    pub fn new(association: Arc<Association>, dtls: Arc<DtlsConnection>) -> Self {
        Self {
            association,
            dtls,
            channels: Arc::new(Mutex::new(Vec::new())),
            next_stream_id: Arc::new(Mutex::new(0)),
        }
    }

    /// Creates a new data channel.
    pub async fn create_channel(&self, config: DataChannelConfig) -> NetResult<Arc<DataChannel>> {
        let stream_id = if let Some(id) = config.id {
            id
        } else {
            let mut next_id = self
                .next_stream_id
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            let id = *next_id;
            *next_id += 2; // Increment by 2 (odd for client, even for server)
            id
        };

        let channel = Arc::new(DataChannel::new(
            config,
            stream_id,
            self.association.clone(),
            self.dtls.clone(),
        ));

        self.channels
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(channel.clone());

        channel.open().await?;

        Ok(channel)
    }

    /// Gets all channels.
    #[must_use]
    pub fn channels(&self) -> Vec<Arc<DataChannel>> {
        self.channels
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }

    /// Finds a channel by stream ID.
    #[must_use]
    pub fn find_channel(&self, stream_id: u16) -> Option<Arc<DataChannel>> {
        self.channels
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .iter()
            .find(|ch| ch.stream_id() == stream_id)
            .cloned()
    }

    /// Processes incoming SCTP packet.
    pub async fn process_packet(&self, data: &[u8]) -> NetResult<()> {
        let packet = super::sctp::Packet::parse(data)?;

        if let Some(response) = self.association.handle_packet(packet)? {
            let encoded = response.encode();
            self.dtls.send(&encoded).await?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_data_channel_config() {
        let config = DataChannelConfig::new("test")
            .ordered(true)
            .max_retransmits(3);

        assert_eq!(config.label, "test");
        assert!(config.ordered);
        assert_eq!(config.max_retransmits, Some(3));
    }

    #[test]
    fn test_message_text() {
        let msg = Message::text("Hello");
        assert_eq!(msg.message_type, MessageType::Text);
        assert_eq!(msg.as_text().expect("should succeed in test"), "Hello");
    }

    #[test]
    fn test_message_binary() {
        let data = vec![1, 2, 3, 4];
        let msg = Message::binary(data.clone());
        assert_eq!(msg.message_type, MessageType::Binary);
        assert_eq!(msg.as_bytes().as_ref(), &data);
    }

    #[test]
    fn test_data_channel_state() {
        assert_ne!(DataChannelState::Open, DataChannelState::Closed);
        assert_eq!(DataChannelState::Open, DataChannelState::Open);
    }
}