pacing_controller.h 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. /*
  2. * Copyright (c) 2019 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. #ifndef MODULES_PACING_PACING_CONTROLLER_H_
  11. #define MODULES_PACING_PACING_CONTROLLER_H_
  12. #include <stddef.h>
  13. #include <stdint.h>
  14. #include <atomic>
  15. #include <memory>
  16. #include <vector>
  17. #include "absl/types/optional.h"
  18. #include "api/function_view.h"
  19. #include "api/rtc_event_log/rtc_event_log.h"
  20. #include "api/transport/field_trial_based_config.h"
  21. #include "api/transport/network_types.h"
  22. #include "api/transport/webrtc_key_value_config.h"
  23. #include "modules/pacing/bitrate_prober.h"
  24. #include "modules/pacing/interval_budget.h"
  25. #include "modules/pacing/round_robin_packet_queue.h"
  26. #include "modules/pacing/rtp_packet_pacer.h"
  27. #include "modules/rtp_rtcp/include/rtp_packet_sender.h"
  28. #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
  29. #include "modules/rtp_rtcp/source/rtp_packet_to_send.h"
  30. #include "rtc_base/experiments/field_trial_parser.h"
  31. #include "rtc_base/thread_annotations.h"
  32. namespace webrtc {
  33. // This class implements a leaky-bucket packet pacing algorithm. It handles the
  34. // logic of determining which packets to send when, but the actual timing of
  35. // the processing is done externally (e.g. PacedSender). Furthermore, the
  36. // forwarding of packets when they are ready to be sent is also handled
  37. // externally, via the PacedSendingController::PacketSender interface.
  38. //
  39. class PacingController {
  40. public:
  41. // Periodic mode uses the IntervalBudget class for tracking bitrate
  42. // budgets, and expected ProcessPackets() to be called a fixed rate,
  43. // e.g. every 5ms as implemented by PacedSender.
  44. // Dynamic mode allows for arbitrary time delta between calls to
  45. // ProcessPackets.
  46. enum class ProcessMode { kPeriodic, kDynamic };
  47. class PacketSender {
  48. public:
  49. virtual ~PacketSender() = default;
  50. virtual void SendPacket(std::unique_ptr<RtpPacketToSend> packet,
  51. const PacedPacketInfo& cluster_info) = 0;
  52. // Should be called after each call to SendPacket().
  53. virtual std::vector<std::unique_ptr<RtpPacketToSend>> FetchFec() = 0;
  54. virtual std::vector<std::unique_ptr<RtpPacketToSend>> GeneratePadding(
  55. DataSize size) = 0;
  56. };
  57. // Expected max pacer delay. If ExpectedQueueTime() is higher than
  58. // this value, the packet producers should wait (eg drop frames rather than
  59. // encoding them). Bitrate sent may temporarily exceed target set by
  60. // UpdateBitrate() so that this limit will be upheld.
  61. static const TimeDelta kMaxExpectedQueueLength;
  62. // Pacing-rate relative to our target send rate.
  63. // Multiplicative factor that is applied to the target bitrate to calculate
  64. // the number of bytes that can be transmitted per interval.
  65. // Increasing this factor will result in lower delays in cases of bitrate
  66. // overshoots from the encoder.
  67. static const float kDefaultPaceMultiplier;
  68. // If no media or paused, wake up at least every |kPausedProcessIntervalMs| in
  69. // order to send a keep-alive packet so we don't get stuck in a bad state due
  70. // to lack of feedback.
  71. static const TimeDelta kPausedProcessInterval;
  72. static const TimeDelta kMinSleepTime;
  73. PacingController(Clock* clock,
  74. PacketSender* packet_sender,
  75. RtcEventLog* event_log,
  76. const WebRtcKeyValueConfig* field_trials,
  77. ProcessMode mode);
  78. ~PacingController();
  79. // Adds the packet to the queue and calls PacketRouter::SendPacket() when
  80. // it's time to send.
  81. void EnqueuePacket(std::unique_ptr<RtpPacketToSend> packet);
  82. void CreateProbeCluster(DataRate bitrate, int cluster_id);
  83. void Pause(); // Temporarily pause all sending.
  84. void Resume(); // Resume sending packets.
  85. bool IsPaused() const;
  86. void SetCongestionWindow(DataSize congestion_window_size);
  87. void UpdateOutstandingData(DataSize outstanding_data);
  88. // Sets the pacing rates. Must be called once before packets can be sent.
  89. void SetPacingRates(DataRate pacing_rate, DataRate padding_rate);
  90. // Currently audio traffic is not accounted by pacer and passed through.
  91. // With the introduction of audio BWE audio traffic will be accounted for
  92. // the pacer budget calculation. The audio traffic still will be injected
  93. // at high priority.
  94. void SetAccountForAudioPackets(bool account_for_audio);
  95. void SetIncludeOverhead();
  96. void SetTransportOverhead(DataSize overhead_per_packet);
  97. // Returns the time since the oldest queued packet was enqueued.
  98. TimeDelta OldestPacketWaitTime() const;
  99. // Number of packets in the pacer queue.
  100. size_t QueueSizePackets() const;
  101. // Totals size of packets in the pacer queue.
  102. DataSize QueueSizeData() const;
  103. // Current buffer level, i.e. max of media and padding debt.
  104. DataSize CurrentBufferLevel() const;
  105. // Returns the time when the first packet was sent;
  106. absl::optional<Timestamp> FirstSentPacketTime() const;
  107. // Returns the number of milliseconds it will take to send the current
  108. // packets in the queue, given the current size and bitrate, ignoring prio.
  109. TimeDelta ExpectedQueueTime() const;
  110. void SetQueueTimeLimit(TimeDelta limit);
  111. // Enable bitrate probing. Enabled by default, mostly here to simplify
  112. // testing. Must be called before any packets are being sent to have an
  113. // effect.
  114. void SetProbingEnabled(bool enabled);
  115. // Returns the next time we expect ProcessPackets() to be called.
  116. Timestamp NextSendTime() const;
  117. // Check queue of pending packets and send them or padding packets, if budget
  118. // is available.
  119. void ProcessPackets();
  120. bool Congested() const;
  121. bool IsProbing() const;
  122. private:
  123. void EnqueuePacketInternal(std::unique_ptr<RtpPacketToSend> packet,
  124. int priority);
  125. TimeDelta UpdateTimeAndGetElapsed(Timestamp now);
  126. bool ShouldSendKeepalive(Timestamp now) const;
  127. // Updates the number of bytes that can be sent for the next time interval.
  128. void UpdateBudgetWithElapsedTime(TimeDelta delta);
  129. void UpdateBudgetWithSentData(DataSize size);
  130. DataSize PaddingToAdd(DataSize recommended_probe_size,
  131. DataSize data_sent) const;
  132. std::unique_ptr<RtpPacketToSend> GetPendingPacket(
  133. const PacedPacketInfo& pacing_info,
  134. Timestamp target_send_time,
  135. Timestamp now);
  136. void OnPacketSent(RtpPacketMediaType packet_type,
  137. DataSize packet_size,
  138. Timestamp send_time);
  139. void OnPaddingSent(DataSize padding_sent);
  140. Timestamp CurrentTime() const;
  141. const ProcessMode mode_;
  142. Clock* const clock_;
  143. PacketSender* const packet_sender_;
  144. const std::unique_ptr<FieldTrialBasedConfig> fallback_field_trials_;
  145. const WebRtcKeyValueConfig* field_trials_;
  146. const bool drain_large_queues_;
  147. const bool send_padding_if_silent_;
  148. const bool pace_audio_;
  149. const bool small_first_probe_packet_;
  150. const bool ignore_transport_overhead_;
  151. // In dynamic mode, indicates the target size when requesting padding,
  152. // expressed as a duration in order to adjust for varying padding rate.
  153. const TimeDelta padding_target_duration_;
  154. TimeDelta min_packet_limit_;
  155. DataSize transport_overhead_per_packet_;
  156. // TODO(webrtc:9716): Remove this when we are certain clocks are monotonic.
  157. // The last millisecond timestamp returned by |clock_|.
  158. mutable Timestamp last_timestamp_;
  159. bool paused_;
  160. // If |use_interval_budget_| is true, |media_budget_| and |padding_budget_|
  161. // will be used to track when packets can be sent. Otherwise the media and
  162. // padding debt counters will be used together with the target rates.
  163. // This is the media budget, keeping track of how many bits of media
  164. // we can pace out during the current interval.
  165. IntervalBudget media_budget_;
  166. // This is the padding budget, keeping track of how many bits of padding we're
  167. // allowed to send out during the current interval. This budget will be
  168. // utilized when there's no media to send.
  169. IntervalBudget padding_budget_;
  170. DataSize media_debt_;
  171. DataSize padding_debt_;
  172. DataRate media_rate_;
  173. DataRate padding_rate_;
  174. BitrateProber prober_;
  175. bool probing_send_failure_;
  176. DataRate pacing_bitrate_;
  177. Timestamp last_process_time_;
  178. Timestamp last_send_time_;
  179. absl::optional<Timestamp> first_sent_packet_time_;
  180. RoundRobinPacketQueue packet_queue_;
  181. uint64_t packet_counter_;
  182. DataSize congestion_window_size_;
  183. DataSize outstanding_data_;
  184. TimeDelta queue_time_limit;
  185. bool account_for_audio_;
  186. bool include_overhead_;
  187. };
  188. } // namespace webrtc
  189. #endif // MODULES_PACING_PACING_CONTROLLER_H_