1 /*
2 * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "modules/rtp_rtcp/source/rtcp_packet/transport_feedback.h"
12
13 #include <algorithm>
14 #include <cstdint>
15 #include <numeric>
16 #include <utility>
17
18 #include "absl/algorithm/container.h"
19 #include "modules/include/module_common_types_public.h"
20 #include "modules/rtp_rtcp/source/byte_io.h"
21 #include "modules/rtp_rtcp/source/rtcp_packet/common_header.h"
22 #include "rtc_base/checks.h"
23 #include "rtc_base/logging.h"
24 #include "rtc_base/trace_event.h"
25
26 namespace webrtc {
27 namespace rtcp {
28 namespace {
29 // Header size:
30 // * 4 bytes Common RTCP Packet Header
31 // * 8 bytes Common Packet Format for RTCP Feedback Messages
32 // * 8 bytes FeedbackPacket header
33 constexpr size_t kTransportFeedbackHeaderSizeBytes = 4 + 8 + 8;
34 constexpr size_t kChunkSizeBytes = 2;
35 // TODO(sprang): Add support for dynamic max size for easier fragmentation,
36 // eg. set it to what's left in the buffer or IP_PACKET_SIZE.
37 // Size constraint imposed by RTCP common header: 16bit size field interpreted
38 // as number of four byte words minus the first header word.
39 constexpr size_t kMaxSizeBytes = (1 << 16) * 4;
40 // Payload size:
41 // * 8 bytes Common Packet Format for RTCP Feedback Messages
42 // * 8 bytes FeedbackPacket header.
43 // * 2 bytes for one chunk.
44 constexpr size_t kMinPayloadSizeBytes = 8 + 8 + 2;
45 constexpr TimeDelta kBaseTimeTick = TransportFeedback::kDeltaTick * (1 << 8);
46 constexpr TimeDelta kTimeWrapPeriod = kBaseTimeTick * (1 << 24);
47
48 // Message format
49 //
50 // 0 1 2 3
51 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
52 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
53 // |V=2|P| FMT=15 | PT=205 | length |
54 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
55 // 0 | SSRC of packet sender |
56 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
57 // 4 | SSRC of media source |
58 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
59 // 8 | base sequence number | packet status count |
60 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
61 // 12 | reference time | fb pkt. count |
62 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
63 // 16 | packet chunk | packet chunk |
64 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
65 // . .
66 // . .
67 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
68 // | packet chunk | recv delta | recv delta |
69 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
70 // . .
71 // . .
72 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
73 // | recv delta | recv delta | zero padding |
74 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
75 } // namespace
76 constexpr uint8_t TransportFeedback::kFeedbackMessageType;
77 constexpr size_t TransportFeedback::kMaxReportedPackets;
78
79 constexpr size_t TransportFeedback::LastChunk::kMaxRunLengthCapacity;
80 constexpr size_t TransportFeedback::LastChunk::kMaxOneBitCapacity;
81 constexpr size_t TransportFeedback::LastChunk::kMaxTwoBitCapacity;
82 constexpr size_t TransportFeedback::LastChunk::kMaxVectorCapacity;
83
LastChunk()84 TransportFeedback::LastChunk::LastChunk() {
85 Clear();
86 }
87
Empty() const88 bool TransportFeedback::LastChunk::Empty() const {
89 return size_ == 0;
90 }
91
Clear()92 void TransportFeedback::LastChunk::Clear() {
93 size_ = 0;
94 all_same_ = true;
95 has_large_delta_ = false;
96 }
97
CanAdd(DeltaSize delta_size) const98 bool TransportFeedback::LastChunk::CanAdd(DeltaSize delta_size) const {
99 RTC_DCHECK_LE(delta_size, 2);
100 if (size_ < kMaxTwoBitCapacity)
101 return true;
102 if (size_ < kMaxOneBitCapacity && !has_large_delta_ && delta_size != kLarge)
103 return true;
104 if (size_ < kMaxRunLengthCapacity && all_same_ &&
105 delta_sizes_[0] == delta_size)
106 return true;
107 return false;
108 }
109
Add(DeltaSize delta_size)110 void TransportFeedback::LastChunk::Add(DeltaSize delta_size) {
111 RTC_DCHECK(CanAdd(delta_size));
112 if (size_ < kMaxVectorCapacity)
113 delta_sizes_[size_] = delta_size;
114 size_++;
115 all_same_ = all_same_ && delta_size == delta_sizes_[0];
116 has_large_delta_ = has_large_delta_ || delta_size == kLarge;
117 }
118
AddMissingPackets(size_t num_missing)119 void TransportFeedback::LastChunk::AddMissingPackets(size_t num_missing) {
120 RTC_DCHECK_EQ(size_, 0);
121 RTC_DCHECK(all_same_);
122 RTC_DCHECK(!has_large_delta_);
123 RTC_DCHECK_LT(num_missing, kMaxRunLengthCapacity);
124 absl::c_fill(delta_sizes_, DeltaSize(0));
125 size_ = num_missing;
126 }
127
Emit()128 uint16_t TransportFeedback::LastChunk::Emit() {
129 RTC_DCHECK(!CanAdd(0) || !CanAdd(1) || !CanAdd(2));
130 if (all_same_) {
131 uint16_t chunk = EncodeRunLength();
132 Clear();
133 return chunk;
134 }
135 if (size_ == kMaxOneBitCapacity) {
136 uint16_t chunk = EncodeOneBit();
137 Clear();
138 return chunk;
139 }
140 RTC_DCHECK_GE(size_, kMaxTwoBitCapacity);
141 uint16_t chunk = EncodeTwoBit(kMaxTwoBitCapacity);
142 // Remove `kMaxTwoBitCapacity` encoded delta sizes:
143 // Shift remaining delta sizes and recalculate all_same_ && has_large_delta_.
144 size_ -= kMaxTwoBitCapacity;
145 all_same_ = true;
146 has_large_delta_ = false;
147 for (size_t i = 0; i < size_; ++i) {
148 DeltaSize delta_size = delta_sizes_[kMaxTwoBitCapacity + i];
149 delta_sizes_[i] = delta_size;
150 all_same_ = all_same_ && delta_size == delta_sizes_[0];
151 has_large_delta_ = has_large_delta_ || delta_size == kLarge;
152 }
153
154 return chunk;
155 }
156
EncodeLast() const157 uint16_t TransportFeedback::LastChunk::EncodeLast() const {
158 RTC_DCHECK_GT(size_, 0);
159 if (all_same_)
160 return EncodeRunLength();
161 if (size_ <= kMaxTwoBitCapacity)
162 return EncodeTwoBit(size_);
163 return EncodeOneBit();
164 }
165
166 // Appends content of the Lastchunk to `deltas`.
AppendTo(std::vector<DeltaSize> * deltas) const167 void TransportFeedback::LastChunk::AppendTo(
168 std::vector<DeltaSize>* deltas) const {
169 if (all_same_) {
170 deltas->insert(deltas->end(), size_, delta_sizes_[0]);
171 } else {
172 deltas->insert(deltas->end(), delta_sizes_.begin(),
173 delta_sizes_.begin() + size_);
174 }
175 }
176
Decode(uint16_t chunk,size_t max_size)177 void TransportFeedback::LastChunk::Decode(uint16_t chunk, size_t max_size) {
178 if ((chunk & 0x8000) == 0) {
179 DecodeRunLength(chunk, max_size);
180 } else if ((chunk & 0x4000) == 0) {
181 DecodeOneBit(chunk, max_size);
182 } else {
183 DecodeTwoBit(chunk, max_size);
184 }
185 }
186
187 // One Bit Status Vector Chunk
188 //
189 // 0 1
190 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
191 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
192 // |T|S| symbol list |
193 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
194 //
195 // T = 1
196 // S = 0
197 // Symbol list = 14 entries where 0 = not received, 1 = received 1-byte delta.
EncodeOneBit() const198 uint16_t TransportFeedback::LastChunk::EncodeOneBit() const {
199 RTC_DCHECK(!has_large_delta_);
200 RTC_DCHECK_LE(size_, kMaxOneBitCapacity);
201 uint16_t chunk = 0x8000;
202 for (size_t i = 0; i < size_; ++i)
203 chunk |= delta_sizes_[i] << (kMaxOneBitCapacity - 1 - i);
204 return chunk;
205 }
206
DecodeOneBit(uint16_t chunk,size_t max_size)207 void TransportFeedback::LastChunk::DecodeOneBit(uint16_t chunk,
208 size_t max_size) {
209 RTC_DCHECK_EQ(chunk & 0xc000, 0x8000);
210 size_ = std::min(kMaxOneBitCapacity, max_size);
211 has_large_delta_ = false;
212 all_same_ = false;
213 for (size_t i = 0; i < size_; ++i)
214 delta_sizes_[i] = (chunk >> (kMaxOneBitCapacity - 1 - i)) & 0x01;
215 }
216
217 // Two Bit Status Vector Chunk
218 //
219 // 0 1
220 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
221 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
222 // |T|S| symbol list |
223 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
224 //
225 // T = 1
226 // S = 1
227 // symbol list = 7 entries of two bits each.
EncodeTwoBit(size_t size) const228 uint16_t TransportFeedback::LastChunk::EncodeTwoBit(size_t size) const {
229 RTC_DCHECK_LE(size, size_);
230 uint16_t chunk = 0xc000;
231 for (size_t i = 0; i < size; ++i)
232 chunk |= delta_sizes_[i] << 2 * (kMaxTwoBitCapacity - 1 - i);
233 return chunk;
234 }
235
DecodeTwoBit(uint16_t chunk,size_t max_size)236 void TransportFeedback::LastChunk::DecodeTwoBit(uint16_t chunk,
237 size_t max_size) {
238 RTC_DCHECK_EQ(chunk & 0xc000, 0xc000);
239 size_ = std::min(kMaxTwoBitCapacity, max_size);
240 has_large_delta_ = true;
241 all_same_ = false;
242 for (size_t i = 0; i < size_; ++i)
243 delta_sizes_[i] = (chunk >> 2 * (kMaxTwoBitCapacity - 1 - i)) & 0x03;
244 }
245
246 // Run Length Status Vector Chunk
247 //
248 // 0 1
249 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
250 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
251 // |T| S | Run Length |
252 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
253 //
254 // T = 0
255 // S = symbol
256 // Run Length = Unsigned integer denoting the run length of the symbol
EncodeRunLength() const257 uint16_t TransportFeedback::LastChunk::EncodeRunLength() const {
258 RTC_DCHECK(all_same_);
259 RTC_DCHECK_LE(size_, kMaxRunLengthCapacity);
260 return (delta_sizes_[0] << 13) | static_cast<uint16_t>(size_);
261 }
262
DecodeRunLength(uint16_t chunk,size_t max_count)263 void TransportFeedback::LastChunk::DecodeRunLength(uint16_t chunk,
264 size_t max_count) {
265 RTC_DCHECK_EQ(chunk & 0x8000, 0);
266 size_ = std::min<size_t>(chunk & 0x1fff, max_count);
267 DeltaSize delta_size = (chunk >> 13) & 0x03;
268 has_large_delta_ = delta_size >= kLarge;
269 all_same_ = true;
270 // To make it consistent with Add function, populate delta_sizes_ beyond 1st.
271 for (size_t i = 0; i < std::min<size_t>(size_, kMaxVectorCapacity); ++i)
272 delta_sizes_[i] = delta_size;
273 }
274
TransportFeedback()275 TransportFeedback::TransportFeedback()
276 : TransportFeedback(/*include_timestamps=*/true, /*include_lost=*/true) {}
277
TransportFeedback(bool include_timestamps,bool include_lost)278 TransportFeedback::TransportFeedback(bool include_timestamps, bool include_lost)
279 : include_lost_(include_lost),
280 base_seq_no_(0),
281 num_seq_no_(0),
282 base_time_ticks_(0),
283 feedback_seq_(0),
284 include_timestamps_(include_timestamps),
285 last_timestamp_(Timestamp::Zero()),
286 size_bytes_(kTransportFeedbackHeaderSizeBytes) {}
287
288 TransportFeedback::TransportFeedback(const TransportFeedback&) = default;
289
TransportFeedback(TransportFeedback && other)290 TransportFeedback::TransportFeedback(TransportFeedback&& other)
291 : include_lost_(other.include_lost_),
292 base_seq_no_(other.base_seq_no_),
293 num_seq_no_(other.num_seq_no_),
294 base_time_ticks_(other.base_time_ticks_),
295 feedback_seq_(other.feedback_seq_),
296 include_timestamps_(other.include_timestamps_),
297 last_timestamp_(other.last_timestamp_),
298 received_packets_(std::move(other.received_packets_)),
299 all_packets_(std::move(other.all_packets_)),
300 encoded_chunks_(std::move(other.encoded_chunks_)),
301 last_chunk_(other.last_chunk_),
302 size_bytes_(other.size_bytes_) {
303 other.Clear();
304 }
305
~TransportFeedback()306 TransportFeedback::~TransportFeedback() {}
307
SetBase(uint16_t base_sequence,Timestamp ref_timestamp)308 void TransportFeedback::SetBase(uint16_t base_sequence,
309 Timestamp ref_timestamp) {
310 RTC_DCHECK_EQ(num_seq_no_, 0);
311 base_seq_no_ = base_sequence;
312 base_time_ticks_ =
313 (ref_timestamp.us() % kTimeWrapPeriod.us()) / kBaseTimeTick.us();
314 last_timestamp_ = BaseTime();
315 }
316
SetFeedbackSequenceNumber(uint8_t feedback_sequence)317 void TransportFeedback::SetFeedbackSequenceNumber(uint8_t feedback_sequence) {
318 feedback_seq_ = feedback_sequence;
319 }
320
AddReceivedPacket(uint16_t sequence_number,Timestamp timestamp)321 bool TransportFeedback::AddReceivedPacket(uint16_t sequence_number,
322 Timestamp timestamp) {
323 // Set delta to zero if timestamps are not included, this will simplify the
324 // encoding process.
325 int16_t delta = 0;
326 if (include_timestamps_) {
327 // Convert to ticks and round.
328 if (last_timestamp_ > timestamp) {
329 timestamp += (last_timestamp_ - timestamp).RoundUpTo(kTimeWrapPeriod);
330 }
331 RTC_DCHECK_GE(timestamp, last_timestamp_);
332 int64_t delta_full =
333 (timestamp - last_timestamp_).us() % kTimeWrapPeriod.us();
334 if (delta_full > kTimeWrapPeriod.us() / 2) {
335 delta_full -= kTimeWrapPeriod.us();
336 delta_full -= kDeltaTick.us() / 2;
337 } else {
338 delta_full += kDeltaTick.us() / 2;
339 }
340 delta_full /= kDeltaTick.us();
341
342 delta = static_cast<int16_t>(delta_full);
343 // If larger than 16bit signed, we can't represent it - need new fb packet.
344 if (delta != delta_full) {
345 RTC_LOG(LS_WARNING) << "Delta value too large ( >= 2^16 ticks )";
346 return false;
347 }
348 }
349
350 uint16_t next_seq_no = base_seq_no_ + num_seq_no_;
351 if (sequence_number != next_seq_no) {
352 uint16_t last_seq_no = next_seq_no - 1;
353 if (!IsNewerSequenceNumber(sequence_number, last_seq_no))
354 return false;
355 uint16_t num_missing_packets = sequence_number - next_seq_no;
356 if (!AddMissingPackets(num_missing_packets))
357 return false;
358 if (include_lost_) {
359 for (; next_seq_no != sequence_number; ++next_seq_no) {
360 all_packets_.emplace_back(next_seq_no);
361 }
362 }
363 }
364
365 DeltaSize delta_size = (delta >= 0 && delta <= 0xff) ? 1 : 2;
366 if (!AddDeltaSize(delta_size))
367 return false;
368
369 received_packets_.emplace_back(sequence_number, delta);
370 if (include_lost_)
371 all_packets_.emplace_back(sequence_number, delta);
372 last_timestamp_ += delta * kDeltaTick;
373 if (include_timestamps_) {
374 size_bytes_ += delta_size;
375 }
376 return true;
377 }
378
379 const std::vector<TransportFeedback::ReceivedPacket>&
GetReceivedPackets() const380 TransportFeedback::GetReceivedPackets() const {
381 return received_packets_;
382 }
383
384 const std::vector<TransportFeedback::ReceivedPacket>&
GetAllPackets() const385 TransportFeedback::GetAllPackets() const {
386 RTC_DCHECK(include_lost_);
387 return all_packets_;
388 }
389
GetBaseSequence() const390 uint16_t TransportFeedback::GetBaseSequence() const {
391 return base_seq_no_;
392 }
393
BaseTime() const394 Timestamp TransportFeedback::BaseTime() const {
395 // Add an extra kTimeWrapPeriod to allow add received packets arrived earlier
396 // than the first added packet (and thus allow to record negative deltas)
397 // even when base_time_ticks_ == 0.
398 return Timestamp::Zero() + kTimeWrapPeriod +
399 int64_t{base_time_ticks_} * kBaseTimeTick;
400 }
401
GetBaseDelta(Timestamp prev_timestamp) const402 TimeDelta TransportFeedback::GetBaseDelta(Timestamp prev_timestamp) const {
403 TimeDelta delta = BaseTime() - prev_timestamp;
404 // Compensate for wrap around.
405 if ((delta - kTimeWrapPeriod).Abs() < delta.Abs()) {
406 delta -= kTimeWrapPeriod; // Wrap backwards.
407 } else if ((delta + kTimeWrapPeriod).Abs() < delta.Abs()) {
408 delta += kTimeWrapPeriod; // Wrap forwards.
409 }
410 return delta;
411 }
412
413 // De-serialize packet.
Parse(const CommonHeader & packet)414 bool TransportFeedback::Parse(const CommonHeader& packet) {
415 RTC_DCHECK_EQ(packet.type(), kPacketType);
416 RTC_DCHECK_EQ(packet.fmt(), kFeedbackMessageType);
417 TRACE_EVENT0("webrtc", "TransportFeedback::Parse");
418
419 if (packet.payload_size_bytes() < kMinPayloadSizeBytes) {
420 RTC_LOG(LS_WARNING) << "Buffer too small (" << packet.payload_size_bytes()
421 << " bytes) to fit a "
422 "FeedbackPacket. Minimum size = "
423 << kMinPayloadSizeBytes;
424 return false;
425 }
426
427 const uint8_t* const payload = packet.payload();
428 ParseCommonFeedback(payload);
429
430 base_seq_no_ = ByteReader<uint16_t>::ReadBigEndian(&payload[8]);
431 uint16_t status_count = ByteReader<uint16_t>::ReadBigEndian(&payload[10]);
432 base_time_ticks_ = ByteReader<uint32_t, 3>::ReadBigEndian(&payload[12]);
433 feedback_seq_ = payload[15];
434 Clear();
435 size_t index = 16;
436 const size_t end_index = packet.payload_size_bytes();
437
438 if (status_count == 0) {
439 RTC_LOG(LS_WARNING) << "Empty feedback messages not allowed.";
440 return false;
441 }
442
443 std::vector<uint8_t> delta_sizes;
444 delta_sizes.reserve(status_count);
445 while (delta_sizes.size() < status_count) {
446 if (index + kChunkSizeBytes > end_index) {
447 RTC_LOG(LS_WARNING) << "Buffer overflow while parsing packet.";
448 Clear();
449 return false;
450 }
451
452 uint16_t chunk = ByteReader<uint16_t>::ReadBigEndian(&payload[index]);
453 index += kChunkSizeBytes;
454 encoded_chunks_.push_back(chunk);
455 last_chunk_.Decode(chunk, status_count - delta_sizes.size());
456 last_chunk_.AppendTo(&delta_sizes);
457 }
458 // Last chunk is stored in the `last_chunk_`.
459 encoded_chunks_.pop_back();
460 RTC_DCHECK_EQ(delta_sizes.size(), status_count);
461 num_seq_no_ = status_count;
462
463 uint16_t seq_no = base_seq_no_;
464 size_t recv_delta_size = absl::c_accumulate(delta_sizes, 0);
465
466 // Determine if timestamps, that is, recv_delta are included in the packet.
467 if (end_index >= index + recv_delta_size) {
468 for (size_t delta_size : delta_sizes) {
469 RTC_DCHECK_LE(index + delta_size, end_index);
470 switch (delta_size) {
471 case 0:
472 if (include_lost_)
473 all_packets_.emplace_back(seq_no);
474 break;
475 case 1: {
476 int16_t delta = payload[index];
477 received_packets_.emplace_back(seq_no, delta);
478 if (include_lost_)
479 all_packets_.emplace_back(seq_no, delta);
480 last_timestamp_ += delta * kDeltaTick;
481 index += delta_size;
482 break;
483 }
484 case 2: {
485 int16_t delta = ByteReader<int16_t>::ReadBigEndian(&payload[index]);
486 received_packets_.emplace_back(seq_no, delta);
487 if (include_lost_)
488 all_packets_.emplace_back(seq_no, delta);
489 last_timestamp_ += delta * kDeltaTick;
490 index += delta_size;
491 break;
492 }
493 case 3:
494 Clear();
495 RTC_LOG(LS_WARNING) << "Invalid delta_size for seq_no " << seq_no;
496
497 return false;
498 default:
499 RTC_DCHECK_NOTREACHED();
500 break;
501 }
502 ++seq_no;
503 }
504 } else {
505 // The packet does not contain receive deltas.
506 include_timestamps_ = false;
507 for (size_t delta_size : delta_sizes) {
508 // Use delta sizes to detect if packet was received.
509 if (delta_size > 0) {
510 received_packets_.emplace_back(seq_no, 0);
511 }
512 if (include_lost_) {
513 if (delta_size > 0) {
514 all_packets_.emplace_back(seq_no, 0);
515 } else {
516 all_packets_.emplace_back(seq_no);
517 }
518 }
519 ++seq_no;
520 }
521 }
522 size_bytes_ = RtcpPacket::kHeaderLength + index;
523 RTC_DCHECK_LE(index, end_index);
524 return true;
525 }
526
ParseFrom(const uint8_t * buffer,size_t length)527 std::unique_ptr<TransportFeedback> TransportFeedback::ParseFrom(
528 const uint8_t* buffer,
529 size_t length) {
530 CommonHeader header;
531 if (!header.Parse(buffer, length))
532 return nullptr;
533 if (header.type() != kPacketType || header.fmt() != kFeedbackMessageType)
534 return nullptr;
535 std::unique_ptr<TransportFeedback> parsed(new TransportFeedback);
536 if (!parsed->Parse(header))
537 return nullptr;
538 return parsed;
539 }
540
IsConsistent() const541 bool TransportFeedback::IsConsistent() const {
542 size_t packet_size = kTransportFeedbackHeaderSizeBytes;
543 std::vector<DeltaSize> delta_sizes;
544 LastChunk chunk_decoder;
545 for (uint16_t chunk : encoded_chunks_) {
546 chunk_decoder.Decode(chunk, kMaxReportedPackets);
547 chunk_decoder.AppendTo(&delta_sizes);
548 packet_size += kChunkSizeBytes;
549 }
550 if (!last_chunk_.Empty()) {
551 last_chunk_.AppendTo(&delta_sizes);
552 packet_size += kChunkSizeBytes;
553 }
554 if (num_seq_no_ != delta_sizes.size()) {
555 RTC_LOG(LS_ERROR) << delta_sizes.size() << " packets encoded. Expected "
556 << num_seq_no_;
557 return false;
558 }
559 Timestamp timestamp = BaseTime();
560 auto packet_it = received_packets_.begin();
561 uint16_t seq_no = base_seq_no_;
562 for (DeltaSize delta_size : delta_sizes) {
563 if (delta_size > 0) {
564 if (packet_it == received_packets_.end()) {
565 RTC_LOG(LS_ERROR) << "Failed to find delta for seq_no " << seq_no;
566 return false;
567 }
568 if (packet_it->sequence_number() != seq_no) {
569 RTC_LOG(LS_ERROR) << "Expected to find delta for seq_no " << seq_no
570 << ". Next delta is for "
571 << packet_it->sequence_number();
572 return false;
573 }
574 if (delta_size == 1 &&
575 (packet_it->delta_ticks() < 0 || packet_it->delta_ticks() > 0xff)) {
576 RTC_LOG(LS_ERROR) << "Delta " << packet_it->delta_ticks()
577 << " for seq_no " << seq_no
578 << " doesn't fit into one byte";
579 return false;
580 }
581 timestamp += packet_it->delta();
582 ++packet_it;
583 }
584 if (include_timestamps_) {
585 packet_size += delta_size;
586 }
587 ++seq_no;
588 }
589 if (packet_it != received_packets_.end()) {
590 RTC_LOG(LS_ERROR) << "Unencoded delta for seq_no "
591 << packet_it->sequence_number();
592 return false;
593 }
594 if (timestamp != last_timestamp_) {
595 RTC_LOG(LS_ERROR) << "Last timestamp mismatch. Calculated: "
596 << ToLogString(timestamp)
597 << ". Saved: " << ToLogString(last_timestamp_);
598 return false;
599 }
600 if (size_bytes_ != packet_size) {
601 RTC_LOG(LS_ERROR) << "Rtcp packet size mismatch. Calculated: "
602 << packet_size << ". Saved: " << size_bytes_;
603 return false;
604 }
605 return true;
606 }
607
BlockLength() const608 size_t TransportFeedback::BlockLength() const {
609 // Round size_bytes_ up to multiple of 32bits.
610 return (size_bytes_ + 3) & (~static_cast<size_t>(3));
611 }
612
PaddingLength() const613 size_t TransportFeedback::PaddingLength() const {
614 return BlockLength() - size_bytes_;
615 }
616
617 // Serialize packet.
Create(uint8_t * packet,size_t * position,size_t max_length,PacketReadyCallback callback) const618 bool TransportFeedback::Create(uint8_t* packet,
619 size_t* position,
620 size_t max_length,
621 PacketReadyCallback callback) const {
622 if (num_seq_no_ == 0)
623 return false;
624
625 while (*position + BlockLength() > max_length) {
626 if (!OnBufferFull(packet, position, callback))
627 return false;
628 }
629 const size_t position_end = *position + BlockLength();
630 const size_t padding_length = PaddingLength();
631 bool has_padding = padding_length > 0;
632 CreateHeader(kFeedbackMessageType, kPacketType, HeaderLength(), has_padding,
633 packet, position);
634 CreateCommonFeedback(packet + *position);
635 *position += kCommonFeedbackLength;
636
637 ByteWriter<uint16_t>::WriteBigEndian(&packet[*position], base_seq_no_);
638 *position += 2;
639
640 ByteWriter<uint16_t>::WriteBigEndian(&packet[*position], num_seq_no_);
641 *position += 2;
642
643 ByteWriter<uint32_t, 3>::WriteBigEndian(&packet[*position], base_time_ticks_);
644 *position += 3;
645
646 packet[(*position)++] = feedback_seq_;
647
648 for (uint16_t chunk : encoded_chunks_) {
649 ByteWriter<uint16_t>::WriteBigEndian(&packet[*position], chunk);
650 *position += 2;
651 }
652 if (!last_chunk_.Empty()) {
653 uint16_t chunk = last_chunk_.EncodeLast();
654 ByteWriter<uint16_t>::WriteBigEndian(&packet[*position], chunk);
655 *position += 2;
656 }
657
658 if (include_timestamps_) {
659 for (const auto& received_packet : received_packets_) {
660 int16_t delta = received_packet.delta_ticks();
661 if (delta >= 0 && delta <= 0xFF) {
662 packet[(*position)++] = delta;
663 } else {
664 ByteWriter<int16_t>::WriteBigEndian(&packet[*position], delta);
665 *position += 2;
666 }
667 }
668 }
669
670 if (padding_length > 0) {
671 for (size_t i = 0; i < padding_length - 1; ++i) {
672 packet[(*position)++] = 0;
673 }
674 packet[(*position)++] = padding_length;
675 }
676 RTC_DCHECK_EQ(*position, position_end);
677 return true;
678 }
679
Clear()680 void TransportFeedback::Clear() {
681 num_seq_no_ = 0;
682 last_timestamp_ = BaseTime();
683 received_packets_.clear();
684 all_packets_.clear();
685 encoded_chunks_.clear();
686 last_chunk_.Clear();
687 size_bytes_ = kTransportFeedbackHeaderSizeBytes;
688 }
689
AddDeltaSize(DeltaSize delta_size)690 bool TransportFeedback::AddDeltaSize(DeltaSize delta_size) {
691 if (num_seq_no_ == kMaxReportedPackets)
692 return false;
693 size_t add_chunk_size = last_chunk_.Empty() ? kChunkSizeBytes : 0;
694 if (size_bytes_ + delta_size + add_chunk_size > kMaxSizeBytes)
695 return false;
696
697 if (last_chunk_.CanAdd(delta_size)) {
698 size_bytes_ += add_chunk_size;
699 last_chunk_.Add(delta_size);
700 ++num_seq_no_;
701 return true;
702 }
703 if (size_bytes_ + delta_size + kChunkSizeBytes > kMaxSizeBytes)
704 return false;
705
706 encoded_chunks_.push_back(last_chunk_.Emit());
707 size_bytes_ += kChunkSizeBytes;
708 last_chunk_.Add(delta_size);
709 ++num_seq_no_;
710 return true;
711 }
712
AddMissingPackets(size_t num_missing_packets)713 bool TransportFeedback::AddMissingPackets(size_t num_missing_packets) {
714 size_t new_num_seq_no = num_seq_no_ + num_missing_packets;
715 if (new_num_seq_no > kMaxReportedPackets) {
716 return false;
717 }
718
719 if (!last_chunk_.Empty()) {
720 while (num_missing_packets > 0 && last_chunk_.CanAdd(0)) {
721 last_chunk_.Add(0);
722 --num_missing_packets;
723 }
724 if (num_missing_packets == 0) {
725 num_seq_no_ = new_num_seq_no;
726 return true;
727 }
728 encoded_chunks_.push_back(last_chunk_.Emit());
729 }
730 RTC_DCHECK(last_chunk_.Empty());
731 size_t full_chunks = num_missing_packets / LastChunk::kMaxRunLengthCapacity;
732 size_t partial_chunk = num_missing_packets % LastChunk::kMaxRunLengthCapacity;
733 size_t num_chunks = full_chunks + (partial_chunk > 0 ? 1 : 0);
734 if (size_bytes_ + kChunkSizeBytes * num_chunks > kMaxSizeBytes) {
735 num_seq_no_ = (new_num_seq_no - num_missing_packets);
736 return false;
737 }
738 size_bytes_ += kChunkSizeBytes * num_chunks;
739 // T = 0, S = 0, run length = kMaxRunLengthCapacity, see EncodeRunLength().
740 encoded_chunks_.insert(encoded_chunks_.end(), full_chunks,
741 LastChunk::kMaxRunLengthCapacity);
742 last_chunk_.AddMissingPackets(partial_chunk);
743 num_seq_no_ = new_num_seq_no;
744 return true;
745 }
746 } // namespace rtcp
747 } // namespace webrtc
748