1 /*
2  *  Copyright (c) 2016 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/flexfec_header_reader_writer.h"
12 
13 #include <string.h>
14 
15 #include "api/scoped_refptr.h"
16 #include "modules/rtp_rtcp/source/byte_io.h"
17 #include "modules/rtp_rtcp/source/forward_error_correction_internal.h"
18 #include "rtc_base/checks.h"
19 #include "rtc_base/logging.h"
20 
21 namespace webrtc {
22 
23 namespace {
24 
25 // Maximum number of media packets that can be protected in one batch.
26 constexpr size_t kMaxMediaPackets = 48;  // Since we are reusing ULPFEC masks.
27 
28 // Maximum number of FEC packets stored inside ForwardErrorCorrection.
29 constexpr size_t kMaxFecPackets = kMaxMediaPackets;
30 
31 // Size (in bytes) of packet masks, given number of K bits set.
32 constexpr size_t kFlexfecPacketMaskSizes[] = {2, 6, 14};
33 
34 // Size (in bytes) of part of header which is not packet mask specific.
35 constexpr size_t kBaseHeaderSize = 12;
36 
37 // Size (in bytes) of part of header which is stream specific.
38 constexpr size_t kStreamSpecificHeaderSize = 6;
39 
40 // Size (in bytes) of header, given the single stream packet mask size, i.e.
41 // the number of K-bits set.
42 constexpr size_t kHeaderSizes[] = {
43     kBaseHeaderSize + kStreamSpecificHeaderSize + kFlexfecPacketMaskSizes[0],
44     kBaseHeaderSize + kStreamSpecificHeaderSize + kFlexfecPacketMaskSizes[1],
45     kBaseHeaderSize + kStreamSpecificHeaderSize + kFlexfecPacketMaskSizes[2]};
46 
47 // We currently only support single-stream protection.
48 // TODO(brandtr): Update this when we support multistream protection.
49 constexpr uint8_t kSsrcCount = 1;
50 
51 // There are three reserved bytes that MUST be set to zero in the header.
52 constexpr uint32_t kReservedBits = 0;
53 
54 // TODO(brandtr): Update this when we support multistream protection.
55 constexpr size_t kPacketMaskOffset =
56     kBaseHeaderSize + kStreamSpecificHeaderSize;
57 
58 // Here we count the K-bits as belonging to the packet mask.
59 // This can be used in conjunction with FlexfecHeaderWriter::MinPacketMaskSize,
60 // which calculates a bound on the needed packet mask size including K-bits,
61 // given a packet mask without K-bits.
FlexfecHeaderSize(size_t packet_mask_size)62 size_t FlexfecHeaderSize(size_t packet_mask_size) {
63   RTC_DCHECK_LE(packet_mask_size, kFlexfecPacketMaskSizes[2]);
64   if (packet_mask_size <= kFlexfecPacketMaskSizes[0]) {
65     return kHeaderSizes[0];
66   } else if (packet_mask_size <= kFlexfecPacketMaskSizes[1]) {
67     return kHeaderSizes[1];
68   }
69   return kHeaderSizes[2];
70 }
71 
72 }  // namespace
73 
FlexfecHeaderReader()74 FlexfecHeaderReader::FlexfecHeaderReader()
75     : FecHeaderReader(kMaxMediaPackets, kMaxFecPackets) {}
76 
77 FlexfecHeaderReader::~FlexfecHeaderReader() = default;
78 
79 // TODO(brandtr): Update this function when we support flexible masks,
80 // retransmissions, and/or several protected SSRCs.
ReadFecHeader(ForwardErrorCorrection::ReceivedFecPacket * fec_packet) const81 bool FlexfecHeaderReader::ReadFecHeader(
82     ForwardErrorCorrection::ReceivedFecPacket* fec_packet) const {
83   if (fec_packet->pkt->data.size() <=
84       kBaseHeaderSize + kStreamSpecificHeaderSize) {
85     RTC_LOG(LS_WARNING) << "Discarding truncated FlexFEC packet.";
86     return false;
87   }
88   uint8_t* const data = fec_packet->pkt->data.MutableData();
89   bool r_bit = (data[0] & 0x80) != 0;
90   if (r_bit) {
91     RTC_LOG(LS_INFO)
92         << "FlexFEC packet with retransmission bit set. We do not yet "
93            "support this, thus discarding the packet.";
94     return false;
95   }
96   bool f_bit = (data[0] & 0x40) != 0;
97   if (f_bit) {
98     RTC_LOG(LS_INFO)
99         << "FlexFEC packet with inflexible generator matrix. We do "
100            "not yet support this, thus discarding packet.";
101     return false;
102   }
103   uint8_t ssrc_count = ByteReader<uint8_t>::ReadBigEndian(&data[8]);
104   if (ssrc_count != 1) {
105     RTC_LOG(LS_INFO)
106         << "FlexFEC packet protecting multiple media SSRCs. We do not "
107            "yet support this, thus discarding packet.";
108     return false;
109   }
110   uint32_t protected_ssrc = ByteReader<uint32_t>::ReadBigEndian(&data[12]);
111   uint16_t seq_num_base = ByteReader<uint16_t>::ReadBigEndian(&data[16]);
112 
113   // Parse the FlexFEC packet mask and remove the interleaved K-bits.
114   // (See FEC header schematic in flexfec_header_reader_writer.h.)
115   // We store the packed packet mask in-band, which "destroys" the standards
116   // compliance of the header. That is fine though, since the code that
117   // reads from the header (from this point and onwards) is aware of this.
118   // TODO(brandtr): When the FEC packet classes have been refactored, store
119   // the packed packet masks out-of-band, thus leaving the FlexFEC header as is.
120   //
121   // We treat the mask parts as unsigned integers with host order endianness
122   // in order to simplify the bit shifting between bytes.
123   if (fec_packet->pkt->data.size() < kHeaderSizes[0]) {
124     RTC_LOG(LS_WARNING) << "Discarding truncated FlexFEC packet.";
125     return false;
126   }
127   uint8_t* const packet_mask = data + kPacketMaskOffset;
128   bool k_bit0 = (packet_mask[0] & 0x80) != 0;
129   uint16_t mask_part0 = ByteReader<uint16_t>::ReadBigEndian(&packet_mask[0]);
130   // Shift away K-bit 0, implicitly clearing the last bit.
131   mask_part0 <<= 1;
132   ByteWriter<uint16_t>::WriteBigEndian(&packet_mask[0], mask_part0);
133   size_t packet_mask_size;
134   if (k_bit0) {
135     // The first K-bit is set, and the packet mask is thus only 2 bytes long.
136     // We have now read the entire FEC header, and the rest of the packet
137     // is payload.
138     packet_mask_size = kFlexfecPacketMaskSizes[0];
139   } else {
140     if (fec_packet->pkt->data.size() < kHeaderSizes[1]) {
141       return false;
142     }
143     bool k_bit1 = (packet_mask[2] & 0x80) != 0;
144     // We have already shifted the first two bytes of the packet mask one step
145     // to the left, thus removing K-bit 0. We will now shift the next four bytes
146     // of the packet mask two steps to the left. (One step for the removed
147     // K-bit 0, and one step for the to be removed K-bit 1).
148     uint8_t bit15 = (packet_mask[2] >> 6) & 0x01;
149     packet_mask[1] |= bit15;
150     uint32_t mask_part1 = ByteReader<uint32_t>::ReadBigEndian(&packet_mask[2]);
151     // Shift away K-bit 1 and bit 15, implicitly clearing the last two bits.
152     mask_part1 <<= 2;
153     ByteWriter<uint32_t>::WriteBigEndian(&packet_mask[2], mask_part1);
154     if (k_bit1) {
155       // The first K-bit is clear, but the second K-bit is set. The packet
156       // mask is thus 6 bytes long.  We have now read the entire FEC header,
157       // and the rest of the packet is payload.
158       packet_mask_size = kFlexfecPacketMaskSizes[1];
159     } else {
160       if (fec_packet->pkt->data.size() < kHeaderSizes[2]) {
161         RTC_LOG(LS_WARNING) << "Discarding truncated FlexFEC packet.";
162         return false;
163       }
164       bool k_bit2 = (packet_mask[6] & 0x80) != 0;
165       if (k_bit2) {
166         // The first and second K-bits are clear, but the third K-bit is set.
167         // The packet mask is thus 14 bytes long. We have now read the entire
168         // FEC header, and the rest of the packet is payload.
169         packet_mask_size = kFlexfecPacketMaskSizes[2];
170       } else {
171         RTC_LOG(LS_WARNING)
172             << "Discarding FlexFEC packet with malformed header.";
173         return false;
174       }
175       // At this point, K-bits 0 and 1 have been removed, and the front-most
176       // part of the FlexFEC packet mask has been packed accordingly. We will
177       // now shift the remaning part of the packet mask three steps to the left.
178       // This corresponds to the (in total) three K-bits, which have been
179       // removed.
180       uint8_t tail_bits = (packet_mask[6] >> 5) & 0x03;
181       packet_mask[5] |= tail_bits;
182       uint64_t mask_part2 =
183           ByteReader<uint64_t>::ReadBigEndian(&packet_mask[6]);
184       // Shift away K-bit 2, bit 46, and bit 47, implicitly clearing the last
185       // three bits.
186       mask_part2 <<= 3;
187       ByteWriter<uint64_t>::WriteBigEndian(&packet_mask[6], mask_part2);
188     }
189   }
190 
191   // Store "ULPFECized" packet mask info.
192   fec_packet->fec_header_size = FlexfecHeaderSize(packet_mask_size);
193   fec_packet->protected_ssrc = protected_ssrc;
194   fec_packet->seq_num_base = seq_num_base;
195   fec_packet->packet_mask_offset = kPacketMaskOffset;
196   fec_packet->packet_mask_size = packet_mask_size;
197 
198   // In FlexFEC, all media packets are protected in their entirety.
199   fec_packet->protection_length =
200       fec_packet->pkt->data.size() - fec_packet->fec_header_size;
201 
202   return true;
203 }
204 
FlexfecHeaderWriter()205 FlexfecHeaderWriter::FlexfecHeaderWriter()
206     : FecHeaderWriter(kMaxMediaPackets, kMaxFecPackets, kHeaderSizes[2]) {}
207 
208 FlexfecHeaderWriter::~FlexfecHeaderWriter() = default;
209 
MinPacketMaskSize(const uint8_t * packet_mask,size_t packet_mask_size) const210 size_t FlexfecHeaderWriter::MinPacketMaskSize(const uint8_t* packet_mask,
211                                               size_t packet_mask_size) const {
212   if (packet_mask_size == kUlpfecPacketMaskSizeLBitClear &&
213       (packet_mask[1] & 0x01) == 0) {
214     // Packet mask is 16 bits long, with bit 15 clear.
215     // It can be used as is.
216     return kFlexfecPacketMaskSizes[0];
217   } else if (packet_mask_size == kUlpfecPacketMaskSizeLBitClear) {
218     // Packet mask is 16 bits long, with bit 15 set.
219     // We must expand the packet mask with zeros in the FlexFEC header.
220     return kFlexfecPacketMaskSizes[1];
221   } else if (packet_mask_size == kUlpfecPacketMaskSizeLBitSet &&
222              (packet_mask[5] & 0x03) == 0) {
223     // Packet mask is 48 bits long, with bits 46 and 47 clear.
224     // It can be used as is.
225     return kFlexfecPacketMaskSizes[1];
226   } else if (packet_mask_size == kUlpfecPacketMaskSizeLBitSet) {
227     // Packet mask is 48 bits long, with at least one of bits 46 and 47 set.
228     // We must expand it with zeros.
229     return kFlexfecPacketMaskSizes[2];
230   }
231   RTC_NOTREACHED() << "Incorrect packet mask size: " << packet_mask_size << ".";
232   return kFlexfecPacketMaskSizes[2];
233 }
234 
FecHeaderSize(size_t packet_mask_size) const235 size_t FlexfecHeaderWriter::FecHeaderSize(size_t packet_mask_size) const {
236   return FlexfecHeaderSize(packet_mask_size);
237 }
238 
239 // This function adapts the precomputed ULPFEC packet masks to the
240 // FlexFEC header standard. Note that the header size is computed by
241 // FecHeaderSize(), so in this function we can be sure that we are
242 // writing in space that is intended for the header.
243 //
244 // TODO(brandtr): Update this function when we support offset-based masks,
245 // retransmissions, and protecting multiple SSRCs.
FinalizeFecHeader(uint32_t media_ssrc,uint16_t seq_num_base,const uint8_t * packet_mask,size_t packet_mask_size,ForwardErrorCorrection::Packet * fec_packet) const246 void FlexfecHeaderWriter::FinalizeFecHeader(
247     uint32_t media_ssrc,
248     uint16_t seq_num_base,
249     const uint8_t* packet_mask,
250     size_t packet_mask_size,
251     ForwardErrorCorrection::Packet* fec_packet) const {
252   uint8_t* data = fec_packet->data.MutableData();
253   data[0] &= 0x7f;  // Clear R bit.
254   data[0] &= 0xbf;  // Clear F bit.
255   ByteWriter<uint8_t>::WriteBigEndian(&data[8], kSsrcCount);
256   ByteWriter<uint32_t, 3>::WriteBigEndian(&data[9], kReservedBits);
257   ByteWriter<uint32_t>::WriteBigEndian(&data[12], media_ssrc);
258   ByteWriter<uint16_t>::WriteBigEndian(&data[16], seq_num_base);
259   // Adapt ULPFEC packet mask to FlexFEC header.
260   //
261   // We treat the mask parts as unsigned integers with host order endianness
262   // in order to simplify the bit shifting between bytes.
263   uint8_t* const written_packet_mask = data + kPacketMaskOffset;
264   if (packet_mask_size == kUlpfecPacketMaskSizeLBitSet) {
265     // The packet mask is 48 bits long.
266     uint16_t tmp_mask_part0 =
267         ByteReader<uint16_t>::ReadBigEndian(&packet_mask[0]);
268     uint32_t tmp_mask_part1 =
269         ByteReader<uint32_t>::ReadBigEndian(&packet_mask[2]);
270 
271     tmp_mask_part0 >>= 1;  // Shift, thus clearing K-bit 0.
272     ByteWriter<uint16_t>::WriteBigEndian(&written_packet_mask[0],
273                                          tmp_mask_part0);
274     tmp_mask_part1 >>= 2;  // Shift, thus clearing K-bit 1 and bit 15.
275     ByteWriter<uint32_t>::WriteBigEndian(&written_packet_mask[2],
276                                          tmp_mask_part1);
277     bool bit15 = (packet_mask[1] & 0x01) != 0;
278     if (bit15)
279       written_packet_mask[2] |= 0x40;  // Set bit 15.
280     bool bit46 = (packet_mask[5] & 0x02) != 0;
281     bool bit47 = (packet_mask[5] & 0x01) != 0;
282     if (!bit46 && !bit47) {
283       written_packet_mask[2] |= 0x80;  // Set K-bit 1.
284     } else {
285       memset(&written_packet_mask[6], 0, 8);  // Clear all trailing bits.
286       written_packet_mask[6] |= 0x80;         // Set K-bit 2.
287       if (bit46)
288         written_packet_mask[6] |= 0x40;  // Set bit 46.
289       if (bit47)
290         written_packet_mask[6] |= 0x20;  // Set bit 47.
291     }
292   } else if (packet_mask_size == kUlpfecPacketMaskSizeLBitClear) {
293     // The packet mask is 16 bits long.
294     uint16_t tmp_mask_part0 =
295         ByteReader<uint16_t>::ReadBigEndian(&packet_mask[0]);
296 
297     tmp_mask_part0 >>= 1;  // Shift, thus clearing K-bit 0.
298     ByteWriter<uint16_t>::WriteBigEndian(&written_packet_mask[0],
299                                          tmp_mask_part0);
300     bool bit15 = (packet_mask[1] & 0x01) != 0;
301     if (!bit15) {
302       written_packet_mask[0] |= 0x80;  // Set K-bit 0.
303     } else {
304       memset(&written_packet_mask[2], 0U, 4);  // Clear all trailing bits.
305       written_packet_mask[2] |= 0x80;          // Set K-bit 1.
306       written_packet_mask[2] |= 0x40;          // Set bit 15.
307     }
308   } else {
309     RTC_NOTREACHED() << "Incorrect packet mask size: " << packet_mask_size
310                      << ".";
311   }
312 }
313 
314 }  // namespace webrtc
315