xref: /aosp_15_r20/external/webrtc/modules/rtp_rtcp/source/rtp_rtcp_interface.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2020 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_SOURCE_RTP_RTCP_INTERFACE_H_
12 #define MODULES_RTP_RTCP_SOURCE_RTP_RTCP_INTERFACE_H_
13 
14 #include <memory>
15 #include <string>
16 #include <vector>
17 
18 #include "absl/strings/string_view.h"
19 #include "absl/types/optional.h"
20 #include "api/field_trials_view.h"
21 #include "api/frame_transformer_interface.h"
22 #include "api/scoped_refptr.h"
23 #include "api/video/video_bitrate_allocation.h"
24 #include "modules/rtp_rtcp/include/receive_statistics.h"
25 #include "modules/rtp_rtcp/include/report_block_data.h"
26 #include "modules/rtp_rtcp/include/rtp_packet_sender.h"
27 #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
28 #include "modules/rtp_rtcp/source/rtp_packet_to_send.h"
29 #include "modules/rtp_rtcp/source/rtp_sequence_number_map.h"
30 #include "modules/rtp_rtcp/source/video_fec_generator.h"
31 #include "system_wrappers/include/ntp_time.h"
32 
33 namespace webrtc {
34 
35 // Forward declarations.
36 class FrameEncryptorInterface;
37 class RateLimiter;
38 class RtcEventLog;
39 class RTPSender;
40 class Transport;
41 class VideoBitrateAllocationObserver;
42 
43 class RtpRtcpInterface : public RtcpFeedbackSenderInterface {
44  public:
45   struct Configuration {
46     Configuration() = default;
47     Configuration(Configuration&& rhs) = default;
48 
49     Configuration(const Configuration&) = delete;
50     Configuration& operator=(const Configuration&) = delete;
51 
52     // True for a audio version of the RTP/RTCP module object false will create
53     // a video version.
54     bool audio = false;
55     bool receiver_only = false;
56 
57     // The clock to use to read time. If nullptr then system clock will be used.
58     Clock* clock = nullptr;
59 
60     ReceiveStatisticsProvider* receive_statistics = nullptr;
61 
62     // Transport object that will be called when packets are ready to be sent
63     // out on the network.
64     Transport* outgoing_transport = nullptr;
65 
66     // Called when the receiver requests an intra frame.
67     RtcpIntraFrameObserver* intra_frame_callback = nullptr;
68 
69     // Called when the receiver sends a loss notification.
70     RtcpLossNotificationObserver* rtcp_loss_notification_observer = nullptr;
71 
72     // Called when we receive a changed estimate from the receiver of out
73     // stream.
74     RtcpBandwidthObserver* bandwidth_callback = nullptr;
75 
76     NetworkStateEstimateObserver* network_state_estimate_observer = nullptr;
77     TransportFeedbackObserver* transport_feedback_callback = nullptr;
78     VideoBitrateAllocationObserver* bitrate_allocation_observer = nullptr;
79     RtcpRttStats* rtt_stats = nullptr;
80     RtcpPacketTypeCounterObserver* rtcp_packet_type_counter_observer = nullptr;
81     // Called on receipt of RTCP report block from remote side.
82     // TODO(bugs.webrtc.org/10679): Consider whether we want to use
83     // only getters or only callbacks. If we decide on getters, the
84     // ReportBlockDataObserver should also be removed in favor of
85     // GetLatestReportBlockData().
86     RtcpCnameCallback* rtcp_cname_callback = nullptr;
87     ReportBlockDataObserver* report_block_data_observer = nullptr;
88 
89     // Spread any bursts of packets into smaller bursts to minimize packet loss.
90     RtpPacketSender* paced_sender = nullptr;
91 
92     // Generates FEC packets.
93     // TODO(sprang): Wire up to RtpSenderEgress.
94     VideoFecGenerator* fec_generator = nullptr;
95 
96     BitrateStatisticsObserver* send_bitrate_observer = nullptr;
97     SendSideDelayObserver* send_side_delay_observer = nullptr;
98     RtcEventLog* event_log = nullptr;
99     SendPacketObserver* send_packet_observer = nullptr;
100     RateLimiter* retransmission_rate_limiter = nullptr;
101     StreamDataCountersCallback* rtp_stats_callback = nullptr;
102 
103     int rtcp_report_interval_ms = 0;
104 
105     // Update network2 instead of pacer_exit field of video timing extension.
106     bool populate_network2_timestamp = false;
107 
108     rtc::scoped_refptr<FrameTransformerInterface> frame_transformer;
109 
110     // E2EE Custom Video Frame Encryption
111     FrameEncryptorInterface* frame_encryptor = nullptr;
112     // Require all outgoing frames to be encrypted with a FrameEncryptor.
113     bool require_frame_encryption = false;
114 
115     // Corresponds to extmap-allow-mixed in SDP negotiation.
116     bool extmap_allow_mixed = false;
117 
118     // If true, the RTP sender will always annotate outgoing packets with
119     // MID and RID header extensions, if provided and negotiated.
120     // If false, the RTP sender will stop sending MID and RID header extensions,
121     // when it knows that the receiver is ready to demux based on SSRC. This is
122     // done by RTCP RR acking.
123     bool always_send_mid_and_rid = false;
124 
125     // If set, field trials are read from `field_trials`, otherwise
126     // defaults to  webrtc::FieldTrialBasedConfig.
127     const FieldTrialsView* field_trials = nullptr;
128 
129     // SSRCs for media and retransmission, respectively.
130     // FlexFec SSRC is fetched from `flexfec_sender`.
131     uint32_t local_media_ssrc = 0;
132     absl::optional<uint32_t> rtx_send_ssrc;
133 
134     bool need_rtp_packet_infos = false;
135 
136     // If true, the RTP packet history will select RTX packets based on
137     // heuristics such as send time, retransmission count etc, in order to
138     // make padding potentially more useful.
139     // If false, the last packet will always be picked. This may reduce CPU
140     // overhead.
141     bool enable_rtx_padding_prioritization = true;
142 
143     // Estimate RTT as non-sender as described in
144     // https://tools.ietf.org/html/rfc3611#section-4.4 and #section-4.5
145     bool non_sender_rtt_measurement = false;
146 
147     // If non-empty, sets the value for sending in the RID (and Repaired) RTP
148     // header extension. RIDs are used to identify an RTP stream if SSRCs are
149     // not negotiated. If the RID and Repaired RID extensions are not
150     // registered, the RID will not be sent.
151     std::string rid;
152   };
153 
154   // Stats for RTCP sender reports (SR) for a specific SSRC.
155   // Refer to https://tools.ietf.org/html/rfc3550#section-6.4.1.
156   struct SenderReportStats {
157     // Arrival NTP timestamp for the last received RTCP SR.
158     NtpTime last_arrival_timestamp;
159     // Received (a.k.a., remote) NTP timestamp for the last received RTCP SR.
160     NtpTime last_remote_timestamp;
161     // Total number of RTP data packets transmitted by the sender since starting
162     // transmission up until the time this SR packet was generated. The count
163     // should be reset if the sender changes its SSRC identifier.
164     uint32_t packets_sent;
165     // Total number of payload octets (i.e., not including header or padding)
166     // transmitted in RTP data packets by the sender since starting transmission
167     // up until the time this SR packet was generated. The count should be reset
168     // if the sender changes its SSRC identifier.
169     uint64_t bytes_sent;
170     // Total number of RTCP SR blocks received.
171     // https://www.w3.org/TR/webrtc-stats/#dom-rtcremoteoutboundrtpstreamstats-reportssent.
172     uint64_t reports_count;
173   };
174   // Stats about the non-sender SSRC, based on RTCP extended reports (XR).
175   // Refer to https://datatracker.ietf.org/doc/html/rfc3611#section-2.
176   struct NonSenderRttStats {
177     // https://www.w3.org/TR/webrtc-stats/#dom-rtcremoteoutboundrtpstreamstats-roundtriptime
178     absl::optional<TimeDelta> round_trip_time;
179     // https://www.w3.org/TR/webrtc-stats/#dom-rtcremoteoutboundrtpstreamstats-totalroundtriptime
180     TimeDelta total_round_trip_time = TimeDelta::Zero();
181     // https://www.w3.org/TR/webrtc-stats/#dom-rtcremoteoutboundrtpstreamstats-roundtriptimemeasurements
182     int round_trip_time_measurements = 0;
183   };
184 
185   // **************************************************************************
186   // Receiver functions
187   // **************************************************************************
188 
189   virtual void IncomingRtcpPacket(const uint8_t* incoming_packet,
190                                   size_t incoming_packet_length) = 0;
191 
192   virtual void SetRemoteSSRC(uint32_t ssrc) = 0;
193 
194   // Called when the local ssrc changes (post initialization) for receive
195   // streams to match with send. Called on the packet receive thread/tq.
196   virtual void SetLocalSsrc(uint32_t ssrc) = 0;
197 
198   // **************************************************************************
199   // Sender
200   // **************************************************************************
201 
202   // Sets the maximum size of an RTP packet, including RTP headers.
203   virtual void SetMaxRtpPacketSize(size_t size) = 0;
204 
205   // Returns max RTP packet size. Takes into account RTP headers and
206   // FEC/ULP/RED overhead (when FEC is enabled).
207   virtual size_t MaxRtpPacketSize() const = 0;
208 
209   virtual void RegisterSendPayloadFrequency(int payload_type,
210                                             int payload_frequency) = 0;
211 
212   // Unregisters a send payload.
213   // `payload_type` - payload type of codec
214   // Returns -1 on failure else 0.
215   virtual int32_t DeRegisterSendPayload(int8_t payload_type) = 0;
216 
217   virtual void SetExtmapAllowMixed(bool extmap_allow_mixed) = 0;
218 
219   // Register extension by uri, triggers CHECK on falure.
220   virtual void RegisterRtpHeaderExtension(absl::string_view uri, int id) = 0;
221 
222   virtual void DeregisterSendRtpHeaderExtension(absl::string_view uri) = 0;
223 
224   // Returns true if RTP module is send media, and any of the extensions
225   // required for bandwidth estimation is registered.
226   virtual bool SupportsPadding() const = 0;
227   // Same as SupportsPadding(), but additionally requires that
228   // SetRtxSendStatus() has been called with the kRtxRedundantPayloads option
229   // enabled.
230   virtual bool SupportsRtxPayloadPadding() const = 0;
231 
232   // Returns start timestamp.
233   virtual uint32_t StartTimestamp() const = 0;
234 
235   // Sets start timestamp. Start timestamp is set to a random value if this
236   // function is never called.
237   virtual void SetStartTimestamp(uint32_t timestamp) = 0;
238 
239   // Returns SequenceNumber.
240   virtual uint16_t SequenceNumber() const = 0;
241 
242   // Sets SequenceNumber, default is a random number.
243   virtual void SetSequenceNumber(uint16_t seq) = 0;
244 
245   virtual void SetRtpState(const RtpState& rtp_state) = 0;
246   virtual void SetRtxState(const RtpState& rtp_state) = 0;
247   virtual RtpState GetRtpState() const = 0;
248   virtual RtpState GetRtxState() const = 0;
249 
250   // This can be used to enable/disable receive-side RTT.
251   virtual void SetNonSenderRttMeasurement(bool enabled) = 0;
252 
253   // Returns SSRC.
254   virtual uint32_t SSRC() const = 0;
255 
256   // Sets the value for sending in the MID RTP header extension.
257   // The MID RTP header extension should be registered for this to do anything.
258   // Once set, this value can not be changed or removed.
259   virtual void SetMid(absl::string_view mid) = 0;
260 
261   // Sets CSRC.
262   // `csrcs` - vector of CSRCs
263   virtual void SetCsrcs(const std::vector<uint32_t>& csrcs) = 0;
264 
265   // Turns on/off sending RTX (RFC 4588). The modes can be set as a combination
266   // of values of the enumerator RtxMode.
267   virtual void SetRtxSendStatus(int modes) = 0;
268 
269   // Returns status of sending RTX (RFC 4588). The returned value can be
270   // a combination of values of the enumerator RtxMode.
271   virtual int RtxSendStatus() const = 0;
272 
273   // Returns the SSRC used for RTX if set, otherwise a nullopt.
274   virtual absl::optional<uint32_t> RtxSsrc() const = 0;
275 
276   // Sets the payload type to use when sending RTX packets. Note that this
277   // doesn't enable RTX, only the payload type is set.
278   virtual void SetRtxSendPayloadType(int payload_type,
279                                      int associated_payload_type) = 0;
280 
281   // Returns the FlexFEC SSRC, if there is one.
282   virtual absl::optional<uint32_t> FlexfecSsrc() const = 0;
283 
284   // Sets sending status. Sends kRtcpByeCode when going from true to false.
285   // Returns -1 on failure else 0.
286   virtual int32_t SetSendingStatus(bool sending) = 0;
287 
288   // Returns current sending status.
289   virtual bool Sending() const = 0;
290 
291   // Starts/Stops media packets. On by default.
292   virtual void SetSendingMediaStatus(bool sending) = 0;
293 
294   // Returns current media sending status.
295   virtual bool SendingMedia() const = 0;
296 
297   // Returns whether audio is configured (i.e. Configuration::audio = true).
298   virtual bool IsAudioConfigured() const = 0;
299 
300   // Indicate that the packets sent by this module should be counted towards the
301   // bitrate estimate since the stream participates in the bitrate allocation.
302   virtual void SetAsPartOfAllocation(bool part_of_allocation) = 0;
303 
304   // Returns bitrate sent (post-pacing) per packet type.
305   virtual RtpSendRates GetSendRates() const = 0;
306 
307   virtual RTPSender* RtpSender() = 0;
308   virtual const RTPSender* RtpSender() const = 0;
309 
310   // Record that a frame is about to be sent. Returns true on success, and false
311   // if the module isn't ready to send.
312   virtual bool OnSendingRtpFrame(uint32_t timestamp,
313                                  int64_t capture_time_ms,
314                                  int payload_type,
315                                  bool force_sender_report) = 0;
316 
317   // Try to send the provided packet. Returns true iff packet matches any of
318   // the SSRCs for this module (media/rtx/fec etc) and was forwarded to the
319   // transport.
320   virtual bool TrySendPacket(RtpPacketToSend* packet,
321                              const PacedPacketInfo& pacing_info) = 0;
322 
323   // Update the FEC protection parameters to use for delta- and key-frames.
324   // Only used when deferred FEC is active.
325   virtual void SetFecProtectionParams(
326       const FecProtectionParams& delta_params,
327       const FecProtectionParams& key_params) = 0;
328 
329   // If deferred FEC generation is enabled, this method should be called after
330   // calling TrySendPacket(). Any generated FEC packets will be removed and
331   // returned from the FEC generator.
332   virtual std::vector<std::unique_ptr<RtpPacketToSend>> FetchFecPackets() = 0;
333 
334   virtual void OnAbortedRetransmissions(
335       rtc::ArrayView<const uint16_t> sequence_numbers) = 0;
336 
337   virtual void OnPacketsAcknowledged(
338       rtc::ArrayView<const uint16_t> sequence_numbers) = 0;
339 
340   virtual std::vector<std::unique_ptr<RtpPacketToSend>> GeneratePadding(
341       size_t target_size_bytes) = 0;
342 
343   virtual std::vector<RtpSequenceNumberMap::Info> GetSentRtpPacketInfos(
344       rtc::ArrayView<const uint16_t> sequence_numbers) const = 0;
345 
346   // Returns an expected per packet overhead representing the main RTP header,
347   // any CSRCs, and the registered header extensions that are expected on all
348   // packets (i.e. disregarding things like abs capture time which is only
349   // populated on a subset of packets, but counting MID/RID type extensions
350   // when we expect to send them).
351   virtual size_t ExpectedPerPacketOverhead() const = 0;
352 
353   // Access to packet state (e.g. sequence numbering) must only be access by
354   // one thread at a time. It may be only one thread, or a construction thread
355   // that calls SetRtpState() - handing over to a pacer thread that calls
356   // TrySendPacket() - and at teardown ownership is handed to a destruciton
357   // thread that calls GetRtpState().
358   // This method is used to signal that "ownership" of the rtp state is being
359   // transferred to another thread.
360   virtual void OnPacketSendingThreadSwitched() = 0;
361 
362   // **************************************************************************
363   // RTCP
364   // **************************************************************************
365 
366   // Returns RTCP status.
367   virtual RtcpMode RTCP() const = 0;
368 
369   // Sets RTCP status i.e on(compound or non-compound)/off.
370   // `method` - RTCP method to use.
371   virtual void SetRTCPStatus(RtcpMode method) = 0;
372 
373   // Sets RTCP CName (i.e unique identifier).
374   // Returns -1 on failure else 0.
375   virtual int32_t SetCNAME(absl::string_view cname) = 0;
376 
377   // Returns remote NTP.
378   // Returns -1 on failure else 0.
379   virtual int32_t RemoteNTP(uint32_t* received_ntp_secs,
380                             uint32_t* received_ntp_frac,
381                             uint32_t* rtcp_arrival_time_secs,
382                             uint32_t* rtcp_arrival_time_frac,
383                             uint32_t* rtcp_timestamp) const = 0;
384 
385   // Returns current RTT (round-trip time) estimate.
386   // Returns -1 on failure else 0.
387   virtual int32_t RTT(uint32_t remote_ssrc,
388                       int64_t* rtt,
389                       int64_t* avg_rtt,
390                       int64_t* min_rtt,
391                       int64_t* max_rtt) const = 0;
392 
393   // Returns the estimated RTT, with fallback to a default value.
394   virtual int64_t ExpectedRetransmissionTimeMs() const = 0;
395 
396   // Forces a send of a RTCP packet. Periodic SR and RR are triggered via the
397   // process function.
398   // Returns -1 on failure else 0.
399   virtual int32_t SendRTCP(RTCPPacketType rtcp_packet_type) = 0;
400 
401   // Returns send statistics for the RTP and RTX stream.
402   virtual void GetSendStreamDataCounters(
403       StreamDataCounters* rtp_counters,
404       StreamDataCounters* rtx_counters) const = 0;
405 
406   // A snapshot of Report Blocks with additional data of interest to statistics.
407   // Within this list, the sender-source SSRC pair is unique and per-pair the
408   // ReportBlockData represents the latest Report Block that was received for
409   // that pair.
410   virtual std::vector<ReportBlockData> GetLatestReportBlockData() const = 0;
411   // Returns stats based on the received RTCP SRs.
412   virtual absl::optional<SenderReportStats> GetSenderReportStats() const = 0;
413   // Returns non-sender RTT stats, based on DLRR.
414   virtual absl::optional<NonSenderRttStats> GetNonSenderRttStats() const = 0;
415 
416   // (REMB) Receiver Estimated Max Bitrate.
417   // Schedules sending REMB on next and following sender/receiver reports.
418   void SetRemb(int64_t bitrate_bps, std::vector<uint32_t> ssrcs) override = 0;
419   // Stops sending REMB on next and following sender/receiver reports.
420   void UnsetRemb() override = 0;
421 
422   // (NACK)
423 
424   // Sends a Negative acknowledgement packet.
425   // Returns -1 on failure else 0.
426   // TODO(philipel): Deprecate this and start using SendNack instead, mostly
427   // because we want a function that actually send NACK for the specified
428   // packets.
429   virtual int32_t SendNACK(const uint16_t* nack_list, uint16_t size) = 0;
430 
431   // Sends NACK for the packets specified.
432   // Note: This assumes the caller keeps track of timing and doesn't rely on
433   // the RTP module to do this.
434   virtual void SendNack(const std::vector<uint16_t>& sequence_numbers) = 0;
435 
436   // Store the sent packets, needed to answer to a Negative acknowledgment
437   // requests.
438   virtual void SetStorePacketsStatus(bool enable, uint16_t numberToStore) = 0;
439 
440   virtual void SetVideoBitrateAllocation(
441       const VideoBitrateAllocation& bitrate) = 0;
442 
443   // **************************************************************************
444   // Video
445   // **************************************************************************
446 
447   // Requests new key frame.
448   // using PLI, https://tools.ietf.org/html/rfc4585#section-6.3.1.1
SendPictureLossIndication()449   void SendPictureLossIndication() { SendRTCP(kRtcpPli); }
450   // using FIR, https://tools.ietf.org/html/rfc5104#section-4.3.1.2
SendFullIntraRequest()451   void SendFullIntraRequest() { SendRTCP(kRtcpFir); }
452 
453   // Sends a LossNotification RTCP message.
454   // Returns -1 on failure else 0.
455   virtual int32_t SendLossNotification(uint16_t last_decoded_seq_num,
456                                        uint16_t last_received_seq_num,
457                                        bool decodability_flag,
458                                        bool buffering_allowed) = 0;
459 };
460 
461 }  // namespace webrtc
462 
463 #endif  // MODULES_RTP_RTCP_SOURCE_RTP_RTCP_INTERFACE_H_
464