You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

502 lines
17 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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. #include "modules/pacing/pacing_controller.h"
  11. #include <algorithm>
  12. #include <memory>
  13. #include <utility>
  14. #include <vector>
  15. #include "modules/pacing/bitrate_prober.h"
  16. #include "modules/pacing/interval_budget.h"
  17. #include "modules/utility/include/process_thread.h"
  18. #include "rtc_base/checks.h"
  19. #include "rtc_base/logging.h"
  20. #include "rtc_base/time_utils.h"
  21. #include "system_wrappers/include/clock.h"
  22. namespace webrtc {
  23. namespace {
  24. // Time limit in milliseconds between packet bursts.
  25. constexpr TimeDelta kDefaultMinPacketLimit = TimeDelta::Millis<5>();
  26. constexpr TimeDelta kCongestedPacketInterval = TimeDelta::Millis<500>();
  27. constexpr TimeDelta kMaxElapsedTime = TimeDelta::Seconds<2>();
  28. // Upper cap on process interval, in case process has not been called in a long
  29. // time.
  30. constexpr TimeDelta kMaxProcessingInterval = TimeDelta::Millis<30>();
  31. constexpr int kFirstPriority = 0;
  32. bool IsDisabled(const WebRtcKeyValueConfig& field_trials,
  33. absl::string_view key) {
  34. return field_trials.Lookup(key).find("Disabled") == 0;
  35. }
  36. bool IsEnabled(const WebRtcKeyValueConfig& field_trials,
  37. absl::string_view key) {
  38. return field_trials.Lookup(key).find("Enabled") == 0;
  39. }
  40. int GetPriorityForType(RtpPacketToSend::Type type) {
  41. // Lower number takes priority over higher.
  42. switch (type) {
  43. case RtpPacketToSend::Type::kAudio:
  44. // Audio is always prioritized over other packet types.
  45. return kFirstPriority + 1;
  46. case RtpPacketToSend::Type::kRetransmission:
  47. // Send retransmissions before new media.
  48. return kFirstPriority + 2;
  49. case RtpPacketToSend::Type::kVideo:
  50. case RtpPacketToSend::Type::kForwardErrorCorrection:
  51. // Video has "normal" priority, in the old speak.
  52. // Send redundancy concurrently to video. If it is delayed it might have a
  53. // lower chance of being useful.
  54. return kFirstPriority + 3;
  55. case RtpPacketToSend::Type::kPadding:
  56. // Packets that are in themselves likely useless, only sent to keep the
  57. // BWE high.
  58. return kFirstPriority + 4;
  59. }
  60. }
  61. } // namespace
  62. const TimeDelta PacingController::kMaxExpectedQueueLength =
  63. TimeDelta::Millis<2000>();
  64. const float PacingController::kDefaultPaceMultiplier = 2.5f;
  65. const TimeDelta PacingController::kPausedProcessInterval =
  66. kCongestedPacketInterval;
  67. PacingController::PacingController(Clock* clock,
  68. PacketSender* packet_sender,
  69. RtcEventLog* event_log,
  70. const WebRtcKeyValueConfig* field_trials)
  71. : clock_(clock),
  72. packet_sender_(packet_sender),
  73. fallback_field_trials_(
  74. !field_trials ? std::make_unique<FieldTrialBasedConfig>() : nullptr),
  75. field_trials_(field_trials ? field_trials : fallback_field_trials_.get()),
  76. drain_large_queues_(
  77. !IsDisabled(*field_trials_, "WebRTC-Pacer-DrainQueue")),
  78. send_padding_if_silent_(
  79. IsEnabled(*field_trials_, "WebRTC-Pacer-PadInSilence")),
  80. pace_audio_(!IsDisabled(*field_trials_, "WebRTC-Pacer-BlockAudio")),
  81. small_first_probe_packet_(
  82. IsEnabled(*field_trials_, "WebRTC-Pacer-SmallFirstProbePacket")),
  83. min_packet_limit_(kDefaultMinPacketLimit),
  84. last_timestamp_(clock_->CurrentTime()),
  85. paused_(false),
  86. media_budget_(0),
  87. padding_budget_(0),
  88. prober_(*field_trials_),
  89. probing_send_failure_(false),
  90. padding_failure_state_(false),
  91. pacing_bitrate_(DataRate::Zero()),
  92. time_last_process_(clock->CurrentTime()),
  93. last_send_time_(time_last_process_),
  94. packet_queue_(time_last_process_, field_trials),
  95. packet_counter_(0),
  96. congestion_window_size_(DataSize::PlusInfinity()),
  97. outstanding_data_(DataSize::Zero()),
  98. queue_time_limit(kMaxExpectedQueueLength),
  99. account_for_audio_(false) {
  100. if (!drain_large_queues_) {
  101. RTC_LOG(LS_WARNING) << "Pacer queues will not be drained,"
  102. "pushback experiment must be enabled.";
  103. }
  104. FieldTrialParameter<int> min_packet_limit_ms("", min_packet_limit_.ms());
  105. ParseFieldTrial({&min_packet_limit_ms},
  106. field_trials_->Lookup("WebRTC-Pacer-MinPacketLimitMs"));
  107. min_packet_limit_ = TimeDelta::ms(min_packet_limit_ms.Get());
  108. UpdateBudgetWithElapsedTime(min_packet_limit_);
  109. }
  110. PacingController::~PacingController() = default;
  111. void PacingController::CreateProbeCluster(DataRate bitrate, int cluster_id) {
  112. prober_.CreateProbeCluster(bitrate.bps(), CurrentTime().ms(), cluster_id);
  113. }
  114. void PacingController::Pause() {
  115. if (!paused_)
  116. RTC_LOG(LS_INFO) << "PacedSender paused.";
  117. paused_ = true;
  118. packet_queue_.SetPauseState(true, CurrentTime());
  119. }
  120. void PacingController::Resume() {
  121. if (paused_)
  122. RTC_LOG(LS_INFO) << "PacedSender resumed.";
  123. paused_ = false;
  124. packet_queue_.SetPauseState(false, CurrentTime());
  125. }
  126. bool PacingController::IsPaused() const {
  127. return paused_;
  128. }
  129. void PacingController::SetCongestionWindow(DataSize congestion_window_size) {
  130. congestion_window_size_ = congestion_window_size;
  131. }
  132. void PacingController::UpdateOutstandingData(DataSize outstanding_data) {
  133. outstanding_data_ = outstanding_data;
  134. }
  135. bool PacingController::Congested() const {
  136. if (congestion_window_size_.IsFinite()) {
  137. return outstanding_data_ >= congestion_window_size_;
  138. }
  139. return false;
  140. }
  141. Timestamp PacingController::CurrentTime() const {
  142. Timestamp time = clock_->CurrentTime();
  143. if (time < last_timestamp_) {
  144. RTC_LOG(LS_WARNING)
  145. << "Non-monotonic clock behavior observed. Previous timestamp: "
  146. << last_timestamp_.ms() << ", new timestamp: " << time.ms();
  147. RTC_DCHECK_GE(time, last_timestamp_);
  148. time = last_timestamp_;
  149. }
  150. last_timestamp_ = time;
  151. return time;
  152. }
  153. void PacingController::SetProbingEnabled(bool enabled) {
  154. RTC_CHECK_EQ(0, packet_counter_);
  155. prober_.SetEnabled(enabled);
  156. }
  157. void PacingController::SetPacingRates(DataRate pacing_rate,
  158. DataRate padding_rate) {
  159. RTC_DCHECK_GT(pacing_rate, DataRate::Zero());
  160. pacing_bitrate_ = pacing_rate;
  161. padding_budget_.set_target_rate_kbps(padding_rate.kbps());
  162. RTC_LOG(LS_VERBOSE) << "bwe:pacer_updated pacing_kbps="
  163. << pacing_bitrate_.kbps()
  164. << " padding_budget_kbps=" << padding_rate.kbps();
  165. }
  166. void PacingController::EnqueuePacket(std::unique_ptr<RtpPacketToSend> packet) {
  167. RTC_DCHECK(pacing_bitrate_ > DataRate::Zero())
  168. << "SetPacingRate must be called before InsertPacket.";
  169. RTC_CHECK(packet->packet_type());
  170. // Get priority first and store in temporary, to avoid chance of object being
  171. // moved before GetPriorityForType() being called.
  172. const int priority = GetPriorityForType(*packet->packet_type());
  173. EnqueuePacketInternal(std::move(packet), priority);
  174. }
  175. void PacingController::SetAccountForAudioPackets(bool account_for_audio) {
  176. account_for_audio_ = account_for_audio;
  177. }
  178. TimeDelta PacingController::ExpectedQueueTime() const {
  179. RTC_DCHECK_GT(pacing_bitrate_, DataRate::Zero());
  180. return TimeDelta::ms(
  181. (QueueSizeData().bytes() * 8 * rtc::kNumMillisecsPerSec) /
  182. pacing_bitrate_.bps());
  183. }
  184. size_t PacingController::QueueSizePackets() const {
  185. return packet_queue_.SizeInPackets();
  186. }
  187. DataSize PacingController::QueueSizeData() const {
  188. return packet_queue_.Size();
  189. }
  190. absl::optional<Timestamp> PacingController::FirstSentPacketTime() const {
  191. return first_sent_packet_time_;
  192. }
  193. TimeDelta PacingController::OldestPacketWaitTime() const {
  194. Timestamp oldest_packet = packet_queue_.OldestEnqueueTime();
  195. if (oldest_packet.IsInfinite()) {
  196. return TimeDelta::Zero();
  197. }
  198. return CurrentTime() - oldest_packet;
  199. }
  200. void PacingController::EnqueuePacketInternal(
  201. std::unique_ptr<RtpPacketToSend> packet,
  202. int priority) {
  203. prober_.OnIncomingPacket(packet->payload_size());
  204. Timestamp now = CurrentTime();
  205. prober_.OnIncomingPacket(packet->payload_size());
  206. // TODO(sprang): Make sure tests respect this, replace with DCHECK.
  207. if (packet->capture_time_ms() < 0) {
  208. packet->set_capture_time_ms(now.ms());
  209. }
  210. packet_queue_.Push(priority, now, packet_counter_++, std::move(packet));
  211. }
  212. TimeDelta PacingController::UpdateTimeAndGetElapsed(Timestamp now) {
  213. TimeDelta elapsed_time = now - time_last_process_;
  214. time_last_process_ = now;
  215. if (elapsed_time > kMaxElapsedTime) {
  216. RTC_LOG(LS_WARNING) << "Elapsed time (" << elapsed_time.ms()
  217. << " ms) longer than expected, limiting to "
  218. << kMaxElapsedTime.ms();
  219. elapsed_time = kMaxElapsedTime;
  220. }
  221. return elapsed_time;
  222. }
  223. bool PacingController::ShouldSendKeepalive(Timestamp now) const {
  224. if (send_padding_if_silent_ || paused_ || Congested()) {
  225. // We send a padding packet every 500 ms to ensure we won't get stuck in
  226. // congested state due to no feedback being received.
  227. TimeDelta elapsed_since_last_send = now - last_send_time_;
  228. if (elapsed_since_last_send >= kCongestedPacketInterval) {
  229. // We can not send padding unless a normal packet has first been sent. If
  230. // we do, timestamps get messed up.
  231. if (packet_counter_ > 0) {
  232. return true;
  233. }
  234. }
  235. }
  236. return false;
  237. }
  238. absl::optional<TimeDelta> PacingController::TimeUntilNextProbe() {
  239. if (!prober_.IsProbing()) {
  240. return absl::nullopt;
  241. }
  242. TimeDelta time_delta =
  243. TimeDelta::ms(prober_.TimeUntilNextProbe(CurrentTime().ms()));
  244. if (time_delta > TimeDelta::Zero() ||
  245. (time_delta == TimeDelta::Zero() && !probing_send_failure_)) {
  246. return time_delta;
  247. }
  248. return absl::nullopt;
  249. }
  250. TimeDelta PacingController::TimeElapsedSinceLastProcess() const {
  251. return CurrentTime() - time_last_process_;
  252. }
  253. void PacingController::ProcessPackets() {
  254. Timestamp now = CurrentTime();
  255. TimeDelta elapsed_time = UpdateTimeAndGetElapsed(now);
  256. if (ShouldSendKeepalive(now)) {
  257. DataSize keepalive_data_sent = DataSize::Zero();
  258. std::vector<std::unique_ptr<RtpPacketToSend>> keepalive_packets =
  259. packet_sender_->GeneratePadding(DataSize::bytes(1));
  260. for (auto& packet : keepalive_packets) {
  261. keepalive_data_sent +=
  262. DataSize::bytes(packet->payload_size() + packet->padding_size());
  263. packet_sender_->SendRtpPacket(std::move(packet), PacedPacketInfo());
  264. }
  265. OnPaddingSent(keepalive_data_sent);
  266. }
  267. if (paused_)
  268. return;
  269. if (elapsed_time > TimeDelta::Zero()) {
  270. DataRate target_rate = pacing_bitrate_;
  271. DataSize queue_size_data = packet_queue_.Size();
  272. if (queue_size_data > DataSize::Zero()) {
  273. // Assuming equal size packets and input/output rate, the average packet
  274. // has avg_time_left_ms left to get queue_size_bytes out of the queue, if
  275. // time constraint shall be met. Determine bitrate needed for that.
  276. packet_queue_.UpdateQueueTime(CurrentTime());
  277. if (drain_large_queues_) {
  278. TimeDelta avg_time_left =
  279. std::max(TimeDelta::ms(1),
  280. queue_time_limit - packet_queue_.AverageQueueTime());
  281. DataRate min_rate_needed = queue_size_data / avg_time_left;
  282. if (min_rate_needed > target_rate) {
  283. target_rate = min_rate_needed;
  284. RTC_LOG(LS_VERBOSE) << "bwe:large_pacing_queue pacing_rate_kbps="
  285. << target_rate.kbps();
  286. }
  287. }
  288. }
  289. media_budget_.set_target_rate_kbps(target_rate.kbps());
  290. UpdateBudgetWithElapsedTime(elapsed_time);
  291. }
  292. bool first_packet_in_probe = false;
  293. bool is_probing = prober_.IsProbing();
  294. PacedPacketInfo pacing_info;
  295. absl::optional<DataSize> recommended_probe_size;
  296. if (is_probing) {
  297. pacing_info = prober_.CurrentCluster();
  298. first_packet_in_probe = pacing_info.probe_cluster_bytes_sent == 0;
  299. recommended_probe_size = DataSize::bytes(prober_.RecommendedMinProbeSize());
  300. }
  301. DataSize data_sent = DataSize::Zero();
  302. // The paused state is checked in the loop since it leaves the critical
  303. // section allowing the paused state to be changed from other code.
  304. while (!paused_) {
  305. if (small_first_probe_packet_ && first_packet_in_probe) {
  306. // If first packet in probe, insert a small padding packet so we have a
  307. // more reliable start window for the rate estimation.
  308. auto padding = packet_sender_->GeneratePadding(DataSize::bytes(1));
  309. // If no RTP modules sending media are registered, we may not get a
  310. // padding packet back.
  311. if (!padding.empty()) {
  312. // Insert with high priority so larger media packets don't preempt it.
  313. EnqueuePacketInternal(std::move(padding[0]), kFirstPriority);
  314. // We should never get more than one padding packets with a requested
  315. // size of 1 byte.
  316. RTC_DCHECK_EQ(padding.size(), 1u);
  317. }
  318. first_packet_in_probe = false;
  319. }
  320. auto* packet = GetPendingPacket(pacing_info);
  321. if (packet == nullptr) {
  322. // No packet available to send, check if we should send padding.
  323. DataSize padding_to_add = PaddingToAdd(recommended_probe_size, data_sent);
  324. if (padding_to_add > DataSize::Zero()) {
  325. std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets =
  326. packet_sender_->GeneratePadding(padding_to_add);
  327. if (padding_packets.empty()) {
  328. // No padding packets were generated, quite send loop.
  329. break;
  330. }
  331. for (auto& packet : padding_packets) {
  332. EnqueuePacket(std::move(packet));
  333. }
  334. // Continue loop to send the padding that was just added.
  335. continue;
  336. }
  337. // Can't fetch new packet and no padding to send, exit send loop.
  338. break;
  339. }
  340. std::unique_ptr<RtpPacketToSend> rtp_packet = packet->ReleasePacket();
  341. RTC_DCHECK(rtp_packet);
  342. packet_sender_->SendRtpPacket(std::move(rtp_packet), pacing_info);
  343. data_sent += packet->size();
  344. // Send succeeded, remove it from the queue.
  345. OnPacketSent(packet);
  346. if (recommended_probe_size && data_sent > *recommended_probe_size)
  347. break;
  348. }
  349. if (is_probing) {
  350. probing_send_failure_ = data_sent == DataSize::Zero();
  351. if (!probing_send_failure_) {
  352. prober_.ProbeSent(CurrentTime().ms(), data_sent.bytes());
  353. }
  354. }
  355. }
  356. DataSize PacingController::PaddingToAdd(
  357. absl::optional<DataSize> recommended_probe_size,
  358. DataSize data_sent) {
  359. if (!packet_queue_.Empty()) {
  360. // Actual payload available, no need to add padding.
  361. return DataSize::Zero();
  362. }
  363. if (Congested()) {
  364. // Don't add padding if congested, even if requested for probing.
  365. return DataSize::Zero();
  366. }
  367. if (packet_counter_ == 0) {
  368. // We can not send padding unless a normal packet has first been sent. If we
  369. // do, timestamps get messed up.
  370. return DataSize::Zero();
  371. }
  372. if (recommended_probe_size) {
  373. if (*recommended_probe_size > data_sent) {
  374. return *recommended_probe_size - data_sent;
  375. }
  376. return DataSize::Zero();
  377. }
  378. return DataSize::bytes(padding_budget_.bytes_remaining());
  379. }
  380. RoundRobinPacketQueue::QueuedPacket* PacingController::GetPendingPacket(
  381. const PacedPacketInfo& pacing_info) {
  382. if (packet_queue_.Empty()) {
  383. return nullptr;
  384. }
  385. // Since we need to release the lock in order to send, we first pop the
  386. // element from the priority queue but keep it in storage, so that we can
  387. // reinsert it if send fails.
  388. RoundRobinPacketQueue::QueuedPacket* packet = packet_queue_.BeginPop();
  389. bool audio_packet = packet->type() == RtpPacketToSend::Type::kAudio;
  390. bool apply_pacing = !audio_packet || pace_audio_;
  391. if (apply_pacing && (Congested() || (media_budget_.bytes_remaining() == 0 &&
  392. pacing_info.probe_cluster_id ==
  393. PacedPacketInfo::kNotAProbe))) {
  394. packet_queue_.CancelPop();
  395. return nullptr;
  396. }
  397. return packet;
  398. }
  399. void PacingController::OnPacketSent(
  400. RoundRobinPacketQueue::QueuedPacket* packet) {
  401. Timestamp now = CurrentTime();
  402. if (!first_sent_packet_time_) {
  403. first_sent_packet_time_ = now;
  404. }
  405. bool audio_packet = packet->type() == RtpPacketToSend::Type::kAudio;
  406. if (!audio_packet || account_for_audio_) {
  407. // Update media bytes sent.
  408. UpdateBudgetWithSentData(packet->size());
  409. last_send_time_ = now;
  410. }
  411. // Send succeeded, remove it from the queue.
  412. packet_queue_.FinalizePop();
  413. padding_failure_state_ = false;
  414. }
  415. void PacingController::OnPaddingSent(DataSize data_sent) {
  416. if (data_sent > DataSize::Zero()) {
  417. UpdateBudgetWithSentData(data_sent);
  418. } else {
  419. padding_failure_state_ = true;
  420. }
  421. last_send_time_ = CurrentTime();
  422. }
  423. void PacingController::UpdateBudgetWithElapsedTime(TimeDelta delta) {
  424. delta = std::min(kMaxProcessingInterval, delta);
  425. media_budget_.IncreaseBudget(delta.ms());
  426. padding_budget_.IncreaseBudget(delta.ms());
  427. }
  428. void PacingController::UpdateBudgetWithSentData(DataSize size) {
  429. outstanding_data_ += size;
  430. media_budget_.UseBudget(size.bytes());
  431. padding_budget_.UseBudget(size.bytes());
  432. }
  433. void PacingController::SetQueueTimeLimit(TimeDelta limit) {
  434. queue_time_limit = limit;
  435. }
  436. } // namespace webrtc