mediasoup-sys 0.12.2

FFI bindings to C++ libmediasoup-worker
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
#define MS_CLASS "RTC::SCTP::OutstandingData"
// #define MS_LOG_DEV_LEVEL 3

#include "RTC/SCTP/tx/OutstandingData.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "RTC/SCTP/packet/chunks/AnyForwardTsnChunk.hpp"
#include "Utils.hpp"
#include <map>

namespace RTC
{
	namespace SCTP
	{
		/* Static. */

		// The number of times a packet must be NACKed before it's retransmitted.
		//
		// @see https://datatracker.ietf.org/doc/html/rfc9260#section-7.2.4
		constexpr uint8_t NumberOfNacksForRetransmission{ 3 };

		/* Instance methods. */

		OutstandingData::Item::Item(
		  uint32_t outgoingMessageId,
		  UserData data,
		  uint64_t timeSentMs,
		  uint16_t maxRetransmissions,
		  uint64_t expiresAtMs,
		  std::optional<uint64_t> lifecycleId)
		  : outgoingMessageId(outgoingMessageId),
		    data(std::move(data)),
		    timeSentMs(timeSentMs),
		    maxRetransmissions(maxRetransmissions),
		    expiresAtMs(expiresAtMs),
		    lifecycleId(lifecycleId)
		{
			MS_TRACE();
		}

		void OutstandingData::Item::Ack()
		{
			MS_TRACE();

			if (this->lifecycle != Lifecycle::ABANDONED)
			{
				this->lifecycle = Lifecycle::ACTIVE;
			}

			this->ackState = AckState::ACKED;
		}

		OutstandingData::Item::NackAction OutstandingData::Item::Nack(bool retransmitNow)
		{
			MS_TRACE();

			this->ackState = AckState::NACKED;
			++this->nackCount;

			if (!ShouldBeRetransmitted() && !IsAbandoned() && (retransmitNow || this->nackCount >= NumberOfNacksForRetransmission))
			{
				// Nacked enough times, it's considered lost.
				if (this->numRetransmissions < this->maxRetransmissions)
				{
					this->lifecycle = Lifecycle::TO_BE_RETRANSMITTED;

					return NackAction::RETRANSMIT;
				}

				Abandon();

				return NackAction::ABANDON;
			}

			return NackAction::NOTHING;
		}

		void OutstandingData::Item::MarkAsRetransmitted()
		{
			MS_TRACE();

			this->lifecycle = Lifecycle::ACTIVE;
			this->ackState  = AckState::UNACKED;
			this->nackCount = 0;
			++this->numRetransmissions;
		}

		void OutstandingData::Item::Abandon()
		{
			MS_TRACE();

			MS_ASSERT(
			  this->expiresAtMs != Types::ExpiresAtMsInfinite ||
			    this->maxRetransmissions != Types::MaxRetransmitsNoLimit,
			  "item should not have infinite expiration time or its retransmission times shouldn't be the maximum");

			this->lifecycle = Lifecycle::ABANDONED;
		}

		OutstandingData::OutstandingData(
		  size_t dataChunkHeaderLength,
		  Types::UnwrappedTsn lastCumulativeTsnAck,
		  std::function<bool(uint16_t /*streamId*/, uint32_t /*outgoingMessageId*/)> discardFromSendQueue)
		  : dataChunkHeaderLength(dataChunkHeaderLength),
		    lastCumulativeTsnAck(lastCumulativeTsnAck),
		    discardFromSendQueue(std::move(discardFromSendQueue))
		{
			MS_TRACE();
		}

		OutstandingData::AckInfo OutstandingData::HandleSack(
		  Types::UnwrappedTsn cumulativeTsnAck,
		  std::span<const SackChunk::GapAckBlock> gapAckBlocks,
		  bool isInFastRecovery)
		{
			MS_TRACE();

			const bool cumulativeTsnAckAdvanced = cumulativeTsnAck > this->lastCumulativeTsnAck;

			OutstandingData::AckInfo ackInfo(cumulativeTsnAck);

			// Erase all items up to cumulativeTsnAck.
			RemoveAcked(cumulativeTsnAck, ackInfo);

			// ACK packets reported in the gap ack blocks.
			AckGapBlocks(cumulativeTsnAck, gapAckBlocks, ackInfo);

			// NACK and possibly mark for retransmit chunks that weren't acked.
			NackBetweenAckBlocks(
			  cumulativeTsnAck, gapAckBlocks, isInFastRecovery, cumulativeTsnAckAdvanced, ackInfo);

			AssertIsConsistent();

			return ackInfo;
		}

		std::vector<std::pair<uint32_t /*tsn*/, UserData>> OutstandingData::GetChunksToBeFastRetransmitted(
		  size_t maxLength)
		{
			MS_TRACE();

			std::vector<std::pair<uint32_t /*tsn*/, UserData>> result =
			  ExtractChunksThatCanFit(this->toBeFastRetransmitted, maxLength);

			// https://datatracker.ietf.org/doc/html/rfc9260#section-7.2.4
			//
			// "Those TSNs marked for retransmission due to the Fast-Retransmit
			// algorithm that did not fit in the sent datagram carrying K other TSNs
			// are also marked as ineligible for a subsequent Fast Retransmit.
			// However, as they are marked for retransmission they will be
			// retransmitted later on as soon as cwnd allows."
			if (!this->toBeFastRetransmitted.empty())
			{
				this->toBeRetransmitted.insert(
				  this->toBeFastRetransmitted.begin(), this->toBeFastRetransmitted.end());

				this->toBeFastRetransmitted.clear();
			}

			AssertIsConsistent();

			return result;
		}

		std::vector<std::pair<uint32_t /*tsn*/, UserData>> OutstandingData::GetChunksToBeRetransmitted(
		  size_t maxLength)
		{
			MS_TRACE();

			// Chunks scheduled for fast retransmission must be sent first.
			MS_ASSERT(this->toBeFastRetransmitted.empty(), "this->toBeFastRetransmitted is not empty");

			return ExtractChunksThatCanFit(this->toBeRetransmitted, maxLength);
		}

		void OutstandingData::ExpireOutstandingChunks(uint64_t nowMs)
		{
			MS_TRACE();

			std::vector<Types::UnwrappedTsn> tsnsToExpire;
			Types::UnwrappedTsn tsn = this->lastCumulativeTsnAck;

			for (const Item& item : this->outstandingData)
			{
				tsn.Increment();

				// Chunks that are nacked can be expired. Care should be taken not to
				// expire unacked (in-flight) chunks as they might have been received,
				// but the SACK is either delayed or in-flight and may be received
				// later.
				if (item.IsAbandoned())
				{
					// Already abandoned.
				}
				else if (item.IsNacked() && item.HasExpired(nowMs))
				{
					tsnsToExpire.push_back(tsn);
				}
				else
				{
					// A non-expired chunk. No need to iterate any further.
					break;
				}
			}

			for (const Types::UnwrappedTsn tsnToExpire : tsnsToExpire)
			{
				// The item is retrieved by TSN, as AbandonAllFor() may have modified
				// `this->outstandingData` and invalidated iterators from the first
				// loop.
				const Item& item = GetItem(tsnToExpire);

				MS_WARN_TAG(
				  sctp,
				  "marking nacked chunk %" PRIu32 " and message %" PRIu32 " as expired",
				  tsnToExpire.Wrap(),
				  item.GetData().GetMessageId());

				AbandonAllFor(item);
			}

			AssertIsConsistent();
		}

		Types::UnwrappedTsn OutstandingData::GetHighestOutstandingTsn() const
		{
			MS_TRACE();

			return Types::UnwrappedTsn::AddTo(this->lastCumulativeTsnAck, this->outstandingData.size());
		}

		std::optional<Types::UnwrappedTsn> OutstandingData::Insert(
		  uint32_t outgoingMessageId,
		  const UserData& data,
		  uint64_t timeSentMs,
		  uint16_t maxRetransmissions,
		  uint64_t expiresAtMs,
		  std::optional<uint64_t> lifecycleId)
		{
			MS_TRACE();

			// All chunks are always padded to be even divisible by 4.
			const size_t chunkLength = GetSerializedChunkLength(data);

			this->unackedPayloadBytes += data.GetPayloadLength();
			this->unackedPacketBytes += chunkLength;
			++this->unackedItems;

			const Types::UnwrappedTsn tsn = GetNextTsn();
			const Item& item              = this->outstandingData.emplace_back(
			  outgoingMessageId, data.Clone(), timeSentMs, maxRetransmissions, expiresAtMs, lifecycleId);

			if (item.HasExpired(timeSentMs))
			{
				// No need to send it, it was expired when it was in the send queue.
				MS_WARN_TAG(
				  sctp,
				  "marking freshly produced chunk %" PRIu32 " and message %" PRIu32 " as expired",
				  tsn.Wrap(),
				  item.GetData().GetMessageId());

				AbandonAllFor(item);

				AssertIsConsistent();

				return std::nullopt;
			}

			AssertIsConsistent();

			return tsn;
		}

		void OutstandingData::NackAll()
		{
			MS_TRACE();

			Types::UnwrappedTsn tsn = this->lastCumulativeTsnAck;

			// A two-pass algorithm is needed, as NackItem will invalidate iterators.
			std::vector<Types::UnwrappedTsn> tsnsToNack;

			for (const Item& item : this->outstandingData)
			{
				tsn.Increment();

				if (!item.IsAcked())
				{
					tsnsToNack.push_back(tsn);
				}
			}

			for (const Types::UnwrappedTsn tsnToNack : tsnsToNack)
			{
				NackItem(
				  tsnToNack,
				  /*retransmitNow*/ true,
				  /*doFastRetransmit*/ false);
			}

			AssertIsConsistent();
		}

		const ForwardTsnChunk* OutstandingData::AddForwardTsn(Packet* packet) const
		{
			MS_TRACE();

			std::map<uint16_t /*streamId*/, uint16_t /*ssn*/> skippedPerOrderedStream;
			Types::UnwrappedTsn newCumulativeAck = this->lastCumulativeTsnAck;
			Types::UnwrappedTsn tsn              = this->lastCumulativeTsnAck;

			for (const Item& item : this->outstandingData)
			{
				tsn.Increment();

				if (
				  this->streamResetBreakpointTsns.contains(tsn) ||
				  (tsn != newCumulativeAck.GetNextValue()) || !item.IsAbandoned())
				{
					break;
				}

				newCumulativeAck = tsn;

				if (
				  !item.GetData().IsUnordered() && item.GetData().GetStreamSequenceNumber() >
				                                     skippedPerOrderedStream[item.GetData().GetStreamId()])
				{
					skippedPerOrderedStream[item.GetData().GetStreamId()] =
					  item.GetData().GetStreamSequenceNumber();
				}
			}

			auto* forwardTsnChunk = packet->BuildChunkInPlace<ForwardTsnChunk>();

			forwardTsnChunk->SetNewCumulativeTsn(newCumulativeAck.Wrap());

			for (const auto& [streamId, ssn] : skippedPerOrderedStream)
			{
				forwardTsnChunk->AddSkippedStream(AnyForwardTsnChunk::SkippedStream{ streamId, ssn });
			}

			forwardTsnChunk->Consolidate();

			return forwardTsnChunk;
		}

		const IForwardTsnChunk* OutstandingData::AddIForwardTsn(Packet* packet) const
		{
			MS_TRACE();

			std::map<std::pair<bool /*unordered*/, uint16_t /*streamId*/>, uint32_t /*mid*/> skippedPerStream;
			Types::UnwrappedTsn newCumulativeAck = this->lastCumulativeTsnAck;
			Types::UnwrappedTsn tsn              = this->lastCumulativeTsnAck;

			for (const Item& item : this->outstandingData)
			{
				tsn.Increment();

				if (
				  this->streamResetBreakpointTsns.contains(tsn) ||
				  (tsn != newCumulativeAck.GetNextValue()) || !item.IsAbandoned())
				{
					break;
				}

				newCumulativeAck = tsn;

				const std::pair<bool /*unordered*/, uint16_t /*streamId*/> stream =
				  std::make_pair(item.GetData().IsUnordered(), item.GetData().GetStreamId());

				skippedPerStream[stream] = std::max(item.GetData().GetMessageId(), skippedPerStream[stream]);
			}

			auto* iForwardTsnChunk = packet->BuildChunkInPlace<IForwardTsnChunk>();

			iForwardTsnChunk->SetNewCumulativeTsn(newCumulativeAck.Wrap());

			for (const auto& [stream, mid] : skippedPerStream)
			{
				const uint16_t streamId = stream.second;
				const bool unordered    = stream.first;

				iForwardTsnChunk->AddSkippedStream(
				  AnyForwardTsnChunk::SkippedStream{ unordered, streamId, mid });
			}

			iForwardTsnChunk->Consolidate();

			return iForwardTsnChunk;
		}

		std::optional<uint64_t> OutstandingData::MeasureRtt(uint64_t nowMs, Types::UnwrappedTsn tsn) const
		{
			MS_TRACE();

			if (tsn > this->lastCumulativeTsnAck && tsn < GetNextTsn())
			{
				const Item& item = GetItem(tsn);

				if (!item.HasBeenRetransmitted())
				{
					// https://datatracker.ietf.org/doc/html/rfc9260#section-6.3.1
					//
					// "Karn's algorithm: RTT measurements MUST NOT be made using packets
					// that were retransmitted (and thus for which it is ambiguous
					// whether the reply was for the first instance of the Chunk or for a
					// later instance)"
					return nowMs - item.GetTimeSentMs();
				}
			}

			return std::nullopt;
		}

		bool OutstandingData::ShouldSendForwardTsn() const
		{
			MS_TRACE();

			if (!this->outstandingData.empty())
			{
				return this->outstandingData.front().IsAbandoned();
			}
			else
			{
				return false;
			}
		}

		void OutstandingData::BeginResetStreams()
		{
			MS_TRACE();

			this->streamResetBreakpointTsns.insert(GetNextTsn());
		}

#ifdef MS_TEST
		std::vector<
		  std::pair<uint32_t /*tsn*/, OutstandingData::State>> OutstandingData::GetChunkStatesForTesting() const
		{
			MS_TRACE();

			std::vector<std::pair<uint32_t /*tsn*/, State>> states;

			states.emplace_back(this->lastCumulativeTsnAck.Wrap(), State::ACKED);

			Types::UnwrappedTsn tsn = this->lastCumulativeTsnAck;

			for (const Item& item : this->outstandingData)
			{
				tsn.Increment();

				State state;

				if (item.IsAbandoned())
				{
					state = State::ABANDONED;
				}
				else if (item.ShouldBeRetransmitted())
				{
					state = State::TO_BE_RETRANSMITTED;
				}
				else if (item.IsAcked())
				{
					state = State::ACKED;
				}
				else if (item.IsNacked())
				{
					state = State::NACKED;
				}
				else if (item.IsOutstanding())
				{
					state = State::IN_FLIGHT;
				}
				else
				{
					MS_THROW_ERROR("should not end here");
				}

				states.emplace_back(tsn.Wrap(), state);
			}

			return states;
		}
#endif

		size_t OutstandingData::GetSerializedChunkLength(const UserData& data) const
		{
			MS_TRACE();

			return Utils::Byte::PadTo4Bytes<size_t>(this->dataChunkHeaderLength + data.GetPayloadLength());
		}

		OutstandingData::Item& OutstandingData::GetItem(Types::UnwrappedTsn tsn)
		{
			MS_TRACE();

			MS_ASSERT(
			  tsn > this->lastCumulativeTsnAck, "tsn must be higher than this->lastCumulativeTsnAck");
			MS_ASSERT(tsn < GetNextTsn(), "tsn must be higher than GetNextTsn()");

			const size_t index = Types::UnwrappedTsn::Difference(tsn, this->lastCumulativeTsnAck) - 1;

			MS_ASSERT(index >= 0, "index must be equal or higher than 0");
			MS_ASSERT(
			  index < this->outstandingData.size(),
			  "index must be lower than this->outstandingData.size()");

			return this->outstandingData[index];
		}

		const OutstandingData::Item& OutstandingData::GetItem(Types::UnwrappedTsn tsn) const
		{
			MS_TRACE();

			MS_ASSERT(
			  tsn > this->lastCumulativeTsnAck, "tsn must be higher than this->lastCumulativeTsnAck");
			MS_ASSERT(tsn < GetNextTsn(), "tsn must be higher than GetNextTsn()");

			const size_t index = Types::UnwrappedTsn::Difference(tsn, this->lastCumulativeTsnAck) - 1;

			MS_ASSERT(index >= 0, "index must be equal or higher than 0");
			MS_ASSERT(
			  index < this->outstandingData.size(),
			  "index must be lower than this->outstandingData.size()");

			return this->outstandingData[index];
		}

		void OutstandingData::RemoveAcked(Types::UnwrappedTsn cumulativeTsnAck, AckInfo& ackInfo)
		{
			MS_TRACE();

			while (!this->outstandingData.empty() && this->lastCumulativeTsnAck < cumulativeTsnAck)
			{
				const Types::UnwrappedTsn tsn = this->lastCumulativeTsnAck.GetNextValue();

				Item& item = this->outstandingData.front();

				AckChunk(ackInfo, tsn, item);

				if (item.GetLifecycleId().has_value())
				{
					MS_ASSERT(item.GetData().IsEnd(), "item.GetData().IsEnd() must be true");

					if (item.IsAbandoned())
					{
						ackInfo.abandonedLifecycleIds.push_back(item.GetLifecycleId().value());
					}
					else
					{
						ackInfo.ackedLifecycleIds.push_back(item.GetLifecycleId().value());
					}
				}

				this->outstandingData.pop_front();
				this->lastCumulativeTsnAck.Increment();
			}

			this->streamResetBreakpointTsns.erase(
			  this->streamResetBreakpointTsns.begin(),
			  this->streamResetBreakpointTsns.upper_bound(cumulativeTsnAck.GetNextValue()));
		}

		void OutstandingData::AckGapBlocks(
		  Types::UnwrappedTsn cumulativeTsnAck,
		  std::span<const SackChunk::GapAckBlock> gapAckBlocks,
		  AckInfo& ackInfo)
		{
			MS_TRACE();

			// Mark all non-gaps as ACKED (but they can't be removed) as (from RFC)
			// "SCTP considers the information carried in the Gap Ack Blocks in the
			// SACK Chunk as advisory". Note that when NR-SACK is supported, this can
			// be handled differently.

			for (const auto& block : gapAckBlocks)
			{
				const Types::UnwrappedTsn start = Types::UnwrappedTsn::AddTo(cumulativeTsnAck, block.start);
				const Types::UnwrappedTsn end   = Types::UnwrappedTsn::AddTo(cumulativeTsnAck, block.end);

				for (Types::UnwrappedTsn tsn = start; tsn <= end; tsn = tsn.GetNextValue())
				{
					if (tsn > this->lastCumulativeTsnAck && tsn < GetNextTsn())
					{
						Item& item = GetItem(tsn);

						AckChunk(ackInfo, tsn, item);
					}
				}
			}
		}

		void OutstandingData::NackBetweenAckBlocks(
		  Types::UnwrappedTsn cumulativeTsnAck,
		  std::span<const SackChunk::GapAckBlock> gapAckBlocks,
		  bool isInFastRecovery,
		  bool cumulativeTsnAckedAdvanced,
		  AckInfo& ackInfo)
		{
			MS_TRACE();

			// Mark everything between the blocks as NACKED/TO_BE_RETRANSMITTED.
			//
			// https://datatracker.ietf.org/doc/html/rfc9260#section-7.2.4
			//
			// "Mark the DATA chunk(s) with three miss indications for retransmission."
			// "For each incoming SACK, miss indications are incremented only for
			// missing TSNs prior to the highest TSN newly acknowledged in the SACK."
			//
			// What this means is that only when there is a increasing stream of data
			// received and there are new packets seen (since last time), packets that
			// are in-flight and between gaps should be nacked. This means that SCTP
			// relies on the T3-RTX-timer to re-send packets otherwise.
			Types::UnwrappedTsn maxTsnToNack = ackInfo.highestTsnAcked;

			if (isInFastRecovery && cumulativeTsnAckedAdvanced)
			{
				// https://datatracker.ietf.org/doc/html/rfc9260#section-7.2.4
				//
				// "If an endpoint is in Fast Recovery and a SACK arrives that advances
				// the Cumulative TSN Ack Point, the miss indications are incremented
				// for all TSNs reported missing in the SACK."
				maxTsnToNack = Types::UnwrappedTsn::AddTo(
				  cumulativeTsnAck, gapAckBlocks.empty() ? 0 : gapAckBlocks.rbegin()->end);
			}

			Types::UnwrappedTsn prevBlockLastAcked = cumulativeTsnAck;

			for (const auto& block : gapAckBlocks)
			{
				const Types::UnwrappedTsn curBlockFirstAcked =
				  Types::UnwrappedTsn::AddTo(cumulativeTsnAck, block.start);

				for (Types::UnwrappedTsn tsn = prevBlockLastAcked.GetNextValue();
				     tsn < curBlockFirstAcked && tsn <= maxTsnToNack && tsn < GetNextTsn();
				     tsn = tsn.GetNextValue())
				{
					ackInfo.hasPacketLoss |= NackItem(
					  tsn,
					  /*retransmitNow*/ false,
					  /*doFastRetransmit*/ !isInFastRecovery);
				}

				prevBlockLastAcked = Types::UnwrappedTsn::AddTo(cumulativeTsnAck, block.end);
			}

			// Note that packets are not NACKED which are above the highest
			// gap-ack-block (or above the cumulative ack TSN if no gap-ack-blocks)
			// as only packets up until the `highestTsnAcked` (see above) should be
			// considered when NACKing.
		}

		void OutstandingData::AckChunk(AckInfo& ackInfo, Types::UnwrappedTsn tsn, Item& item)
		{
			MS_TRACE();

			if (!item.IsAcked())
			{
				const size_t serializedLength = GetSerializedChunkLength(item.GetData());

				ackInfo.bytesAcked += serializedLength;

				if (item.IsOutstanding())
				{
					this->unackedPayloadBytes -= item.GetData().GetPayloadLength();
					this->unackedPacketBytes -= serializedLength;
					--this->unackedItems;
				}

				if (item.ShouldBeRetransmitted())
				{
					MS_ASSERT(
					  !this->toBeFastRetransmitted.contains(tsn),
					  "tsn should not be present in this->toBeFastRetransmitted");

					this->toBeRetransmitted.erase(tsn);
				}

				item.Ack();

				ackInfo.highestTsnAcked = std::max(ackInfo.highestTsnAcked, tsn);
			}
		}

		bool OutstandingData::NackItem(Types::UnwrappedTsn tsn, bool retransmitNow, bool doFastRetransmit)
		{
			MS_TRACE();

			Item& item = GetItem(tsn);

			// Ignore NACKs for chunks that have already been acknowledged.
			if (item.IsAcked())
			{
				return false;
			}

			const bool wasOutstanding     = item.IsOutstanding();
			const Item::NackAction action = item.Nack(retransmitNow);

			if (wasOutstanding && !item.IsOutstanding())
			{
				this->unackedPayloadBytes -= item.GetData().GetPayloadLength();
				this->unackedPacketBytes -= GetSerializedChunkLength(item.GetData());
				--this->unackedItems;
			}

			switch (action)
			{
				case Item::NackAction::NOTHING:
				{
					return false;
				}

				case Item::NackAction::RETRANSMIT:
				{
					if (doFastRetransmit)
					{
						this->toBeFastRetransmitted.insert(tsn);
					}
					else
					{
						this->toBeRetransmitted.insert(tsn);
					}

					MS_DEBUG_TAG(sctp, "tsn %" PRIu32 " marked for retransmission", tsn.Wrap());

					break;
				}

				case Item::NackAction::ABANDON:
				{
					MS_DEBUG_TAG(sctp, "tsn %" PRIu32 " nacked, resulted in abandoning", tsn.Wrap());

					AbandonAllFor(item);

					break;
				}
			}

			return true;
		}

		void OutstandingData::AbandonAllFor(const OutstandingData::Item& item)
		{
			MS_TRACE();

			// Erase all remaining chunks from the producer, if any.
			if (this->discardFromSendQueue(item.GetData().GetStreamId(), item.GetOutgoingMessageId()))
			{
				// There were remaining chunks to be produced for this message. Since the
				// receiver may have already received all chunks (up till now) for this
				// message, we can't just FORWARD-TSN to the last fragment in this
				// (abandoned) message and start sending a new message, as the receiver will
				// then see a new message before the end of the previous one was seen (or
				// skipped over). So create a new fragment, representing the end, that the
				// received will never see as it is abandoned immediately and used as cum
				// TSN in the sent FORWARD-TSN.
				UserData messageEnd(
				  item.GetData().GetStreamId(),
				  item.GetData().GetStreamSequenceNumber(),
				  item.GetData().GetMessageId(),
				  item.GetData().GetFragmentSequenceNumber(),
				  item.GetData().GetPayloadProtocolId(),
				  std::vector<uint8_t>(),
				  /*isBeginning*/ false,
				  /*isEnd*/ true,
				  /*isUnordered*/ item.GetData().IsUnordered());

				const Types::UnwrappedTsn tsn = GetNextTsn();

				Item& addedItem = this->outstandingData.emplace_back(
				  item.GetOutgoingMessageId(),
				  std::move(messageEnd),
				  /*timeSentMs*/ 0,
				  /*maxRetransmissions*/ 0,
				  /*expiresAtMs*/ Types::ExpiresAtMsInfinite,
				  /*lifecycleId*/ std::nullopt);

				// The added chunk shouldn't be included in `this->unackedPacketBytes`,
				// so set it as acked.
				addedItem.Ack();

				MS_DEBUG_TAG(sctp, "adding unsent end placeholder for message at TSN %" PRIu32, tsn.Wrap());
			}

			Types::UnwrappedTsn tsn = this->lastCumulativeTsnAck;

			for (Item& other : this->outstandingData)
			{
				tsn.Increment();

				if (
				  !other.IsAbandoned() && other.GetData().GetStreamId() == item.GetData().GetStreamId() &&
				  other.GetOutgoingMessageId() == item.GetOutgoingMessageId())
				{
					MS_WARN_TAG(sctp, "marking chunk %" PRIu32 " as abandoned", tsn.Wrap());

					if (other.ShouldBeRetransmitted())
					{
						this->toBeFastRetransmitted.erase(tsn);
						this->toBeRetransmitted.erase(tsn);
					}

					const bool wasOutstanding = other.IsOutstanding();

					other.Abandon();

					if (wasOutstanding)
					{
						this->unackedPayloadBytes -= other.GetData().GetPayloadLength();
						this->unackedPacketBytes -= GetSerializedChunkLength(other.GetData());
						--this->unackedItems;
					}
				}
			}
		}

		std::vector<std::pair<uint32_t /*tsn*/, UserData>> OutstandingData::ExtractChunksThatCanFit(
		  std::set<Types::UnwrappedTsn>& chunks, size_t maxLength)
		{
			MS_TRACE();

			std::vector<std::pair<uint32_t /*tsn*/, UserData>> result;

			for (auto it = chunks.begin(); it != chunks.end();)
			{
				const Types::UnwrappedTsn tsn = *it;

				Item& item = GetItem(tsn);

				MS_ASSERT(item.ShouldBeRetransmitted(), "item should be retransmitted");
				MS_ASSERT(!item.IsOutstanding(), "item should not be outstanding");
				MS_ASSERT(!item.IsAbandoned(), "item should not be abandoned");
				MS_ASSERT(!item.IsAcked(), "item should not be acked");

				const size_t serializedLength = GetSerializedChunkLength(item.GetData());

				if (serializedLength <= maxLength)
				{
					item.MarkAsRetransmitted();
					result.emplace_back(tsn.Wrap(), item.GetData().Clone());
					maxLength -= serializedLength;

					this->unackedPayloadBytes += item.GetData().GetPayloadLength();
					this->unackedPacketBytes += serializedLength;
					++this->unackedItems;

					it = chunks.erase(it);
				}
				else
				{
					++it;
				}

				// No point in continuing if the packet is full.
				if (maxLength <= this->dataChunkHeaderLength)
				{
					break;
				}
			}

			return result;
		}

		void OutstandingData::AssertIsConsistent() const
		{
			MS_TRACE();

			size_t actualUnackedPayloadBytes{ 0 };
			size_t actualUnackedPacketBytes{ 0 };
			size_t actualUnackedItems{ 0 };

			std::set<Types::UnwrappedTsn> combinedToBeRetransmitted;

			combinedToBeRetransmitted.insert(this->toBeRetransmitted.begin(), this->toBeRetransmitted.end());
			combinedToBeRetransmitted.insert(
			  this->toBeFastRetransmitted.begin(), this->toBeFastRetransmitted.end());

			std::set<Types::UnwrappedTsn> actualCombinedToBeRetransmitted;
			Types::UnwrappedTsn tsn = this->lastCumulativeTsnAck;

			for (const Item& item : this->outstandingData)
			{
				tsn.Increment();

				if (item.IsOutstanding())
				{
					actualUnackedPayloadBytes += item.GetData().GetPayloadLength();
					actualUnackedPacketBytes += GetSerializedChunkLength(item.GetData());
					++actualUnackedItems;
				}

				if (item.ShouldBeRetransmitted())
				{
					actualCombinedToBeRetransmitted.insert(tsn);
				}
			}

			MS_ASSERT(
			  actualUnackedPayloadBytes == this->unackedPayloadBytes,
			  "actualUnackedPayloadBytes != this->unackedPayloadBytes");
			MS_ASSERT(
			  actualUnackedPacketBytes == this->unackedPacketBytes,
			  "actualUnackedPacketBytes != this->unackedPacketBytes");
			MS_ASSERT(actualUnackedItems == this->unackedItems, "actualUnackedItems != this->unackedItems");
			MS_ASSERT(
			  actualCombinedToBeRetransmitted == combinedToBeRetransmitted,
			  "actualCombinedToBeRetransmitted != combinedToBeRetransmitted");
		}
	} // namespace SCTP
} // namespace RTC