rtci 0.5.0

A sans-I/O WebRTC implementation: peer connections with ICE, DTLS-SRTP, SCTP data channels, RTP/RTCP and JSEP negotiation
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! # RTC - Sans-I/O WebRTC Implementation
//!
//! A Rust implementation of the [WebRTC specification](https://www.w3.org/TR/webrtc/) using a
//! **sans-I/O architecture**. This crate provides full WebRTC functionality while giving you
//! complete control over networking, threading, and async runtime integration.
//!
//! ## What is Sans-I/O?
//!
//! Sans-I/O (without I/O) is a design pattern that separates protocol logic from I/O operations.
//! Instead of the library performing network reads and writes directly, **you** provide the
//! network data and handle the output. This gives you:
//!
//! - **Runtime Independence**: Works with tokio, async-std, smol, or blocking I/O
//! - **Full Control**: You control threading, scheduling, and I/O multiplexing
//! - **Testability**: Protocol logic can be tested without real network I/O
//! - **Flexibility**: Easy integration with existing networking code
//!
//! ## Quick Start
//!
//! ```no_run
//! # use std::time::Instant;
//! use rtci::peer_connection::RTCPeerConnectionBuilder;
//! use rtci::peer_connection::configuration::RTCConfigurationBuilder;
//! use rtci::peer_connection::transport::RTCIceServer;
//! use rtci::peer_connection::sdp::RTCSessionDescription;
//! use rtci::peer_connection::transport::{CandidateConfig, CandidateHostConfig, RTCIceCandidate};
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // 1. Create a peer connection with ICE servers
//! let mut pc = RTCPeerConnectionBuilder::new()
//!     .with_configuration(
//!         RTCConfigurationBuilder::new()
//!             .with_ice_servers(vec![RTCIceServer {
//!                 urls: vec!["stun:stun.l.google.com:19302".to_string()],
//!                 ..Default::default()
//!             }])
//!             .build()
//!     )
//!     .build(Instant::now())?;
//!
//! // 2. Create an offer
//! let offer = pc.create_offer(None)?;
//! pc.set_local_description(Instant::now(), offer.clone())?;
//!
//! // Send offer to remote peer via your signaling channel
//! // signaling.send(offer.sdp)?;
//!
//! // 3. Receive answer from remote peer
//! // let answer_sdp = signaling.receive()?;
//! # let answer_sdp = String::new();
//! let answer = RTCSessionDescription::answer(answer_sdp)?;
//! pc.set_remote_description(Instant::now(), answer)?;
//!
//! // 4. Add local ICE candidate
//! # use std::net::{IpAddr, Ipv4Addr};
//! let candidate = CandidateHostConfig {
//!     base_config: CandidateConfig {
//!         network: "udp".to_owned(),
//!         address: "192.168.1.100".to_string(),
//!         port: 8080,
//!         component: 1,
//!         ..Default::default()
//!     },
//!     ..Default::default()
//! }
//! .new_candidate_host()?;
//! let local_candidate_init = RTCIceCandidate::from(&candidate).to_json()?;
//! pc.add_local_candidate(local_candidate_init)?;
//!
//! // 5. Event loop - see complete example below
//! # Ok(())
//! # }
//! ```
//!
//! ## Complete Event Loop with All API Calls
//!
//! This example demonstrates the full sans-I/O event loop pattern with all key API methods:
//!
//! ```no_run
//! use rtci::peer_connection::RTCPeerConnectionBuilder;
//! use rtci::peer_connection::configuration::{RTCConfigurationBuilder, media_engine::MediaEngine};
//! use rtci::peer_connection::transport::RTCIceServer;
//! use rtci::peer_connection::event::{RTCPeerConnectionEvent, RTCTrackEvent};
//! use rtci::peer_connection::state::{RTCPeerConnectionState, RTCIceConnectionState};
//! use rtci::peer_connection::message::{RTCMessage, TaggedRTCMessage};
//! use rtci::shared::{TaggedBytesMut, TransportContext, TransportProtocol};
//! use rtci::sansio::Protocol;
//! use std::time::{Duration, Instant};
//! use tokio::net::UdpSocket;
//! use bytes::BytesMut;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Configure media codecs
//! let media_engine = MediaEngine::default();
//!
//! // Create peer connection
//! let mut pc = RTCPeerConnectionBuilder::new()
//!     .with_configuration(
//!         RTCConfigurationBuilder::new()
//!             .with_ice_servers(vec![RTCIceServer {
//!                 urls: vec!["stun:stun.l.google.com:19302".to_string()],
//!                 ..Default::default()
//!             }])
//!             .build()
//!     )
//!     .with_media_engine(media_engine)
//!     .build(Instant::now())?;
//!
//! // Bind UDP socket for network I/O, on the concrete address of the host candidate you add:
//! // `local_addr` must be a local candidate's address, and a socket bound to 0.0.0.0 reports
//! // 0.0.0.0:port, which none is (README, "The local address of a datagram").
//! let socket = UdpSocket::bind("192.168.1.100:0").await?;
//! let local_addr = socket.local_addr()?;
//!
//! let mut buf = vec![0u8; 2000];
//! const DEFAULT_TIMEOUT: Duration = Duration::from_secs(86400);
//!
//! // Main event loop
//! loop {
//!     // 1. poll_write() - Get outgoing network packets
//!     while let Some(msg) = pc.poll_write() {
//!         socket.send_to(&msg.message, msg.transport.peer_addr).await?;
//!     }
//!
//!     // 2. poll_event() - Process connection state changes and events
//!     while let Some(event) = pc.poll_event() {
//!         match event {
//!             RTCPeerConnectionEvent::OnIceConnectionStateChangeEvent(state) => {
//!                 println!("ICE Connection State: {state}");
//!                 if state == RTCIceConnectionState::Failed {
//!                     break;
//!                 }
//!             }
//!             RTCPeerConnectionEvent::OnConnectionStateChangeEvent(state) => {
//!                 println!("Connection State: {state}");
//!                 if state == RTCPeerConnectionState::Failed {
//!                     return Ok(());
//!                 }
//!             }
//!             RTCPeerConnectionEvent::OnDataChannel(dc_event) => {
//!                 println!("Data channel event: {:?}", dc_event);
//!             }
//!             RTCPeerConnectionEvent::OnTrack(track_event) => {
//!                 match track_event {
//!                     RTCTrackEvent::OnOpen(init) => {
//!                         println!("Track opened: track_id={}, receiver_id={:?}",
//!                             init.track_id, init.receiver_id);
//!                     }
//!                     RTCTrackEvent::OnClose(track_id) => {
//!                         println!("Track closed: {track_id}");
//!                     }
//!                     _ => {}
//!                 }
//!             }
//!             _ => {}
//!         }
//!     }
//!
//!     // 3. poll_read() - Get incoming application messages (RTP/RTCP/data)
//!     while let Some(TaggedRTCMessage { message, .. }) = pc.poll_read() {
//!         match message {
//!             RTCMessage::RtpPacket(track_id, rtp_packet) => {
//!                 println!("Received RTP packet on track {track_id}");
//!                 // Process RTP packet
//!             }
//!             RTCMessage::RtcpPacket(receiver_id, rtcp_packets) => {
//!                 println!("Received RTCP packets on receiver {:?}", receiver_id);
//!                 // Process RTCP packets
//!             }
//!             RTCMessage::DataChannelMessage(channel_id, message) => {
//!                 println!("Received data channel message on channel {:?}", channel_id);
//!                 // Process data channel message
//!             }
//!             // RTCMessage is #[non_exhaustive]: a wildcard arm is required.
//!             _ => {}
//!         }
//!     }
//!
//!     // 4. poll_timeout() - Get next timer deadline
//!     let timeout = pc.poll_timeout()
//!         .unwrap_or(Instant::now() + DEFAULT_TIMEOUT);
//!     let delay = timeout.saturating_duration_since(Instant::now());
//!
//!     // Handle immediate timeout
//!     if delay.is_zero() {
//!         // 6. handle_timeout() - Notify about timer expiration
//!         pc.handle_timeout(Instant::now())?;
//!         continue;
//!     }
//!
//!     // Wait for events using tokio::select!
//!     let timer = tokio::time::sleep(delay);
//!     tokio::pin!(timer);
//!
//!     tokio::select! {
//!         biased;
//!
//!         // Timer expired
//!         _ = timer => {
//!             pc.handle_timeout(Instant::now())?;
//!         }
//!         // Received network packet
//!         Ok((n, peer_addr)) = socket.recv_from(&mut buf) => {
//!             // 5. handle_read() - Feed incoming network packets
//!             pc.handle_read(TaggedBytesMut {
//!                 now: Instant::now(),
//!                 transport: TransportContext {
//!                     local_addr,
//!                     peer_addr,
//!                     ecn: None,
//!                     transport_protocol: TransportProtocol::UDP,
//!                 },
//!                 message: BytesMut::from(&buf[..n]),
//!             })?;
//!         }
//!         // Ctrl-C to exit
//!         _ = tokio::signal::ctrl_c() => {
//!             break;
//!         }
//!     }
//! }
//!
//! pc.close()?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Core API Methods
//!
//! ### Sans-I/O Event Loop Methods
//!
//! The event loop uses these six core methods:
//!
//! 1. **`poll_write()`** - Get outgoing network packets to send via UDP
//! 2. **`poll_event()`** - Process connection state changes and notifications
//! 3. **`poll_read()`** - Get incoming application messages (RTP, RTCP, data)
//! 4. **`poll_timeout()`** - Get next timer deadline for retransmissions/keepalives
//! 5. **`handle_read()`** - Feed incoming network packets into the connection
//! 6. **`handle_timeout()`** - Notify about timer expiration
//!
//! Additional methods for external control:
//!
//! - **`handle_write()`** - Queue application messages (RTP/RTCP/data) for sending
//! - **`handle_event()`** - Inject external events into the connection
//!
//! ### Signaling with Complete Example
//!
//! WebRTC requires an external signaling channel to exchange offers, answers, and ICE
//! candidates. This example shows the complete offer/answer flow:
//!
//! ```no_run
//! # use std::time::Instant;
//! use rtci::peer_connection::RTCPeerConnectionBuilder;
//! use rtci::peer_connection::configuration::RTCConfigurationBuilder;
//! use rtci::peer_connection::transport::RTCIceServer;
//! use rtci::peer_connection::sdp::RTCSessionDescription;
//! use rtci::peer_connection::transport::{CandidateConfig, CandidateHostConfig, RTCIceCandidate};
//!
//! # fn send_to_remote_peer(_: &str) {}
//! # fn receive_from_remote_peer() -> String { String::new() }
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Offerer side - creates the offer
//! let mut offerer = RTCPeerConnectionBuilder::new()
//!     .with_configuration(
//!         RTCConfigurationBuilder::new()
//!             .with_ice_servers(vec![RTCIceServer {
//!                 urls: vec!["stun:stun.l.google.com:19302".to_string()],
//!                 ..Default::default()
//!             }])
//!             .build()
//!     )
//!     .build(Instant::now())?;
//!
//! // 1. Create offer
//! let offer = offerer.create_offer(None)?;
//!
//! // 2. Set local description
//! offerer.set_local_description(Instant::now(), offer.clone())?;
//!
//! // 3. Add local ICE candidate
//! let candidate = CandidateHostConfig {
//!     base_config: CandidateConfig {
//!         network: "udp".to_owned(),
//!         address: "192.168.1.100".to_string(),
//!         port: 8080,
//!         component: 1,
//!         ..Default::default()
//!     },
//!     ..Default::default()
//! }
//! .new_candidate_host()?;
//! offerer.add_local_candidate(RTCIceCandidate::from(&candidate).to_json()?)?;
//!
//! // 4. Send offer to remote peer (your signaling channel)
//! send_to_remote_peer(&serde_json::to_string(&offer)?);
//!
//! // --- On answerer side ---
//! let mut answerer = RTCPeerConnectionBuilder::new()
//!     .with_configuration(
//!         RTCConfigurationBuilder::new()
//!             .with_ice_servers(vec![RTCIceServer {
//!                 urls: vec!["stun:stun.l.google.com:19302".to_string()],
//!                 ..Default::default()
//!             }])
//!             .build()
//!     )
//!     .build(Instant::now())?;
//!
//! // 5. Receive and set remote description
//! let offer_json = receive_from_remote_peer();
//! let remote_offer: RTCSessionDescription = serde_json::from_str(&offer_json)?;
//! answerer.set_remote_description(Instant::now(), remote_offer)?;
//!
//! // 6. Create answer
//! let answer = answerer.create_answer(None)?;
//!
//! // 7. Set local description
//! answerer.set_local_description(Instant::now(), answer.clone())?;
//!
//! // 8. Send answer back to offerer
//! send_to_remote_peer(&serde_json::to_string(&answer)?);
//!
//! // --- Back on offerer side ---
//! // 9. Receive and set remote description
//! let answer_json = receive_from_remote_peer();
//! let remote_answer: RTCSessionDescription = serde_json::from_str(&answer_json)?;
//! offerer.set_remote_description(Instant::now(), remote_answer)?;
//!
//! // Now both peers are connected!
//! # Ok(())
//! # }
//! ```
//!
//! ## Module Organization
//!
//! ### [`peer_connection`]
//!
//! Core WebRTC peer connection implementation:
//!
//! - **[`RTCPeerConnection`](peer_connection::RTCPeerConnection)** - Peer connection interface
//! - **[`certificate`](peer_connection::certificate)** - Peer connection certficiate
//! - **[`configuration`](peer_connection::configuration)** - Peer connection configuration
//!   - **[`interceptor_registry`](peer_connection::configuration::interceptor_registry)** - NACK, TWCC, RTCP Reports configuration
//!   - **[`media_engine`](peer_connection::configuration::media_engine)** - Codec and RTP extension configuration
//!   - **[`setting_engine`](peer_connection::configuration::setting_engine)** - Low-level transport settings
//! - **[`event`](peer_connection::event)** - Peer connection events
//! - **[`message`](peer_connection::message)** - RTP/RTCP Packets and Application messages
//! - **[`sdp`](peer_connection::sdp)** - SDP offer/answer types
//! - **[`state`](peer_connection::state)** - Peer connection state types
//! - **[`transport`](peer_connection::transport)** - ICE, DTLS, SCTP transport types
//!
//! ### [`data_channel`]
//!
//! WebRTC data channels for arbitrary data transfer:
//!
//! - **[`RTCDataChannel`](data_channel::RTCDataChannel)** - Data channel interface
//! - **[`RTCDataChannelInit`](data_channel::RTCDataChannelInit)** - Channel configuration
//! - **[`RTCDataChannelMessage`](data_channel::RTCDataChannelMessage)** - Data channel messages
//!
//! ### [`rtp_transceiver`]
//!
//! RTP media transmission and reception:
//!
//! - **[`RTCRtpSender`](rtp_transceiver::rtp_sender::RTCRtpSender)** - Media sender
//! - **[`RTCRtpReceiver`](rtp_transceiver::rtp_receiver::RTCRtpReceiver)** - Media receiver
//!
//! ### [`media_stream`]
//!
//! Media track management:
//!
//! - **[`MediaStreamTrack`](media_stream::track::MediaStreamTrack)** - Audio/video track
//!
//! ## Features
//!
//! - ✅ **ICE (Interactive Connectivity Establishment)** - NAT traversal with STUN/TURN
//! - ✅ **DTLS (Datagram Transport Layer Security)** - Encryption for media and data
//! - ✅ **SCTP (Stream Control Transmission Protocol)** - Reliable data channels
//! - ✅ **RTP/RTCP** - Real-time media transport and control
//! - ✅ **SDP (Session Description Protocol)** - Offer/answer negotiation
//! - ✅ **Data Channels** - Bidirectional peer-to-peer data transfer
//! - ✅ **Media Tracks** - Audio/video transmission
//! - ✅ **Trickle ICE** - Progressive candidate gathering
//! - ✅ **ICE Restart** - Connection recovery
//! - ✅ **Simulcast & SVC** - Scalable video coding
//!
//! ## Working Examples
//!
//! The crate includes comprehensive examples in the `examples/` directory:
//!
//! - **data-channels-offer-answer** - Complete data channel setup with signaling
//! - **save-to-disk-vpx** - Receive and save VP8/VP9 video to disk
//! - **play-from-disk-vpx** - Send VP8/VP9 video from disk
//! - **rtp-forwarder** - Forward RTP streams between peers
//! - **simulcast** - Multiple quality streams
//! - **trickle-ice** - Progressive ICE candidate exchange
//!
//! See the `examples/` directory for complete, runnable code.
//!
//! ## Gathering
//!
//! The engine has no sockets, so the application gathers: it binds its UDP sockets, gives
//! each host candidate to [`RTCPeerConnection::add_local_candidate`] (with the `sdp_mid` of
//! the transport's first section when sections are not bundled, see
//! [`RTCPeerConnection::ice_transport_sections`]), signals each candidate the engine surfaces
//! (`OnIceCandidateEvent`) to the peer, and ends a generation with an empty candidate. From a
//! host candidate the engine gathers the rest by itself when it is configured to, from the first
//! local description on (RFC 9429 section 3.5.4; what it finds for an ICE generation no local
//! description represents yet waits for one, W3C webrtc-pc 5.6): the
//! server-reflexive candidates of the STUN servers, the TURN allocations, the ICE-TCP
//! candidates (through the stream interface).
//!
//! ### A transport that needs new candidates
//!
//! A new DTLS association over UDP runs on a new 3-tuple (RFC 8842 section 5.1: "a new
//! 3-tuple (transport/source address/source port) MUST be allocated by at least one of the
//! endpoints"). So when one is set up on a transport that had one, the engine drops the
//! transport's local candidates and refuses their UDP addresses
//! (`Error::ErrICECandidateAddressOfPreviousDtlsAssociation`), and the application must gather
//! again on new ports. It is told with
//! [`RTCPeerConnectionEvent::OnLocalCandidatesNeeded`](peer_connection::event::RTCPeerConnectionEvent::OnLocalCandidatesNeeded),
//! which names the transport (its ids, the mids of its sections, the first one's index), the
//! reason ([`RTCLocalCandidatesNeededReason`](peer_connection::event::RTCLocalCandidatesNeededReason))
//! and the refused addresses. It fires when the description that starts the transport's new
//! gathering is set locally (W3C webrtc-pc 5.6 begins gathering a generation at
//! `setLocalDescription`), right before the transport's `gatheringstatechange` to
//! "gathering":
//!
//! - an ICE restart made for a new DTLS association: `renew_dtls_association`, automatic SRTP
//!   re-keying (`SrtpRekeying`, on the side that asked), an offer that replaces a data-only
//!   association to key SRTP, or a peer's offer with a new `a=tls-id` (the answer, when it is
//!   set); per transport, each with its own event;
//! - the transport that replaced one an answer closed by rejecting every m= section
//!   (`TransportReplaced`): when the next description, which gives it a section, is set;
//! - every ICE restart with `with_discard_local_candidates_during_ice_restart(true)`
//!   (`DiscardedBySetting`; no address is refused then).
//! - the first local offer rolled back before any answer (`RolledBack`; no address is
//!   refused): RFC 9429 section 5.7 discards everything gathered for it ("Any resources or
//!   candidates that were allocated by the abandoned local description are discarded":
//!   the host candidates, the STUN probes, the TURN allocations, the ICE-TCP listeners),
//!   and the next local description (the answer to the peer's offer, say) gathers anew.
//!   The same sockets may be given again.
//!
//! What to do: bind new UDP sockets, add a host candidate for each with `sdp_mid` set to the
//! event's first mid, signal the candidates the engine surfaces, end the generation with an
//! empty candidate for that mid. Keep the previous sockets open and reading: the selected
//! pair keeps carrying the transport's packets until a pair on a new socket is selected
//! (`SelectedCandidatePairChange` on that transport), or until the transport closes; close
//! them then, after a few seconds more: the peer selects on its own and may still send to
//! the previous address for a while. The engine's own gathering follows the new host candidates by itself: it asks
//! the STUN servers from each new base (the probes from a refused base end, so no mapped
//! address of the previous socket is announced), allocates TURN again from a base that is not
//! refused, and gives the ICE-TCP candidates of the address again (RFC 8842 section 5.1 asks a
//! new 3-tuple of unordered transports only; their listener is kept).
//!
//! A local offer that is rolled back takes its ICE restart back (RFC 9429 section 5.7: "Any
//! resources or candidates that were allocated by the abandoned local description are
//! discarded"), its `OnLocalCandidatesNeeded` included, although the event has already
//! fired: the transport holds its previous candidates again, on the previous addresses,
//! which are no longer refused, and the candidates given for the abandoned generation are
//! dropped (the peer, which ignored or never got that offer, drops the ones signalled to it:
//! they carry the abandoned username fragment). The application then
//!
//! - keeps the previous sockets open and no longer counts them as retired: they carry the
//!   transport's packets as before the offer;
//! - closes the sockets it bound for the abandoned generation (or keeps them for the next
//!   one: an address that no association used is not refused);
//! - waits for the next `OnLocalCandidatesNeeded`: the answer to the peer's offer (the usual
//!   end of an offer collision, W3C webrtc-pc "perfect negotiation") fires one when it sets up
//!   a new association, and so does the next offer of this side that asks for one.
//!
//! The transport's candidates are what
//! [`RTCIceTransport::get_local_candidates`](peer_connection::transport::RTCIceTransport::get_local_candidates)
//! returns, so the application can match its sockets against them once the connection is
//! back in the stable state (`OnSignalingStateChangeEvent(Stable)`). `rtci-stream-driver`'s
//! `PeerDriver` does that.
//!
//! ```no_run
//! use rtci::peer_connection::RTCPeerConnection;
//! use rtci::peer_connection::event::{RTCLocalCandidatesNeededEvent, RTCPeerConnectionEvent};
//! use rtci::peer_connection::transport::RTCIceCandidateInit;
//! use std::net::UdpSocket;
//!
//! fn on_event(
//!     pc: &mut RTCPeerConnection,
//!     sockets: &mut Vec<UdpSocket>,
//!     event: RTCPeerConnectionEvent,
//! ) -> Result<(), Box<dyn std::error::Error>> {
//!     if let RTCPeerConnectionEvent::OnLocalCandidatesNeeded(needed) = event {
//!         let RTCLocalCandidatesNeededEvent { mids, sdp_mline_index, .. } = needed;
//!         // A new port on the same interface (port 0: the system picks a free one).
//!         let socket = UdpSocket::bind("192.0.2.1:0")?;
//!         let local = socket.local_addr()?;
//!         pc.add_local_candidate(RTCIceCandidateInit {
//!             candidate: format!(
//!                 "candidate:1 1 udp 2130706431 {} {} typ host",
//!                 local.ip(),
//!                 local.port()
//!             ),
//!             sdp_mid: mids.first().cloned(),
//!             sdp_mline_index,
//!             ..Default::default()
//!         })?;
//!         // The end of this transport's generation.
//!         pc.add_local_candidate(RTCIceCandidateInit {
//!             sdp_mid: mids.first().cloned(),
//!             ..Default::default()
//!         })?;
//!         // The previous sockets stay open until a pair on the new one is selected.
//!         sockets.push(socket);
//!     }
//!     Ok(())
//! }
//! ```
//!
//! The reference driver, `rtci-stream-driver`, does all of this by itself (its `peer`
//! module).
//!
//! An application with one fixed socket, which cannot move to a new port, turns it off with
//! [`SettingEngineBuilder::with_dtls_new_association_on_previous_addresses(true)`](peer_connection::configuration::setting_engine::SettingEngineBuilder::with_dtls_new_association_on_previous_addresses):
//! the candidates are kept, their addresses accepted, and no event fires; the new association
//! then shares the previous one's 3-tuple, which RFC 8842 section 5.1 allows only when the
//! peer allocates a new one.
//!
//! [`RTCPeerConnection::add_local_candidate`]: peer_connection::RTCPeerConnection::add_local_candidate
//! [`RTCPeerConnection::ice_transport_sections`]: peer_connection::RTCPeerConnection::ice_transport_sections
//!
//! ## Common Patterns
//!
//! ### Configuring Interceptors (NACK, TWCC, RTCP Reports)
//!
//! Interceptors process RTP/RTCP packets as they flow through the media pipeline.
//! Use the [`interceptor_registry`](peer_connection::configuration::interceptor_registry) module
//! to configure packet loss recovery, congestion control, and quality monitoring:
//!
//! ```no_run
//! # use std::time::Instant;
//! use rtci::peer_connection::RTCPeerConnectionBuilder;
//! use rtci::peer_connection::configuration::RTCConfigurationBuilder;
//! use rtci::peer_connection::configuration::media_engine::MediaEngine;
//! use rtci::peer_connection::configuration::interceptor_registry::{
//!     Registry, register_default_interceptors,
//! };
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create media engine with default codecs
//! let mut media_engine = MediaEngine::default();
//!
//! // Collect the default interceptors:
//! // - NACK: Packet loss recovery for video
//! // - RTCP Reports: Sender/Receiver quality statistics
//! // - TWCC Receiver: Congestion control feedback
//! //
//! // `build` sorts them wire-to-application, so the order these are asked for does not matter.
//! let registry = Registry::new();
//! let registry = register_default_interceptors(registry, &mut media_engine)?;
//!
//! // Build peer connection with interceptors
//! let mut pc = RTCPeerConnectionBuilder::new()
//!     .with_media_engine(media_engine)
//!     .with_interceptor_registry(registry)
//!     .build(Instant::now())?;
//! # Ok(())
//! # }
//! ```
//!
//! For custom interceptor configuration:
//!
//! ```no_run
//! # use std::time::Instant;
//! use rtci::peer_connection::RTCPeerConnectionBuilder;
//! use rtci::peer_connection::configuration::RTCConfigurationBuilder;
//! use rtci::peer_connection::configuration::media_engine::MediaEngine;
//! use rtci::peer_connection::configuration::interceptor_registry::{
//!     Registry,
//!     configure_nack,
//!     configure_rtcp_reports,
//!     configure_twcc,
//! };
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut media_engine = MediaEngine::default();
//! let registry = Registry::new();
//!
//! // Ask for what you want, in any order — each interceptor carries the slot it belongs in.
//! let registry = configure_nack(registry, &mut media_engine);     // Packet loss recovery
//! let registry = configure_rtcp_reports(registry);                // SR/RR statistics
//! let registry = configure_twcc(registry, &mut media_engine)?;    // Full TWCC (sender + receiver)
//!
//! let registry = registry;
//!
//! let mut pc = RTCPeerConnectionBuilder::new()
//!     .with_media_engine(media_engine)
//!     .with_interceptor_registry(registry)
//!     .build(Instant::now())?;
//! # Ok(())
//! # }
//! ```
//!
//! #### One connection type, whatever the chain
//!
//! A chain is a flat list of interceptors, and
//! [`RTCPeerConnection`](peer_connection::RTCPeerConnection) has one concrete type no matter what
//! the list contains. Nothing that holds a connection has to know how its chain was assembled,
//! chains can be chosen at runtime, and connections built from different chains share a
//! collection:
//!
//! ```no_run
//! # use std::time::Instant;
//! use rtci::peer_connection::configuration::interceptor_registry::{
//!     Registry, register_default_interceptors,
//! };
//! use rtci::peer_connection::configuration::media_engine::MediaEngine;
//! use rtci::peer_connection::{RTCPeerConnection, RTCPeerConnectionBuilder};
//!
//! // No type parameter: this struct does not have to know the chain.
//! struct Session {
//!     peer_connection: RTCPeerConnection,
//! }
//!
//! # fn example(with_nack: bool) -> Result<(), Box<dyn std::error::Error>> {
//! let mut media_engine = MediaEngine::default();
//! let registry =
//!     register_default_interceptors(Registry::new(), &mut media_engine)?;
//!
//! let mut sessions: Vec<Session> = Vec::new();
//! sessions.push(Session {
//!     peer_connection: RTCPeerConnectionBuilder::new()
//!         .with_media_engine(media_engine)
//!         .with_interceptor_registry(registry)
//!         .build(Instant::now())?,
//! });
//! # Ok(())
//! # }
//! ```
//!
//! The cost is one virtual call per interceptor per packet, which is nothing beside SRTP.
//! Static dispatch is still the default — keep the generic form when the chain is fixed at
//! compile time.
//!
//! ### Creating and Using Data Channels
//!
//! ```no_run
//! use rtci::peer_connection::RTCPeerConnection;
//! use rtci::peer_connection::configuration::RTCConfiguration;
//! use rtci::data_channel::RTCDataChannelInit;
//! use rtci::peer_connection::event::RTCPeerConnectionEvent;
//! use std::time::Instant;
//! use rtci::peer_connection::message::{RTCMessage, TaggedRTCMessage};
//! use rtci::sansio::Protocol;
//! use bytes::BytesMut;
//!
//! # fn example(mut pc: RTCPeerConnection) -> Result<(), Box<dyn std::error::Error>> {
//! // Create data channel with ordered, reliable delivery
//! let init = RTCDataChannelInit {
//!     ordered: true,
//!     max_retransmits: None,
//!     ..Default::default()
//! };
//!
//! let mut dc = pc.create_data_channel("my-channel", Some(init))?;
//! let channel_id = dc.id();
//!
//! // Send text message
//! dc.send_text(Instant::now(), "Hello, WebRTC!")?;
//!
//! // Send binary message
//! dc.send(Instant::now(), BytesMut::from(&[0x01, 0x02, 0x03, 0x04][..]))?;
//!
//! // Later, retrieve the data channel by ID
//! if let Some(mut dc) = pc.data_channel(channel_id) {
//!     dc.send_text(Instant::now(), "Another message")?;
//! }
//!
//! // Receive messages in event loop
//! while let Some(TaggedRTCMessage { message, .. }) = pc.poll_read() {
//!     if let RTCMessage::DataChannelMessage(channel_id, msg) = message {
//!         if msg.is_string {
//!             let text = String::from_utf8_lossy(&msg.data);
//!             println!("Received text: {text}");
//!         } else {
//!             println!("Received binary: {} bytes", msg.data.len());
//!         }
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ### Adding Media Tracks with Codecs
//!
//! ```no_run
//! use rtci::peer_connection::RTCPeerConnection;
//! use rtci::media_stream::MediaStreamTrack;
//! use rtci::rtp_transceiver::rtp_sender::{RTCRtpCodec, RTCRtpCodecParameters, RtpCodecKind};
//! use rtci::rtp_transceiver::rtp_sender::{RTCRtpEncodingParameters, RTCRtpCodingParameters};
//! use rtci::peer_connection::configuration::media_engine::{MIME_TYPE_VP8, MIME_TYPE_OPUS};
//!
//! # fn example(mut pc: RTCPeerConnection) -> Result<(), Box<dyn std::error::Error>> {
//! // Configure VP8 video codec
//! let video_codec = RTCRtpCodec {
//!     mime_type: MIME_TYPE_VP8.to_owned(),
//!     clock_rate: 90000,
//!     channels: 0,
//!     sdp_fmtp_line: "".to_owned(),
//!     rtcp_feedback: vec![],
//! };
//!
//! // Create video track
//! let video_track = MediaStreamTrack::new(
//!     "stream-id".to_string(),
//!     "video-track-id".to_string(),
//!     "video-label".to_string(),
//!     RtpCodecKind::Video,
//!     vec![RTCRtpEncodingParameters {
//!         rtp_coding_parameters: RTCRtpCodingParameters {
//!             ssrc: Some(rand::random::<u32>()),
//!             ..Default::default()
//!         },
//!         codec: video_codec.clone(),
//!         ..Default::default()
//!     }],
//! );
//!
//! // Add track to peer connection
//! let sender_id = pc.add_track(video_track)?;
//!
//! // Send RTP packets
//! if let Some(mut sender) = pc.rtp_sender(sender_id) {
//!     // sender.write_rtp(Instant::now(), rtp_packet)?;
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ### Receiving Media Tracks
//!
//! ```no_run
//! use rtci::peer_connection::RTCPeerConnection;
//! use rtci::peer_connection::event::{RTCPeerConnectionEvent, RTCTrackEvent};
//! use rtci::peer_connection::message::{RTCMessage, TaggedRTCMessage};
//! use rtci::sansio::Protocol;
//! use std::collections::HashMap;
//!
//! # fn example(mut pc: RTCPeerConnection) -> Result<(), Box<dyn std::error::Error>> {
//! // Track mapping for received tracks
//! let mut track_to_receiver = HashMap::new();
//!
//! // Handle track events
//! while let Some(event) = pc.poll_event() {
//!     if let RTCPeerConnectionEvent::OnTrack(track_event) = event {
//!         match track_event {
//!             RTCTrackEvent::OnOpen(init) => {
//!                 println!("New track: track_id={}, receiver_id={:?}",
//!                     init.track_id, init.receiver_id);
//!                 track_to_receiver.insert(init.track_id.clone(), init.receiver_id);
//!             }
//!             RTCTrackEvent::OnClose(track_id) => {
//!                 println!("Track closed: {track_id}");
//!                 track_to_receiver.remove(&track_id);
//!             }
//!             _ => {}
//!         }
//!     }
//! }
//!
//! // Receive RTP packets
//! while let Some(TaggedRTCMessage { message, .. }) = pc.poll_read() {
//!     if let RTCMessage::RtpPacket(track_id, rtp_packet) = message {
//!         println!("RTP packet on track {}: {} bytes",
//!             track_id, rtp_packet.payload.len());
//!         
//!         // Access receiver to get track metadata
//!         if let Some(&receiver_id) = track_to_receiver.get(&track_id) {
//!             if let Some(receiver) = pc.rtp_receiver(receiver_id) {
//!                 let track = receiver.track();
//!                 let ssrcs: Vec<u32> = track.ssrcs().collect();
//!                 println!("  SSRCs: {:?}, Kind: {:?}", ssrcs, track.kind());
//!             }
//!         }
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ### Sending RTCP Packets (e.g., PLI for keyframes)
//!
//! ```no_run
//! use rtci::peer_connection::RTCPeerConnection;
//! use rtci::rtp_transceiver::RTCRtpReceiverId;
//! use rtci::rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
//! use std::time::Instant;
//!
//! # fn example(mut pc: RTCPeerConnection, receiver_id: RTCRtpReceiverId, media_ssrc: u32)
//! #     -> Result<(), Box<dyn std::error::Error>> {
//! // Request keyframe by sending Picture Loss Indication (PLI)
//! if let Some(mut receiver) = pc.rtp_receiver(receiver_id) {
//!     receiver.write_rtcp(Instant::now(), vec![Box::new(PictureLossIndication {
//!         sender_ssrc: 0,
//!         media_ssrc,
//!     })])?;
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Specification Compliance
//!
//! This implementation follows these specifications:
//!
//! - [W3C WebRTC 1.0] - Main WebRTC API specification
//! - [RFC 9429] - JSEP: JavaScript Session Establishment Protocol  
//! - [RFC 8866] - SDP: Session Description Protocol
//! - [RFC 8445] - ICE: Interactive Connectivity Establishment
//! - [RFC 6347] - DTLS: Datagram Transport Layer Security
//! - [RFC 8831] - WebRTC Data Channels
//! - [RFC 3550] - RTP: Real-time Transport Protocol
//!
//! [W3C WebRTC 1.0]: https://www.w3.org/TR/webrtc/
//! [RFC 9429]: https://datatracker.ietf.org/doc/html/rfc9429
//! [RFC 8866]: https://datatracker.ietf.org/doc/html/rfc8866
//! [RFC 8445]: https://datatracker.ietf.org/doc/html/rfc8445
//! [RFC 6347]: https://datatracker.ietf.org/doc/html/rfc6347
//! [RFC 8831]: https://datatracker.ietf.org/doc/html/rfc8831
//! [RFC 3550]: https://datatracker.ietf.org/doc/html/rfc3550
//!
//! ## Further Reading
//!
//! - [Sans-I/O Approach](https://sans-io.readthedocs.io/) - Detailed explanation of sans-I/O design
//! - [WebRTC for the Curious](https://webrtcforthecurious.com/) - Comprehensive WebRTC guide
//! - [MDN WebRTC API](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API) - Browser WebRTC documentation

#![doc(
    html_logo_url = "https://raw.githubusercontent.com/webrtc-rs/webrtc-rs.github.io/master/res/rtc.png"
)]
#![warn(rust_2018_idioms)]
#![warn(missing_docs)]
#![allow(dead_code)]

pub use {
    crypto, datachannel, dtls, ice, interceptor, mdns, media, rtcp, rtp, sansio, sctp, sdp, sframe,
    shared, srtp, stun, turn,
};

pub mod data_channel;
/// Entry points for stateful fuzz targets. Gated behind `cfg(fuzzing)`; not part of the
/// supported API.
#[cfg(fuzzing)]
pub mod fuzzing;
pub mod media_stream;
pub mod peer_connection;
pub mod rtp_transceiver;
pub mod statistics;

// The README's Rust examples are doctests: CI compiles them (they are `no_run`, they bind
// sockets), so the README cannot drift from the API.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;