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.

938 lines
36 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright (c) 2015 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 "audio/audio_send_stream.h"
  11. #include <memory>
  12. #include <string>
  13. #include <utility>
  14. #include <vector>
  15. #include "api/audio_codecs/audio_encoder.h"
  16. #include "api/audio_codecs/audio_encoder_factory.h"
  17. #include "api/audio_codecs/audio_format.h"
  18. #include "api/call/transport.h"
  19. #include "api/crypto/frame_encryptor_interface.h"
  20. #include "api/function_view.h"
  21. #include "api/rtc_event_log/rtc_event_log.h"
  22. #include "api/transport/media/media_transport_config.h"
  23. #include "audio/audio_state.h"
  24. #include "audio/channel_send.h"
  25. #include "audio/conversion.h"
  26. #include "call/rtp_config.h"
  27. #include "call/rtp_transport_controller_send_interface.h"
  28. #include "common_audio/vad/include/vad.h"
  29. #include "logging/rtc_event_log/events/rtc_event_audio_send_stream_config.h"
  30. #include "logging/rtc_event_log/rtc_stream_config.h"
  31. #include "modules/audio_coding/codecs/cng/audio_encoder_cng.h"
  32. #include "modules/audio_processing/include/audio_processing.h"
  33. #include "rtc_base/checks.h"
  34. #include "rtc_base/event.h"
  35. #include "rtc_base/logging.h"
  36. #include "rtc_base/strings/audio_format_to_string.h"
  37. #include "rtc_base/task_queue.h"
  38. #include "system_wrappers/include/field_trial.h"
  39. namespace webrtc {
  40. namespace {
  41. // TODO(eladalon): Subsequent CL will make these values experiment-dependent.
  42. constexpr size_t kPacketLossTrackerMaxWindowSizeMs = 15000;
  43. constexpr size_t kPacketLossRateMinNumAckedPackets = 50;
  44. constexpr size_t kRecoverablePacketLossRateMinNumAckedPairs = 40;
  45. void UpdateEventLogStreamConfig(RtcEventLog* event_log,
  46. const AudioSendStream::Config& config,
  47. const AudioSendStream::Config* old_config) {
  48. using SendCodecSpec = AudioSendStream::Config::SendCodecSpec;
  49. // Only update if any of the things we log have changed.
  50. auto payload_types_equal = [](const absl::optional<SendCodecSpec>& a,
  51. const absl::optional<SendCodecSpec>& b) {
  52. if (a.has_value() && b.has_value()) {
  53. return a->format.name == b->format.name &&
  54. a->payload_type == b->payload_type;
  55. }
  56. return !a.has_value() && !b.has_value();
  57. };
  58. if (old_config && config.rtp.ssrc == old_config->rtp.ssrc &&
  59. config.rtp.extensions == old_config->rtp.extensions &&
  60. payload_types_equal(config.send_codec_spec,
  61. old_config->send_codec_spec)) {
  62. return;
  63. }
  64. auto rtclog_config = std::make_unique<rtclog::StreamConfig>();
  65. rtclog_config->local_ssrc = config.rtp.ssrc;
  66. rtclog_config->rtp_extensions = config.rtp.extensions;
  67. if (config.send_codec_spec) {
  68. rtclog_config->codecs.emplace_back(config.send_codec_spec->format.name,
  69. config.send_codec_spec->payload_type, 0);
  70. }
  71. event_log->Log(std::make_unique<RtcEventAudioSendStreamConfig>(
  72. std::move(rtclog_config)));
  73. }
  74. } // namespace
  75. constexpr char AudioAllocationConfig::kKey[];
  76. std::unique_ptr<StructParametersParser> AudioAllocationConfig::Parser() {
  77. return StructParametersParser::Create( //
  78. "min", &min_bitrate, //
  79. "max", &max_bitrate, //
  80. "prio_rate", &priority_bitrate, //
  81. "prio_rate_raw", &priority_bitrate_raw, //
  82. "rate_prio", &bitrate_priority);
  83. }
  84. AudioAllocationConfig::AudioAllocationConfig() {
  85. Parser()->Parse(field_trial::FindFullName(kKey));
  86. if (priority_bitrate_raw && !priority_bitrate.IsZero()) {
  87. RTC_LOG(LS_WARNING) << "'priority_bitrate' and '_raw' are mutually "
  88. "exclusive but both were configured.";
  89. }
  90. }
  91. namespace internal {
  92. AudioSendStream::AudioSendStream(
  93. Clock* clock,
  94. const webrtc::AudioSendStream::Config& config,
  95. const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
  96. TaskQueueFactory* task_queue_factory,
  97. ProcessThread* module_process_thread,
  98. RtpTransportControllerSendInterface* rtp_transport,
  99. BitrateAllocatorInterface* bitrate_allocator,
  100. RtcEventLog* event_log,
  101. RtcpRttStats* rtcp_rtt_stats,
  102. const absl::optional<RtpState>& suspended_rtp_state)
  103. : AudioSendStream(clock,
  104. config,
  105. audio_state,
  106. task_queue_factory,
  107. rtp_transport,
  108. bitrate_allocator,
  109. event_log,
  110. rtcp_rtt_stats,
  111. suspended_rtp_state,
  112. voe::CreateChannelSend(clock,
  113. task_queue_factory,
  114. module_process_thread,
  115. config.media_transport_config,
  116. /*overhead_observer=*/this,
  117. config.send_transport,
  118. rtcp_rtt_stats,
  119. event_log,
  120. config.frame_encryptor,
  121. config.crypto_options,
  122. config.rtp.extmap_allow_mixed,
  123. config.rtcp_report_interval_ms,
  124. config.rtp.ssrc)) {}
  125. AudioSendStream::AudioSendStream(
  126. Clock* clock,
  127. const webrtc::AudioSendStream::Config& config,
  128. const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
  129. TaskQueueFactory* task_queue_factory,
  130. RtpTransportControllerSendInterface* rtp_transport,
  131. BitrateAllocatorInterface* bitrate_allocator,
  132. RtcEventLog* event_log,
  133. RtcpRttStats* rtcp_rtt_stats,
  134. const absl::optional<RtpState>& suspended_rtp_state,
  135. std::unique_ptr<voe::ChannelSendInterface> channel_send)
  136. : clock_(clock),
  137. worker_queue_(rtp_transport->GetWorkerQueue()),
  138. audio_send_side_bwe_(field_trial::IsEnabled("WebRTC-Audio-SendSideBwe")),
  139. allocate_audio_without_feedback_(
  140. field_trial::IsEnabled("WebRTC-Audio-ABWENoTWCC")),
  141. enable_audio_alr_probing_(
  142. !field_trial::IsDisabled("WebRTC-Audio-AlrProbing")),
  143. send_side_bwe_with_overhead_(
  144. field_trial::IsEnabled("WebRTC-SendSideBwe-WithOverhead")),
  145. config_(Config(/*send_transport=*/nullptr, MediaTransportConfig())),
  146. audio_state_(audio_state),
  147. channel_send_(std::move(channel_send)),
  148. event_log_(event_log),
  149. use_legacy_overhead_calculation_(
  150. !field_trial::IsDisabled("WebRTC-Audio-LegacyOverhead")),
  151. bitrate_allocator_(bitrate_allocator),
  152. rtp_transport_(rtp_transport),
  153. packet_loss_tracker_(kPacketLossTrackerMaxWindowSizeMs,
  154. kPacketLossRateMinNumAckedPackets,
  155. kRecoverablePacketLossRateMinNumAckedPairs),
  156. rtp_rtcp_module_(nullptr),
  157. suspended_rtp_state_(suspended_rtp_state) {
  158. RTC_LOG(LS_INFO) << "AudioSendStream: " << config.rtp.ssrc;
  159. RTC_DCHECK(worker_queue_);
  160. RTC_DCHECK(audio_state_);
  161. RTC_DCHECK(channel_send_);
  162. RTC_DCHECK(bitrate_allocator_);
  163. // Currently we require the rtp transport even when media transport is used.
  164. RTC_DCHECK(rtp_transport);
  165. // TODO(nisse): Eventually, we should have only media_transport. But for the
  166. // time being, we can have either. When media transport is injected, there
  167. // should be no rtp_transport, and below check should be strengthened to XOR
  168. // (either rtp_transport or media_transport but not both).
  169. RTC_DCHECK(rtp_transport || config.media_transport_config.media_transport);
  170. if (config.media_transport_config.media_transport) {
  171. // TODO(sukhanov): Currently media transport audio overhead is considered
  172. // constant, we will not get overhead_observer calls when using
  173. // media_transport. In the future when we introduce RTP media transport we
  174. // should make audio overhead interface consistent and work for both RTP and
  175. // non-RTP implementations.
  176. audio_overhead_per_packet_bytes_ =
  177. config.media_transport_config.media_transport->GetAudioPacketOverhead();
  178. }
  179. rtp_rtcp_module_ = channel_send_->GetRtpRtcp();
  180. RTC_DCHECK(rtp_rtcp_module_);
  181. ConfigureStream(config, true);
  182. pacer_thread_checker_.Detach();
  183. // Signal congestion controller this object is ready for OnPacket* callbacks.
  184. rtp_transport_->RegisterPacketFeedbackObserver(this);
  185. }
  186. AudioSendStream::~AudioSendStream() {
  187. RTC_DCHECK(worker_thread_checker_.IsCurrent());
  188. RTC_LOG(LS_INFO) << "~AudioSendStream: " << config_.rtp.ssrc;
  189. RTC_DCHECK(!sending_);
  190. rtp_transport_->DeRegisterPacketFeedbackObserver(this);
  191. channel_send_->ResetSenderCongestionControlObjects();
  192. // Blocking call to synchronize state with worker queue to ensure that there
  193. // are no pending tasks left that keeps references to audio.
  194. rtc::Event thread_sync_event;
  195. worker_queue_->PostTask([&] { thread_sync_event.Set(); });
  196. thread_sync_event.Wait(rtc::Event::kForever);
  197. }
  198. const webrtc::AudioSendStream::Config& AudioSendStream::GetConfig() const {
  199. RTC_DCHECK(worker_thread_checker_.IsCurrent());
  200. return config_;
  201. }
  202. void AudioSendStream::Reconfigure(
  203. const webrtc::AudioSendStream::Config& new_config) {
  204. RTC_DCHECK(worker_thread_checker_.IsCurrent());
  205. ConfigureStream(new_config, false);
  206. }
  207. AudioSendStream::ExtensionIds AudioSendStream::FindExtensionIds(
  208. const std::vector<RtpExtension>& extensions) {
  209. ExtensionIds ids;
  210. for (const auto& extension : extensions) {
  211. if (extension.uri == RtpExtension::kAudioLevelUri) {
  212. ids.audio_level = extension.id;
  213. } else if (extension.uri == RtpExtension::kAbsSendTimeUri) {
  214. ids.abs_send_time = extension.id;
  215. } else if (extension.uri == RtpExtension::kTransportSequenceNumberUri) {
  216. ids.transport_sequence_number = extension.id;
  217. } else if (extension.uri == RtpExtension::kMidUri) {
  218. ids.mid = extension.id;
  219. } else if (extension.uri == RtpExtension::kRidUri) {
  220. ids.rid = extension.id;
  221. } else if (extension.uri == RtpExtension::kRepairedRidUri) {
  222. ids.repaired_rid = extension.id;
  223. }
  224. }
  225. return ids;
  226. }
  227. int AudioSendStream::TransportSeqNumId(const AudioSendStream::Config& config) {
  228. return FindExtensionIds(config.rtp.extensions).transport_sequence_number;
  229. }
  230. void AudioSendStream::ConfigureStream(
  231. const webrtc::AudioSendStream::Config& new_config,
  232. bool first_time) {
  233. RTC_LOG(LS_INFO) << "AudioSendStream::ConfigureStream: "
  234. << new_config.ToString();
  235. UpdateEventLogStreamConfig(event_log_, new_config,
  236. first_time ? nullptr : &config_);
  237. const auto& old_config = config_;
  238. config_cs_.Enter();
  239. // Configuration parameters which cannot be changed.
  240. RTC_DCHECK(first_time ||
  241. old_config.send_transport == new_config.send_transport);
  242. RTC_DCHECK(first_time || old_config.rtp.ssrc == new_config.rtp.ssrc);
  243. if (suspended_rtp_state_ && first_time) {
  244. rtp_rtcp_module_->SetRtpState(*suspended_rtp_state_);
  245. }
  246. if (first_time || old_config.rtp.c_name != new_config.rtp.c_name) {
  247. channel_send_->SetRTCP_CNAME(new_config.rtp.c_name);
  248. }
  249. // Enable the frame encryptor if a new frame encryptor has been provided.
  250. if (first_time || new_config.frame_encryptor != old_config.frame_encryptor) {
  251. channel_send_->SetFrameEncryptor(new_config.frame_encryptor);
  252. }
  253. if (first_time ||
  254. new_config.rtp.extmap_allow_mixed != old_config.rtp.extmap_allow_mixed) {
  255. channel_send_->SetExtmapAllowMixed(new_config.rtp.extmap_allow_mixed);
  256. }
  257. const ExtensionIds old_ids = FindExtensionIds(old_config.rtp.extensions);
  258. const ExtensionIds new_ids = FindExtensionIds(new_config.rtp.extensions);
  259. config_cs_.Leave();
  260. // Audio level indication
  261. if (first_time || new_ids.audio_level != old_ids.audio_level) {
  262. channel_send_->SetSendAudioLevelIndicationStatus(new_ids.audio_level != 0,
  263. new_ids.audio_level);
  264. }
  265. if (first_time || new_ids.abs_send_time != old_ids.abs_send_time) {
  266. channel_send_->GetRtpRtcp()->DeregisterSendRtpHeaderExtension(
  267. kRtpExtensionAbsoluteSendTime);
  268. if (new_ids.abs_send_time) {
  269. rtp_rtcp_module_->RegisterRtpHeaderExtension(AbsoluteSendTime::kUri,
  270. new_ids.abs_send_time);
  271. }
  272. }
  273. bool transport_seq_num_id_changed =
  274. new_ids.transport_sequence_number != old_ids.transport_sequence_number;
  275. if (first_time ||
  276. (transport_seq_num_id_changed && !allocate_audio_without_feedback_)) {
  277. if (!first_time) {
  278. channel_send_->ResetSenderCongestionControlObjects();
  279. }
  280. RtcpBandwidthObserver* bandwidth_observer = nullptr;
  281. if (audio_send_side_bwe_ && !allocate_audio_without_feedback_ &&
  282. new_ids.transport_sequence_number != 0) {
  283. channel_send_->EnableSendTransportSequenceNumber(
  284. new_ids.transport_sequence_number);
  285. // Probing in application limited region is only used in combination with
  286. // send side congestion control, wich depends on feedback packets which
  287. // requires transport sequence numbers to be enabled.
  288. // Optionally request ALR probing but do not override any existing
  289. // request from other streams.
  290. if (enable_audio_alr_probing_) {
  291. rtp_transport_->EnablePeriodicAlrProbing(true);
  292. }
  293. bandwidth_observer = rtp_transport_->GetBandwidthObserver();
  294. }
  295. channel_send_->RegisterSenderCongestionControlObjects(rtp_transport_,
  296. bandwidth_observer);
  297. }
  298. config_cs_.Enter();
  299. // MID RTP header extension.
  300. if ((first_time || new_ids.mid != old_ids.mid ||
  301. new_config.rtp.mid != old_config.rtp.mid) &&
  302. new_ids.mid != 0 && !new_config.rtp.mid.empty()) {
  303. channel_send_->SetMid(new_config.rtp.mid, new_ids.mid);
  304. }
  305. // RID RTP header extension
  306. if ((first_time || new_ids.rid != old_ids.rid ||
  307. new_ids.repaired_rid != old_ids.repaired_rid ||
  308. new_config.rtp.rid != old_config.rtp.rid)) {
  309. channel_send_->SetRid(new_config.rtp.rid, new_ids.rid,
  310. new_ids.repaired_rid);
  311. }
  312. if (!ReconfigureSendCodec(new_config)) {
  313. RTC_LOG(LS_ERROR) << "Failed to set up send codec state.";
  314. }
  315. if (sending_) {
  316. ReconfigureBitrateObserver(new_config);
  317. }
  318. config_ = new_config;
  319. config_cs_.Leave();
  320. }
  321. void AudioSendStream::Start() {
  322. RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  323. if (sending_) {
  324. return;
  325. }
  326. if (!config_.has_dscp && config_.min_bitrate_bps != -1 &&
  327. config_.max_bitrate_bps != -1 &&
  328. (allocate_audio_without_feedback_ || TransportSeqNumId(config_) != 0)) {
  329. rtp_transport_->AccountForAudioPacketsInPacedSender(true);
  330. rtp_rtcp_module_->SetAsPartOfAllocation(true);
  331. rtc::Event thread_sync_event;
  332. worker_queue_->PostTask([&] {
  333. RTC_DCHECK_RUN_ON(worker_queue_);
  334. ConfigureBitrateObserver();
  335. thread_sync_event.Set();
  336. });
  337. thread_sync_event.Wait(rtc::Event::kForever);
  338. } else {
  339. rtp_rtcp_module_->SetAsPartOfAllocation(false);
  340. }
  341. channel_send_->StartSend();
  342. sending_ = true;
  343. audio_state()->AddSendingStream(this, encoder_sample_rate_hz_,
  344. encoder_num_channels_);
  345. }
  346. void AudioSendStream::Stop() {
  347. RTC_DCHECK(worker_thread_checker_.IsCurrent());
  348. if (!sending_) {
  349. return;
  350. }
  351. RemoveBitrateObserver();
  352. channel_send_->StopSend();
  353. sending_ = false;
  354. audio_state()->RemoveSendingStream(this);
  355. }
  356. void AudioSendStream::SendAudioData(std::unique_ptr<AudioFrame> audio_frame) {
  357. RTC_CHECK_RUNS_SERIALIZED(&audio_capture_race_checker_);
  358. RTC_DCHECK_GT(audio_frame->sample_rate_hz_, 0);
  359. double duration = static_cast<double>(audio_frame->samples_per_channel_) /
  360. audio_frame->sample_rate_hz_;
  361. {
  362. // Note: SendAudioData() passes the frame further down the pipeline and it
  363. // may eventually get sent. But this method is invoked even if we are not
  364. // connected, as long as we have an AudioSendStream (created as a result of
  365. // an O/A exchange). This means that we are calculating audio levels whether
  366. // or not we are sending samples.
  367. // TODO(https://crbug.com/webrtc/10771): All "media-source" related stats
  368. // should move from send-streams to the local audio sources or tracks; a
  369. // send-stream should not be required to read the microphone audio levels.
  370. rtc::CritScope cs(&audio_level_lock_);
  371. audio_level_.ComputeLevel(*audio_frame, duration);
  372. }
  373. channel_send_->ProcessAndEncodeAudio(std::move(audio_frame));
  374. }
  375. bool AudioSendStream::SendTelephoneEvent(int payload_type,
  376. int payload_frequency,
  377. int event,
  378. int duration_ms) {
  379. RTC_DCHECK(worker_thread_checker_.IsCurrent());
  380. channel_send_->SetSendTelephoneEventPayloadType(payload_type,
  381. payload_frequency);
  382. return channel_send_->SendTelephoneEventOutband(event, duration_ms);
  383. }
  384. void AudioSendStream::SetMuted(bool muted) {
  385. RTC_DCHECK(worker_thread_checker_.IsCurrent());
  386. channel_send_->SetInputMute(muted);
  387. }
  388. webrtc::AudioSendStream::Stats AudioSendStream::GetStats() const {
  389. return GetStats(true);
  390. }
  391. webrtc::AudioSendStream::Stats AudioSendStream::GetStats(
  392. bool has_remote_tracks) const {
  393. RTC_DCHECK(worker_thread_checker_.IsCurrent());
  394. webrtc::AudioSendStream::Stats stats;
  395. stats.local_ssrc = config_.rtp.ssrc;
  396. stats.target_bitrate_bps = channel_send_->GetBitrate();
  397. webrtc::CallSendStatistics call_stats = channel_send_->GetRTCPStatistics();
  398. stats.payload_bytes_sent = call_stats.payload_bytes_sent;
  399. stats.header_and_padding_bytes_sent =
  400. call_stats.header_and_padding_bytes_sent;
  401. stats.retransmitted_bytes_sent = call_stats.retransmitted_bytes_sent;
  402. stats.packets_sent = call_stats.packetsSent;
  403. stats.retransmitted_packets_sent = call_stats.retransmitted_packets_sent;
  404. // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
  405. // returns 0 to indicate an error value.
  406. if (call_stats.rttMs > 0) {
  407. stats.rtt_ms = call_stats.rttMs;
  408. }
  409. if (config_.send_codec_spec) {
  410. const auto& spec = *config_.send_codec_spec;
  411. stats.codec_name = spec.format.name;
  412. stats.codec_payload_type = spec.payload_type;
  413. // Get data from the last remote RTCP report.
  414. for (const auto& block : channel_send_->GetRemoteRTCPReportBlocks()) {
  415. // Lookup report for send ssrc only.
  416. if (block.source_SSRC == stats.local_ssrc) {
  417. stats.packets_lost = block.cumulative_num_packets_lost;
  418. stats.fraction_lost = Q8ToFloat(block.fraction_lost);
  419. // Convert timestamps to milliseconds.
  420. if (spec.format.clockrate_hz / 1000 > 0) {
  421. stats.jitter_ms =
  422. block.interarrival_jitter / (spec.format.clockrate_hz / 1000);
  423. }
  424. break;
  425. }
  426. }
  427. }
  428. {
  429. rtc::CritScope cs(&audio_level_lock_);
  430. stats.audio_level = audio_level_.LevelFullRange();
  431. stats.total_input_energy = audio_level_.TotalEnergy();
  432. stats.total_input_duration = audio_level_.TotalDuration();
  433. }
  434. stats.typing_noise_detected = audio_state()->typing_noise_detected();
  435. stats.ana_statistics = channel_send_->GetANAStatistics();
  436. RTC_DCHECK(audio_state_->audio_processing());
  437. stats.apm_statistics =
  438. audio_state_->audio_processing()->GetStatistics(has_remote_tracks);
  439. stats.report_block_datas = std::move(call_stats.report_block_datas);
  440. return stats;
  441. }
  442. void AudioSendStream::DeliverRtcp(const uint8_t* packet, size_t length) {
  443. // TODO(solenberg): Tests call this function on a network thread, libjingle
  444. // calls on the worker thread. We should move towards always using a network
  445. // thread. Then this check can be enabled.
  446. // RTC_DCHECK(!worker_thread_checker_.IsCurrent());
  447. channel_send_->ReceivedRTCPPacket(packet, length);
  448. }
  449. uint32_t AudioSendStream::OnBitrateUpdated(BitrateAllocationUpdate update) {
  450. RTC_DCHECK_RUN_ON(worker_queue_);
  451. // Pick a target bitrate between the constraints. Overrules the allocator if
  452. // it 1) allocated a bitrate of zero to disable the stream or 2) allocated a
  453. // higher than max to allow for e.g. extra FEC.
  454. auto constraints = GetMinMaxBitrateConstraints();
  455. update.target_bitrate.Clamp(constraints.min, constraints.max);
  456. channel_send_->OnBitrateAllocation(update);
  457. // The amount of audio protection is not exposed by the encoder, hence
  458. // always returning 0.
  459. return 0;
  460. }
  461. void AudioSendStream::OnPacketAdded(uint32_t ssrc, uint16_t seq_num) {
  462. RTC_DCHECK(pacer_thread_checker_.IsCurrent());
  463. // Only packets that belong to this stream are of interest.
  464. bool same_ssrc;
  465. {
  466. rtc::CritScope lock(&config_cs_);
  467. same_ssrc = ssrc == config_.rtp.ssrc;
  468. }
  469. if (same_ssrc) {
  470. rtc::CritScope lock(&packet_loss_tracker_cs_);
  471. // TODO(eladalon): This function call could potentially reset the window,
  472. // setting both PLR and RPLR to unknown. Consider (during upcoming
  473. // refactoring) passing an indication of such an event.
  474. packet_loss_tracker_.OnPacketAdded(seq_num, clock_->TimeInMilliseconds());
  475. }
  476. }
  477. void AudioSendStream::OnPacketFeedbackVector(
  478. const std::vector<PacketFeedback>& packet_feedback_vector) {
  479. RTC_DCHECK(worker_thread_checker_.IsCurrent());
  480. absl::optional<float> plr;
  481. absl::optional<float> rplr;
  482. {
  483. rtc::CritScope lock(&packet_loss_tracker_cs_);
  484. packet_loss_tracker_.OnPacketFeedbackVector(packet_feedback_vector);
  485. plr = packet_loss_tracker_.GetPacketLossRate();
  486. rplr = packet_loss_tracker_.GetRecoverablePacketLossRate();
  487. }
  488. // TODO(eladalon): If R/PLR go back to unknown, no indication is given that
  489. // the previously sent value is no longer relevant. This will be taken care
  490. // of with some refactoring which is now being done.
  491. if (plr) {
  492. channel_send_->OnTwccBasedUplinkPacketLossRate(*plr);
  493. }
  494. if (rplr) {
  495. channel_send_->OnRecoverableUplinkPacketLossRate(*rplr);
  496. }
  497. }
  498. void AudioSendStream::SetTransportOverhead(
  499. int transport_overhead_per_packet_bytes) {
  500. RTC_DCHECK(worker_thread_checker_.IsCurrent());
  501. rtc::CritScope cs(&overhead_per_packet_lock_);
  502. transport_overhead_per_packet_bytes_ = transport_overhead_per_packet_bytes;
  503. UpdateOverheadForEncoder();
  504. }
  505. void AudioSendStream::OnOverheadChanged(
  506. size_t overhead_bytes_per_packet_bytes) {
  507. rtc::CritScope cs(&overhead_per_packet_lock_);
  508. audio_overhead_per_packet_bytes_ = overhead_bytes_per_packet_bytes;
  509. UpdateOverheadForEncoder();
  510. }
  511. void AudioSendStream::UpdateOverheadForEncoder() {
  512. const size_t overhead_per_packet_bytes = GetPerPacketOverheadBytes();
  513. if (overhead_per_packet_bytes == 0) {
  514. return; // Overhead is not known yet, do not tell the encoder.
  515. }
  516. channel_send_->CallEncoder([&](AudioEncoder* encoder) {
  517. encoder->OnReceivedOverhead(overhead_per_packet_bytes);
  518. });
  519. worker_queue_->PostTask([this, overhead_per_packet_bytes] {
  520. RTC_DCHECK_RUN_ON(worker_queue_);
  521. if (total_packet_overhead_bytes_ != overhead_per_packet_bytes) {
  522. total_packet_overhead_bytes_ = overhead_per_packet_bytes;
  523. if (registered_with_allocator_) {
  524. ConfigureBitrateObserver();
  525. }
  526. }
  527. });
  528. }
  529. size_t AudioSendStream::TestOnlyGetPerPacketOverheadBytes() const {
  530. rtc::CritScope cs(&overhead_per_packet_lock_);
  531. return GetPerPacketOverheadBytes();
  532. }
  533. size_t AudioSendStream::GetPerPacketOverheadBytes() const {
  534. return transport_overhead_per_packet_bytes_ +
  535. audio_overhead_per_packet_bytes_;
  536. }
  537. RtpState AudioSendStream::GetRtpState() const {
  538. return rtp_rtcp_module_->GetRtpState();
  539. }
  540. const voe::ChannelSendInterface* AudioSendStream::GetChannel() const {
  541. return channel_send_.get();
  542. }
  543. internal::AudioState* AudioSendStream::audio_state() {
  544. internal::AudioState* audio_state =
  545. static_cast<internal::AudioState*>(audio_state_.get());
  546. RTC_DCHECK(audio_state);
  547. return audio_state;
  548. }
  549. const internal::AudioState* AudioSendStream::audio_state() const {
  550. internal::AudioState* audio_state =
  551. static_cast<internal::AudioState*>(audio_state_.get());
  552. RTC_DCHECK(audio_state);
  553. return audio_state;
  554. }
  555. void AudioSendStream::StoreEncoderProperties(int sample_rate_hz,
  556. size_t num_channels) {
  557. RTC_DCHECK(worker_thread_checker_.IsCurrent());
  558. encoder_sample_rate_hz_ = sample_rate_hz;
  559. encoder_num_channels_ = num_channels;
  560. if (sending_) {
  561. // Update AudioState's information about the stream.
  562. audio_state()->AddSendingStream(this, sample_rate_hz, num_channels);
  563. }
  564. }
  565. // Apply current codec settings to a single voe::Channel used for sending.
  566. bool AudioSendStream::SetupSendCodec(const Config& new_config) {
  567. RTC_DCHECK(new_config.send_codec_spec);
  568. const auto& spec = *new_config.send_codec_spec;
  569. RTC_DCHECK(new_config.encoder_factory);
  570. std::unique_ptr<AudioEncoder> encoder =
  571. new_config.encoder_factory->MakeAudioEncoder(
  572. spec.payload_type, spec.format, new_config.codec_pair_id);
  573. if (!encoder) {
  574. RTC_DLOG(LS_ERROR) << "Unable to create encoder for "
  575. << rtc::ToString(spec.format);
  576. return false;
  577. }
  578. // If a bitrate has been specified for the codec, use it over the
  579. // codec's default.
  580. if (spec.target_bitrate_bps) {
  581. encoder->OnReceivedTargetAudioBitrate(*spec.target_bitrate_bps);
  582. }
  583. // Enable ANA if configured (currently only used by Opus).
  584. if (new_config.audio_network_adaptor_config) {
  585. if (encoder->EnableAudioNetworkAdaptor(
  586. *new_config.audio_network_adaptor_config, event_log_)) {
  587. RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
  588. << new_config.rtp.ssrc;
  589. } else {
  590. RTC_NOTREACHED();
  591. }
  592. }
  593. // Wrap the encoder in a an AudioEncoderCNG, if VAD is enabled.
  594. if (spec.cng_payload_type) {
  595. AudioEncoderCngConfig cng_config;
  596. cng_config.num_channels = encoder->NumChannels();
  597. cng_config.payload_type = *spec.cng_payload_type;
  598. cng_config.speech_encoder = std::move(encoder);
  599. cng_config.vad_mode = Vad::kVadNormal;
  600. encoder = CreateComfortNoiseEncoder(std::move(cng_config));
  601. RegisterCngPayloadType(*spec.cng_payload_type,
  602. new_config.send_codec_spec->format.clockrate_hz);
  603. }
  604. // Set currently known overhead (used in ANA, opus only).
  605. // If overhead changes later, it will be updated in UpdateOverheadForEncoder.
  606. {
  607. rtc::CritScope cs(&overhead_per_packet_lock_);
  608. if (GetPerPacketOverheadBytes() > 0) {
  609. encoder->OnReceivedOverhead(GetPerPacketOverheadBytes());
  610. }
  611. }
  612. worker_queue_->PostTask(
  613. [this, length_range = encoder->GetFrameLengthRange()] {
  614. RTC_DCHECK_RUN_ON(worker_queue_);
  615. frame_length_range_ = length_range;
  616. });
  617. StoreEncoderProperties(encoder->SampleRateHz(), encoder->NumChannels());
  618. channel_send_->SetEncoder(new_config.send_codec_spec->payload_type,
  619. std::move(encoder));
  620. return true;
  621. }
  622. bool AudioSendStream::ReconfigureSendCodec(const Config& new_config) {
  623. const auto& old_config = config_;
  624. if (!new_config.send_codec_spec) {
  625. // We cannot de-configure a send codec. So we will do nothing.
  626. // By design, the send codec should have not been configured.
  627. RTC_DCHECK(!old_config.send_codec_spec);
  628. return true;
  629. }
  630. if (new_config.send_codec_spec == old_config.send_codec_spec &&
  631. new_config.audio_network_adaptor_config ==
  632. old_config.audio_network_adaptor_config) {
  633. return true;
  634. }
  635. // If we have no encoder, or the format or payload type's changed, create a
  636. // new encoder.
  637. if (!old_config.send_codec_spec ||
  638. new_config.send_codec_spec->format !=
  639. old_config.send_codec_spec->format ||
  640. new_config.send_codec_spec->payload_type !=
  641. old_config.send_codec_spec->payload_type) {
  642. return SetupSendCodec(new_config);
  643. }
  644. const absl::optional<int>& new_target_bitrate_bps =
  645. new_config.send_codec_spec->target_bitrate_bps;
  646. // If a bitrate has been specified for the codec, use it over the
  647. // codec's default.
  648. if (new_target_bitrate_bps &&
  649. new_target_bitrate_bps !=
  650. old_config.send_codec_spec->target_bitrate_bps) {
  651. channel_send_->CallEncoder([&](AudioEncoder* encoder) {
  652. encoder->OnReceivedTargetAudioBitrate(*new_target_bitrate_bps);
  653. });
  654. }
  655. ReconfigureANA(new_config);
  656. ReconfigureCNG(new_config);
  657. // Set currently known overhead (used in ANA, opus only).
  658. {
  659. rtc::CritScope cs(&overhead_per_packet_lock_);
  660. UpdateOverheadForEncoder();
  661. }
  662. return true;
  663. }
  664. void AudioSendStream::ReconfigureANA(const Config& new_config) {
  665. if (new_config.audio_network_adaptor_config ==
  666. config_.audio_network_adaptor_config) {
  667. return;
  668. }
  669. if (new_config.audio_network_adaptor_config) {
  670. channel_send_->CallEncoder([&](AudioEncoder* encoder) {
  671. if (encoder->EnableAudioNetworkAdaptor(
  672. *new_config.audio_network_adaptor_config, event_log_)) {
  673. RTC_DLOG(LS_INFO) << "Audio network adaptor enabled on SSRC "
  674. << new_config.rtp.ssrc;
  675. } else {
  676. RTC_NOTREACHED();
  677. }
  678. });
  679. } else {
  680. channel_send_->CallEncoder(
  681. [&](AudioEncoder* encoder) { encoder->DisableAudioNetworkAdaptor(); });
  682. RTC_DLOG(LS_INFO) << "Audio network adaptor disabled on SSRC "
  683. << new_config.rtp.ssrc;
  684. }
  685. }
  686. void AudioSendStream::ReconfigureCNG(const Config& new_config) {
  687. if (new_config.send_codec_spec->cng_payload_type ==
  688. config_.send_codec_spec->cng_payload_type) {
  689. return;
  690. }
  691. // Register the CNG payload type if it's been added, don't do anything if CNG
  692. // is removed. Payload types must not be redefined.
  693. if (new_config.send_codec_spec->cng_payload_type) {
  694. RegisterCngPayloadType(*new_config.send_codec_spec->cng_payload_type,
  695. new_config.send_codec_spec->format.clockrate_hz);
  696. }
  697. // Wrap or unwrap the encoder in an AudioEncoderCNG.
  698. channel_send_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder_ptr) {
  699. std::unique_ptr<AudioEncoder> old_encoder(std::move(*encoder_ptr));
  700. auto sub_encoders = old_encoder->ReclaimContainedEncoders();
  701. if (!sub_encoders.empty()) {
  702. // Replace enc with its sub encoder. We need to put the sub
  703. // encoder in a temporary first, since otherwise the old value
  704. // of enc would be destroyed before the new value got assigned,
  705. // which would be bad since the new value is a part of the old
  706. // value.
  707. auto tmp = std::move(sub_encoders[0]);
  708. old_encoder = std::move(tmp);
  709. }
  710. if (new_config.send_codec_spec->cng_payload_type) {
  711. AudioEncoderCngConfig config;
  712. config.speech_encoder = std::move(old_encoder);
  713. config.num_channels = config.speech_encoder->NumChannels();
  714. config.payload_type = *new_config.send_codec_spec->cng_payload_type;
  715. config.vad_mode = Vad::kVadNormal;
  716. *encoder_ptr = CreateComfortNoiseEncoder(std::move(config));
  717. } else {
  718. *encoder_ptr = std::move(old_encoder);
  719. }
  720. });
  721. }
  722. void AudioSendStream::ReconfigureBitrateObserver(
  723. const webrtc::AudioSendStream::Config& new_config) {
  724. RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  725. // Since the Config's default is for both of these to be -1, this test will
  726. // allow us to configure the bitrate observer if the new config has bitrate
  727. // limits set, but would only have us call RemoveBitrateObserver if we were
  728. // previously configured with bitrate limits.
  729. if (config_.min_bitrate_bps == new_config.min_bitrate_bps &&
  730. config_.max_bitrate_bps == new_config.max_bitrate_bps &&
  731. config_.bitrate_priority == new_config.bitrate_priority &&
  732. (TransportSeqNumId(config_) == TransportSeqNumId(new_config) ||
  733. !audio_send_side_bwe_)) {
  734. return;
  735. }
  736. if (!new_config.has_dscp && new_config.min_bitrate_bps != -1 &&
  737. new_config.max_bitrate_bps != -1 && TransportSeqNumId(new_config) != 0) {
  738. rtp_transport_->AccountForAudioPacketsInPacedSender(true);
  739. rtc::Event thread_sync_event;
  740. worker_queue_->PostTask([&] {
  741. RTC_DCHECK_RUN_ON(worker_queue_);
  742. registered_with_allocator_ = true;
  743. // We may get a callback immediately as the observer is registered, so
  744. // make
  745. // sure the bitrate limits in config_ are up-to-date.
  746. config_.min_bitrate_bps = new_config.min_bitrate_bps;
  747. config_.max_bitrate_bps = new_config.max_bitrate_bps;
  748. config_.bitrate_priority = new_config.bitrate_priority;
  749. ConfigureBitrateObserver();
  750. thread_sync_event.Set();
  751. });
  752. thread_sync_event.Wait(rtc::Event::kForever);
  753. rtp_rtcp_module_->SetAsPartOfAllocation(true);
  754. } else {
  755. rtp_transport_->AccountForAudioPacketsInPacedSender(false);
  756. RemoveBitrateObserver();
  757. rtp_rtcp_module_->SetAsPartOfAllocation(false);
  758. }
  759. }
  760. void AudioSendStream::ConfigureBitrateObserver() {
  761. // This either updates the current observer or adds a new observer.
  762. // TODO(srte): Add overhead compensation here.
  763. auto constraints = GetMinMaxBitrateConstraints();
  764. DataRate priority_bitrate = allocation_settings_.priority_bitrate;
  765. if (send_side_bwe_with_overhead_) {
  766. if (use_legacy_overhead_calculation_) {
  767. // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
  768. constexpr int kOverheadPerPacket = 20 + 8 + 10 + 12;
  769. const TimeDelta kMinPacketDuration = TimeDelta::ms(20);
  770. DataRate max_overhead =
  771. DataSize::bytes(kOverheadPerPacket) / kMinPacketDuration;
  772. priority_bitrate += max_overhead;
  773. } else {
  774. RTC_DCHECK(frame_length_range_);
  775. const DataSize kOverheadPerPacket =
  776. DataSize::bytes(total_packet_overhead_bytes_);
  777. DataRate max_overhead = kOverheadPerPacket / frame_length_range_->first;
  778. priority_bitrate += max_overhead;
  779. }
  780. }
  781. if (allocation_settings_.priority_bitrate_raw)
  782. priority_bitrate = *allocation_settings_.priority_bitrate_raw;
  783. bitrate_allocator_->AddObserver(
  784. this,
  785. MediaStreamAllocationConfig{
  786. constraints.min.bps<uint32_t>(), constraints.max.bps<uint32_t>(), 0,
  787. priority_bitrate.bps(), true,
  788. allocation_settings_.bitrate_priority.value_or(
  789. config_.bitrate_priority)});
  790. }
  791. void AudioSendStream::RemoveBitrateObserver() {
  792. RTC_DCHECK(worker_thread_checker_.IsCurrent());
  793. rtc::Event thread_sync_event;
  794. worker_queue_->PostTask([this, &thread_sync_event] {
  795. RTC_DCHECK_RUN_ON(worker_queue_);
  796. registered_with_allocator_ = false;
  797. bitrate_allocator_->RemoveObserver(this);
  798. thread_sync_event.Set();
  799. });
  800. thread_sync_event.Wait(rtc::Event::kForever);
  801. }
  802. AudioSendStream::TargetAudioBitrateConstraints
  803. AudioSendStream::GetMinMaxBitrateConstraints() const {
  804. TargetAudioBitrateConstraints constraints{
  805. DataRate::bps(config_.min_bitrate_bps),
  806. DataRate::bps(config_.max_bitrate_bps)};
  807. // If bitrates were explicitly overriden via field trial, use those values.
  808. if (allocation_settings_.min_bitrate)
  809. constraints.min = *allocation_settings_.min_bitrate;
  810. if (allocation_settings_.max_bitrate)
  811. constraints.max = *allocation_settings_.max_bitrate;
  812. RTC_DCHECK_GE(constraints.min, DataRate::Zero());
  813. RTC_DCHECK_GE(constraints.max, DataRate::Zero());
  814. RTC_DCHECK_GE(constraints.max, constraints.min);
  815. if (send_side_bwe_with_overhead_) {
  816. if (use_legacy_overhead_calculation_) {
  817. // OverheadPerPacket = Ipv4(20B) + UDP(8B) + SRTP(10B) + RTP(12)
  818. const DataSize kOverheadPerPacket = DataSize::bytes(20 + 8 + 10 + 12);
  819. const TimeDelta kMaxFrameLength =
  820. TimeDelta::ms(60); // Based on Opus spec
  821. const DataRate kMinOverhead = kOverheadPerPacket / kMaxFrameLength;
  822. constraints.min += kMinOverhead;
  823. constraints.max += kMinOverhead;
  824. } else {
  825. RTC_DCHECK(frame_length_range_);
  826. const DataSize kOverheadPerPacket =
  827. DataSize::bytes(total_packet_overhead_bytes_);
  828. constraints.min += kOverheadPerPacket / frame_length_range_->second;
  829. constraints.max += kOverheadPerPacket / frame_length_range_->first;
  830. }
  831. }
  832. return constraints;
  833. }
  834. void AudioSendStream::RegisterCngPayloadType(int payload_type,
  835. int clockrate_hz) {
  836. channel_send_->RegisterCngPayloadType(payload_type, clockrate_hz);
  837. }
  838. } // namespace internal
  839. } // namespace webrtc