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.

685 lines
26 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2018 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 "video/video_send_stream_impl.h"
  11. #include <stdio.h>
  12. #include <algorithm>
  13. #include <cstdint>
  14. #include <string>
  15. #include <utility>
  16. #include "absl/algorithm/container.h"
  17. #include "api/crypto/crypto_options.h"
  18. #include "api/rtp_parameters.h"
  19. #include "api/scoped_refptr.h"
  20. #include "api/video_codecs/video_codec.h"
  21. #include "call/rtp_transport_controller_send_interface.h"
  22. #include "call/video_send_stream.h"
  23. #include "modules/pacing/paced_sender.h"
  24. #include "rtc_base/atomic_ops.h"
  25. #include "rtc_base/checks.h"
  26. #include "rtc_base/experiments/alr_experiment.h"
  27. #include "rtc_base/experiments/field_trial_parser.h"
  28. #include "rtc_base/experiments/min_video_bitrate_experiment.h"
  29. #include "rtc_base/experiments/rate_control_settings.h"
  30. #include "rtc_base/logging.h"
  31. #include "rtc_base/numerics/safe_conversions.h"
  32. #include "rtc_base/synchronization/sequence_checker.h"
  33. #include "rtc_base/thread_checker.h"
  34. #include "rtc_base/trace_event.h"
  35. #include "system_wrappers/include/clock.h"
  36. #include "system_wrappers/include/field_trial.h"
  37. namespace webrtc {
  38. namespace internal {
  39. namespace {
  40. // Max positive size difference to treat allocations as "similar".
  41. static constexpr int kMaxVbaSizeDifferencePercent = 10;
  42. // Max time we will throttle similar video bitrate allocations.
  43. static constexpr int64_t kMaxVbaThrottleTimeMs = 500;
  44. constexpr TimeDelta kEncoderTimeOut = TimeDelta::Seconds<2>();
  45. bool TransportSeqNumExtensionConfigured(const VideoSendStream::Config& config) {
  46. const std::vector<RtpExtension>& extensions = config.rtp.extensions;
  47. return absl::c_any_of(extensions, [](const RtpExtension& ext) {
  48. return ext.uri == RtpExtension::kTransportSequenceNumberUri;
  49. });
  50. }
  51. // Calculate max padding bitrate for a multi layer codec.
  52. int CalculateMaxPadBitrateBps(const std::vector<VideoStream>& streams,
  53. VideoEncoderConfig::ContentType content_type,
  54. int min_transmit_bitrate_bps,
  55. bool pad_to_min_bitrate,
  56. bool alr_probing) {
  57. int pad_up_to_bitrate_bps = 0;
  58. // Filter out only the active streams;
  59. std::vector<VideoStream> active_streams;
  60. for (const VideoStream& stream : streams) {
  61. if (stream.active)
  62. active_streams.emplace_back(stream);
  63. }
  64. if (active_streams.size() > 1) {
  65. if (alr_probing) {
  66. // With alr probing, just pad to the min bitrate of the lowest stream,
  67. // probing will handle the rest of the rampup.
  68. pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
  69. } else {
  70. // Without alr probing, pad up to start bitrate of the
  71. // highest active stream.
  72. const double hysteresis_factor =
  73. RateControlSettings::ParseFromFieldTrials()
  74. .GetSimulcastHysteresisFactor(content_type);
  75. const size_t top_active_stream_idx = active_streams.size() - 1;
  76. pad_up_to_bitrate_bps = std::min(
  77. static_cast<int>(
  78. hysteresis_factor *
  79. active_streams[top_active_stream_idx].min_bitrate_bps +
  80. 0.5),
  81. active_streams[top_active_stream_idx].target_bitrate_bps);
  82. // Add target_bitrate_bps of the lower active streams.
  83. for (size_t i = 0; i < top_active_stream_idx; ++i) {
  84. pad_up_to_bitrate_bps += active_streams[i].target_bitrate_bps;
  85. }
  86. }
  87. } else if (!active_streams.empty() && pad_to_min_bitrate) {
  88. pad_up_to_bitrate_bps = active_streams[0].min_bitrate_bps;
  89. }
  90. pad_up_to_bitrate_bps =
  91. std::max(pad_up_to_bitrate_bps, min_transmit_bitrate_bps);
  92. return pad_up_to_bitrate_bps;
  93. }
  94. RtpSenderFrameEncryptionConfig CreateFrameEncryptionConfig(
  95. const VideoSendStream::Config* config) {
  96. RtpSenderFrameEncryptionConfig frame_encryption_config;
  97. frame_encryption_config.frame_encryptor = config->frame_encryptor;
  98. frame_encryption_config.crypto_options = config->crypto_options;
  99. return frame_encryption_config;
  100. }
  101. RtpSenderObservers CreateObservers(CallStats* call_stats,
  102. EncoderRtcpFeedback* encoder_feedback,
  103. SendStatisticsProxy* stats_proxy,
  104. SendDelayStats* send_delay_stats) {
  105. RtpSenderObservers observers;
  106. observers.rtcp_rtt_stats = call_stats;
  107. observers.intra_frame_callback = encoder_feedback;
  108. observers.rtcp_loss_notification_observer = encoder_feedback;
  109. observers.rtcp_stats = stats_proxy;
  110. observers.report_block_data_observer = stats_proxy;
  111. observers.rtp_stats = stats_proxy;
  112. observers.bitrate_observer = stats_proxy;
  113. observers.frame_count_observer = stats_proxy;
  114. observers.rtcp_type_observer = stats_proxy;
  115. observers.send_delay_observer = stats_proxy;
  116. observers.send_packet_observer = send_delay_stats;
  117. return observers;
  118. }
  119. absl::optional<AlrExperimentSettings> GetAlrSettings(
  120. VideoEncoderConfig::ContentType content_type) {
  121. if (content_type == VideoEncoderConfig::ContentType::kScreen) {
  122. return AlrExperimentSettings::CreateFromFieldTrial(
  123. AlrExperimentSettings::kScreenshareProbingBweExperimentName);
  124. }
  125. return AlrExperimentSettings::CreateFromFieldTrial(
  126. AlrExperimentSettings::kStrictPacingAndProbingExperimentName);
  127. }
  128. bool SameStreamsEnabled(const VideoBitrateAllocation& lhs,
  129. const VideoBitrateAllocation& rhs) {
  130. for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
  131. for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
  132. if (lhs.HasBitrate(si, ti) != rhs.HasBitrate(si, ti)) {
  133. return false;
  134. }
  135. }
  136. }
  137. return true;
  138. }
  139. } // namespace
  140. PacingConfig::PacingConfig()
  141. : pacing_factor("factor", PacedSender::kDefaultPaceMultiplier),
  142. max_pacing_delay("max_delay",
  143. TimeDelta::ms(PacedSender::kMaxQueueLengthMs)) {
  144. ParseFieldTrial({&pacing_factor, &max_pacing_delay},
  145. field_trial::FindFullName("WebRTC-Video-Pacing"));
  146. }
  147. PacingConfig::PacingConfig(const PacingConfig&) = default;
  148. PacingConfig::~PacingConfig() = default;
  149. VideoSendStreamImpl::VideoSendStreamImpl(
  150. Clock* clock,
  151. SendStatisticsProxy* stats_proxy,
  152. rtc::TaskQueue* worker_queue,
  153. CallStats* call_stats,
  154. RtpTransportControllerSendInterface* transport,
  155. BitrateAllocatorInterface* bitrate_allocator,
  156. SendDelayStats* send_delay_stats,
  157. VideoStreamEncoderInterface* video_stream_encoder,
  158. RtcEventLog* event_log,
  159. const VideoSendStream::Config* config,
  160. int initial_encoder_max_bitrate,
  161. double initial_encoder_bitrate_priority,
  162. std::map<uint32_t, RtpState> suspended_ssrcs,
  163. std::map<uint32_t, RtpPayloadState> suspended_payload_states,
  164. VideoEncoderConfig::ContentType content_type,
  165. std::unique_ptr<FecController> fec_controller,
  166. MediaTransportInterface* media_transport)
  167. : clock_(clock),
  168. has_alr_probing_(config->periodic_alr_bandwidth_probing ||
  169. GetAlrSettings(content_type)),
  170. pacing_config_(PacingConfig()),
  171. stats_proxy_(stats_proxy),
  172. config_(config),
  173. worker_queue_(worker_queue),
  174. timed_out_(false),
  175. call_stats_(call_stats),
  176. transport_(transport),
  177. bitrate_allocator_(bitrate_allocator),
  178. disable_padding_(true),
  179. max_padding_bitrate_(0),
  180. encoder_min_bitrate_bps_(0),
  181. encoder_target_rate_bps_(0),
  182. encoder_bitrate_priority_(initial_encoder_bitrate_priority),
  183. has_packet_feedback_(false),
  184. video_stream_encoder_(video_stream_encoder),
  185. encoder_feedback_(clock, config_->rtp.ssrcs, video_stream_encoder),
  186. bandwidth_observer_(transport->GetBandwidthObserver()),
  187. rtp_video_sender_(transport_->CreateRtpVideoSender(
  188. suspended_ssrcs,
  189. suspended_payload_states,
  190. config_->rtp,
  191. config_->rtcp_report_interval_ms,
  192. config_->send_transport,
  193. CreateObservers(call_stats,
  194. &encoder_feedback_,
  195. stats_proxy_,
  196. send_delay_stats),
  197. event_log,
  198. std::move(fec_controller),
  199. CreateFrameEncryptionConfig(config_))),
  200. weak_ptr_factory_(this),
  201. media_transport_(media_transport) {
  202. video_stream_encoder->SetFecControllerOverride(rtp_video_sender_);
  203. RTC_DCHECK_RUN_ON(worker_queue_);
  204. RTC_LOG(LS_INFO) << "VideoSendStreamInternal: " << config_->ToString();
  205. weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
  206. encoder_feedback_.SetRtpVideoSender(rtp_video_sender_);
  207. if (media_transport_) {
  208. // The configured ssrc is interpreted as a channel id, so there must be
  209. // exactly one.
  210. RTC_DCHECK_EQ(config_->rtp.ssrcs.size(), 1);
  211. media_transport_->SetKeyFrameRequestCallback(&encoder_feedback_);
  212. } else {
  213. RTC_DCHECK(!config_->rtp.ssrcs.empty());
  214. }
  215. RTC_DCHECK(call_stats_);
  216. RTC_DCHECK(transport_);
  217. RTC_DCHECK_NE(initial_encoder_max_bitrate, 0);
  218. if (initial_encoder_max_bitrate > 0) {
  219. encoder_max_bitrate_bps_ =
  220. rtc::dchecked_cast<uint32_t>(initial_encoder_max_bitrate);
  221. } else {
  222. // TODO(srte): Make sure max bitrate is not set to negative values. We don't
  223. // have any way to handle unset values in downstream code, such as the
  224. // bitrate allocator. Previously -1 was implicitly casted to UINT32_MAX, a
  225. // behaviour that is not safe. Converting to 10 Mbps should be safe for
  226. // reasonable use cases as it allows adding the max of multiple streams
  227. // without wrappping around.
  228. const int kFallbackMaxBitrateBps = 10000000;
  229. RTC_DLOG(LS_ERROR) << "ERROR: Initial encoder max bitrate = "
  230. << initial_encoder_max_bitrate << " which is <= 0!";
  231. RTC_DLOG(LS_INFO) << "Using default encoder max bitrate = 10 Mbps";
  232. encoder_max_bitrate_bps_ = kFallbackMaxBitrateBps;
  233. }
  234. RTC_CHECK(AlrExperimentSettings::MaxOneFieldTrialEnabled());
  235. // If send-side BWE is enabled, check if we should apply updated probing and
  236. // pacing settings.
  237. if (TransportSeqNumExtensionConfigured(*config_)) {
  238. has_packet_feedback_ = true;
  239. absl::optional<AlrExperimentSettings> alr_settings =
  240. GetAlrSettings(content_type);
  241. if (alr_settings) {
  242. transport->EnablePeriodicAlrProbing(true);
  243. transport->SetPacingFactor(alr_settings->pacing_factor);
  244. configured_pacing_factor_ = alr_settings->pacing_factor;
  245. transport->SetQueueTimeLimit(alr_settings->max_paced_queue_time);
  246. } else {
  247. RateControlSettings rate_control_settings =
  248. RateControlSettings::ParseFromFieldTrials();
  249. transport->EnablePeriodicAlrProbing(
  250. rate_control_settings.UseAlrProbing());
  251. const double pacing_factor =
  252. rate_control_settings.GetPacingFactor().value_or(
  253. pacing_config_.pacing_factor);
  254. transport->SetPacingFactor(pacing_factor);
  255. configured_pacing_factor_ = pacing_factor;
  256. transport->SetQueueTimeLimit(pacing_config_.max_pacing_delay.Get().ms());
  257. }
  258. }
  259. if (config_->periodic_alr_bandwidth_probing) {
  260. transport->EnablePeriodicAlrProbing(true);
  261. }
  262. RTC_DCHECK_GE(config_->rtp.payload_type, 0);
  263. RTC_DCHECK_LE(config_->rtp.payload_type, 127);
  264. video_stream_encoder_->SetStartBitrate(
  265. bitrate_allocator_->GetStartBitrate(this));
  266. // Only request rotation at the source when we positively know that the remote
  267. // side doesn't support the rotation extension. This allows us to prepare the
  268. // encoder in the expectation that rotation is supported - which is the common
  269. // case.
  270. bool rotation_applied = absl::c_none_of(
  271. config_->rtp.extensions, [](const RtpExtension& extension) {
  272. return extension.uri == RtpExtension::kVideoRotationUri;
  273. });
  274. video_stream_encoder_->SetSink(this, rotation_applied);
  275. }
  276. VideoSendStreamImpl::~VideoSendStreamImpl() {
  277. RTC_DCHECK_RUN_ON(worker_queue_);
  278. RTC_DCHECK(!rtp_video_sender_->IsActive())
  279. << "VideoSendStreamImpl::Stop not called";
  280. RTC_LOG(LS_INFO) << "~VideoSendStreamInternal: " << config_->ToString();
  281. transport_->DestroyRtpVideoSender(rtp_video_sender_);
  282. if (media_transport_) {
  283. media_transport_->SetKeyFrameRequestCallback(nullptr);
  284. }
  285. }
  286. void VideoSendStreamImpl::RegisterProcessThread(
  287. ProcessThread* module_process_thread) {
  288. rtp_video_sender_->RegisterProcessThread(module_process_thread);
  289. }
  290. void VideoSendStreamImpl::DeRegisterProcessThread() {
  291. rtp_video_sender_->DeRegisterProcessThread();
  292. }
  293. void VideoSendStreamImpl::DeliverRtcp(const uint8_t* packet, size_t length) {
  294. // Runs on a network thread.
  295. RTC_DCHECK(!worker_queue_->IsCurrent());
  296. rtp_video_sender_->DeliverRtcp(packet, length);
  297. }
  298. void VideoSendStreamImpl::UpdateActiveSimulcastLayers(
  299. const std::vector<bool> active_layers) {
  300. RTC_DCHECK_RUN_ON(worker_queue_);
  301. RTC_LOG(LS_INFO) << "VideoSendStream::UpdateActiveSimulcastLayers";
  302. bool previously_active = rtp_video_sender_->IsActive();
  303. rtp_video_sender_->SetActiveModules(active_layers);
  304. if (!rtp_video_sender_->IsActive() && previously_active) {
  305. // Payload router switched from active to inactive.
  306. StopVideoSendStream();
  307. } else if (rtp_video_sender_->IsActive() && !previously_active) {
  308. // Payload router switched from inactive to active.
  309. StartupVideoSendStream();
  310. }
  311. }
  312. void VideoSendStreamImpl::Start() {
  313. RTC_DCHECK_RUN_ON(worker_queue_);
  314. RTC_LOG(LS_INFO) << "VideoSendStream::Start";
  315. if (rtp_video_sender_->IsActive())
  316. return;
  317. TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Start");
  318. rtp_video_sender_->SetActive(true);
  319. StartupVideoSendStream();
  320. }
  321. void VideoSendStreamImpl::StartupVideoSendStream() {
  322. RTC_DCHECK_RUN_ON(worker_queue_);
  323. bitrate_allocator_->AddObserver(this, GetAllocationConfig());
  324. // Start monitoring encoder activity.
  325. {
  326. RTC_DCHECK(!check_encoder_activity_task_.Running());
  327. activity_ = false;
  328. timed_out_ = false;
  329. check_encoder_activity_task_ = RepeatingTaskHandle::DelayedStart(
  330. worker_queue_->Get(), kEncoderTimeOut, [this] {
  331. RTC_DCHECK_RUN_ON(worker_queue_);
  332. if (!activity_) {
  333. if (!timed_out_) {
  334. SignalEncoderTimedOut();
  335. }
  336. timed_out_ = true;
  337. disable_padding_ = true;
  338. } else if (timed_out_) {
  339. SignalEncoderActive();
  340. timed_out_ = false;
  341. }
  342. activity_ = false;
  343. return kEncoderTimeOut;
  344. });
  345. }
  346. video_stream_encoder_->SendKeyFrame();
  347. }
  348. void VideoSendStreamImpl::Stop() {
  349. RTC_DCHECK_RUN_ON(worker_queue_);
  350. RTC_LOG(LS_INFO) << "VideoSendStream::Stop";
  351. if (!rtp_video_sender_->IsActive())
  352. return;
  353. TRACE_EVENT_INSTANT0("webrtc", "VideoSendStream::Stop");
  354. rtp_video_sender_->SetActive(false);
  355. StopVideoSendStream();
  356. }
  357. void VideoSendStreamImpl::StopVideoSendStream() {
  358. bitrate_allocator_->RemoveObserver(this);
  359. check_encoder_activity_task_.Stop();
  360. video_stream_encoder_->OnBitrateUpdated(DataRate::Zero(), DataRate::Zero(),
  361. DataRate::Zero(), 0, 0);
  362. stats_proxy_->OnSetEncoderTargetRate(0);
  363. }
  364. void VideoSendStreamImpl::SignalEncoderTimedOut() {
  365. RTC_DCHECK_RUN_ON(worker_queue_);
  366. // If the encoder has not produced anything the last kEncoderTimeOut and it
  367. // is supposed to, deregister as BitrateAllocatorObserver. This can happen
  368. // if a camera stops producing frames.
  369. if (encoder_target_rate_bps_ > 0) {
  370. RTC_LOG(LS_INFO) << "SignalEncoderTimedOut, Encoder timed out.";
  371. bitrate_allocator_->RemoveObserver(this);
  372. }
  373. }
  374. void VideoSendStreamImpl::OnBitrateAllocationUpdated(
  375. const VideoBitrateAllocation& allocation) {
  376. if (!worker_queue_->IsCurrent()) {
  377. auto ptr = weak_ptr_;
  378. worker_queue_->PostTask([=] {
  379. if (!ptr.get())
  380. return;
  381. ptr->OnBitrateAllocationUpdated(allocation);
  382. });
  383. return;
  384. }
  385. RTC_DCHECK_RUN_ON(worker_queue_);
  386. int64_t now_ms = clock_->TimeInMilliseconds();
  387. if (encoder_target_rate_bps_ != 0) {
  388. if (video_bitrate_allocation_context_) {
  389. // If new allocation is within kMaxVbaSizeDifferencePercent larger than
  390. // the previously sent allocation and the same streams are still enabled,
  391. // it is considered "similar". We do not want send similar allocations
  392. // more once per kMaxVbaThrottleTimeMs.
  393. const VideoBitrateAllocation& last =
  394. video_bitrate_allocation_context_->last_sent_allocation;
  395. const bool is_similar =
  396. allocation.get_sum_bps() >= last.get_sum_bps() &&
  397. allocation.get_sum_bps() <
  398. (last.get_sum_bps() * (100 + kMaxVbaSizeDifferencePercent)) /
  399. 100 &&
  400. SameStreamsEnabled(allocation, last);
  401. if (is_similar &&
  402. (now_ms - video_bitrate_allocation_context_->last_send_time_ms) <
  403. kMaxVbaThrottleTimeMs) {
  404. // This allocation is too similar, cache it and return.
  405. video_bitrate_allocation_context_->throttled_allocation = allocation;
  406. return;
  407. }
  408. } else {
  409. video_bitrate_allocation_context_.emplace();
  410. }
  411. video_bitrate_allocation_context_->last_sent_allocation = allocation;
  412. video_bitrate_allocation_context_->throttled_allocation.reset();
  413. video_bitrate_allocation_context_->last_send_time_ms = now_ms;
  414. // Send bitrate allocation metadata only if encoder is not paused.
  415. rtp_video_sender_->OnBitrateAllocationUpdated(allocation);
  416. }
  417. }
  418. void VideoSendStreamImpl::SignalEncoderActive() {
  419. RTC_DCHECK_RUN_ON(worker_queue_);
  420. if (rtp_video_sender_->IsActive()) {
  421. RTC_LOG(LS_INFO) << "SignalEncoderActive, Encoder is active.";
  422. bitrate_allocator_->AddObserver(this, GetAllocationConfig());
  423. }
  424. }
  425. MediaStreamAllocationConfig VideoSendStreamImpl::GetAllocationConfig() const {
  426. return MediaStreamAllocationConfig{
  427. static_cast<uint32_t>(encoder_min_bitrate_bps_),
  428. encoder_max_bitrate_bps_,
  429. static_cast<uint32_t>(disable_padding_ ? 0 : max_padding_bitrate_),
  430. /* priority_bitrate */ 0,
  431. !config_->suspend_below_min_bitrate,
  432. encoder_bitrate_priority_};
  433. }
  434. void VideoSendStreamImpl::OnEncoderConfigurationChanged(
  435. std::vector<VideoStream> streams,
  436. VideoEncoderConfig::ContentType content_type,
  437. int min_transmit_bitrate_bps) {
  438. if (!worker_queue_->IsCurrent()) {
  439. rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
  440. worker_queue_->PostTask([send_stream, streams, content_type,
  441. min_transmit_bitrate_bps]() mutable {
  442. if (send_stream) {
  443. send_stream->OnEncoderConfigurationChanged(
  444. std::move(streams), content_type, min_transmit_bitrate_bps);
  445. }
  446. });
  447. return;
  448. }
  449. RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
  450. TRACE_EVENT0("webrtc", "VideoSendStream::OnEncoderConfigurationChanged");
  451. RTC_DCHECK_GE(config_->rtp.ssrcs.size(), streams.size());
  452. RTC_DCHECK_RUN_ON(worker_queue_);
  453. const VideoCodecType codec_type =
  454. PayloadStringToCodecType(config_->rtp.payload_name);
  455. const absl::optional<DataRate> experimental_min_bitrate =
  456. GetExperimentalMinVideoBitrate(codec_type);
  457. encoder_min_bitrate_bps_ =
  458. experimental_min_bitrate
  459. ? experimental_min_bitrate->bps()
  460. : std::max(streams[0].min_bitrate_bps, kDefaultMinVideoBitrateBps);
  461. encoder_max_bitrate_bps_ = 0;
  462. double stream_bitrate_priority_sum = 0;
  463. for (const auto& stream : streams) {
  464. // We don't want to allocate more bitrate than needed to inactive streams.
  465. encoder_max_bitrate_bps_ += stream.active ? stream.max_bitrate_bps : 0;
  466. if (stream.bitrate_priority) {
  467. RTC_DCHECK_GT(*stream.bitrate_priority, 0);
  468. stream_bitrate_priority_sum += *stream.bitrate_priority;
  469. }
  470. }
  471. RTC_DCHECK_GT(stream_bitrate_priority_sum, 0);
  472. encoder_bitrate_priority_ = stream_bitrate_priority_sum;
  473. encoder_max_bitrate_bps_ =
  474. std::max(static_cast<uint32_t>(encoder_min_bitrate_bps_),
  475. encoder_max_bitrate_bps_);
  476. // TODO(bugs.webrtc.org/10266): Query the VideoBitrateAllocator instead.
  477. if (codec_type == kVideoCodecVP9) {
  478. max_padding_bitrate_ = has_alr_probing_ ? streams[0].min_bitrate_bps
  479. : streams[0].target_bitrate_bps;
  480. } else {
  481. max_padding_bitrate_ = CalculateMaxPadBitrateBps(
  482. streams, content_type, min_transmit_bitrate_bps,
  483. config_->suspend_below_min_bitrate, has_alr_probing_);
  484. }
  485. // Clear stats for disabled layers.
  486. for (size_t i = streams.size(); i < config_->rtp.ssrcs.size(); ++i) {
  487. stats_proxy_->OnInactiveSsrc(config_->rtp.ssrcs[i]);
  488. }
  489. const size_t num_temporal_layers =
  490. streams.back().num_temporal_layers.value_or(1);
  491. rtp_video_sender_->SetEncodingData(streams[0].width, streams[0].height,
  492. num_temporal_layers);
  493. if (rtp_video_sender_->IsActive()) {
  494. // The send stream is started already. Update the allocator with new bitrate
  495. // limits.
  496. bitrate_allocator_->AddObserver(this, GetAllocationConfig());
  497. }
  498. }
  499. EncodedImageCallback::Result VideoSendStreamImpl::OnEncodedImage(
  500. const EncodedImage& encoded_image,
  501. const CodecSpecificInfo* codec_specific_info,
  502. const RTPFragmentationHeader* fragmentation) {
  503. // Encoded is called on whatever thread the real encoder implementation run
  504. // on. In the case of hardware encoders, there might be several encoders
  505. // running in parallel on different threads.
  506. // Indicate that there still is activity going on.
  507. activity_ = true;
  508. auto enable_padding_task = [this]() {
  509. if (disable_padding_) {
  510. RTC_DCHECK_RUN_ON(worker_queue_);
  511. disable_padding_ = false;
  512. // To ensure that padding bitrate is propagated to the bitrate allocator.
  513. SignalEncoderActive();
  514. }
  515. };
  516. if (!worker_queue_->IsCurrent()) {
  517. worker_queue_->PostTask(enable_padding_task);
  518. } else {
  519. enable_padding_task();
  520. }
  521. EncodedImageCallback::Result result(EncodedImageCallback::Result::OK);
  522. if (media_transport_) {
  523. int64_t frame_id;
  524. {
  525. // TODO(nisse): Responsibility for allocation of frame ids should move to
  526. // VideoStreamEncoder.
  527. rtc::CritScope cs(&media_transport_id_lock_);
  528. frame_id = media_transport_frame_id_++;
  529. }
  530. // TODO(nisse): Responsibility for reference meta data should be moved
  531. // upstream, ideally close to the encoders, but probably VideoStreamEncoder
  532. // will need to do some translation to produce reference info using frame
  533. // ids.
  534. std::vector<int64_t> referenced_frame_ids;
  535. if (encoded_image._frameType != VideoFrameType::kVideoFrameKey) {
  536. RTC_DCHECK_GT(frame_id, 0);
  537. referenced_frame_ids.push_back(frame_id - 1);
  538. }
  539. media_transport_->SendVideoFrame(
  540. config_->rtp.ssrcs[0], webrtc::MediaTransportEncodedVideoFrame(
  541. frame_id, referenced_frame_ids,
  542. config_->rtp.payload_type, encoded_image));
  543. } else {
  544. result = rtp_video_sender_->OnEncodedImage(
  545. encoded_image, codec_specific_info, fragmentation);
  546. }
  547. // Check if there's a throttled VideoBitrateAllocation that we should try
  548. // sending.
  549. rtc::WeakPtr<VideoSendStreamImpl> send_stream = weak_ptr_;
  550. auto update_task = [send_stream]() {
  551. if (send_stream) {
  552. RTC_DCHECK_RUN_ON(send_stream->worker_queue_);
  553. auto& context = send_stream->video_bitrate_allocation_context_;
  554. if (context && context->throttled_allocation) {
  555. send_stream->OnBitrateAllocationUpdated(*context->throttled_allocation);
  556. }
  557. }
  558. };
  559. if (!worker_queue_->IsCurrent()) {
  560. worker_queue_->PostTask(update_task);
  561. } else {
  562. update_task();
  563. }
  564. return result;
  565. }
  566. std::map<uint32_t, RtpState> VideoSendStreamImpl::GetRtpStates() const {
  567. return rtp_video_sender_->GetRtpStates();
  568. }
  569. std::map<uint32_t, RtpPayloadState> VideoSendStreamImpl::GetRtpPayloadStates()
  570. const {
  571. return rtp_video_sender_->GetRtpPayloadStates();
  572. }
  573. uint32_t VideoSendStreamImpl::OnBitrateUpdated(BitrateAllocationUpdate update) {
  574. RTC_DCHECK_RUN_ON(worker_queue_);
  575. RTC_DCHECK(rtp_video_sender_->IsActive())
  576. << "VideoSendStream::Start has not been called.";
  577. // When the BWE algorithm doesn't pass a stable estimate, we'll use the
  578. // unstable one instead.
  579. if (update.stable_target_bitrate.IsZero()) {
  580. update.stable_target_bitrate = update.target_bitrate;
  581. }
  582. rtp_video_sender_->OnBitrateUpdated(update, stats_proxy_->GetSendFrameRate());
  583. encoder_target_rate_bps_ = rtp_video_sender_->GetPayloadBitrateBps();
  584. const uint32_t protection_bitrate_bps =
  585. rtp_video_sender_->GetProtectionBitrateBps();
  586. DataRate link_allocation = DataRate::Zero();
  587. if (encoder_target_rate_bps_ > protection_bitrate_bps) {
  588. link_allocation =
  589. DataRate::bps(encoder_target_rate_bps_ - protection_bitrate_bps);
  590. }
  591. DataRate overhead =
  592. update.target_bitrate - DataRate::bps(encoder_target_rate_bps_);
  593. DataRate encoder_stable_target_rate = update.stable_target_bitrate;
  594. if (encoder_stable_target_rate > overhead) {
  595. encoder_stable_target_rate = encoder_stable_target_rate - overhead;
  596. } else {
  597. encoder_stable_target_rate = DataRate::bps(encoder_target_rate_bps_);
  598. }
  599. encoder_target_rate_bps_ =
  600. std::min(encoder_max_bitrate_bps_, encoder_target_rate_bps_);
  601. encoder_stable_target_rate = std::min(DataRate::bps(encoder_max_bitrate_bps_),
  602. encoder_stable_target_rate);
  603. DataRate encoder_target_rate = DataRate::bps(encoder_target_rate_bps_);
  604. link_allocation = std::max(encoder_target_rate, link_allocation);
  605. video_stream_encoder_->OnBitrateUpdated(
  606. encoder_target_rate, encoder_stable_target_rate, link_allocation,
  607. rtc::dchecked_cast<uint8_t>(update.packet_loss_ratio * 256),
  608. update.round_trip_time.ms());
  609. stats_proxy_->OnSetEncoderTargetRate(encoder_target_rate_bps_);
  610. return protection_bitrate_bps;
  611. }
  612. } // namespace internal
  613. } // namespace webrtc