• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright (c) 2012 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 #ifndef MODULES_RTP_RTCP_INCLUDE_RTP_RTCP_DEFINES_H_
12 #define MODULES_RTP_RTCP_INCLUDE_RTP_RTCP_DEFINES_H_
13 
14 #include <stddef.h>
15 
16 #include <list>
17 #include <memory>
18 #include <vector>
19 
20 #include "absl/algorithm/container.h"
21 #include "absl/strings/string_view.h"
22 #include "absl/types/optional.h"
23 #include "absl/types/variant.h"
24 #include "api/array_view.h"
25 #include "api/audio_codecs/audio_format.h"
26 #include "api/rtp_headers.h"
27 #include "api/transport/network_types.h"
28 #include "api/units/time_delta.h"
29 #include "modules/rtp_rtcp/source/rtcp_packet/remote_estimate.h"
30 #include "system_wrappers/include/clock.h"
31 
32 #define RTCP_CNAME_SIZE 256  // RFC 3550 page 44, including null termination
33 #define IP_PACKET_SIZE 1500  // we assume ethernet
34 
35 namespace webrtc {
36 class RtpPacket;
37 class RtpPacketToSend;
38 namespace rtcp {
39 class TransportFeedback;
40 }
41 
42 const int kVideoPayloadTypeFrequency = 90000;
43 
44 // TODO(bugs.webrtc.org/6458): Remove this when all the depending projects are
45 // updated to correctly set rtp rate for RtcpSender.
46 const int kBogusRtpRateForAudioRtcp = 8000;
47 
48 // Minimum RTP header size in bytes.
49 const uint8_t kRtpHeaderSize = 12;
50 
51 bool IsLegalMidName(absl::string_view name);
52 bool IsLegalRsidName(absl::string_view name);
53 
54 // This enum must not have any gaps, i.e., all integers between
55 // kRtpExtensionNone and kRtpExtensionNumberOfExtensions must be valid enum
56 // entries.
57 enum RTPExtensionType : int {
58   kRtpExtensionNone,
59   kRtpExtensionTransmissionTimeOffset,
60   kRtpExtensionAudioLevel,
61   kRtpExtensionCsrcAudioLevel,
62   kRtpExtensionInbandComfortNoise,
63   kRtpExtensionAbsoluteSendTime,
64   kRtpExtensionAbsoluteCaptureTime,
65   kRtpExtensionVideoRotation,
66   kRtpExtensionTransportSequenceNumber,
67   kRtpExtensionTransportSequenceNumber02,
68   kRtpExtensionPlayoutDelay,
69   kRtpExtensionVideoContentType,
70   kRtpExtensionVideoLayersAllocation,
71   kRtpExtensionVideoTiming,
72   kRtpExtensionRtpStreamId,
73   kRtpExtensionRepairedRtpStreamId,
74   kRtpExtensionMid,
75   kRtpExtensionGenericFrameDescriptor00,
76   kRtpExtensionGenericFrameDescriptor = kRtpExtensionGenericFrameDescriptor00,
77   kRtpExtensionGenericFrameDescriptor02,
78   kRtpExtensionColorSpace,
79   kRtpExtensionVideoFrameTrackingId,
80   kRtpExtensionNumberOfExtensions  // Must be the last entity in the enum.
81 };
82 
83 enum RTCPAppSubTypes { kAppSubtypeBwe = 0x00 };
84 
85 // TODO(sprang): Make this an enum class once rtcp_receiver has been cleaned up.
86 enum RTCPPacketType : uint32_t {
87   kRtcpReport = 0x0001,
88   kRtcpSr = 0x0002,
89   kRtcpRr = 0x0004,
90   kRtcpSdes = 0x0008,
91   kRtcpBye = 0x0010,
92   kRtcpPli = 0x0020,
93   kRtcpNack = 0x0040,
94   kRtcpFir = 0x0080,
95   kRtcpTmmbr = 0x0100,
96   kRtcpTmmbn = 0x0200,
97   kRtcpSrReq = 0x0400,
98   kRtcpLossNotification = 0x2000,
99   kRtcpRemb = 0x10000,
100   kRtcpTransmissionTimeOffset = 0x20000,
101   kRtcpXrReceiverReferenceTime = 0x40000,
102   kRtcpXrDlrrReportBlock = 0x80000,
103   kRtcpTransportFeedback = 0x100000,
104   kRtcpXrTargetBitrate = 0x200000
105 };
106 
107 enum class KeyFrameReqMethod : uint8_t {
108   kNone,     // Don't request keyframes.
109   kPliRtcp,  // Request keyframes through Picture Loss Indication.
110   kFirRtcp   // Request keyframes through Full Intra-frame Request.
111 };
112 
113 enum RtxMode {
114   kRtxOff = 0x0,
115   kRtxRetransmitted = 0x1,     // Only send retransmissions over RTX.
116   kRtxRedundantPayloads = 0x2  // Preventively send redundant payloads
117                                // instead of padding.
118 };
119 
120 const size_t kRtxHeaderSize = 2;
121 
122 struct RTCPReportBlock {
RTCPReportBlockRTCPReportBlock123   RTCPReportBlock()
124       : sender_ssrc(0),
125         source_ssrc(0),
126         fraction_lost(0),
127         packets_lost(0),
128         extended_highest_sequence_number(0),
129         jitter(0),
130         last_sender_report_timestamp(0),
131         delay_since_last_sender_report(0) {}
132 
RTCPReportBlockRTCPReportBlock133   RTCPReportBlock(uint32_t sender_ssrc,
134                   uint32_t source_ssrc,
135                   uint8_t fraction_lost,
136                   int32_t packets_lost,
137                   uint32_t extended_highest_sequence_number,
138                   uint32_t jitter,
139                   uint32_t last_sender_report_timestamp,
140                   uint32_t delay_since_last_sender_report)
141       : sender_ssrc(sender_ssrc),
142         source_ssrc(source_ssrc),
143         fraction_lost(fraction_lost),
144         packets_lost(packets_lost),
145         extended_highest_sequence_number(extended_highest_sequence_number),
146         jitter(jitter),
147         last_sender_report_timestamp(last_sender_report_timestamp),
148         delay_since_last_sender_report(delay_since_last_sender_report) {}
149 
150   // Fields as described by RFC 3550 6.4.2.
151   uint32_t sender_ssrc;  // SSRC of sender of this report.
152   uint32_t source_ssrc;  // SSRC of the RTP packet sender.
153   uint8_t fraction_lost;
154   int32_t packets_lost;  // 24 bits valid.
155   uint32_t extended_highest_sequence_number;
156   uint32_t jitter;
157   uint32_t last_sender_report_timestamp;
158   uint32_t delay_since_last_sender_report;
159 };
160 
161 typedef std::list<RTCPReportBlock> ReportBlockList;
162 
163 struct RtpState {
RtpStateRtpState164   RtpState()
165       : sequence_number(0),
166         start_timestamp(0),
167         timestamp(0),
168         capture_time_ms(-1),
169         last_timestamp_time_ms(-1),
170         ssrc_has_acked(false) {}
171   uint16_t sequence_number;
172   uint32_t start_timestamp;
173   uint32_t timestamp;
174   int64_t capture_time_ms;
175   int64_t last_timestamp_time_ms;
176   bool ssrc_has_acked;
177 };
178 
179 // Callback interface for packets recovered by FlexFEC or ULPFEC. In
180 // the FlexFEC case, the implementation should be able to demultiplex
181 // the recovered RTP packets based on SSRC.
182 class RecoveredPacketReceiver {
183  public:
184   virtual void OnRecoveredPacket(const uint8_t* packet, size_t length) = 0;
185 
186  protected:
187   virtual ~RecoveredPacketReceiver() = default;
188 };
189 
190 class RtcpIntraFrameObserver {
191  public:
~RtcpIntraFrameObserver()192   virtual ~RtcpIntraFrameObserver() {}
193 
194   virtual void OnReceivedIntraFrameRequest(uint32_t ssrc) = 0;
195 };
196 
197 // Observer for incoming LossNotification RTCP messages.
198 // See the documentation of LossNotification for details.
199 class RtcpLossNotificationObserver {
200  public:
201   virtual ~RtcpLossNotificationObserver() = default;
202 
203   virtual void OnReceivedLossNotification(uint32_t ssrc,
204                                           uint16_t seq_num_of_last_decodable,
205                                           uint16_t seq_num_of_last_received,
206                                           bool decodability_flag) = 0;
207 };
208 
209 class RtcpBandwidthObserver {
210  public:
211   // REMB or TMMBR
212   virtual void OnReceivedEstimatedBitrate(uint32_t bitrate) = 0;
213 
214   virtual void OnReceivedRtcpReceiverReport(
215       const ReportBlockList& report_blocks,
216       int64_t rtt,
217       int64_t now_ms) = 0;
218 
~RtcpBandwidthObserver()219   virtual ~RtcpBandwidthObserver() {}
220 };
221 
222 // NOTE! `kNumMediaTypes` must be kept in sync with RtpPacketMediaType!
223 static constexpr size_t kNumMediaTypes = 5;
224 enum class RtpPacketMediaType : size_t {
225   kAudio,                         // Audio media packets.
226   kVideo,                         // Video media packets.
227   kRetransmission,                // Retransmisions, sent as response to NACK.
228   kForwardErrorCorrection,        // FEC packets.
229   kPadding = kNumMediaTypes - 1,  // RTX or plain padding sent to maintain BWE.
230   // Again, don't forget to udate `kNumMediaTypes` if you add another value!
231 };
232 
233 struct RtpPacketSendInfo {
234   uint16_t transport_sequence_number = 0;
235   absl::optional<uint32_t> media_ssrc;
236   uint16_t rtp_sequence_number = 0;  // Only valid if `media_ssrc` is set.
237   uint32_t rtp_timestamp = 0;
238   size_t length = 0;
239   absl::optional<RtpPacketMediaType> packet_type;
240   PacedPacketInfo pacing_info;
241 };
242 
243 class NetworkStateEstimateObserver {
244  public:
245   virtual void OnRemoteNetworkEstimate(NetworkStateEstimate estimate) = 0;
246   virtual ~NetworkStateEstimateObserver() = default;
247 };
248 
249 class TransportFeedbackObserver {
250  public:
TransportFeedbackObserver()251   TransportFeedbackObserver() {}
~TransportFeedbackObserver()252   virtual ~TransportFeedbackObserver() {}
253 
254   virtual void OnAddPacket(const RtpPacketSendInfo& packet_info) = 0;
255   virtual void OnTransportFeedback(const rtcp::TransportFeedback& feedback) = 0;
256 };
257 
258 // Interface for PacketRouter to send rtcp feedback on behalf of
259 // congestion controller.
260 // TODO(bugs.webrtc.org/8239): Remove and use RtcpTransceiver directly
261 // when RtcpTransceiver always present in rtp transport.
262 class RtcpFeedbackSenderInterface {
263  public:
264   virtual ~RtcpFeedbackSenderInterface() = default;
265   virtual void SendCombinedRtcpPacket(
266       std::vector<std::unique_ptr<rtcp::RtcpPacket>> rtcp_packets) = 0;
267   virtual void SetRemb(int64_t bitrate_bps, std::vector<uint32_t> ssrcs) = 0;
268   virtual void UnsetRemb() = 0;
269 };
270 
271 class StreamFeedbackObserver {
272  public:
273   struct StreamPacketInfo {
274     bool received;
275 
276     // `rtp_sequence_number` and `is_retransmission` are only valid if `ssrc`
277     // is populated.
278     absl::optional<uint32_t> ssrc;
279     uint16_t rtp_sequence_number;
280     bool is_retransmission;
281   };
282   virtual ~StreamFeedbackObserver() = default;
283 
284   virtual void OnPacketFeedbackVector(
285       std::vector<StreamPacketInfo> packet_feedback_vector) = 0;
286 };
287 
288 class StreamFeedbackProvider {
289  public:
290   virtual void RegisterStreamFeedbackObserver(
291       std::vector<uint32_t> ssrcs,
292       StreamFeedbackObserver* observer) = 0;
293   virtual void DeRegisterStreamFeedbackObserver(
294       StreamFeedbackObserver* observer) = 0;
295   virtual ~StreamFeedbackProvider() = default;
296 };
297 
298 class RtcpRttStats {
299  public:
300   virtual void OnRttUpdate(int64_t rtt) = 0;
301 
302   virtual int64_t LastProcessedRtt() const = 0;
303 
~RtcpRttStats()304   virtual ~RtcpRttStats() {}
305 };
306 
307 struct RtpPacketCounter {
RtpPacketCounterRtpPacketCounter308   RtpPacketCounter()
309       : header_bytes(0), payload_bytes(0), padding_bytes(0), packets(0) {}
310 
311   explicit RtpPacketCounter(const RtpPacket& packet);
312   explicit RtpPacketCounter(const RtpPacketToSend& packet_to_send);
313 
AddRtpPacketCounter314   void Add(const RtpPacketCounter& other) {
315     header_bytes += other.header_bytes;
316     payload_bytes += other.payload_bytes;
317     padding_bytes += other.padding_bytes;
318     packets += other.packets;
319     total_packet_delay += other.total_packet_delay;
320   }
321 
SubtractRtpPacketCounter322   void Subtract(const RtpPacketCounter& other) {
323     RTC_DCHECK_GE(header_bytes, other.header_bytes);
324     header_bytes -= other.header_bytes;
325     RTC_DCHECK_GE(payload_bytes, other.payload_bytes);
326     payload_bytes -= other.payload_bytes;
327     RTC_DCHECK_GE(padding_bytes, other.padding_bytes);
328     padding_bytes -= other.padding_bytes;
329     RTC_DCHECK_GE(packets, other.packets);
330     packets -= other.packets;
331     RTC_DCHECK_GE(total_packet_delay, other.total_packet_delay);
332     total_packet_delay -= other.total_packet_delay;
333   }
334 
335   bool operator==(const RtpPacketCounter& other) const {
336     return header_bytes == other.header_bytes &&
337            payload_bytes == other.payload_bytes &&
338            padding_bytes == other.padding_bytes && packets == other.packets &&
339            total_packet_delay == other.total_packet_delay;
340   }
341 
342   // Not inlined, since use of RtpPacket would result in circular includes.
343   void AddPacket(const RtpPacket& packet);
344   void AddPacket(const RtpPacketToSend& packet_to_send);
345 
TotalBytesRtpPacketCounter346   size_t TotalBytes() const {
347     return header_bytes + payload_bytes + padding_bytes;
348   }
349 
350   size_t header_bytes;   // Number of bytes used by RTP headers.
351   size_t payload_bytes;  // Payload bytes, excluding RTP headers and padding.
352   size_t padding_bytes;  // Number of padding bytes.
353   uint32_t packets;      // Number of packets.
354   // The total delay of all `packets`. For RtpPacketToSend packets, this is
355   // `time_in_send_queue()`. For receive packets, this is zero.
356   webrtc::TimeDelta total_packet_delay = webrtc::TimeDelta::Zero();
357 };
358 
359 // Data usage statistics for a (rtp) stream.
360 struct StreamDataCounters {
361   StreamDataCounters();
362 
AddStreamDataCounters363   void Add(const StreamDataCounters& other) {
364     transmitted.Add(other.transmitted);
365     retransmitted.Add(other.retransmitted);
366     fec.Add(other.fec);
367     if (other.first_packet_time_ms != -1 &&
368         (other.first_packet_time_ms < first_packet_time_ms ||
369          first_packet_time_ms == -1)) {
370       // Use oldest time.
371       first_packet_time_ms = other.first_packet_time_ms;
372     }
373   }
374 
SubtractStreamDataCounters375   void Subtract(const StreamDataCounters& other) {
376     transmitted.Subtract(other.transmitted);
377     retransmitted.Subtract(other.retransmitted);
378     fec.Subtract(other.fec);
379     if (other.first_packet_time_ms != -1 &&
380         (other.first_packet_time_ms > first_packet_time_ms ||
381          first_packet_time_ms == -1)) {
382       // Use youngest time.
383       first_packet_time_ms = other.first_packet_time_ms;
384     }
385   }
386 
TimeSinceFirstPacketInMsStreamDataCounters387   int64_t TimeSinceFirstPacketInMs(int64_t now_ms) const {
388     return (first_packet_time_ms == -1) ? -1 : (now_ms - first_packet_time_ms);
389   }
390 
391   // Returns the number of bytes corresponding to the actual media payload (i.e.
392   // RTP headers, padding, retransmissions and fec packets are excluded).
393   // Note this function does not have meaning for an RTX stream.
MediaPayloadBytesStreamDataCounters394   size_t MediaPayloadBytes() const {
395     return transmitted.payload_bytes - retransmitted.payload_bytes -
396            fec.payload_bytes;
397   }
398 
399   int64_t first_packet_time_ms;  // Time when first packet is sent/received.
400   // The timestamp at which the last packet was received, i.e. the time of the
401   // local clock when it was received - not the RTP timestamp of that packet.
402   // https://w3c.github.io/webrtc-stats/#dom-rtcinboundrtpstreamstats-lastpacketreceivedtimestamp
403   absl::optional<int64_t> last_packet_received_timestamp_ms;
404   RtpPacketCounter transmitted;    // Number of transmitted packets/bytes.
405   RtpPacketCounter retransmitted;  // Number of retransmitted packets/bytes.
406   RtpPacketCounter fec;            // Number of redundancy packets/bytes.
407 };
408 
409 class RtpSendRates {
410   template <std::size_t... Is>
make_zero_array(std::index_sequence<Is...>)411   constexpr std::array<DataRate, sizeof...(Is)> make_zero_array(
412       std::index_sequence<Is...>) {
413     return {{(static_cast<void>(Is), DataRate::Zero())...}};
414   }
415 
416  public:
RtpSendRates()417   RtpSendRates()
418       : send_rates_(
419             make_zero_array(std::make_index_sequence<kNumMediaTypes>())) {}
420   RtpSendRates(const RtpSendRates& rhs) = default;
421   RtpSendRates& operator=(const RtpSendRates&) = default;
422 
423   DataRate& operator[](RtpPacketMediaType type) {
424     return send_rates_[static_cast<size_t>(type)];
425   }
426   const DataRate& operator[](RtpPacketMediaType type) const {
427     return send_rates_[static_cast<size_t>(type)];
428   }
Sum()429   DataRate Sum() const {
430     return absl::c_accumulate(send_rates_, DataRate::Zero());
431   }
432 
433  private:
434   std::array<DataRate, kNumMediaTypes> send_rates_;
435 };
436 
437 // Callback, called whenever byte/packet counts have been updated.
438 class StreamDataCountersCallback {
439  public:
~StreamDataCountersCallback()440   virtual ~StreamDataCountersCallback() {}
441 
442   virtual void DataCountersUpdated(const StreamDataCounters& counters,
443                                    uint32_t ssrc) = 0;
444 };
445 
446 // Information exposed through the GetStats api.
447 struct RtpReceiveStats {
448   // `packets_lost` and `jitter` are defined by RFC 3550, and exposed in the
449   // RTCReceivedRtpStreamStats dictionary, see
450   // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*
451   int32_t packets_lost = 0;
452   // Interarrival jitter in samples.
453   uint32_t jitter = 0;
454   // Interarrival jitter in time.
455   webrtc::TimeDelta interarrival_jitter = webrtc::TimeDelta::Zero();
456 
457   // Timestamp and counters exposed in RTCInboundRtpStreamStats, see
458   // https://w3c.github.io/webrtc-stats/#inboundrtpstats-dict*
459   absl::optional<int64_t> last_packet_received_timestamp_ms;
460   RtpPacketCounter packet_counter;
461 };
462 
463 // Callback, used to notify an observer whenever new rates have been estimated.
464 class BitrateStatisticsObserver {
465  public:
~BitrateStatisticsObserver()466   virtual ~BitrateStatisticsObserver() {}
467 
468   virtual void Notify(uint32_t total_bitrate_bps,
469                       uint32_t retransmit_bitrate_bps,
470                       uint32_t ssrc) = 0;
471 };
472 
473 // Callback, used to notify an observer whenever the send-side delay is updated.
474 class SendSideDelayObserver {
475  public:
~SendSideDelayObserver()476   virtual ~SendSideDelayObserver() {}
477   virtual void SendSideDelayUpdated(int avg_delay_ms,
478                                     int max_delay_ms,
479                                     uint32_t ssrc) = 0;
480 };
481 
482 // Callback, used to notify an observer whenever a packet is sent to the
483 // transport.
484 // TODO(asapersson): This class will remove the need for SendSideDelayObserver.
485 // Remove SendSideDelayObserver once possible.
486 class SendPacketObserver {
487  public:
~SendPacketObserver()488   virtual ~SendPacketObserver() {}
489   virtual void OnSendPacket(uint16_t packet_id,
490                             int64_t capture_time_ms,
491                             uint32_t ssrc) = 0;
492 };
493 
494 }  // namespace webrtc
495 #endif  // MODULES_RTP_RTCP_INCLUDE_RTP_RTCP_DEFINES_H_
496