str0m 0.6.3

WebRTC library in Sans-IO style
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
//! Strategy that amends the [`Rtc`] via SDP OFFER/ANSWER negotiation.

use std::fmt;
use std::ops::{Deref, DerefMut};

use crate::channel::ChannelId;
use crate::crypto::Fingerprint;
use crate::format::CodecConfig;
use crate::format::PayloadParams;
use crate::io::Id;
use crate::media::Media;
use crate::packet::MediaKind;
use crate::rtp_::Rid;
use crate::rtp_::{Direction, Extension, ExtensionMap, Mid, Pt, Ssrc};
use crate::sctp::ChannelConfig;
use crate::sdp::SimulcastGroups;
use crate::sdp::{self, MediaAttribute, MediaLine, MediaType, Msid, Sdp};
use crate::sdp::{Proto, SessionAttribute, Setup};
use crate::session::Session;
use crate::Rtc;
use crate::RtcError;
use crate::{Candidate, IceCreds};

pub use crate::sdp::{SdpAnswer, SdpOffer};
use crate::streams::{Streams, DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP};

/// Changes to the Rtc via SDP Offer/Answer dance.
pub struct SdpApi<'a> {
    rtc: &'a mut Rtc,
    changes: Changes,
}

impl<'a> SdpApi<'a> {
    pub(crate) fn new(rtc: &'a mut Rtc) -> Self {
        SdpApi {
            rtc,
            changes: Changes::default(),
        }
    }

    /// Accept an [`SdpOffer`] from the remote peer. If this call returns successfully, the
    /// changes will have been made to the session. The resulting [`SdpAnswer`] should be
    /// sent to the remote peer.
    ///
    /// <b>Note. Pending changes from a previous non-completed [`SdpApi`][super::SdpApi] will be
    /// considered rolled back when calling this function.</b>
    ///
    /// The incoming SDP is validated in various ways which can cause this call to fail.
    /// Example of such problems would be an SDP without any m-lines, missing `a=fingerprint`
    /// or if `a=group` doesn't match the number of m-lines.
    ///
    /// ```no_run
    /// # use str0m::Rtc;
    /// # use str0m::change::{SdpOffer};
    /// // obtain offer from remote peer.
    /// let json_offer: &[u8] = todo!();
    /// let offer: SdpOffer = serde_json::from_slice(json_offer).unwrap();
    ///
    /// let mut rtc = Rtc::new();
    /// let answer = rtc.sdp_api().accept_offer(offer).unwrap();
    ///
    /// // send json_answer to remote peer.
    /// let json_answer = serde_json::to_vec(&answer).unwrap();
    /// ```
    pub fn accept_offer(self, offer: SdpOffer) -> Result<SdpAnswer, RtcError> {
        debug!("Accept offer");

        // Invalidate any outstanding PendingOffer.
        self.rtc.next_change_id();

        if offer.media_lines.is_empty() {
            return Err(RtcError::RemoteSdp("No m-lines in offer".into()));
        }

        if self.rtc.ice.ice_lite() && offer.session.ice_lite() {
            return Err(RtcError::RemoteSdp(
                "Both peers being ICE-Lite not supported".into(),
            ));
        }

        add_ice_details(self.rtc, &offer, None)?;

        if self.rtc.remote_fingerprint.is_none() {
            if let Some(f) = offer.fingerprint() {
                self.rtc.remote_fingerprint = Some(f);
            } else {
                self.rtc.disconnect();
                return Err(RtcError::RemoteSdp("missing a=fingerprint".into()));
            }
        }

        if !self.rtc.dtls.is_inited() {
            // The side that makes the first offer is the controlling side, unless they
            // are ICE Lite, in which case the roles are reversed (see RFC 5245).
            self.rtc.ice.set_controlling(offer.session.ice_lite());
        }

        // Ensure setup=active/passive is corresponding remote and init dtls.
        init_dtls(self.rtc, &offer)?;

        // Modify session with offer
        apply_offer(&mut self.rtc.session, offer)?;

        // Handle potentially new m=application line.
        let client = self.rtc.dtls.is_active().expect("DTLS active to be set");
        if self.rtc.session.app().is_some() {
            self.rtc.init_sctp(client);
        }

        let params = AsSdpParams::new(self.rtc, None);
        let sdp = as_sdp(&self.rtc.session, params);

        debug!("Create answer");
        Ok(sdp.into())
    }

    /// Accept an answer to a previously created [`SdpOffer`].
    ///
    /// This function returns an [`RtcError::ChangesOutOfOrder`] if we have created and applied another
    /// [`SdpApi`][super::SdpApi] before calling this. The same also happens if we use
    /// [`SdpApi::accept_offer()`] before using this pending instance.
    ///
    /// ```no_run
    /// # use str0m::Rtc;
    /// # use str0m::media::{MediaKind, Direction};
    /// # use str0m::change::SdpAnswer;
    /// let mut rtc = Rtc::new();
    ///
    /// let mut changes = rtc.sdp_api();
    /// let mid = changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None);
    /// let (offer, pending) = changes.apply().unwrap();
    ///
    /// // send offer to remote peer, receive answer back
    /// let answer: SdpAnswer = todo!();
    ///
    /// rtc.sdp_api().accept_answer(pending, answer).unwrap();
    /// ```
    pub fn accept_answer(
        self,
        mut pending: SdpPendingOffer,
        answer: SdpAnswer,
    ) -> Result<(), RtcError> {
        debug!("Accept answer");

        // Ensure we don't use the wrong changes below. We must use that of pending.
        drop(self.changes);

        if !self.rtc.is_correct_change_id(pending.change_id) {
            return Err(RtcError::ChangesOutOfOrder);
        }

        if self.rtc.ice.ice_lite() && answer.session.ice_lite() {
            return Err(RtcError::RemoteSdp(
                "Both peers being ICE-Lite not supported".into(),
            ));
        }

        add_ice_details(self.rtc, &answer, Some(&pending))?;

        // Ensure setup=active/passive is corresponding remote and init dtls.
        init_dtls(self.rtc, &answer)?;

        if self.rtc.remote_fingerprint.is_none() {
            if let Some(f) = answer.fingerprint() {
                self.rtc.remote_fingerprint = Some(f);
            } else {
                self.rtc.disconnect();
                return Err(RtcError::RemoteSdp("missing a=fingerprint".into()));
            }
        }

        // Split out new channels, since that is not handled by the Session.
        let new_channels = pending.changes.take_new_channels();

        // Modify session with answer
        apply_answer(&mut self.rtc.session, pending.changes, answer)?;

        // Handle potentially new m=application line.
        let client = self.rtc.dtls.is_active().expect("DTLS to be inited");
        if self.rtc.session.app().is_some() {
            self.rtc.init_sctp(client);
        }

        for (id, config) in new_channels {
            self.rtc.chan.confirm(id, config);
        }

        Ok(())
    }

    /// Test if any changes have been made.
    ///
    /// If changes have been made, nothing happens until we call [`SdpApi::apply()`].
    ///
    /// ```
    /// # use str0m::{Rtc, media::MediaKind, media::Direction};
    /// let mut rtc = Rtc::new();
    ///
    /// let mut changes = rtc.sdp_api();
    /// assert!(!changes.has_changes());
    ///
    /// let mid = changes.add_media(MediaKind::Audio, Direction::SendRecv, None, None);
    /// assert!(changes.has_changes());
    /// ```
    pub fn has_changes(&self) -> bool {
        !self.changes.0.is_empty()
    }

    /// Add audio or video media and get the `mid` that will be used.
    ///
    /// Each call will result in a new m-line in the offer identified by the [`Mid`].
    ///
    /// The mid is not valid to use until the SDP offer-answer dance is complete and
    /// the mid been advertised via [`Event::MediaAdded`][crate::Event::MediaAdded].
    ///
    /// * `stream_id` is used to synchronize media. It is `a=msid-semantic: WMS <streamId>` line in SDP.
    /// * `track_id` is becomes both the track id in `a=msid <streamId> <trackId>` as well as the
    ///   CNAME in the RTP SDES.
    ///
    /// ```
    /// # use str0m::{Rtc, media::MediaKind, media::Direction};
    /// let mut rtc = Rtc::new();
    ///
    /// let mut changes = rtc.sdp_api();
    ///
    /// let mid = changes.add_media(MediaKind::Audio, Direction::SendRecv, None, None);
    /// ```
    pub fn add_media(
        &mut self,
        kind: MediaKind,
        dir: Direction,
        stream_id: Option<String>,
        track_id: Option<String>,
    ) -> Mid {
        let mid = self.rtc.new_mid();

        // https://www.rfc-editor.org/rfc/rfc8830
        // msid-id = 1*64token-char
        fn is_token_char(c: &char) -> bool {
            // token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39
            // / %x41-5A / %x5E-7E
            let u = *c as u32;
            u == 0x21
                || (0x23..=0x27).contains(&u)
                || (0x2a..=0x2b).contains(&u)
                || (0x2d..=0x2e).contains(&u)
                || (0x30..=0x39).contains(&u)
                || (0x41..=0x5a).contains(&u)
                || (0x5e..0x7e).contains(&u)
        }

        let stream_id = if let Some(stream_id) = stream_id {
            stream_id.chars().filter(is_token_char).take(64).collect()
        } else {
            Id::<20>::random().to_string()
        };

        let track_id = if let Some(track_id) = track_id {
            track_id.chars().filter(is_token_char).take(64).collect()
        } else {
            Id::<20>::random().to_string()
        };

        let rtx = kind.is_video().then(|| self.rtc.session.streams.new_ssrc());
        let ssrcs = vec![(self.rtc.session.streams.new_ssrc(), rtx)];

        // TODO: let user configure stream/track name.
        let msid = Msid {
            stream_id,
            track_id: track_id.clone(),
        };

        let add = AddMedia {
            mid,
            cname: track_id,
            msid,
            kind,
            dir,
            ssrcs,

            // Added later
            pts: vec![],
            exts: ExtensionMap::empty(),
            index: 0,
        };

        self.changes.0.push(Change::AddMedia(add));
        mid
    }

    /// Change the direction of an already existing media.
    ///
    /// All media have a direction. The media can be added by this side via
    /// [`SdpApi::add_media()`] or by the remote peer. Either way, the direction
    /// of the line can be changed at any time.
    ///
    /// It's possible to set the direction [`Direction::Inactive`] for media that
    /// will not be used by the session anymore.
    ///
    /// If the direction is set for media that doesn't exist, or if the direction is
    /// the same that's already set [`SdpApi::apply()`] not require a negotiation.
    pub fn set_direction(&mut self, mid: Mid, dir: Direction) {
        let changed = self.rtc.session.set_direction(mid, dir);

        if changed {
            self.changes.0.push(Change::Direction(mid, dir));
        }
    }

    /// Add a new reliable ordered data channel and get the `id` that will be used.
    ///
    /// Use `add_channel_with_config` when unreliable or unordered data channels are preferred.
    ///
    /// The first ever data channel added to a WebRTC session results in a media
    /// of a special "application" type in the SDP. The m-line is for a SCTP association over
    /// DTLS, and all data channels are multiplexed over this single association.
    ///
    /// That means only the first ever `add_channel` will result in an [`SdpOffer`].
    /// Consecutive channels will be opened without needing a negotiation.
    ///
    /// The label is used to identify the data channel to the remote peer. This is mostly
    /// useful when multiple channels are in use at the same time.
    ///
    /// ```
    /// # use str0m::Rtc;
    /// let mut rtc = Rtc::new();
    ///
    /// let mut changes = rtc.sdp_api();
    ///
    /// let cid = changes.add_channel("my special channel".to_string());
    /// ```
    pub fn add_channel(&mut self, label: String) -> ChannelId {
        self.add_channel_with_config(ChannelConfig {
            label,
            ..Default::default()
        })
    }

    /// Add a new data channel with a given configuration and get the `id` that will be used.
    ///
    /// Refer to `add_channel` for more details.
    ///
    /// ```
    /// # use str0m::{channel::{ChannelConfig, Reliability}, Rtc};
    /// let mut rtc = Rtc::new();
    ///
    /// let mut changes = rtc.sdp_api();
    ///
    /// let cid = changes.add_channel_with_config(ChannelConfig {
    ///     label: "my special channel".to_string(),
    ///     reliability: Reliability::MaxRetransmits{ retransmits: 0 },
    ///     ordered: false,
    ///     ..Default::default()
    /// });
    /// ```
    pub fn add_channel_with_config(&mut self, config: ChannelConfig) -> ChannelId {
        let has_media = self.rtc.session.app().is_some();
        let changes_contains_add_app = self.changes.contains_add_app();

        if !has_media && !changes_contains_add_app {
            let mid = self.rtc.new_mid();
            self.changes.0.push(Change::AddApp(mid));
        }

        let id = self.rtc.chan.new_channel(&config);

        self.changes.0.push(Change::AddChannel((id, config)));

        id
    }

    /// Perform an ICE restart.
    ///
    /// Only one ICE restart can be pending at the time. Calling this repeatedly removes any other
    /// pending ICE restart.
    ///
    /// The local ICE candidates can be kept as is, or be cleared out, in which case new ice
    /// candidates must be added via [`Rtc::add_local_candidate`] before connectivity can be
    /// re-established.
    ///
    /// Returns the new ICE credentials that will be used going forward.
    pub fn ice_restart(&mut self, keep_local_candidates: bool) -> IceCreds {
        self.changes
            .retain(|c| !matches!(c, Change::IceRestart(_, _)));

        let new_creds = IceCreds::new();
        self.changes
            .push(Change::IceRestart(new_creds.clone(), keep_local_candidates));

        new_creds
    }

    /// Attempt to apply the changes made.
    ///
    /// If this returns [`SdpOffer`], the caller the changes are
    /// not happening straight away, and the caller is expected to do a negotiation with the remote
    /// peer and apply the answer using [`SdpPendingOffer`].
    ///
    /// In case this returns `None`, there either were no changes, or the changes could be applied
    /// without doing a negotiation. Specifically for additional [`SdpApi::add_channel()`]
    /// after the first, there is no negotiation needed.
    ///
    /// The [`SdpPendingOffer`] is valid until the next time we call this function, at which
    /// point using it will raise an error. Using [`SdpApi::accept_offer()`] will also invalidate
    /// the current [`SdpPendingOffer`].
    ///
    /// ```
    /// # use str0m::Rtc;
    /// let mut rtc = Rtc::new();
    ///
    /// let changes = rtc.sdp_api();
    /// assert!(changes.apply().is_none());
    /// ```
    pub fn apply(self) -> Option<(SdpOffer, SdpPendingOffer)> {
        if self.changes.is_empty() {
            return None;
        }

        let change_id = self.rtc.next_change_id();

        let requires_negotiation = self.changes.0.iter().any(requires_negotiation);

        if requires_negotiation {
            let offer = create_offer(self.rtc, &self.changes);
            let pending = SdpPendingOffer {
                change_id,
                changes: self.changes,
            };
            debug!("Create offer");
            Some((offer, pending))
        } else {
            debug!("Apply direct changes");
            apply_direct_changes(self.rtc, self.changes);
            None
        }
    }

    /// Combines the modifications made in [`SdpApi`] with those in [`SdpPendingOffer`].
    ///
    /// This function merges the changes present in [`SdpApi`] with the changes
    /// in [`SdpPendingOffer`]. In result this [`SdpApi`] will incorporate modifications
    /// from both the previous [`SdpPendingOffer`] and any newly added changes.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use str0m::media::{Direction, MediaKind};
    /// # use str0m::Rtc;
    /// let mut rtc = Rtc::new();
    /// let mut changes = rtc.sdp_api();
    /// changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None);
    /// let (_offer, pending) = changes.apply().unwrap();
    ///
    /// let mut changes = rtc.sdp_api();
    /// changes.add_media(MediaKind::Video, Direction::SendOnly, None, None);
    /// changes.merge(pending);
    ///
    /// // This `SdpOffer` will have changes from the first `SdpPendingChanges`
    /// // and new changes from `SdpApi`
    /// let (_offer, pending) = changes.apply().unwrap();
    /// ```
    pub fn merge(&mut self, mut pending_offer: SdpPendingOffer) {
        pending_offer.retain_relevant(self.rtc);
        self.changes.extend(pending_offer.changes.drain(..));
    }
}

/// Pending offer from a previous [`Rtc::sdp_api()`] call.
///
/// This allows us to accept a remote answer. No changes have been made to the session
/// before we call [`SdpApi::accept_answer()`], which means that rolling back a
/// change is as simple as dropping this instance.
///
/// ```no_run
/// # use str0m::Rtc;
/// # use str0m::media::{MediaKind, Direction};
/// # use str0m::change::SdpAnswer;
/// let mut rtc = Rtc::new();
///
/// let mut changes = rtc.sdp_api();
/// let mid = changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None);
/// let (offer, pending) = changes.apply().unwrap();
///
/// // send offer to remote peer, receive answer back
/// let answer: SdpAnswer = todo!();
///
/// rtc.sdp_api().accept_answer(pending, answer).unwrap();
/// ```
pub struct SdpPendingOffer {
    change_id: usize,
    changes: Changes,
}

impl SdpPendingOffer {
    /// Retains only the relevant changes in the `changes` vector based on the provided `Rtc` instance.
    ///
    /// This function filters the vector of `Change` instances stored in the current object and retains
    /// only those changes that are considered relevant with respect to the provided `Rtc` instance.
    fn retain_relevant(&mut self, rtc: &Rtc) {
        fn is_relevant(rtc: &Rtc, c: &Change) -> bool {
            match c {
                Change::AddMedia(v) => rtc.media(v.mid).is_none(),
                Change::AddApp(_) => rtc.session.app().is_none(),
                Change::AddChannel(v) => rtc.chan.stream_id_by_channel_id(v.0).is_none(),
                Change::Direction(m, d) => {
                    // If mid is missing, this is not relevant.
                    rtc.media(*m).map(|m| m.direction() != *d).unwrap_or(false)
                }
                Change::IceRestart(v, _) => rtc.ice.local_credentials() != v,
            }
        }

        self.changes.retain(|c| is_relevant(rtc, c));
    }
}

#[derive(Default)]
pub(crate) struct Changes(pub Vec<Change>);

impl Changes {
    /// Details of the active ICE restart, if any.
    ///
    /// Returns the new local ICE credentials and the whether to keep local ICE candidates if an
    /// ICE restart has been initiated in the offer, otherwise [`None`].
    fn ice_restart(&self) -> Option<(IceCreds, bool)> {
        self.iter().find_map(|c| match c {
            Change::IceRestart(creds, keep_local_candidates) => {
                Some((creds.clone(), *keep_local_candidates))
            }
            _ => None,
        })
    }
}

#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub(crate) enum Change {
    AddMedia(AddMedia),
    AddApp(Mid),
    AddChannel((ChannelId, ChannelConfig)),
    Direction(Mid, Direction),
    IceRestart(IceCreds, bool),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AddMedia {
    pub mid: Mid,
    pub cname: String,
    pub msid: Msid,
    pub kind: MediaKind,
    pub dir: Direction,
    pub ssrcs: Vec<(Ssrc, Option<Ssrc>)>,

    // pts and index are filled in when creating the SDP OFFER.
    // The default PT order is set by the Session (BUNDLE).
    // TODO: We can make this configurable here too.
    pub pts: Vec<Pt>,
    pub exts: ExtensionMap,
    pub index: usize,
}

impl Deref for Changes {
    type Target = Vec<Change>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Changes {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

fn requires_negotiation(c: &Change) -> bool {
    match c {
        Change::IceRestart(_, _) => true,
        Change::AddMedia(_) => true,
        Change::AddApp(_) => true,
        Change::AddChannel(_) => false,
        Change::Direction(_, _) => true,
    }
}

fn apply_direct_changes(rtc: &mut Rtc, mut changes: Changes) {
    // Split out new channels, since that is not handled by the Session.
    let new_channels = changes.take_new_channels();

    for (id, config) in new_channels {
        rtc.chan.confirm(id, config);
    }
}

fn create_offer(rtc: &mut Rtc, changes: &Changes) -> SdpOffer {
    if !rtc.dtls.is_inited() {
        // The side that makes the first offer is the controlling side, unless they
        // are ICE Lite, in which case the roles are reversed (see RFC 5245).
        rtc.ice.set_controlling(!rtc.ice.ice_lite());
    }

    let params = AsSdpParams::new(rtc, Some(changes));
    let sdp = as_sdp(&rtc.session, params);

    sdp.into()
}

fn add_ice_details(
    rtc: &mut Rtc,
    sdp: &Sdp,
    pending: Option<&SdpPendingOffer>,
) -> Result<(), RtcError> {
    let Some(creds) = sdp.ice_creds() else {
        return Err(RtcError::RemoteSdp("missing a=ice-ufrag/pwd".into()));
    };

    // If we are handling an **offer** from the remote, differing ICE credentials indicate an ICE
    // restart initiated by the remote.
    //
    // If we are handling an **answer** from the remote, differing ICE credentials indicate an
    // acceptance of an ICE restart we requested.
    let ice_restart = match rtc.ice.remote_credentials() {
        Some(v) => *v != creds,
        None => false,
    };
    if ice_restart {
        let (new_local_creds, keep_local_candidates) = if let Some(pending) = pending {
            // Since we have a pending, this is an answer to our offer.
            pending.changes.ice_restart().ok_or_else(||
                // Answer contained changed remote creds, indicating an ice restart
                // but since we have no pending ice-creds, we didn't initiate it
                // Ice restart in an ANSWER breaks spec.
                    RtcError::RemoteSdp(
                    "Ice restart in answer without one in the preceeding offer".into(),
                ))?
        } else {
            // The remote OFFER had an ice restart, and we need to respond with
            // new credentials in the ANSWER.
            (IceCreds::new(), true)
        };

        rtc.ice
            .ice_restart(new_local_creds.clone(), keep_local_candidates);
    }

    rtc.ice.set_remote_credentials(creds);

    for r in sdp.ice_candidates() {
        rtc.ice.add_remote_candidate(r.clone());
    }

    Ok(())
}

fn init_dtls(rtc: &mut Rtc, remote_sdp: &Sdp) -> Result<(), RtcError> {
    let setup = match remote_sdp.setup() {
        Some(v) => match v {
            // Remote being ActPass, we take Passive role.
            Setup::ActPass => Setup::Passive,
            _ => v.invert(),
        },

        None => {
            warn!("Missing a=setup line");
            Setup::Passive
        }
    };

    let active = setup == Setup::Active;
    rtc.init_dtls(active)?;

    Ok(())
}

fn as_sdp(session: &Session, params: AsSdpParams) -> Sdp {
    let (media_lines, mids, stream_ids) = {
        let mut v = as_media_lines(session);

        let mut new_lines = vec![];

        // When creating new m-lines from the pending changes, the m-line index starts from this.
        let new_index_start = v.len();

        // If there are additions in the pending changes, prepend them now.
        if let Some(pending) = params.pending {
            new_lines = pending
                .as_new_medias(new_index_start, &session.codec_config, &session.exts)
                .collect();
        }

        // Add potentially new m-lines to the existing ones.
        v.extend(new_lines.iter().map(|n| n as &dyn AsSdpMediaLine));

        // Turn into sdp::MediaLine (m-line).
        let mut lines = v
            .iter()
            .map(|m| {
                // Candidates should only be in the first BUNDLE mid
                let include_candidates = m.index() == 0;

                let attrs = params.media_attributes(include_candidates);

                // Already made send stream SSRCs
                let mut ssrcs = session.streams.ssrcs_tx(m.mid());

                // Merged with pending stream SSRCs
                if let Some(pending) = params.pending {
                    ssrcs.extend(pending.ssrcs_for_mid(m.mid()))
                }

                let params: Vec<_> = session
                    .codec_config
                    .all_for_kind(m.kind())
                    .cloned()
                    .collect();

                m.as_media_line(attrs, &ssrcs, &session.exts, &params)
            })
            .collect::<Vec<_>>();

        if let Some(pending) = params.pending {
            pending.apply_to(&mut lines);
        }

        // Mids go into the session part of the SDP.
        let mids = v.iter().map(|m| m.mid()).collect();

        let mut stream_ids = vec![];
        for msid in v.iter().filter_map(|v| v.msid()) {
            if !stream_ids.contains(&msid.stream_id) {
                stream_ids.push(msid.stream_id.clone());
            }
        }

        (lines, mids, stream_ids)
    };

    // AllowMixedExts adds "a=extmap-allow-mixed" at session level to signal
    // support for mixing one-byte and two-byte RTP header extensions.
    // TODO: It would make sense to perform an actual negotiation, however
    //       just adding this line should work fine:
    //       https://github.com/meetecho/janus-gateway/blob/d2e74fdf9bb8aa7a39ed68ed28394afe1e0cd22d/src/sdp.c#L1519
    let mut attrs = vec![
        SessionAttribute::Group {
            typ: "BUNDLE".into(),
            mids,
        },
        SessionAttribute::AllowMixedExts,
        SessionAttribute::MsidSemantic {
            semantic: "WMS".to_string(),
            stream_ids,
        },
    ];

    if session.ice_lite {
        attrs.push(SessionAttribute::IceLite);
    }

    Sdp {
        session: sdp::Session {
            id: session.id(),
            bw: None,
            attrs,
        },
        media_lines,
    }
}

fn apply_offer(session: &mut Session, offer: SdpOffer) -> Result<(), RtcError> {
    offer.assert_consistency()?;

    update_session(session, &offer);

    let new_lines = sync_medias(session, &offer).map_err(RtcError::RemoteSdp)?;

    add_new_lines(session, &new_lines, true).map_err(RtcError::RemoteSdp)?;

    ensure_stream_tx(session);

    Ok(())
}

fn apply_answer(
    session: &mut Session,
    pending: Changes,
    answer: SdpAnswer,
) -> Result<(), RtcError> {
    answer.assert_consistency()?;

    update_session(session, &answer);

    let new_lines = sync_medias(session, &answer).map_err(RtcError::RemoteSdp)?;

    // The new_lines from the answer must correspond to what we sent in the offer.
    if let Some(err) = pending.ensure_correct_answer(&new_lines) {
        return Err(RtcError::RemoteSdp(err));
    }

    add_new_lines(session, &new_lines, false).map_err(RtcError::RemoteSdp)?;

    // Add all pending changes (since we pre-allocated SSRC communicated in the Offer).
    add_pending_changes(session, pending);

    ensure_stream_tx(session);

    Ok(())
}

fn ensure_stream_tx(session: &mut Session) {
    for media in &session.medias {
        // Only make send streams when we have to.
        if !media.direction().is_sending() {
            continue;
        }

        let mut rids: Vec<Option<Rid>> = vec![];

        if let Some(sim) = media.simulcast() {
            for rid in &*sim.send {
                let rid: Rid = rid.0.as_str().into();
                rids.push(Some(rid));
            }
        } else {
            rids.push(None);
        }

        // If any payload param has RTX, we need to prepare for RTX. This is because we always
        // communicate a=ssrc lines, which need to be complete with main and RTX SSRC.
        let has_rtx = session
            .codec_config
            .iter()
            .filter(|p| media.remote_pts().contains(&p.pt))
            .any(|p| p.resend().is_some());

        for rid in rids {
            // If we already have the stream, we don't make any new one.
            let has_stream = session
                .streams
                .stream_tx_by_mid_rid(media.mid(), rid)
                .is_some();

            if has_stream {
                continue;
            }

            let (ssrc, rtx) = if has_rtx {
                let (ssrc, rtx) = session.streams.new_ssrc_pair();
                (ssrc, Some(rtx))
            } else {
                let ssrc = session.streams.new_ssrc();
                (ssrc, None)
            };

            let stream = session
                .streams
                .declare_stream_tx(ssrc, rtx, media.mid(), rid);

            // Configure cache size
            let size = if media.kind().is_audio() {
                session.send_buffer_audio
            } else {
                session.send_buffer_video
            };

            stream.set_rtx_cache(size, DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP);
        }
    }
}

fn add_pending_changes(session: &mut Session, pending: Changes) {
    // For pending AddMedia, we have outgoing SSRC communicated that needs to be added.
    for change in pending.0 {
        let add_media = match change {
            Change::AddMedia(v) => v,
            _ => continue,
        };

        let media = session
            .medias
            .iter_mut()
            .find(|m| m.mid() == add_media.mid)
            .expect("Media to be added for pending mid");

        // the cname/msid has already been communicated in the offer, we need to kep
        // it the same once the m-line is created.
        media.set_cname(add_media.cname);
        media.set_msid(add_media.msid);

        for (ssrc, rtx) in add_media.ssrcs {
            // TODO: When we allow sending RID, we need to add that here.
            let stream = session
                .streams
                .declare_stream_tx(ssrc, rtx, add_media.mid, None);

            let size = if media.kind().is_audio() {
                session.send_buffer_audio
            } else {
                session.send_buffer_video
            };

            stream.set_rtx_cache(size, DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP);
        }
    }
}

/// Compares m-lines in Sdp with that already in the session.
///
/// * Existing m-lines can apply changes (such as direction change).
/// * New m-lines are returned to the caller.
fn sync_medias<'a>(session: &mut Session, sdp: &'a Sdp) -> Result<Vec<&'a MediaLine>, String> {
    let mut new_lines = Vec::with_capacity(sdp.media_lines.len());

    for (idx, m) in sdp.media_lines.iter().enumerate() {
        // First, match existing m-lines.
        match m.typ {
            MediaType::Application => {
                if let Some((_, index)) = session.app() {
                    if idx != *index {
                        return index_err(m.mid());
                    }
                    continue;
                }
            }
            MediaType::Audio | MediaType::Video => {
                if let Some(media) = session.medias.iter_mut().find(|l| l.mid() == m.mid()) {
                    if idx != media.index() {
                        return index_err(m.mid());
                    }

                    update_media(
                        media,
                        m,
                        &mut session.codec_config,
                        &session.exts,
                        &mut session.streams,
                    );

                    continue;
                }
            }
            _ => {
                continue;
            }
        }

        // Second, discover new m-lines.
        new_lines.push(m);
    }

    fn index_err<T>(mid: Mid) -> Result<T, String> {
        Err(format!("Changed order for m-line with mid: {mid}"))
    }

    Ok(new_lines)
}

/// Adds new m-lines as found in an offer or answer.
fn add_new_lines(
    session: &mut Session,
    new_lines: &[&MediaLine],
    is_offer: bool,
) -> Result<(), String> {
    for m in new_lines {
        let idx = session.line_count();

        if m.typ.is_media() {
            let mut media = Media::from_remote_media_line(m, idx, is_offer);
            media.need_open_event = is_offer;

            // Match/remap remote params.
            session
                .codec_config
                .update_params(&m.rtp_params(), m.direction());

            // Remap the extension to that of the answer.
            session.exts.remap(&m.extmaps());

            update_media(
                &mut media,
                m,
                &mut session.codec_config,
                &session.exts,
                &mut session.streams,
            );

            session.add_media(media);
        } else if m.typ.is_channel() {
            session.set_app(m.mid(), idx)?;
        } else {
            return Err(format!(
                "New m-line is neither media nor channel: {}",
                m.mid()
            ));
        }
    }

    Ok(())
}

/// Update session level properties like
/// Extensions from offer or answer.
fn update_session(session: &mut Session, sdp: &Sdp) {
    // Does any m-line contain a a=rtcp-fb:xx transport-cc?
    let has_transport_cc = sdp
        .media_lines
        .iter()
        .any(|m| m.rtp_params().iter().any(|p| p.fb_transport_cc));

    // Is the session level sequence number enabled?
    let has_twcc_header = session
        .exts
        .id_of(Extension::TransportSequenceNumber)
        .is_some();

    // Since twcc feedback is session wide we enable it if there are _any_
    // m-line with a a=rtcp-fb transport-cc parameter and the sequence number
    // header is enabled. It can later be disabled for specific m-lines based
    // on the extensions map.
    if has_transport_cc && has_twcc_header {
        session.enable_twcc_feedback();
    }
}

/// Returns all media/channels as `AsMediaLine` trait.
fn as_media_lines(session: &Session) -> Vec<&dyn AsSdpMediaLine> {
    let mut v = vec![];

    if let Some(app) = session.app() {
        v.push(app as &dyn AsSdpMediaLine);
    }
    v.extend(session.medias().iter().map(|m| m as &dyn AsSdpMediaLine));
    v.sort_by_key(|f| f.index());
    v
}

fn update_media(
    media: &mut Media,
    m: &MediaLine,
    config: &mut CodecConfig,
    exts: &ExtensionMap,
    streams: &mut Streams,
) {
    // Direction changes
    //
    // All changes come from the other side, either via an incoming OFFER
    // or a ANSWER from our OFFER. Either way, the direction is inverted to
    // how we have it locally.
    let new_dir = m.direction().invert();
    //
    let change_direction_disallowed = !media.remote_created()
        && media.direction() == Direction::Inactive
        && new_dir == Direction::SendOnly;

    if change_direction_disallowed {
        info!(
            "Ignore attempt to change inactive to recvonly by remote peer for locally created mid: {}",
            media.mid()
        );
    } else {
        media.set_direction(new_dir);
    }

    for rid in m.rids().iter() {
        media.expect_rid(*rid);
    }

    // Narrowing/ordering of of PT
    let pts: Vec<Pt> = m
        .rtp_params()
        .into_iter()
        .filter_map(|p| config.sdp_match_remote(p, m.direction()))
        .collect();
    media.set_remote_pts(pts);

    let mut remote_extmap = ExtensionMap::empty();
    for (id, ext) in m.extmaps().into_iter() {
        // The remapping of extensions should already have happened, which
        // means the ID are matching in the session to the remote.

        // Does the ID exist in session?
        let in_session = match exts.lookup(id) {
            Some(v) => v,
            None => continue,
        };

        if in_session != ext {
            // Don't set any extensions that aren't enabled in Session.
            continue;
        }

        // Use the Extension from session, since there might be a special
        // serializer for cases like VLA.
        remote_extmap.set(id, in_session.clone());
    }
    media.set_remote_extmap(remote_extmap);

    if new_dir.is_receiving() {
        // SSRC changes
        // This will always be for ReceiverSource since any incoming a=ssrc line will be
        // about the remote side's SSRC.
        let infos = m.ssrc_info();
        let main = infos.iter().filter(|i| i.repairs.is_none());

        if m.simulcast().is_none() {
            // Only use pre-communicated SSRC if we are running without simulcast.
            // We found a bug in FF where the order of the simulcast lines does not
            // correspond to the order of the simulcast declarations. In this case
            // it's better to fall back on mid/rid dynamic mapping.

            for i in main {
                // TODO: If the remote is communicating _BOTH_ rid and a=ssrc this will fail.
                info!("Adding pre-communicated SSRC: {:?}", i);
                let repair_ssrc = infos
                    .iter()
                    .find(|r| r.repairs == Some(i.ssrc))
                    .map(|r| r.ssrc);

                // If remote communicated a main a=ssrc, but no RTX, we will not send nacks.
                let suppress_nack = repair_ssrc.is_none();
                streams.expect_stream_rx(i.ssrc, repair_ssrc, media.mid(), None, suppress_nack);
            }
        }

        // Simulcast configuration
        if let Some(s) = m.simulcast() {
            if s.is_munged {
                warn!("Not supporting simulcast via munging SDP");
            } else if media.simulcast().is_none() {
                // Invert before setting, since it has a recv and send config.
                media.set_simulcast(s.invert());
            }
        }
    }
}

trait AsSdpMediaLine {
    fn mid(&self) -> Mid;
    fn msid(&self) -> Option<&Msid>;
    fn index(&self) -> usize;
    fn kind(&self) -> MediaKind;
    fn as_media_line(
        &self,
        attrs: Vec<MediaAttribute>,
        ssrcs_tx: &[(Ssrc, Option<Ssrc>)],
        exts: &ExtensionMap,
        params: &[PayloadParams],
    ) -> MediaLine;
}

impl AsSdpMediaLine for (Mid, usize) {
    fn mid(&self) -> Mid {
        self.0
    }
    fn msid(&self) -> Option<&Msid> {
        None
    }
    fn index(&self) -> usize {
        self.1
    }
    fn kind(&self) -> MediaKind {
        MediaKind::Audio // doesn't matter for App
    }
    fn as_media_line(
        &self,
        mut attrs: Vec<MediaAttribute>,
        _ssrcs_tx: &[(Ssrc, Option<Ssrc>)],
        _exts: &ExtensionMap,
        _params: &[PayloadParams],
    ) -> MediaLine {
        attrs.push(MediaAttribute::Mid(self.0));
        attrs.push(MediaAttribute::SctpPort(5000));
        attrs.push(MediaAttribute::MaxMessageSize(262144));

        MediaLine {
            typ: sdp::MediaType::Application,
            disabled: false,
            proto: Proto::Sctp,
            pts: vec![],
            bw: None,
            attrs,
        }
    }
}

impl AsSdpMediaLine for Media {
    fn mid(&self) -> Mid {
        Media::mid(self)
    }
    fn msid(&self) -> Option<&Msid> {
        Some(Media::msid(self))
    }
    fn index(&self) -> usize {
        Media::index(self)
    }
    fn kind(&self) -> MediaKind {
        Media::kind(self)
    }
    fn as_media_line(
        &self,
        mut attrs: Vec<MediaAttribute>,
        ssrcs_tx: &[(Ssrc, Option<Ssrc>)],
        exts: &ExtensionMap,
        params: &[PayloadParams],
    ) -> MediaLine {
        if self.app_tmp {
            let app = (self.mid(), self.index());
            return app.as_media_line(attrs, ssrcs_tx, exts, params);
        }

        attrs.push(MediaAttribute::Mid(self.mid()));

        let audio = self.kind() == MediaKind::Audio;
        for (id, ext) in self.remote_extmap().iter_by_media_type(audio) {
            attrs.push(MediaAttribute::ExtMap {
                id,
                ext: ext.clone(),
            });
        }

        attrs.push(self.direction().into());
        attrs.push(MediaAttribute::Msid(self.msid().clone()));
        attrs.push(MediaAttribute::RtcpMux);

        // The effective params start from the Session::codec_config to retain the
        // user's configured preferred order, however they are narrowed only include
        // those the remote peer wants.
        let effective_params = params.iter().filter(|p| self.remote_pts().contains(&p.pt));

        let mut pts = vec![];

        for p in effective_params {
            p.as_media_attrs(&mut attrs);

            // The pts that will be advertised in the SDP
            pts.push(p.pt());
            if let Some(rtx) = p.resend() {
                pts.push(rtx);
            }
        }

        if let Some(s) = self.simulcast() {
            fn to_rids<'a>(
                gs: &'a SimulcastGroups,
                direction: &'static str,
            ) -> impl Iterator<Item = MediaAttribute> + 'a {
                gs.iter().map(move |rid| MediaAttribute::Rid {
                    id: rid.clone(),
                    direction,
                    pt: vec![],
                    restriction: vec![],
                })
            }
            attrs.extend(to_rids(&s.recv, "recv"));
            attrs.extend(to_rids(&s.send, "send"));
            attrs.push(MediaAttribute::Simulcast(s.clone()));
        }

        // Outgoing SSRCs
        let msid = format!("{} {}", self.msid().stream_id, self.msid().track_id);
        for (ssrc, ssrc_rtx) in ssrcs_tx {
            attrs.push(MediaAttribute::Ssrc {
                ssrc: *ssrc,
                attr: "cname".to_string(),
                value: self.cname().to_string(),
            });
            attrs.push(MediaAttribute::Ssrc {
                ssrc: *ssrc,
                attr: "msid".to_string(),
                value: msid.clone(),
            });
            if let Some(ssrc_rtx) = ssrc_rtx {
                attrs.push(MediaAttribute::Ssrc {
                    ssrc: *ssrc_rtx,
                    attr: "cname".to_string(),
                    value: self.cname().to_string(),
                });
                attrs.push(MediaAttribute::Ssrc {
                    ssrc: *ssrc_rtx,
                    attr: "msid".to_string(),
                    value: msid.clone(),
                });
            }
        }

        let count = ssrcs_tx.len();
        #[allow(clippy::comparison_chain)]
        if count == 1 {
            let (ssrc, ssrc_rtx) = &ssrcs_tx[0];
            if let Some(ssrc_rtx) = ssrc_rtx {
                attrs.push(MediaAttribute::SsrcGroup {
                    semantics: "FID".to_string(),
                    ssrcs: vec![*ssrc, *ssrc_rtx],
                });
            }
        } else {
            // TODO: handle simulcast
        }

        MediaLine {
            typ: self.kind().into(),
            disabled: false,
            proto: Proto::Srtp,
            pts,
            bw: None,
            attrs,
        }
    }
}

impl From<MediaKind> for MediaType {
    fn from(value: MediaKind) -> Self {
        match value {
            MediaKind::Audio => MediaType::Audio,
            MediaKind::Video => MediaType::Video,
        }
    }
}

struct AsSdpParams<'a, 'b> {
    pub candidates: Vec<Candidate>,
    pub creds: IceCreds,
    pub fingerprint: &'a Fingerprint,
    pub setup: Setup,
    pub pending: Option<&'b Changes>,
}

impl<'a, 'b> AsSdpParams<'a, 'b> {
    pub fn new(rtc: &'a Rtc, pending: Option<&'b Changes>) -> Self {
        let (creds, candidates) = if let Some((new_creds, keep_local_candidates)) =
            pending.and_then(|p| p.ice_restart())
        {
            if keep_local_candidates {
                // If we are performing an ICE restart and we are keeping the same
                // candidates we need to use ufrag from the new ICE credentials
                // in our offer.
                let mut new_candidates = rtc.ice.local_candidates().to_vec();
                for c in &mut new_candidates {
                    c.set_ufrag(&new_creds.ufrag);
                }

                (new_creds, new_candidates)
            } else {
                (new_creds, vec![])
            }
        } else {
            (
                rtc.ice.local_credentials().clone(),
                rtc.ice.local_candidates().to_vec(),
            )
        };

        AsSdpParams {
            candidates,
            creds,
            fingerprint: rtc.dtls.local_fingerprint(),
            setup: match rtc.dtls.is_active() {
                Some(true) => Setup::Active,
                Some(false) => Setup::Passive,
                None => Setup::ActPass,
            },
            pending,
        }
    }

    fn media_attributes(&self, include_candidates: bool) -> Vec<MediaAttribute> {
        use MediaAttribute::*;

        let mut v = if include_candidates {
            self.candidates
                .iter()
                .map(|c| Candidate(c.clone()))
                .collect()
        } else {
            vec![]
        };

        v.push(IceUfrag(self.creds.ufrag.clone()));
        v.push(IcePwd(self.creds.pass.clone()));
        v.push(IceOptions("trickle".into()));
        v.push(Fingerprint(self.fingerprint.clone()));
        v.push(Setup(self.setup));

        v
    }
}

impl fmt::Debug for SdpPendingOffer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SdpPendingOffer").finish()
    }
}

impl Changes {
    pub fn contains_add_app(&self) -> bool {
        for i in 0..self.0.len() {
            if matches!(&self.0[i], Change::AddApp(_)) {
                return true;
            }
        }
        false
    }

    pub fn take_new_channels(&mut self) -> Vec<(ChannelId, ChannelConfig)> {
        let mut v = vec![];

        if self.0.is_empty() {
            return v;
        }

        for i in (0..self.0.len()).rev() {
            if matches!(&self.0[i], Change::AddChannel(_)) {
                if let Change::AddChannel(id) = self.0.remove(i) {
                    v.push(id);
                }
            }
        }

        v
    }

    /// Tests the given lines (from answer) corresponds to changes.
    fn ensure_correct_answer(&self, lines: &[&MediaLine]) -> Option<String> {
        if self.count_new_medias() != lines.len() {
            return Some(format!(
                "Differing m-line count in offer vs answer: {} != {}",
                self.count_new_medias(),
                lines.len()
            ));
        }

        'next: for l in lines {
            let mid = l.mid();

            for m in &self.0 {
                use Change::*;
                match m {
                    AddMedia(v) if v.mid == mid => {
                        if !l.typ.is_media() {
                            return Some(format!(
                                "Answer m-line for mid ({}) is not of media type: {:?}",
                                mid, l.typ
                            ));
                        }
                        continue 'next;
                    }
                    AddApp(v) if *v == mid => {
                        if !l.typ.is_channel() {
                            return Some(format!(
                                "Answer m-line for mid ({}) is not a data channel: {:?}",
                                mid, l.typ
                            ));
                        }
                        continue 'next;
                    }
                    _ => {}
                }
            }

            return Some(format!("Mid in answer is not in offer: {mid}"));
        }

        None
    }

    fn count_new_medias(&self) -> usize {
        self.0
            .iter()
            .filter(|c| matches!(c, Change::AddMedia(_) | Change::AddApp(_)))
            .count()
    }

    pub fn as_new_medias<'a, 'b: 'a>(
        &'a self,
        index_start: usize,
        config: &'b CodecConfig,
        exts: &'b ExtensionMap,
    ) -> impl Iterator<Item = Media> + 'a {
        self.0
            .iter()
            .enumerate()
            .filter_map(move |(idx, c)| c.as_new_media(index_start + idx, config, exts))
    }

    pub(crate) fn apply_to(&self, lines: &mut [MediaLine]) {
        for change in &self.0 {
            if let Change::Direction(mid, dir) = change {
                if let Some(line) = lines.iter_mut().find(|l| l.mid() == *mid) {
                    if let Some(dir_pos) = line.attrs.iter().position(|a| a.is_direction()) {
                        line.attrs[dir_pos] = (*dir).into();
                    }
                }
            }
        }
    }

    fn ssrcs_for_mid(&self, mid: Mid) -> &[(Ssrc, Option<Ssrc>)] {
        let maybe_add_media = self
            .0
            .iter()
            .filter_map(|c| {
                if let Change::AddMedia(m) = c {
                    Some(m)
                } else {
                    None
                }
            })
            .find(|m| m.mid == mid);

        let Some(m) = maybe_add_media else {
            return &[];
        };

        &m.ssrcs
    }
}

impl Change {
    fn as_new_media(
        &self,
        index: usize,
        config: &CodecConfig,
        exts: &ExtensionMap,
    ) -> Option<Media> {
        use Change::*;
        match self {
            AddMedia(v) => {
                // TODO can we avoid all this cloning?
                let mut add = v.clone();
                add.pts = config.all_for_kind(v.kind).map(|p| p.pt()).collect();
                add.exts = exts.cloned_with_type(v.kind.is_audio());
                add.index = index;

                Some(Media::from_add_media(add))
            }
            AddApp(mid) => Some(Media::from_app_tmp(*mid, index)),
            _ => None,
        }
    }
}

#[cfg(test)]
mod test {
    use crate::format::Codec;
    use crate::sdp::RtpMap;

    use super::*;

    fn resolve_pt(m_line: &MediaLine, needle: Pt) -> RtpMap {
        m_line
            .attrs
            .iter()
            .find_map(|attr| match attr {
                MediaAttribute::RtpMap { pt, value } if *pt == needle => Some(*value),
                _ => None,
            })
            .unwrap_or_else(|| panic!("Expected to find RtpMap for {needle}"))
    }

    #[test]
    fn test_out_of_order_error() {
        let mut rtc1 = Rtc::new();
        let mut rtc2 = Rtc::new();

        let mut change1 = rtc1.sdp_api();
        change1.add_channel("ch1".into());
        let (offer1, pending1) = change1.apply().unwrap();

        let mut change2 = rtc2.sdp_api();
        change2.add_channel("ch2".into());
        let (offer2, _) = change2.apply().unwrap();

        // invalidates pending1
        let _ = rtc1.sdp_api().accept_offer(offer2).unwrap();
        let answer2 = rtc2.sdp_api().accept_offer(offer1).unwrap();

        let r = rtc1.sdp_api().accept_answer(pending1, answer2);

        assert!(matches!(r, Err(RtcError::ChangesOutOfOrder)));
    }

    #[test]
    fn sdp_api_merge_works() {
        let mut rtc = Rtc::new();
        let mut changes = rtc.sdp_api();
        changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None);
        let (offer, pending) = changes.apply().unwrap();

        let mut changes = rtc.sdp_api();
        changes.add_media(MediaKind::Video, Direction::SendOnly, None, None);
        changes.merge(pending);
        let (new_offer, _) = changes.apply().unwrap();

        assert_eq!(offer.media_lines[0], new_offer.media_lines[1]);
        assert_eq!(new_offer.media_lines.len(), 2);
    }

    #[test]
    fn test_rtp_payload_priority() {
        let mut rtc1 = Rtc::builder()
            .clear_codecs()
            .enable_h264(true)
            .enable_vp8(true)
            .enable_vp9(true)
            .build();
        let mut rtc2 = Rtc::builder()
            .clear_codecs()
            .enable_vp8(true)
            .enable_h264(true)
            .build();

        let mut change1 = rtc1.sdp_api();
        change1.add_media(MediaKind::Video, Direction::SendOnly, None, None);
        let (offer1, _) = change1.apply().unwrap();

        let answer = rtc2.sdp_api().accept_offer(offer1).unwrap();
        assert_eq!(
            answer.media_lines.len(),
            1,
            "There should be one mline only"
        );

        let first_mline = &answer.media_lines[0];
        let first_pt = resolve_pt(first_mline, first_mline.pts[0]);

        assert_eq!(
            first_pt.codec, Codec::Vp8,
            "The first PT returned should be the highest priority PT from the answer that is supported."
        );

        let vp9_unsupported = first_mline
            .pts
            .iter()
            .any(|pt| resolve_pt(first_mline, *pt).codec == Codec::Vp9);

        assert!(
            !vp9_unsupported,
            "VP9 was not offered, so it should not be present in the answer"
        );
    }
}