blob: dd866f3f7b5298a7b749434c0722e307e9a8c66c [file] [log] [blame]
Niels Möller530ead42018-10-04 14:28:39 +02001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "audio/channel_send.h"
12
13#include <algorithm>
14#include <map>
15#include <memory>
16#include <string>
17#include <utility>
18#include <vector>
19
Niels Möller530ead42018-10-04 14:28:39 +020020#include "api/array_view.h"
Niels Möllerdced9f62018-11-19 10:27:07 +010021#include "api/call/transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "api/crypto/frame_encryptor_interface.h"
Danil Chapovalov83bbe912019-08-07 12:24:53 +020023#include "api/rtc_event_log/rtc_event_log.h"
Niels Möller530ead42018-10-04 14:28:39 +020024#include "audio/utility/audio_frame_operations.h"
25#include "call/rtp_transport_controller_send_interface.h"
26#include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
Niels Möller530ead42018-10-04 14:28:39 +020027#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
Niels Möllerdced9f62018-11-19 10:27:07 +010028#include "modules/audio_coding/include/audio_coding_module.h"
29#include "modules/audio_processing/rms_level.h"
Niels Möller530ead42018-10-04 14:28:39 +020030#include "modules/pacing/packet_router.h"
31#include "modules/utility/include/process_thread.h"
32#include "rtc_base/checks.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020033#include "rtc_base/event.h"
Niels Möller530ead42018-10-04 14:28:39 +020034#include "rtc_base/format_macros.h"
35#include "rtc_base/location.h"
36#include "rtc_base/logging.h"
Niels Möller26815232018-11-16 09:32:40 +010037#include "rtc_base/numerics/safe_conversions.h"
Niels Möllerdced9f62018-11-19 10:27:07 +010038#include "rtc_base/race_checker.h"
Niels Möller530ead42018-10-04 14:28:39 +020039#include "rtc_base/rate_limiter.h"
40#include "rtc_base/task_queue.h"
41#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080042#include "rtc_base/time_utils.h"
Sebastian Jansson977b3352019-03-04 17:43:34 +010043#include "system_wrappers/include/clock.h"
Niels Möller530ead42018-10-04 14:28:39 +020044#include "system_wrappers/include/field_trial.h"
45#include "system_wrappers/include/metrics.h"
46
47namespace webrtc {
48namespace voe {
49
50namespace {
51
52constexpr int64_t kMaxRetransmissionWindowMs = 1000;
53constexpr int64_t kMinRetransmissionWindowMs = 30;
54
Niels Möllerdced9f62018-11-19 10:27:07 +010055class RtpPacketSenderProxy;
56class TransportFeedbackProxy;
57class TransportSequenceNumberProxy;
58class VoERtcpObserver;
59
Benjamin Wright17b050f2019-03-13 17:35:46 -070060class ChannelSend : public ChannelSendInterface,
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -080061 public AudioPacketizationCallback { // receive encoded
62 // packets from the ACM
Niels Möllerdced9f62018-11-19 10:27:07 +010063 public:
64 // TODO(nisse): Make OnUplinkPacketLossRate public, and delete friend
65 // declaration.
66 friend class VoERtcpObserver;
67
Sebastian Jansson977b3352019-03-04 17:43:34 +010068 ChannelSend(Clock* clock,
Sebastian Jansson44dd9f22019-03-08 14:50:30 +010069 TaskQueueFactory* task_queue_factory,
Niels Möllerdced9f62018-11-19 10:27:07 +010070 ProcessThread* module_process_thread,
Anton Sukhanov626015d2019-02-04 15:16:06 -080071 OverheadObserver* overhead_observer,
Niels Möllere9771992018-11-26 10:55:07 +010072 Transport* rtp_transport,
Niels Möllerdced9f62018-11-19 10:27:07 +010073 RtcpRttStats* rtcp_rtt_stats,
74 RtcEventLog* rtc_event_log,
75 FrameEncryptorInterface* frame_encryptor,
76 const webrtc::CryptoOptions& crypto_options,
77 bool extmap_allow_mixed,
Erik Språng4c2c4122019-07-11 15:20:15 +020078 int rtcp_report_interval_ms,
79 uint32_t ssrc);
Niels Möllerdced9f62018-11-19 10:27:07 +010080
81 ~ChannelSend() override;
82
83 // Send using this encoder, with this payload type.
Niels Möller8fb1a6a2019-03-05 14:29:42 +010084 void SetEncoder(int payload_type,
Niels Möllerdced9f62018-11-19 10:27:07 +010085 std::unique_ptr<AudioEncoder> encoder) override;
86 void ModifyEncoder(rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)>
87 modifier) override;
Sebastian Jansson14a7cf92019-02-13 15:11:42 +010088 void CallEncoder(rtc::FunctionView<void(AudioEncoder*)> modifier) override;
Niels Möllerdced9f62018-11-19 10:27:07 +010089
90 // API methods
Niels Möllerdced9f62018-11-19 10:27:07 +010091 void StartSend() override;
92 void StopSend() override;
93
94 // Codecs
Sebastian Jansson254d8692018-11-21 19:19:00 +010095 void OnBitrateAllocation(BitrateAllocationUpdate update) override;
Niels Möllerdced9f62018-11-19 10:27:07 +010096 int GetBitrate() const override;
97
98 // Network
Niels Möller8fb1a6a2019-03-05 14:29:42 +010099 void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
Niels Möllerdced9f62018-11-19 10:27:07 +0100100
101 // Muting, Volume and Level.
102 void SetInputMute(bool enable) override;
103
104 // Stats.
105 ANAStats GetANAStatistics() const override;
106
107 // Used by AudioSendStream.
108 RtpRtcp* GetRtpRtcp() const override;
109
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100110 void RegisterCngPayloadType(int payload_type, int payload_frequency) override;
111
Niels Möllerdced9f62018-11-19 10:27:07 +0100112 // DTMF.
113 bool SendTelephoneEventOutband(int event, int duration_ms) override;
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100114 void SetSendTelephoneEventPayloadType(int payload_type,
Niels Möllerdced9f62018-11-19 10:27:07 +0100115 int payload_frequency) override;
116
117 // RTP+RTCP
Niels Möllerdced9f62018-11-19 10:27:07 +0100118 void SetSendAudioLevelIndicationStatus(bool enable, int id) override;
Niels Möllerdced9f62018-11-19 10:27:07 +0100119
120 void RegisterSenderCongestionControlObjects(
121 RtpTransportControllerSendInterface* transport,
122 RtcpBandwidthObserver* bandwidth_observer) override;
123 void ResetSenderCongestionControlObjects() override;
124 void SetRTCP_CNAME(absl::string_view c_name) override;
125 std::vector<ReportBlock> GetRemoteRTCPReportBlocks() const override;
126 CallSendStatistics GetRTCPStatistics() const override;
Niels Möllerdced9f62018-11-19 10:27:07 +0100127
128 // ProcessAndEncodeAudio() posts a task on the shared encoder task queue,
129 // which in turn calls (on the queue) ProcessAndEncodeAudioOnTaskQueue() where
130 // the actual processing of the audio takes place. The processing mainly
131 // consists of encoding and preparing the result for sending by adding it to a
132 // send queue.
133 // The main reason for using a task queue here is to release the native,
134 // OS-specific, audio capture thread as soon as possible to ensure that it
135 // can go back to sleep and be prepared to deliver an new captured audio
136 // packet.
137 void ProcessAndEncodeAudio(std::unique_ptr<AudioFrame> audio_frame) override;
138
Niels Möllerdced9f62018-11-19 10:27:07 +0100139 int64_t GetRTT() const override;
140
141 // E2EE Custom Audio Frame Encryption
142 void SetFrameEncryptor(
143 rtc::scoped_refptr<FrameEncryptorInterface> frame_encryptor) override;
144
145 private:
Niels Möllerdced9f62018-11-19 10:27:07 +0100146 // From AudioPacketizationCallback in the ACM
Niels Möller87e2d782019-03-07 10:18:23 +0100147 int32_t SendData(AudioFrameType frameType,
Niels Möllerdced9f62018-11-19 10:27:07 +0100148 uint8_t payloadType,
Minyue Liff0e4db2020-01-23 13:45:50 +0100149 uint32_t rtp_timestamp,
Niels Möllerdced9f62018-11-19 10:27:07 +0100150 const uint8_t* payloadData,
Minyue Liff0e4db2020-01-23 13:45:50 +0100151 size_t payloadSize,
152 int64_t absolute_capture_timestamp_ms) override;
Niels Möllerdced9f62018-11-19 10:27:07 +0100153
Niels Möllerdced9f62018-11-19 10:27:07 +0100154 void OnUplinkPacketLossRate(float packet_loss_rate);
155 bool InputMute() const;
156
Niels Möller87e2d782019-03-07 10:18:23 +0100157 int32_t SendRtpAudio(AudioFrameType frameType,
Niels Möllerdced9f62018-11-19 10:27:07 +0100158 uint8_t payloadType,
Minyue Liff0e4db2020-01-23 13:45:50 +0100159 uint32_t rtp_timestamp,
160 rtc::ArrayView<const uint8_t> payload,
161 int64_t absolute_capture_timestamp_ms)
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100162 RTC_RUN_ON(encoder_queue_);
Niels Möllerdced9f62018-11-19 10:27:07 +0100163
Niels Möllerdced9f62018-11-19 10:27:07 +0100164 void OnReceivedRtt(int64_t rtt_ms);
165
Niels Möllerdced9f62018-11-19 10:27:07 +0100166 // Thread checkers document and lock usage of some methods on voe::Channel to
167 // specific threads we know about. The goal is to eventually split up
168 // voe::Channel into parts with single-threaded semantics, and thereby reduce
169 // the need for locks.
170 rtc::ThreadChecker worker_thread_checker_;
171 rtc::ThreadChecker module_process_thread_checker_;
172 // Methods accessed from audio and video threads are checked for sequential-
173 // only access. We don't necessarily own and control these threads, so thread
174 // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
175 // audio thread to another, but access is still sequential.
176 rtc::RaceChecker audio_thread_race_checker_;
177
Niels Möllerdced9f62018-11-19 10:27:07 +0100178 rtc::CriticalSection volume_settings_critsect_;
179
Niels Möller26e88b02018-11-19 15:08:13 +0100180 bool sending_ RTC_GUARDED_BY(&worker_thread_checker_) = false;
Niels Möllerdced9f62018-11-19 10:27:07 +0100181
182 RtcEventLog* const event_log_;
183
184 std::unique_ptr<RtpRtcp> _rtpRtcpModule;
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100185 std::unique_ptr<RTPSenderAudio> rtp_sender_audio_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100186
187 std::unique_ptr<AudioCodingModule> audio_coding_;
188 uint32_t _timeStamp RTC_GUARDED_BY(encoder_queue_);
189
Niels Möllerdced9f62018-11-19 10:27:07 +0100190 // uses
Niels Möller985a1f32018-11-19 16:08:42 +0100191 ProcessThread* const _moduleProcessThreadPtr;
Niels Möllerdced9f62018-11-19 10:27:07 +0100192 RmsLevel rms_level_ RTC_GUARDED_BY(encoder_queue_);
193 bool input_mute_ RTC_GUARDED_BY(volume_settings_critsect_);
194 bool previous_frame_muted_ RTC_GUARDED_BY(encoder_queue_);
195 // VoeRTP_RTCP
196 // TODO(henrika): can today be accessed on the main thread and on the
197 // task queue; hence potential race.
198 bool _includeAudioLevelIndication;
Anton Sukhanov626015d2019-02-04 15:16:06 -0800199
Niels Möllerdced9f62018-11-19 10:27:07 +0100200 // RtcpBandwidthObserver
Niels Möller985a1f32018-11-19 16:08:42 +0100201 const std::unique_ptr<VoERtcpObserver> rtcp_observer_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100202
Niels Möller985a1f32018-11-19 16:08:42 +0100203 PacketRouter* packet_router_ RTC_GUARDED_BY(&worker_thread_checker_) =
204 nullptr;
205 const std::unique_ptr<TransportFeedbackProxy> feedback_observer_proxy_;
Erik Språng59b86542019-06-23 18:24:46 +0200206 const std::unique_ptr<RtpPacketSenderProxy> rtp_packet_pacer_proxy_;
Niels Möller985a1f32018-11-19 16:08:42 +0100207 const std::unique_ptr<RateLimiter> retransmission_rate_limiter_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100208
209 rtc::ThreadChecker construction_thread_;
210
Niels Möllerdced9f62018-11-19 10:27:07 +0100211
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100212 bool encoder_queue_is_active_ RTC_GUARDED_BY(encoder_queue_) = false;
Niels Möllerdced9f62018-11-19 10:27:07 +0100213
Niels Möllerdced9f62018-11-19 10:27:07 +0100214 // E2EE Audio Frame Encryption
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100215 rtc::scoped_refptr<FrameEncryptorInterface> frame_encryptor_
216 RTC_GUARDED_BY(encoder_queue_);
Niels Möllerdced9f62018-11-19 10:27:07 +0100217 // E2EE Frame Encryption Options
Niels Möller985a1f32018-11-19 16:08:42 +0100218 const webrtc::CryptoOptions crypto_options_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100219
220 rtc::CriticalSection bitrate_crit_section_;
221 int configured_bitrate_bps_ RTC_GUARDED_BY(bitrate_crit_section_) = 0;
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100222
223 // Defined last to ensure that there are no running tasks when the other
224 // members are destroyed.
225 rtc::TaskQueue encoder_queue_;
Niels Möllerdced9f62018-11-19 10:27:07 +0100226};
Niels Möller530ead42018-10-04 14:28:39 +0200227
228const int kTelephoneEventAttenuationdB = 10;
229
230class TransportFeedbackProxy : public TransportFeedbackObserver {
231 public:
232 TransportFeedbackProxy() : feedback_observer_(nullptr) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200233 pacer_thread_.Detach();
234 network_thread_.Detach();
Niels Möller530ead42018-10-04 14:28:39 +0200235 }
236
237 void SetTransportFeedbackObserver(
238 TransportFeedbackObserver* feedback_observer) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200239 RTC_DCHECK(thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200240 rtc::CritScope lock(&crit_);
241 feedback_observer_ = feedback_observer;
242 }
243
244 // Implements TransportFeedbackObserver.
Erik Språng30a276b2019-04-23 12:00:11 +0200245 void OnAddPacket(const RtpPacketSendInfo& packet_info) override {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200246 RTC_DCHECK(pacer_thread_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200247 rtc::CritScope lock(&crit_);
248 if (feedback_observer_)
Erik Språng30a276b2019-04-23 12:00:11 +0200249 feedback_observer_->OnAddPacket(packet_info);
Niels Möller530ead42018-10-04 14:28:39 +0200250 }
251
252 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200253 RTC_DCHECK(network_thread_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200254 rtc::CritScope lock(&crit_);
255 if (feedback_observer_)
256 feedback_observer_->OnTransportFeedback(feedback);
257 }
258
259 private:
260 rtc::CriticalSection crit_;
261 rtc::ThreadChecker thread_checker_;
262 rtc::ThreadChecker pacer_thread_;
263 rtc::ThreadChecker network_thread_;
264 TransportFeedbackObserver* feedback_observer_ RTC_GUARDED_BY(&crit_);
265};
266
Erik Språngaa59eca2019-07-24 14:52:55 +0200267class RtpPacketSenderProxy : public RtpPacketSender {
Niels Möller530ead42018-10-04 14:28:39 +0200268 public:
Erik Språng59b86542019-06-23 18:24:46 +0200269 RtpPacketSenderProxy() : rtp_packet_pacer_(nullptr) {}
Niels Möller530ead42018-10-04 14:28:39 +0200270
Erik Språngaa59eca2019-07-24 14:52:55 +0200271 void SetPacketPacer(RtpPacketSender* rtp_packet_pacer) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200272 RTC_DCHECK(thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200273 rtc::CritScope lock(&crit_);
Erik Språng59b86542019-06-23 18:24:46 +0200274 rtp_packet_pacer_ = rtp_packet_pacer;
275 }
276
Erik Språngea55b082019-10-02 14:57:46 +0200277 void EnqueuePackets(
278 std::vector<std::unique_ptr<RtpPacketToSend>> packets) override {
Erik Språng59b86542019-06-23 18:24:46 +0200279 rtc::CritScope lock(&crit_);
Erik Språngea55b082019-10-02 14:57:46 +0200280 rtp_packet_pacer_->EnqueuePackets(std::move(packets));
Niels Möller530ead42018-10-04 14:28:39 +0200281 }
282
Niels Möller530ead42018-10-04 14:28:39 +0200283 private:
284 rtc::ThreadChecker thread_checker_;
285 rtc::CriticalSection crit_;
Erik Språngaa59eca2019-07-24 14:52:55 +0200286 RtpPacketSender* rtp_packet_pacer_ RTC_GUARDED_BY(&crit_);
Niels Möller530ead42018-10-04 14:28:39 +0200287};
288
289class VoERtcpObserver : public RtcpBandwidthObserver {
290 public:
291 explicit VoERtcpObserver(ChannelSend* owner)
292 : owner_(owner), bandwidth_observer_(nullptr) {}
Mirko Bonadeife055c12019-01-29 22:53:28 +0100293 ~VoERtcpObserver() override {}
Niels Möller530ead42018-10-04 14:28:39 +0200294
295 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
296 rtc::CritScope lock(&crit_);
297 bandwidth_observer_ = bandwidth_observer;
298 }
299
300 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
301 rtc::CritScope lock(&crit_);
302 if (bandwidth_observer_) {
303 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
304 }
305 }
306
307 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
308 int64_t rtt,
309 int64_t now_ms) override {
310 {
311 rtc::CritScope lock(&crit_);
312 if (bandwidth_observer_) {
313 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
314 now_ms);
315 }
316 }
317 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
318 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
319 // report for VoiceEngine?
320 if (report_blocks.empty())
321 return;
322
323 int fraction_lost_aggregate = 0;
324 int total_number_of_packets = 0;
325
326 // If receiving multiple report blocks, calculate the weighted average based
327 // on the number of packets a report refers to.
328 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
329 block_it != report_blocks.end(); ++block_it) {
330 // Find the previous extended high sequence number for this remote SSRC,
331 // to calculate the number of RTP packets this report refers to. Ignore if
332 // we haven't seen this SSRC before.
333 std::map<uint32_t, uint32_t>::iterator seq_num_it =
334 extended_max_sequence_number_.find(block_it->source_ssrc);
335 int number_of_packets = 0;
336 if (seq_num_it != extended_max_sequence_number_.end()) {
337 number_of_packets =
338 block_it->extended_highest_sequence_number - seq_num_it->second;
339 }
340 fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
341 total_number_of_packets += number_of_packets;
342
343 extended_max_sequence_number_[block_it->source_ssrc] =
344 block_it->extended_highest_sequence_number;
345 }
346 int weighted_fraction_lost = 0;
347 if (total_number_of_packets > 0) {
348 weighted_fraction_lost =
349 (fraction_lost_aggregate + total_number_of_packets / 2) /
350 total_number_of_packets;
351 }
352 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
353 }
354
355 private:
356 ChannelSend* owner_;
357 // Maps remote side ssrc to extended highest sequence number received.
358 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
359 rtc::CriticalSection crit_;
360 RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(crit_);
361};
362
Niels Möller87e2d782019-03-07 10:18:23 +0100363int32_t ChannelSend::SendData(AudioFrameType frameType,
Niels Möller530ead42018-10-04 14:28:39 +0200364 uint8_t payloadType,
Minyue Liff0e4db2020-01-23 13:45:50 +0100365 uint32_t rtp_timestamp,
Niels Möller530ead42018-10-04 14:28:39 +0200366 const uint8_t* payloadData,
Minyue Liff0e4db2020-01-23 13:45:50 +0100367 size_t payloadSize,
368 int64_t absolute_capture_timestamp_ms) {
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100369 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller7d76a312018-10-26 12:57:07 +0200370 rtc::ArrayView<const uint8_t> payload(payloadData, payloadSize);
Minyue Liff0e4db2020-01-23 13:45:50 +0100371 return SendRtpAudio(frameType, payloadType, rtp_timestamp, payload,
372 absolute_capture_timestamp_ms);
Niels Möller7d76a312018-10-26 12:57:07 +0200373}
374
Niels Möller87e2d782019-03-07 10:18:23 +0100375int32_t ChannelSend::SendRtpAudio(AudioFrameType frameType,
Niels Möller7d76a312018-10-26 12:57:07 +0200376 uint8_t payloadType,
Minyue Liff0e4db2020-01-23 13:45:50 +0100377 uint32_t rtp_timestamp,
378 rtc::ArrayView<const uint8_t> payload,
379 int64_t absolute_capture_timestamp_ms) {
Niels Möller530ead42018-10-04 14:28:39 +0200380 if (_includeAudioLevelIndication) {
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100381 // Store current audio level in the RTP sender.
Niels Möller530ead42018-10-04 14:28:39 +0200382 // The level will be used in combination with voice-activity state
383 // (frameType) to add an RTP header extension
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100384 rtp_sender_audio_->SetAudioLevel(rms_level_.Average());
Niels Möller530ead42018-10-04 14:28:39 +0200385 }
386
Benjamin Wright84583f62018-10-04 14:22:34 -0700387 // E2EE Custom Audio Frame Encryption (This is optional).
388 // Keep this buffer around for the lifetime of the send call.
389 rtc::Buffer encrypted_audio_payload;
Minyue Li9ab520e2019-05-28 13:27:40 +0200390 // We don't invoke encryptor if payload is empty, which means we are to send
391 // DTMF, or the encoder entered DTX.
392 // TODO(minyue): see whether DTMF packets should be encrypted or not. In
393 // current implementation, they are not.
Minyue Lif48bca72019-06-20 23:37:02 +0200394 if (!payload.empty()) {
395 if (frame_encryptor_ != nullptr) {
396 // TODO(benwright@webrtc.org) - Allocate enough to always encrypt inline.
397 // Allocate a buffer to hold the maximum possible encrypted payload.
398 size_t max_ciphertext_size = frame_encryptor_->GetMaxCiphertextByteSize(
399 cricket::MEDIA_TYPE_AUDIO, payload.size());
400 encrypted_audio_payload.SetSize(max_ciphertext_size);
Benjamin Wright84583f62018-10-04 14:22:34 -0700401
Minyue Lif48bca72019-06-20 23:37:02 +0200402 // Encrypt the audio payload into the buffer.
403 size_t bytes_written = 0;
404 int encrypt_status = frame_encryptor_->Encrypt(
405 cricket::MEDIA_TYPE_AUDIO, _rtpRtcpModule->SSRC(),
406 /*additional_data=*/nullptr, payload, encrypted_audio_payload,
407 &bytes_written);
408 if (encrypt_status != 0) {
409 RTC_DLOG(LS_ERROR)
410 << "Channel::SendData() failed encrypt audio payload: "
411 << encrypt_status;
412 return -1;
413 }
414 // Resize the buffer to the exact number of bytes actually used.
415 encrypted_audio_payload.SetSize(bytes_written);
416 // Rewrite the payloadData and size to the new encrypted payload.
417 payload = encrypted_audio_payload;
418 } else if (crypto_options_.sframe.require_frame_encryption) {
419 RTC_DLOG(LS_ERROR) << "Channel::SendData() failed sending audio payload: "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100420 "A frame encryptor is required but one is not set.";
Benjamin Wright84583f62018-10-04 14:22:34 -0700421 return -1;
422 }
Benjamin Wright84583f62018-10-04 14:22:34 -0700423 }
424
Niels Möller530ead42018-10-04 14:28:39 +0200425 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
426 // packetization.
Minyue Liff0e4db2020-01-23 13:45:50 +0100427 if (!_rtpRtcpModule->OnSendingRtpFrame(rtp_timestamp,
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100428 // Leaving the time when this frame was
429 // received from the capture device as
430 // undefined for voice for now.
431 -1, payloadType,
432 /*force_sender_report=*/false)) {
Mirko Bonadeif2c08182019-11-27 08:47:51 +0100433 return -1;
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100434 }
435
436 // RTCPSender has it's own copy of the timestamp offset, added in
437 // RTCPSender::BuildSR, hence we must not add the in the offset for the above
438 // call.
439 // TODO(nisse): Delete RTCPSender:timestamp_offset_, and see if we can confine
440 // knowledge of the offset to a single place.
Minyue Liff0e4db2020-01-23 13:45:50 +0100441
Niels Möller530ead42018-10-04 14:28:39 +0200442 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Minyue Liff0e4db2020-01-23 13:45:50 +0100443 if (!rtp_sender_audio_->SendAudio(
444 frameType, payloadType,
445 rtp_timestamp + _rtpRtcpModule->StartTimestamp(), payload.data(),
446 payload.size(), absolute_capture_timestamp_ms)) {
Niels Möller530ead42018-10-04 14:28:39 +0200447 RTC_DLOG(LS_ERROR)
448 << "ChannelSend::SendData() failed to send data to RTP/RTCP module";
449 return -1;
450 }
451
452 return 0;
453}
454
Sebastian Jansson977b3352019-03-04 17:43:34 +0100455ChannelSend::ChannelSend(Clock* clock,
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100456 TaskQueueFactory* task_queue_factory,
Niels Möller530ead42018-10-04 14:28:39 +0200457 ProcessThread* module_process_thread,
Anton Sukhanov626015d2019-02-04 15:16:06 -0800458 OverheadObserver* overhead_observer,
Niels Möllere9771992018-11-26 10:55:07 +0100459 Transport* rtp_transport,
Niels Möller530ead42018-10-04 14:28:39 +0200460 RtcpRttStats* rtcp_rtt_stats,
Benjamin Wright84583f62018-10-04 14:22:34 -0700461 RtcEventLog* rtc_event_log,
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700462 FrameEncryptorInterface* frame_encryptor,
Johannes Kron9190b822018-10-29 11:22:05 +0100463 const webrtc::CryptoOptions& crypto_options,
Jiawei Ou55718122018-11-09 13:17:39 -0800464 bool extmap_allow_mixed,
Erik Språng4c2c4122019-07-11 15:20:15 +0200465 int rtcp_report_interval_ms,
466 uint32_t ssrc)
Niels Möller530ead42018-10-04 14:28:39 +0200467 : event_log_(rtc_event_log),
468 _timeStamp(0), // This is just an offset, RTP module will add it's own
469 // random offset
Niels Möller530ead42018-10-04 14:28:39 +0200470 _moduleProcessThreadPtr(module_process_thread),
Niels Möller530ead42018-10-04 14:28:39 +0200471 input_mute_(false),
472 previous_frame_muted_(false),
473 _includeAudioLevelIndication(false),
Niels Möller530ead42018-10-04 14:28:39 +0200474 rtcp_observer_(new VoERtcpObserver(this)),
475 feedback_observer_proxy_(new TransportFeedbackProxy()),
Erik Språng59b86542019-06-23 18:24:46 +0200476 rtp_packet_pacer_proxy_(new RtpPacketSenderProxy()),
Sebastian Jansson977b3352019-03-04 17:43:34 +0100477 retransmission_rate_limiter_(
478 new RateLimiter(clock, kMaxRetransmissionWindowMs)),
Benjamin Wrightbfb444c2018-10-15 10:20:24 -0700479 frame_encryptor_(frame_encryptor),
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100480 crypto_options_(crypto_options),
481 encoder_queue_(task_queue_factory->CreateTaskQueue(
482 "AudioEncoder",
483 TaskQueueFactory::Priority::NORMAL)) {
Niels Möller530ead42018-10-04 14:28:39 +0200484 RTC_DCHECK(module_process_thread);
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200485 module_process_thread_checker_.Detach();
Niels Möllerdced9f62018-11-19 10:27:07 +0100486
Niels Möller530ead42018-10-04 14:28:39 +0200487 audio_coding_.reset(AudioCodingModule::Create(AudioCodingModule::Config()));
488
489 RtpRtcp::Configuration configuration;
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800490 configuration.overhead_observer = overhead_observer;
491 configuration.bandwidth_callback = rtcp_observer_.get();
492 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
Mirko Bonadeif2c08182019-11-27 08:47:51 +0100493 configuration.clock = (clock ? clock : Clock::GetRealTimeClock());
Niels Möller530ead42018-10-04 14:28:39 +0200494 configuration.audio = true;
Fredrik Solenberg3d2ed192018-12-18 09:18:33 +0100495 configuration.outgoing_transport = rtp_transport;
Niels Möller530ead42018-10-04 14:28:39 +0200496
Erik Språng59b86542019-06-23 18:24:46 +0200497 configuration.paced_sender = rtp_packet_pacer_proxy_.get();
Niels Möller530ead42018-10-04 14:28:39 +0200498
499 configuration.event_log = event_log_;
500 configuration.rtt_stats = rtcp_rtt_stats;
501 configuration.retransmission_rate_limiter =
502 retransmission_rate_limiter_.get();
Johannes Kron9190b822018-10-29 11:22:05 +0100503 configuration.extmap_allow_mixed = extmap_allow_mixed;
Jiawei Ou8b5d9d82018-11-15 16:44:37 -0800504 configuration.rtcp_report_interval_ms = rtcp_report_interval_ms;
Niels Möller530ead42018-10-04 14:28:39 +0200505
Erik Språng54d5d2c2019-08-20 17:22:36 +0200506 configuration.local_media_ssrc = ssrc;
Erik Språng4c2c4122019-07-11 15:20:15 +0200507
Danil Chapovalovc44f6cc2019-03-06 11:31:09 +0100508 _rtpRtcpModule = RtpRtcp::Create(configuration);
Niels Möller530ead42018-10-04 14:28:39 +0200509 _rtpRtcpModule->SetSendingMediaStatus(false);
Niels Möller530ead42018-10-04 14:28:39 +0200510
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200511 rtp_sender_audio_ = std::make_unique<RTPSenderAudio>(
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100512 configuration.clock, _rtpRtcpModule->RtpSender());
513
Niels Möller530ead42018-10-04 14:28:39 +0200514 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
515
Niels Möller530ead42018-10-04 14:28:39 +0200516 // Ensure that RTCP is enabled by default for the created channel.
Niels Möller530ead42018-10-04 14:28:39 +0200517 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
518
Fredrik Solenbergeb134842018-11-19 14:13:15 +0100519 int error = audio_coding_->RegisterTransportCallback(this);
Niels Möller530ead42018-10-04 14:28:39 +0200520 RTC_DCHECK_EQ(0, error);
521}
522
Fredrik Solenberg645a3af2018-11-16 12:51:15 +0100523ChannelSend::~ChannelSend() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200524 RTC_DCHECK(construction_thread_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200525
526 StopSend();
Niels Möller530ead42018-10-04 14:28:39 +0200527 int error = audio_coding_->RegisterTransportCallback(NULL);
528 RTC_DCHECK_EQ(0, error);
529
Niels Möller530ead42018-10-04 14:28:39 +0200530 if (_moduleProcessThreadPtr)
531 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
Niels Möller530ead42018-10-04 14:28:39 +0200532}
533
Niels Möller26815232018-11-16 09:32:40 +0100534void ChannelSend::StartSend() {
Niels Möller26e88b02018-11-19 15:08:13 +0100535 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Fredrik Solenbergeb134842018-11-19 14:13:15 +0100536 RTC_DCHECK(!sending_);
537 sending_ = true;
Niels Möller530ead42018-10-04 14:28:39 +0200538
Niels Möller530ead42018-10-04 14:28:39 +0200539 _rtpRtcpModule->SetSendingMediaStatus(true);
Niels Möller26815232018-11-16 09:32:40 +0100540 int ret = _rtpRtcpModule->SetSendingStatus(true);
541 RTC_DCHECK_EQ(0, ret);
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100542 // It is now OK to start processing on the encoder task queue.
543 encoder_queue_.PostTask([this] {
544 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller530ead42018-10-04 14:28:39 +0200545 encoder_queue_is_active_ = true;
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100546 });
Niels Möller530ead42018-10-04 14:28:39 +0200547}
548
549void ChannelSend::StopSend() {
Niels Möller26e88b02018-11-19 15:08:13 +0100550 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Fredrik Solenbergeb134842018-11-19 14:13:15 +0100551 if (!sending_) {
Niels Möller530ead42018-10-04 14:28:39 +0200552 return;
553 }
Fredrik Solenbergeb134842018-11-19 14:13:15 +0100554 sending_ = false;
Niels Möller530ead42018-10-04 14:28:39 +0200555
Niels Möllerc572ff32018-11-07 08:43:50 +0100556 rtc::Event flush;
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100557 encoder_queue_.PostTask([this, &flush]() {
558 RTC_DCHECK_RUN_ON(&encoder_queue_);
Niels Möller530ead42018-10-04 14:28:39 +0200559 encoder_queue_is_active_ = false;
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100560 flush.Set();
561 });
Niels Möller530ead42018-10-04 14:28:39 +0200562 flush.Wait(rtc::Event::kForever);
563
Niels Möller530ead42018-10-04 14:28:39 +0200564 // Reset sending SSRC and sequence number and triggers direct transmission
565 // of RTCP BYE
566 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
567 RTC_DLOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending";
568 }
569 _rtpRtcpModule->SetSendingMediaStatus(false);
570}
571
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100572void ChannelSend::SetEncoder(int payload_type,
Niels Möller530ead42018-10-04 14:28:39 +0200573 std::unique_ptr<AudioEncoder> encoder) {
Niels Möller26e88b02018-11-19 15:08:13 +0100574 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200575 RTC_DCHECK_GE(payload_type, 0);
576 RTC_DCHECK_LE(payload_type, 127);
Niels Möller530ead42018-10-04 14:28:39 +0200577
578 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
579 // as well as some other things, so we collect this info and send it along.
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100580 _rtpRtcpModule->RegisterSendPayloadFrequency(payload_type,
581 encoder->RtpTimestampRateHz());
582 rtp_sender_audio_->RegisterAudioPayload("audio", payload_type,
583 encoder->RtpTimestampRateHz(),
584 encoder->NumChannels(), 0);
Niels Möller530ead42018-10-04 14:28:39 +0200585
586 audio_coding_->SetEncoder(std::move(encoder));
Niels Möller530ead42018-10-04 14:28:39 +0200587}
588
589void ChannelSend::ModifyEncoder(
590 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
Anton Sukhanov626015d2019-02-04 15:16:06 -0800591 // This method can be called on the worker thread, module process thread
592 // or network thread. Audio coding is thread safe, so we do not need to
593 // enforce the calling thread.
Niels Möller530ead42018-10-04 14:28:39 +0200594 audio_coding_->ModifyEncoder(modifier);
595}
596
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100597void ChannelSend::CallEncoder(rtc::FunctionView<void(AudioEncoder*)> modifier) {
598 ModifyEncoder([modifier](std::unique_ptr<AudioEncoder>* encoder_ptr) {
599 if (*encoder_ptr) {
600 modifier(encoder_ptr->get());
601 } else {
602 RTC_DLOG(LS_WARNING) << "Trying to call unset encoder.";
603 }
604 });
605}
606
Sebastian Jansson254d8692018-11-21 19:19:00 +0100607void ChannelSend::OnBitrateAllocation(BitrateAllocationUpdate update) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100608 // This method can be called on the worker thread, module process thread
609 // or on a TaskQueue via VideoSendStreamImpl::OnEncoderConfigurationChanged.
610 // TODO(solenberg): Figure out a good way to check this or enforce calling
611 // rules.
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200612 // RTC_DCHECK(worker_thread_checker_.IsCurrent() ||
613 // module_process_thread_checker_.IsCurrent());
Piotr (Peter) Slatala1eebec92018-11-16 09:03:35 -0800614 rtc::CritScope lock(&bitrate_crit_section_);
Niels Möllerdced9f62018-11-19 10:27:07 +0100615
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100616 CallEncoder([&](AudioEncoder* encoder) {
617 encoder->OnReceivedUplinkAllocation(update);
Niels Möller530ead42018-10-04 14:28:39 +0200618 });
Sebastian Jansson254d8692018-11-21 19:19:00 +0100619 retransmission_rate_limiter_->SetMaxRate(update.target_bitrate.bps());
620 configured_bitrate_bps_ = update.target_bitrate.bps();
Sebastian Jansson359d60a2018-10-25 16:22:02 +0200621}
622
Niels Möllerdced9f62018-11-19 10:27:07 +0100623int ChannelSend::GetBitrate() const {
Piotr (Peter) Slatala1eebec92018-11-16 09:03:35 -0800624 rtc::CritScope lock(&bitrate_crit_section_);
Sebastian Jansson359d60a2018-10-25 16:22:02 +0200625 return configured_bitrate_bps_;
Niels Möller530ead42018-10-04 14:28:39 +0200626}
627
Niels Möller530ead42018-10-04 14:28:39 +0200628void ChannelSend::OnUplinkPacketLossRate(float packet_loss_rate) {
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100629 CallEncoder([&](AudioEncoder* encoder) {
630 encoder->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
Niels Möller530ead42018-10-04 14:28:39 +0200631 });
632}
633
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100634void ChannelSend::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
Niels Möller530ead42018-10-04 14:28:39 +0200635 // Deliver RTCP packet to RTP/RTCP module for parsing
636 _rtpRtcpModule->IncomingRtcpPacket(data, length);
637
638 int64_t rtt = GetRTT();
639 if (rtt == 0) {
640 // Waiting for valid RTT.
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100641 return;
Niels Möller530ead42018-10-04 14:28:39 +0200642 }
643
644 int64_t nack_window_ms = rtt;
645 if (nack_window_ms < kMinRetransmissionWindowMs) {
646 nack_window_ms = kMinRetransmissionWindowMs;
647 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
648 nack_window_ms = kMaxRetransmissionWindowMs;
649 }
650 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
651
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800652 OnReceivedRtt(rtt);
Niels Möller530ead42018-10-04 14:28:39 +0200653}
654
655void ChannelSend::SetInputMute(bool enable) {
Niels Möller26e88b02018-11-19 15:08:13 +0100656 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200657 rtc::CritScope cs(&volume_settings_critsect_);
658 input_mute_ = enable;
659}
660
661bool ChannelSend::InputMute() const {
662 rtc::CritScope cs(&volume_settings_critsect_);
663 return input_mute_;
664}
665
Niels Möller26815232018-11-16 09:32:40 +0100666bool ChannelSend::SendTelephoneEventOutband(int event, int duration_ms) {
Niels Möller26e88b02018-11-19 15:08:13 +0100667 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200668 RTC_DCHECK_LE(0, event);
669 RTC_DCHECK_GE(255, event);
670 RTC_DCHECK_LE(0, duration_ms);
671 RTC_DCHECK_GE(65535, duration_ms);
Fredrik Solenbergeb134842018-11-19 14:13:15 +0100672 if (!sending_) {
Niels Möller26815232018-11-16 09:32:40 +0100673 return false;
Niels Möller530ead42018-10-04 14:28:39 +0200674 }
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100675 if (rtp_sender_audio_->SendTelephoneEvent(
Niels Möller530ead42018-10-04 14:28:39 +0200676 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100677 RTC_DLOG(LS_ERROR) << "SendTelephoneEvent() failed to send event";
Niels Möller26815232018-11-16 09:32:40 +0100678 return false;
Niels Möller530ead42018-10-04 14:28:39 +0200679 }
Niels Möller26815232018-11-16 09:32:40 +0100680 return true;
Niels Möller530ead42018-10-04 14:28:39 +0200681}
682
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100683void ChannelSend::RegisterCngPayloadType(int payload_type,
684 int payload_frequency) {
685 _rtpRtcpModule->RegisterSendPayloadFrequency(payload_type, payload_frequency);
686 rtp_sender_audio_->RegisterAudioPayload("CN", payload_type, payload_frequency,
687 1, 0);
688}
689
Niels Möller8fb1a6a2019-03-05 14:29:42 +0100690void ChannelSend::SetSendTelephoneEventPayloadType(int payload_type,
Niels Möller26815232018-11-16 09:32:40 +0100691 int payload_frequency) {
Niels Möller26e88b02018-11-19 15:08:13 +0100692 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200693 RTC_DCHECK_LE(0, payload_type);
694 RTC_DCHECK_GE(127, payload_type);
Niels Mölleree5ccbc2019-03-06 16:47:29 +0100695 _rtpRtcpModule->RegisterSendPayloadFrequency(payload_type, payload_frequency);
696 rtp_sender_audio_->RegisterAudioPayload("telephone-event", payload_type,
697 payload_frequency, 0, 0);
Niels Möller530ead42018-10-04 14:28:39 +0200698}
699
Niels Möller26815232018-11-16 09:32:40 +0100700void ChannelSend::SetSendAudioLevelIndicationStatus(bool enable, int id) {
Niels Möller26e88b02018-11-19 15:08:13 +0100701 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200702 _includeAudioLevelIndication = enable;
Sebastian Jansson6298b562020-01-14 17:55:19 +0100703 if (enable) {
704 _rtpRtcpModule->RegisterRtpHeaderExtension(AudioLevel::kUri, id);
705 } else {
706 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(AudioLevel::kUri);
707 }
Niels Möller530ead42018-10-04 14:28:39 +0200708}
709
710void ChannelSend::RegisterSenderCongestionControlObjects(
711 RtpTransportControllerSendInterface* transport,
712 RtcpBandwidthObserver* bandwidth_observer) {
Niels Möller26e88b02018-11-19 15:08:13 +0100713 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Erik Språngaa59eca2019-07-24 14:52:55 +0200714 RtpPacketSender* rtp_packet_pacer = transport->packet_sender();
Niels Möller530ead42018-10-04 14:28:39 +0200715 TransportFeedbackObserver* transport_feedback_observer =
716 transport->transport_feedback_observer();
717 PacketRouter* packet_router = transport->packet_router();
718
Erik Språng59b86542019-06-23 18:24:46 +0200719 RTC_DCHECK(rtp_packet_pacer);
Niels Möller530ead42018-10-04 14:28:39 +0200720 RTC_DCHECK(transport_feedback_observer);
721 RTC_DCHECK(packet_router);
722 RTC_DCHECK(!packet_router_);
723 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
724 feedback_observer_proxy_->SetTransportFeedbackObserver(
725 transport_feedback_observer);
Erik Språng59b86542019-06-23 18:24:46 +0200726 rtp_packet_pacer_proxy_->SetPacketPacer(rtp_packet_pacer);
Niels Möller530ead42018-10-04 14:28:39 +0200727 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
728 constexpr bool remb_candidate = false;
729 packet_router->AddSendRtpModule(_rtpRtcpModule.get(), remb_candidate);
730 packet_router_ = packet_router;
731}
732
733void ChannelSend::ResetSenderCongestionControlObjects() {
Niels Möller26e88b02018-11-19 15:08:13 +0100734 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200735 RTC_DCHECK(packet_router_);
736 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
737 rtcp_observer_->SetBandwidthObserver(nullptr);
738 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
Niels Möller530ead42018-10-04 14:28:39 +0200739 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
740 packet_router_ = nullptr;
Erik Språng59b86542019-06-23 18:24:46 +0200741 rtp_packet_pacer_proxy_->SetPacketPacer(nullptr);
Niels Möller530ead42018-10-04 14:28:39 +0200742}
743
Niels Möller26815232018-11-16 09:32:40 +0100744void ChannelSend::SetRTCP_CNAME(absl::string_view c_name) {
Niels Möller26e88b02018-11-19 15:08:13 +0100745 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller26815232018-11-16 09:32:40 +0100746 // Note: SetCNAME() accepts a c string of length at most 255.
747 const std::string c_name_limited(c_name.substr(0, 255));
748 int ret = _rtpRtcpModule->SetCNAME(c_name_limited.c_str()) != 0;
749 RTC_DCHECK_EQ(0, ret) << "SetRTCP_CNAME() failed to set RTCP CNAME";
Niels Möller530ead42018-10-04 14:28:39 +0200750}
751
Niels Möller26815232018-11-16 09:32:40 +0100752std::vector<ReportBlock> ChannelSend::GetRemoteRTCPReportBlocks() const {
Niels Möller26e88b02018-11-19 15:08:13 +0100753 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200754 // Get the report blocks from the latest received RTCP Sender or Receiver
755 // Report. Each element in the vector contains the sender's SSRC and a
756 // report block according to RFC 3550.
757 std::vector<RTCPReportBlock> rtcp_report_blocks;
Niels Möller530ead42018-10-04 14:28:39 +0200758
Niels Möller26815232018-11-16 09:32:40 +0100759 int ret = _rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks);
760 RTC_DCHECK_EQ(0, ret);
761
762 std::vector<ReportBlock> report_blocks;
Niels Möller530ead42018-10-04 14:28:39 +0200763
764 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
765 for (; it != rtcp_report_blocks.end(); ++it) {
766 ReportBlock report_block;
767 report_block.sender_SSRC = it->sender_ssrc;
768 report_block.source_SSRC = it->source_ssrc;
769 report_block.fraction_lost = it->fraction_lost;
770 report_block.cumulative_num_packets_lost = it->packets_lost;
771 report_block.extended_highest_sequence_number =
772 it->extended_highest_sequence_number;
773 report_block.interarrival_jitter = it->jitter;
774 report_block.last_SR_timestamp = it->last_sender_report_timestamp;
775 report_block.delay_since_last_SR = it->delay_since_last_sender_report;
Niels Möller26815232018-11-16 09:32:40 +0100776 report_blocks.push_back(report_block);
Niels Möller530ead42018-10-04 14:28:39 +0200777 }
Niels Möller26815232018-11-16 09:32:40 +0100778 return report_blocks;
Niels Möller530ead42018-10-04 14:28:39 +0200779}
780
Niels Möller26815232018-11-16 09:32:40 +0100781CallSendStatistics ChannelSend::GetRTCPStatistics() const {
Niels Möller26e88b02018-11-19 15:08:13 +0100782 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller26815232018-11-16 09:32:40 +0100783 CallSendStatistics stats = {0};
Niels Möller530ead42018-10-04 14:28:39 +0200784 stats.rttMs = GetRTT();
785
Henrik Boströmcf96e0f2019-04-17 13:51:53 +0200786 StreamDataCounters rtp_stats;
787 StreamDataCounters rtx_stats;
788 _rtpRtcpModule->GetSendStreamDataCounters(&rtp_stats, &rtx_stats);
Niels Möllerac0a4cb2019-10-09 15:01:33 +0200789 stats.payload_bytes_sent =
790 rtp_stats.transmitted.payload_bytes + rtx_stats.transmitted.payload_bytes;
791 stats.header_and_padding_bytes_sent =
792 rtp_stats.transmitted.padding_bytes + rtp_stats.transmitted.header_bytes +
793 rtx_stats.transmitted.padding_bytes + rtx_stats.transmitted.header_bytes;
794
Henrik Boströmcf96e0f2019-04-17 13:51:53 +0200795 // TODO(https://crbug.com/webrtc/10555): RTX retransmissions should show up in
796 // separate outbound-rtp stream objects.
797 stats.retransmitted_bytes_sent = rtp_stats.retransmitted.payload_bytes;
798 stats.packetsSent =
799 rtp_stats.transmitted.packets + rtx_stats.transmitted.packets;
800 stats.retransmitted_packets_sent = rtp_stats.retransmitted.packets;
Henrik Boström6e436d12019-05-27 12:19:33 +0200801 stats.report_block_datas = _rtpRtcpModule->GetLatestReportBlockData();
Niels Möller530ead42018-10-04 14:28:39 +0200802
Niels Möller26815232018-11-16 09:32:40 +0100803 return stats;
Niels Möller530ead42018-10-04 14:28:39 +0200804}
805
Niels Möller530ead42018-10-04 14:28:39 +0200806void ChannelSend::ProcessAndEncodeAudio(
807 std::unique_ptr<AudioFrame> audio_frame) {
Niels Möllerdced9f62018-11-19 10:27:07 +0100808 RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
Sebastian Janssonee5ec9a2019-09-17 20:34:03 +0200809 RTC_DCHECK_GT(audio_frame->samples_per_channel_, 0);
810 RTC_DCHECK_LE(audio_frame->num_channels_, 8);
811
Niels Möller530ead42018-10-04 14:28:39 +0200812 // Profile time between when the audio frame is added to the task queue and
813 // when the task is actually executed.
814 audio_frame->UpdateProfileTimeStamp();
Sebastian Janssonee5ec9a2019-09-17 20:34:03 +0200815 encoder_queue_.PostTask(
816 [this, audio_frame = std::move(audio_frame)]() mutable {
817 RTC_DCHECK_RUN_ON(&encoder_queue_);
818 if (!encoder_queue_is_active_) {
819 return;
820 }
821 // Measure time between when the audio frame is added to the task queue
822 // and when the task is actually executed. Goal is to keep track of
823 // unwanted extra latency added by the task queue.
824 RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
825 audio_frame->ElapsedProfileTimeMs());
Niels Möller530ead42018-10-04 14:28:39 +0200826
Sebastian Janssonee5ec9a2019-09-17 20:34:03 +0200827 bool is_muted = InputMute();
828 AudioFrameOperations::Mute(audio_frame.get(), previous_frame_muted_,
829 is_muted);
Niels Möller530ead42018-10-04 14:28:39 +0200830
Sebastian Janssonee5ec9a2019-09-17 20:34:03 +0200831 if (_includeAudioLevelIndication) {
832 size_t length =
833 audio_frame->samples_per_channel_ * audio_frame->num_channels_;
834 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
835 if (is_muted && previous_frame_muted_) {
836 rms_level_.AnalyzeMuted(length);
837 } else {
838 rms_level_.Analyze(
839 rtc::ArrayView<const int16_t>(audio_frame->data(), length));
840 }
841 }
842 previous_frame_muted_ = is_muted;
Niels Möller530ead42018-10-04 14:28:39 +0200843
Sebastian Janssonee5ec9a2019-09-17 20:34:03 +0200844 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
Niels Möller530ead42018-10-04 14:28:39 +0200845
Sebastian Janssonee5ec9a2019-09-17 20:34:03 +0200846 // The ACM resamples internally.
847 audio_frame->timestamp_ = _timeStamp;
848 // This call will trigger AudioPacketizationCallback::SendData if
849 // encoding is done and payload is ready for packetization and
850 // transmission. Otherwise, it will return without invoking the
851 // callback.
852 if (audio_coding_->Add10MsData(*audio_frame) < 0) {
853 RTC_DLOG(LS_ERROR) << "ACM::Add10MsData() failed.";
854 return;
855 }
Niels Möller530ead42018-10-04 14:28:39 +0200856
Sebastian Janssonee5ec9a2019-09-17 20:34:03 +0200857 _timeStamp += static_cast<uint32_t>(audio_frame->samples_per_channel_);
858 });
Niels Möller530ead42018-10-04 14:28:39 +0200859}
860
Niels Möller530ead42018-10-04 14:28:39 +0200861ANAStats ChannelSend::GetANAStatistics() const {
Niels Möller26e88b02018-11-19 15:08:13 +0100862 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Niels Möller530ead42018-10-04 14:28:39 +0200863 return audio_coding_->GetANAStats();
864}
865
866RtpRtcp* ChannelSend::GetRtpRtcp() const {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200867 RTC_DCHECK(module_process_thread_checker_.IsCurrent());
Niels Möller530ead42018-10-04 14:28:39 +0200868 return _rtpRtcpModule.get();
869}
870
Niels Möller530ead42018-10-04 14:28:39 +0200871int64_t ChannelSend::GetRTT() const {
Niels Möller530ead42018-10-04 14:28:39 +0200872 std::vector<RTCPReportBlock> report_blocks;
873 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
874
875 if (report_blocks.empty()) {
876 return 0;
877 }
878
879 int64_t rtt = 0;
880 int64_t avg_rtt = 0;
881 int64_t max_rtt = 0;
882 int64_t min_rtt = 0;
883 // We don't know in advance the remote ssrc used by the other end's receiver
884 // reports, so use the SSRC of the first report block for calculating the RTT.
885 if (_rtpRtcpModule->RTT(report_blocks[0].sender_ssrc, &rtt, &avg_rtt,
886 &min_rtt, &max_rtt) != 0) {
887 return 0;
888 }
889 return rtt;
890}
891
Benjamin Wright78410ad2018-10-25 09:52:57 -0700892void ChannelSend::SetFrameEncryptor(
893 rtc::scoped_refptr<FrameEncryptorInterface> frame_encryptor) {
Niels Möller26e88b02018-11-19 15:08:13 +0100894 RTC_DCHECK_RUN_ON(&worker_thread_checker_);
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100895 encoder_queue_.PostTask([this, frame_encryptor]() mutable {
896 RTC_DCHECK_RUN_ON(&encoder_queue_);
Sebastian Jansson7949f212019-03-05 13:41:48 +0000897 frame_encryptor_ = std::move(frame_encryptor);
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100898 });
Benjamin Wright84583f62018-10-04 14:22:34 -0700899}
900
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800901void ChannelSend::OnReceivedRtt(int64_t rtt_ms) {
902 // Invoke audio encoders OnReceivedRtt().
Sebastian Jansson14a7cf92019-02-13 15:11:42 +0100903 CallEncoder(
904 [rtt_ms](AudioEncoder* encoder) { encoder->OnReceivedRtt(rtt_ms); });
Piotr (Peter) Slatala179a3922018-11-16 09:57:58 -0800905}
906
Niels Möllerdced9f62018-11-19 10:27:07 +0100907} // namespace
908
909std::unique_ptr<ChannelSendInterface> CreateChannelSend(
Sebastian Jansson977b3352019-03-04 17:43:34 +0100910 Clock* clock,
Sebastian Jansson44dd9f22019-03-08 14:50:30 +0100911 TaskQueueFactory* task_queue_factory,
Niels Möllerdced9f62018-11-19 10:27:07 +0100912 ProcessThread* module_process_thread,
Anton Sukhanov626015d2019-02-04 15:16:06 -0800913 OverheadObserver* overhead_observer,
Niels Möllere9771992018-11-26 10:55:07 +0100914 Transport* rtp_transport,
Niels Möllerdced9f62018-11-19 10:27:07 +0100915 RtcpRttStats* rtcp_rtt_stats,
916 RtcEventLog* rtc_event_log,
917 FrameEncryptorInterface* frame_encryptor,
918 const webrtc::CryptoOptions& crypto_options,
919 bool extmap_allow_mixed,
Erik Språng4c2c4122019-07-11 15:20:15 +0200920 int rtcp_report_interval_ms,
921 uint32_t ssrc) {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200922 return std::make_unique<ChannelSend>(
Bjorn A Mellem7a9a0922019-11-26 09:19:40 -0800923 clock, task_queue_factory, module_process_thread, overhead_observer,
924 rtp_transport, rtcp_rtt_stats, rtc_event_log, frame_encryptor,
925 crypto_options, extmap_allow_mixed, rtcp_report_interval_ms, ssrc);
Niels Möllerdced9f62018-11-19 10:27:07 +0100926}
927
Niels Möller530ead42018-10-04 14:28:39 +0200928} // namespace voe
929} // namespace webrtc