• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
20 #include "api/array_view.h"
21 #include "api/call/transport.h"
22 #include "api/crypto/frame_encryptor_interface.h"
23 #include "api/rtc_event_log/rtc_event_log.h"
24 #include "audio/channel_send_frame_transformer_delegate.h"
25 #include "audio/utility/audio_frame_operations.h"
26 #include "call/rtp_transport_controller_send_interface.h"
27 #include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
28 #include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
29 #include "modules/audio_coding/include/audio_coding_module.h"
30 #include "modules/audio_processing/rms_level.h"
31 #include "modules/pacing/packet_router.h"
32 #include "modules/rtp_rtcp/source/rtp_rtcp_impl2.h"
33 #include "modules/utility/include/process_thread.h"
34 #include "rtc_base/checks.h"
35 #include "rtc_base/event.h"
36 #include "rtc_base/format_macros.h"
37 #include "rtc_base/location.h"
38 #include "rtc_base/logging.h"
39 #include "rtc_base/numerics/safe_conversions.h"
40 #include "rtc_base/race_checker.h"
41 #include "rtc_base/rate_limiter.h"
42 #include "rtc_base/synchronization/mutex.h"
43 #include "rtc_base/task_queue.h"
44 #include "rtc_base/thread_checker.h"
45 #include "rtc_base/time_utils.h"
46 #include "system_wrappers/include/clock.h"
47 #include "system_wrappers/include/field_trial.h"
48 #include "system_wrappers/include/metrics.h"
49 
50 namespace webrtc {
51 namespace voe {
52 
53 namespace {
54 
55 constexpr int64_t kMaxRetransmissionWindowMs = 1000;
56 constexpr int64_t kMinRetransmissionWindowMs = 30;
57 
58 class RtpPacketSenderProxy;
59 class TransportSequenceNumberProxy;
60 class VoERtcpObserver;
61 
62 class ChannelSend : public ChannelSendInterface,
63                     public AudioPacketizationCallback {  // receive encoded
64                                                          // packets from the ACM
65  public:
66   // TODO(nisse): Make OnUplinkPacketLossRate public, and delete friend
67   // declaration.
68   friend class VoERtcpObserver;
69 
70   ChannelSend(Clock* clock,
71               TaskQueueFactory* task_queue_factory,
72               ProcessThread* module_process_thread,
73               Transport* rtp_transport,
74               RtcpRttStats* rtcp_rtt_stats,
75               RtcEventLog* rtc_event_log,
76               FrameEncryptorInterface* frame_encryptor,
77               const webrtc::CryptoOptions& crypto_options,
78               bool extmap_allow_mixed,
79               int rtcp_report_interval_ms,
80               uint32_t ssrc,
81               rtc::scoped_refptr<FrameTransformerInterface> frame_transformer,
82               TransportFeedbackObserver* feedback_observer);
83 
84   ~ChannelSend() override;
85 
86   // Send using this encoder, with this payload type.
87   void SetEncoder(int payload_type,
88                   std::unique_ptr<AudioEncoder> encoder) override;
89   void ModifyEncoder(rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)>
90                          modifier) override;
91   void CallEncoder(rtc::FunctionView<void(AudioEncoder*)> modifier) override;
92 
93   // API methods
94   void StartSend() override;
95   void StopSend() override;
96 
97   // Codecs
98   void OnBitrateAllocation(BitrateAllocationUpdate update) override;
99   int GetBitrate() const override;
100 
101   // Network
102   void ReceivedRTCPPacket(const uint8_t* data, size_t length) override;
103 
104   // Muting, Volume and Level.
105   void SetInputMute(bool enable) override;
106 
107   // Stats.
108   ANAStats GetANAStatistics() const override;
109 
110   // Used by AudioSendStream.
111   RtpRtcpInterface* GetRtpRtcp() const override;
112 
113   void RegisterCngPayloadType(int payload_type, int payload_frequency) override;
114 
115   // DTMF.
116   bool SendTelephoneEventOutband(int event, int duration_ms) override;
117   void SetSendTelephoneEventPayloadType(int payload_type,
118                                         int payload_frequency) override;
119 
120   // RTP+RTCP
121   void SetSendAudioLevelIndicationStatus(bool enable, int id) override;
122 
123   void RegisterSenderCongestionControlObjects(
124       RtpTransportControllerSendInterface* transport,
125       RtcpBandwidthObserver* bandwidth_observer) override;
126   void ResetSenderCongestionControlObjects() override;
127   void SetRTCP_CNAME(absl::string_view c_name) override;
128   std::vector<ReportBlock> GetRemoteRTCPReportBlocks() const override;
129   CallSendStatistics GetRTCPStatistics() const override;
130 
131   // ProcessAndEncodeAudio() posts a task on the shared encoder task queue,
132   // which in turn calls (on the queue) ProcessAndEncodeAudioOnTaskQueue() where
133   // the actual processing of the audio takes place. The processing mainly
134   // consists of encoding and preparing the result for sending by adding it to a
135   // send queue.
136   // The main reason for using a task queue here is to release the native,
137   // OS-specific, audio capture thread as soon as possible to ensure that it
138   // can go back to sleep and be prepared to deliver an new captured audio
139   // packet.
140   void ProcessAndEncodeAudio(std::unique_ptr<AudioFrame> audio_frame) override;
141 
142   int64_t GetRTT() const override;
143 
144   // E2EE Custom Audio Frame Encryption
145   void SetFrameEncryptor(
146       rtc::scoped_refptr<FrameEncryptorInterface> frame_encryptor) override;
147 
148   // Sets a frame transformer between encoder and packetizer, to transform
149   // encoded frames before sending them out the network.
150   void SetEncoderToPacketizerFrameTransformer(
151       rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)
152       override;
153 
154  private:
155   // From AudioPacketizationCallback in the ACM
156   int32_t SendData(AudioFrameType frameType,
157                    uint8_t payloadType,
158                    uint32_t rtp_timestamp,
159                    const uint8_t* payloadData,
160                    size_t payloadSize,
161                    int64_t absolute_capture_timestamp_ms) override;
162 
163   void OnUplinkPacketLossRate(float packet_loss_rate);
164   bool InputMute() const;
165 
166   int32_t SendRtpAudio(AudioFrameType frameType,
167                        uint8_t payloadType,
168                        uint32_t rtp_timestamp,
169                        rtc::ArrayView<const uint8_t> payload,
170                        int64_t absolute_capture_timestamp_ms)
171       RTC_RUN_ON(encoder_queue_);
172 
173   void OnReceivedRtt(int64_t rtt_ms);
174 
175   void InitFrameTransformerDelegate(
176       rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer);
177 
178   // Thread checkers document and lock usage of some methods on voe::Channel to
179   // specific threads we know about. The goal is to eventually split up
180   // voe::Channel into parts with single-threaded semantics, and thereby reduce
181   // the need for locks.
182   rtc::ThreadChecker worker_thread_checker_;
183   rtc::ThreadChecker module_process_thread_checker_;
184   // Methods accessed from audio and video threads are checked for sequential-
185   // only access. We don't necessarily own and control these threads, so thread
186   // checkers cannot be used. E.g. Chromium may transfer "ownership" from one
187   // audio thread to another, but access is still sequential.
188   rtc::RaceChecker audio_thread_race_checker_;
189 
190   mutable Mutex volume_settings_mutex_;
191 
192   bool sending_ RTC_GUARDED_BY(&worker_thread_checker_) = false;
193 
194   RtcEventLog* const event_log_;
195 
196   std::unique_ptr<ModuleRtpRtcpImpl2> rtp_rtcp_;
197   std::unique_ptr<RTPSenderAudio> rtp_sender_audio_;
198 
199   std::unique_ptr<AudioCodingModule> audio_coding_;
200   uint32_t _timeStamp RTC_GUARDED_BY(encoder_queue_);
201 
202   // uses
203   ProcessThread* const _moduleProcessThreadPtr;
204   RmsLevel rms_level_ RTC_GUARDED_BY(encoder_queue_);
205   bool input_mute_ RTC_GUARDED_BY(volume_settings_mutex_);
206   bool previous_frame_muted_ RTC_GUARDED_BY(encoder_queue_);
207   // VoeRTP_RTCP
208   // TODO(henrika): can today be accessed on the main thread and on the
209   // task queue; hence potential race.
210   bool _includeAudioLevelIndication;
211 
212   // RtcpBandwidthObserver
213   const std::unique_ptr<VoERtcpObserver> rtcp_observer_;
214 
215   PacketRouter* packet_router_ RTC_GUARDED_BY(&worker_thread_checker_) =
216       nullptr;
217   TransportFeedbackObserver* const feedback_observer_;
218   const std::unique_ptr<RtpPacketSenderProxy> rtp_packet_pacer_proxy_;
219   const std::unique_ptr<RateLimiter> retransmission_rate_limiter_;
220 
221   rtc::ThreadChecker construction_thread_;
222 
223 
224   bool encoder_queue_is_active_ RTC_GUARDED_BY(encoder_queue_) = false;
225 
226   // E2EE Audio Frame Encryption
227   rtc::scoped_refptr<FrameEncryptorInterface> frame_encryptor_
228       RTC_GUARDED_BY(encoder_queue_);
229   // E2EE Frame Encryption Options
230   const webrtc::CryptoOptions crypto_options_;
231 
232   // Delegates calls to a frame transformer to transform audio, and
233   // receives callbacks with the transformed frames; delegates calls to
234   // ChannelSend::SendRtpAudio to send the transformed audio.
235   rtc::scoped_refptr<ChannelSendFrameTransformerDelegate>
236       frame_transformer_delegate_ RTC_GUARDED_BY(encoder_queue_);
237 
238   mutable Mutex bitrate_mutex_;
239   int configured_bitrate_bps_ RTC_GUARDED_BY(bitrate_mutex_) = 0;
240 
241   // Defined last to ensure that there are no running tasks when the other
242   // members are destroyed.
243   rtc::TaskQueue encoder_queue_;
244 };
245 
246 const int kTelephoneEventAttenuationdB = 10;
247 
248 class RtpPacketSenderProxy : public RtpPacketSender {
249  public:
RtpPacketSenderProxy()250   RtpPacketSenderProxy() : rtp_packet_pacer_(nullptr) {}
251 
SetPacketPacer(RtpPacketSender * rtp_packet_pacer)252   void SetPacketPacer(RtpPacketSender* rtp_packet_pacer) {
253     RTC_DCHECK(thread_checker_.IsCurrent());
254     MutexLock lock(&mutex_);
255     rtp_packet_pacer_ = rtp_packet_pacer;
256   }
257 
EnqueuePackets(std::vector<std::unique_ptr<RtpPacketToSend>> packets)258   void EnqueuePackets(
259       std::vector<std::unique_ptr<RtpPacketToSend>> packets) override {
260     MutexLock lock(&mutex_);
261     rtp_packet_pacer_->EnqueuePackets(std::move(packets));
262   }
263 
264  private:
265   rtc::ThreadChecker thread_checker_;
266   Mutex mutex_;
267   RtpPacketSender* rtp_packet_pacer_ RTC_GUARDED_BY(&mutex_);
268 };
269 
270 class VoERtcpObserver : public RtcpBandwidthObserver {
271  public:
VoERtcpObserver(ChannelSend * owner)272   explicit VoERtcpObserver(ChannelSend* owner)
273       : owner_(owner), bandwidth_observer_(nullptr) {}
~VoERtcpObserver()274   ~VoERtcpObserver() override {}
275 
SetBandwidthObserver(RtcpBandwidthObserver * bandwidth_observer)276   void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
277     MutexLock lock(&mutex_);
278     bandwidth_observer_ = bandwidth_observer;
279   }
280 
OnReceivedEstimatedBitrate(uint32_t bitrate)281   void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
282     MutexLock lock(&mutex_);
283     if (bandwidth_observer_) {
284       bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
285     }
286   }
287 
OnReceivedRtcpReceiverReport(const ReportBlockList & report_blocks,int64_t rtt,int64_t now_ms)288   void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
289                                     int64_t rtt,
290                                     int64_t now_ms) override {
291     {
292       MutexLock lock(&mutex_);
293       if (bandwidth_observer_) {
294         bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
295                                                           now_ms);
296       }
297     }
298     // TODO(mflodman): Do we need to aggregate reports here or can we jut send
299     // what we get? I.e. do we ever get multiple reports bundled into one RTCP
300     // report for VoiceEngine?
301     if (report_blocks.empty())
302       return;
303 
304     int fraction_lost_aggregate = 0;
305     int total_number_of_packets = 0;
306 
307     // If receiving multiple report blocks, calculate the weighted average based
308     // on the number of packets a report refers to.
309     for (ReportBlockList::const_iterator block_it = report_blocks.begin();
310          block_it != report_blocks.end(); ++block_it) {
311       // Find the previous extended high sequence number for this remote SSRC,
312       // to calculate the number of RTP packets this report refers to. Ignore if
313       // we haven't seen this SSRC before.
314       std::map<uint32_t, uint32_t>::iterator seq_num_it =
315           extended_max_sequence_number_.find(block_it->source_ssrc);
316       int number_of_packets = 0;
317       if (seq_num_it != extended_max_sequence_number_.end()) {
318         number_of_packets =
319             block_it->extended_highest_sequence_number - seq_num_it->second;
320       }
321       fraction_lost_aggregate += number_of_packets * block_it->fraction_lost;
322       total_number_of_packets += number_of_packets;
323 
324       extended_max_sequence_number_[block_it->source_ssrc] =
325           block_it->extended_highest_sequence_number;
326     }
327     int weighted_fraction_lost = 0;
328     if (total_number_of_packets > 0) {
329       weighted_fraction_lost =
330           (fraction_lost_aggregate + total_number_of_packets / 2) /
331           total_number_of_packets;
332     }
333     owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
334   }
335 
336  private:
337   ChannelSend* owner_;
338   // Maps remote side ssrc to extended highest sequence number received.
339   std::map<uint32_t, uint32_t> extended_max_sequence_number_;
340   Mutex mutex_;
341   RtcpBandwidthObserver* bandwidth_observer_ RTC_GUARDED_BY(mutex_);
342 };
343 
SendData(AudioFrameType frameType,uint8_t payloadType,uint32_t rtp_timestamp,const uint8_t * payloadData,size_t payloadSize,int64_t absolute_capture_timestamp_ms)344 int32_t ChannelSend::SendData(AudioFrameType frameType,
345                               uint8_t payloadType,
346                               uint32_t rtp_timestamp,
347                               const uint8_t* payloadData,
348                               size_t payloadSize,
349                               int64_t absolute_capture_timestamp_ms) {
350   RTC_DCHECK_RUN_ON(&encoder_queue_);
351   rtc::ArrayView<const uint8_t> payload(payloadData, payloadSize);
352   if (frame_transformer_delegate_) {
353     // Asynchronously transform the payload before sending it. After the payload
354     // is transformed, the delegate will call SendRtpAudio to send it.
355     frame_transformer_delegate_->Transform(
356         frameType, payloadType, rtp_timestamp, rtp_rtcp_->StartTimestamp(),
357         payloadData, payloadSize, absolute_capture_timestamp_ms,
358         rtp_rtcp_->SSRC());
359     return 0;
360   }
361   return SendRtpAudio(frameType, payloadType, rtp_timestamp, payload,
362                       absolute_capture_timestamp_ms);
363 }
364 
SendRtpAudio(AudioFrameType frameType,uint8_t payloadType,uint32_t rtp_timestamp,rtc::ArrayView<const uint8_t> payload,int64_t absolute_capture_timestamp_ms)365 int32_t ChannelSend::SendRtpAudio(AudioFrameType frameType,
366                                   uint8_t payloadType,
367                                   uint32_t rtp_timestamp,
368                                   rtc::ArrayView<const uint8_t> payload,
369                                   int64_t absolute_capture_timestamp_ms) {
370   if (_includeAudioLevelIndication) {
371     // Store current audio level in the RTP sender.
372     // The level will be used in combination with voice-activity state
373     // (frameType) to add an RTP header extension
374     rtp_sender_audio_->SetAudioLevel(rms_level_.Average());
375   }
376 
377   // E2EE Custom Audio Frame Encryption (This is optional).
378   // Keep this buffer around for the lifetime of the send call.
379   rtc::Buffer encrypted_audio_payload;
380   // We don't invoke encryptor if payload is empty, which means we are to send
381   // DTMF, or the encoder entered DTX.
382   // TODO(minyue): see whether DTMF packets should be encrypted or not. In
383   // current implementation, they are not.
384   if (!payload.empty()) {
385     if (frame_encryptor_ != nullptr) {
386       // TODO(benwright@webrtc.org) - Allocate enough to always encrypt inline.
387       // Allocate a buffer to hold the maximum possible encrypted payload.
388       size_t max_ciphertext_size = frame_encryptor_->GetMaxCiphertextByteSize(
389           cricket::MEDIA_TYPE_AUDIO, payload.size());
390       encrypted_audio_payload.SetSize(max_ciphertext_size);
391 
392       // Encrypt the audio payload into the buffer.
393       size_t bytes_written = 0;
394       int encrypt_status = frame_encryptor_->Encrypt(
395           cricket::MEDIA_TYPE_AUDIO, rtp_rtcp_->SSRC(),
396           /*additional_data=*/nullptr, payload, encrypted_audio_payload,
397           &bytes_written);
398       if (encrypt_status != 0) {
399         RTC_DLOG(LS_ERROR)
400             << "Channel::SendData() failed encrypt audio payload: "
401             << encrypt_status;
402         return -1;
403       }
404       // Resize the buffer to the exact number of bytes actually used.
405       encrypted_audio_payload.SetSize(bytes_written);
406       // Rewrite the payloadData and size to the new encrypted payload.
407       payload = encrypted_audio_payload;
408     } else if (crypto_options_.sframe.require_frame_encryption) {
409       RTC_DLOG(LS_ERROR) << "Channel::SendData() failed sending audio payload: "
410                             "A frame encryptor is required but one is not set.";
411       return -1;
412     }
413   }
414 
415   // Push data from ACM to RTP/RTCP-module to deliver audio frame for
416   // packetization.
417   if (!rtp_rtcp_->OnSendingRtpFrame(rtp_timestamp,
418                                     // Leaving the time when this frame was
419                                     // received from the capture device as
420                                     // undefined for voice for now.
421                                     -1, payloadType,
422                                     /*force_sender_report=*/false)) {
423     return -1;
424   }
425 
426   // RTCPSender has it's own copy of the timestamp offset, added in
427   // RTCPSender::BuildSR, hence we must not add the in the offset for the above
428   // call.
429   // TODO(nisse): Delete RTCPSender:timestamp_offset_, and see if we can confine
430   // knowledge of the offset to a single place.
431 
432   // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
433   if (!rtp_sender_audio_->SendAudio(
434           frameType, payloadType, rtp_timestamp + rtp_rtcp_->StartTimestamp(),
435           payload.data(), payload.size(), absolute_capture_timestamp_ms)) {
436     RTC_DLOG(LS_ERROR)
437         << "ChannelSend::SendData() failed to send data to RTP/RTCP module";
438     return -1;
439   }
440 
441   return 0;
442 }
443 
ChannelSend(Clock * clock,TaskQueueFactory * task_queue_factory,ProcessThread * module_process_thread,Transport * rtp_transport,RtcpRttStats * rtcp_rtt_stats,RtcEventLog * rtc_event_log,FrameEncryptorInterface * frame_encryptor,const webrtc::CryptoOptions & crypto_options,bool extmap_allow_mixed,int rtcp_report_interval_ms,uint32_t ssrc,rtc::scoped_refptr<FrameTransformerInterface> frame_transformer,TransportFeedbackObserver * feedback_observer)444 ChannelSend::ChannelSend(
445     Clock* clock,
446     TaskQueueFactory* task_queue_factory,
447     ProcessThread* module_process_thread,
448     Transport* rtp_transport,
449     RtcpRttStats* rtcp_rtt_stats,
450     RtcEventLog* rtc_event_log,
451     FrameEncryptorInterface* frame_encryptor,
452     const webrtc::CryptoOptions& crypto_options,
453     bool extmap_allow_mixed,
454     int rtcp_report_interval_ms,
455     uint32_t ssrc,
456     rtc::scoped_refptr<FrameTransformerInterface> frame_transformer,
457     TransportFeedbackObserver* feedback_observer)
458     : event_log_(rtc_event_log),
459       _timeStamp(0),  // This is just an offset, RTP module will add it's own
460                       // random offset
461       _moduleProcessThreadPtr(module_process_thread),
462       input_mute_(false),
463       previous_frame_muted_(false),
464       _includeAudioLevelIndication(false),
465       rtcp_observer_(new VoERtcpObserver(this)),
466       feedback_observer_(feedback_observer),
467       rtp_packet_pacer_proxy_(new RtpPacketSenderProxy()),
468       retransmission_rate_limiter_(
469           new RateLimiter(clock, kMaxRetransmissionWindowMs)),
470       frame_encryptor_(frame_encryptor),
471       crypto_options_(crypto_options),
472       encoder_queue_(task_queue_factory->CreateTaskQueue(
473           "AudioEncoder",
474           TaskQueueFactory::Priority::NORMAL)) {
475   RTC_DCHECK(module_process_thread);
476   module_process_thread_checker_.Detach();
477 
478   audio_coding_.reset(AudioCodingModule::Create(AudioCodingModule::Config()));
479 
480   RtpRtcpInterface::Configuration configuration;
481   configuration.bandwidth_callback = rtcp_observer_.get();
482   configuration.transport_feedback_callback = feedback_observer_;
483   configuration.clock = (clock ? clock : Clock::GetRealTimeClock());
484   configuration.audio = true;
485   configuration.outgoing_transport = rtp_transport;
486 
487   configuration.paced_sender = rtp_packet_pacer_proxy_.get();
488 
489   configuration.event_log = event_log_;
490   configuration.rtt_stats = rtcp_rtt_stats;
491   configuration.retransmission_rate_limiter =
492       retransmission_rate_limiter_.get();
493   configuration.extmap_allow_mixed = extmap_allow_mixed;
494   configuration.rtcp_report_interval_ms = rtcp_report_interval_ms;
495 
496   configuration.local_media_ssrc = ssrc;
497 
498   rtp_rtcp_ = ModuleRtpRtcpImpl2::Create(configuration);
499   rtp_rtcp_->SetSendingMediaStatus(false);
500 
501   rtp_sender_audio_ = std::make_unique<RTPSenderAudio>(configuration.clock,
502                                                        rtp_rtcp_->RtpSender());
503 
504   _moduleProcessThreadPtr->RegisterModule(rtp_rtcp_.get(), RTC_FROM_HERE);
505 
506   // Ensure that RTCP is enabled by default for the created channel.
507   rtp_rtcp_->SetRTCPStatus(RtcpMode::kCompound);
508 
509   int error = audio_coding_->RegisterTransportCallback(this);
510   RTC_DCHECK_EQ(0, error);
511   if (frame_transformer)
512     InitFrameTransformerDelegate(std::move(frame_transformer));
513 }
514 
~ChannelSend()515 ChannelSend::~ChannelSend() {
516   RTC_DCHECK(construction_thread_.IsCurrent());
517 
518   // Resets the delegate's callback to ChannelSend::SendRtpAudio.
519   if (frame_transformer_delegate_)
520     frame_transformer_delegate_->Reset();
521 
522   StopSend();
523   int error = audio_coding_->RegisterTransportCallback(NULL);
524   RTC_DCHECK_EQ(0, error);
525 
526   if (_moduleProcessThreadPtr)
527     _moduleProcessThreadPtr->DeRegisterModule(rtp_rtcp_.get());
528 }
529 
StartSend()530 void ChannelSend::StartSend() {
531   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
532   RTC_DCHECK(!sending_);
533   sending_ = true;
534 
535   rtp_rtcp_->SetSendingMediaStatus(true);
536   int ret = rtp_rtcp_->SetSendingStatus(true);
537   RTC_DCHECK_EQ(0, ret);
538   // It is now OK to start processing on the encoder task queue.
539   encoder_queue_.PostTask([this] {
540     RTC_DCHECK_RUN_ON(&encoder_queue_);
541     encoder_queue_is_active_ = true;
542   });
543 }
544 
StopSend()545 void ChannelSend::StopSend() {
546   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
547   if (!sending_) {
548     return;
549   }
550   sending_ = false;
551 
552   rtc::Event flush;
553   encoder_queue_.PostTask([this, &flush]() {
554     RTC_DCHECK_RUN_ON(&encoder_queue_);
555     encoder_queue_is_active_ = false;
556     flush.Set();
557   });
558   flush.Wait(rtc::Event::kForever);
559 
560   // Reset sending SSRC and sequence number and triggers direct transmission
561   // of RTCP BYE
562   if (rtp_rtcp_->SetSendingStatus(false) == -1) {
563     RTC_DLOG(LS_ERROR) << "StartSend() RTP/RTCP failed to stop sending";
564   }
565   rtp_rtcp_->SetSendingMediaStatus(false);
566 }
567 
SetEncoder(int payload_type,std::unique_ptr<AudioEncoder> encoder)568 void ChannelSend::SetEncoder(int payload_type,
569                              std::unique_ptr<AudioEncoder> encoder) {
570   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
571   RTC_DCHECK_GE(payload_type, 0);
572   RTC_DCHECK_LE(payload_type, 127);
573 
574   // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
575   // as well as some other things, so we collect this info and send it along.
576   rtp_rtcp_->RegisterSendPayloadFrequency(payload_type,
577                                           encoder->RtpTimestampRateHz());
578   rtp_sender_audio_->RegisterAudioPayload("audio", payload_type,
579                                           encoder->RtpTimestampRateHz(),
580                                           encoder->NumChannels(), 0);
581 
582   audio_coding_->SetEncoder(std::move(encoder));
583 }
584 
ModifyEncoder(rtc::FunctionView<void (std::unique_ptr<AudioEncoder> *)> modifier)585 void ChannelSend::ModifyEncoder(
586     rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
587   // This method can be called on the worker thread, module process thread
588   // or network thread. Audio coding is thread safe, so we do not need to
589   // enforce the calling thread.
590   audio_coding_->ModifyEncoder(modifier);
591 }
592 
CallEncoder(rtc::FunctionView<void (AudioEncoder *)> modifier)593 void ChannelSend::CallEncoder(rtc::FunctionView<void(AudioEncoder*)> modifier) {
594   ModifyEncoder([modifier](std::unique_ptr<AudioEncoder>* encoder_ptr) {
595     if (*encoder_ptr) {
596       modifier(encoder_ptr->get());
597     } else {
598       RTC_DLOG(LS_WARNING) << "Trying to call unset encoder.";
599     }
600   });
601 }
602 
OnBitrateAllocation(BitrateAllocationUpdate update)603 void ChannelSend::OnBitrateAllocation(BitrateAllocationUpdate update) {
604   // This method can be called on the worker thread, module process thread
605   // or on a TaskQueue via VideoSendStreamImpl::OnEncoderConfigurationChanged.
606   // TODO(solenberg): Figure out a good way to check this or enforce calling
607   // rules.
608   // RTC_DCHECK(worker_thread_checker_.IsCurrent() ||
609   //            module_process_thread_checker_.IsCurrent());
610   MutexLock lock(&bitrate_mutex_);
611 
612   CallEncoder([&](AudioEncoder* encoder) {
613     encoder->OnReceivedUplinkAllocation(update);
614   });
615   retransmission_rate_limiter_->SetMaxRate(update.target_bitrate.bps());
616   configured_bitrate_bps_ = update.target_bitrate.bps();
617 }
618 
GetBitrate() const619 int ChannelSend::GetBitrate() const {
620   MutexLock lock(&bitrate_mutex_);
621   return configured_bitrate_bps_;
622 }
623 
OnUplinkPacketLossRate(float packet_loss_rate)624 void ChannelSend::OnUplinkPacketLossRate(float packet_loss_rate) {
625   CallEncoder([&](AudioEncoder* encoder) {
626     encoder->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
627   });
628 }
629 
ReceivedRTCPPacket(const uint8_t * data,size_t length)630 void ChannelSend::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
631   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
632 
633   // Deliver RTCP packet to RTP/RTCP module for parsing
634   rtp_rtcp_->IncomingRtcpPacket(data, length);
635 
636   int64_t rtt = GetRTT();
637   if (rtt == 0) {
638     // Waiting for valid RTT.
639     return;
640   }
641 
642   int64_t nack_window_ms = rtt;
643   if (nack_window_ms < kMinRetransmissionWindowMs) {
644     nack_window_ms = kMinRetransmissionWindowMs;
645   } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
646     nack_window_ms = kMaxRetransmissionWindowMs;
647   }
648   retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
649 
650   OnReceivedRtt(rtt);
651 }
652 
SetInputMute(bool enable)653 void ChannelSend::SetInputMute(bool enable) {
654   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
655   MutexLock lock(&volume_settings_mutex_);
656   input_mute_ = enable;
657 }
658 
InputMute() const659 bool ChannelSend::InputMute() const {
660   MutexLock lock(&volume_settings_mutex_);
661   return input_mute_;
662 }
663 
SendTelephoneEventOutband(int event,int duration_ms)664 bool ChannelSend::SendTelephoneEventOutband(int event, int duration_ms) {
665   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
666   RTC_DCHECK_LE(0, event);
667   RTC_DCHECK_GE(255, event);
668   RTC_DCHECK_LE(0, duration_ms);
669   RTC_DCHECK_GE(65535, duration_ms);
670   if (!sending_) {
671     return false;
672   }
673   if (rtp_sender_audio_->SendTelephoneEvent(
674           event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
675     RTC_DLOG(LS_ERROR) << "SendTelephoneEvent() failed to send event";
676     return false;
677   }
678   return true;
679 }
680 
RegisterCngPayloadType(int payload_type,int payload_frequency)681 void ChannelSend::RegisterCngPayloadType(int payload_type,
682                                          int payload_frequency) {
683   rtp_rtcp_->RegisterSendPayloadFrequency(payload_type, payload_frequency);
684   rtp_sender_audio_->RegisterAudioPayload("CN", payload_type, payload_frequency,
685                                           1, 0);
686 }
687 
SetSendTelephoneEventPayloadType(int payload_type,int payload_frequency)688 void ChannelSend::SetSendTelephoneEventPayloadType(int payload_type,
689                                                    int payload_frequency) {
690   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
691   RTC_DCHECK_LE(0, payload_type);
692   RTC_DCHECK_GE(127, payload_type);
693   rtp_rtcp_->RegisterSendPayloadFrequency(payload_type, payload_frequency);
694   rtp_sender_audio_->RegisterAudioPayload("telephone-event", payload_type,
695                                           payload_frequency, 0, 0);
696 }
697 
SetSendAudioLevelIndicationStatus(bool enable,int id)698 void ChannelSend::SetSendAudioLevelIndicationStatus(bool enable, int id) {
699   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
700   _includeAudioLevelIndication = enable;
701   if (enable) {
702     rtp_rtcp_->RegisterRtpHeaderExtension(AudioLevel::kUri, id);
703   } else {
704     rtp_rtcp_->DeregisterSendRtpHeaderExtension(AudioLevel::kUri);
705   }
706 }
707 
RegisterSenderCongestionControlObjects(RtpTransportControllerSendInterface * transport,RtcpBandwidthObserver * bandwidth_observer)708 void ChannelSend::RegisterSenderCongestionControlObjects(
709     RtpTransportControllerSendInterface* transport,
710     RtcpBandwidthObserver* bandwidth_observer) {
711   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
712   RtpPacketSender* rtp_packet_pacer = transport->packet_sender();
713   PacketRouter* packet_router = transport->packet_router();
714 
715   RTC_DCHECK(rtp_packet_pacer);
716   RTC_DCHECK(packet_router);
717   RTC_DCHECK(!packet_router_);
718   rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
719   rtp_packet_pacer_proxy_->SetPacketPacer(rtp_packet_pacer);
720   rtp_rtcp_->SetStorePacketsStatus(true, 600);
721   constexpr bool remb_candidate = false;
722   packet_router->AddSendRtpModule(rtp_rtcp_.get(), remb_candidate);
723   packet_router_ = packet_router;
724 }
725 
ResetSenderCongestionControlObjects()726 void ChannelSend::ResetSenderCongestionControlObjects() {
727   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
728   RTC_DCHECK(packet_router_);
729   rtp_rtcp_->SetStorePacketsStatus(false, 600);
730   rtcp_observer_->SetBandwidthObserver(nullptr);
731   packet_router_->RemoveSendRtpModule(rtp_rtcp_.get());
732   packet_router_ = nullptr;
733   rtp_packet_pacer_proxy_->SetPacketPacer(nullptr);
734 }
735 
SetRTCP_CNAME(absl::string_view c_name)736 void ChannelSend::SetRTCP_CNAME(absl::string_view c_name) {
737   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
738   // Note: SetCNAME() accepts a c string of length at most 255.
739   const std::string c_name_limited(c_name.substr(0, 255));
740   int ret = rtp_rtcp_->SetCNAME(c_name_limited.c_str()) != 0;
741   RTC_DCHECK_EQ(0, ret) << "SetRTCP_CNAME() failed to set RTCP CNAME";
742 }
743 
GetRemoteRTCPReportBlocks() const744 std::vector<ReportBlock> ChannelSend::GetRemoteRTCPReportBlocks() const {
745   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
746   // Get the report blocks from the latest received RTCP Sender or Receiver
747   // Report. Each element in the vector contains the sender's SSRC and a
748   // report block according to RFC 3550.
749   std::vector<RTCPReportBlock> rtcp_report_blocks;
750 
751   int ret = rtp_rtcp_->RemoteRTCPStat(&rtcp_report_blocks);
752   RTC_DCHECK_EQ(0, ret);
753 
754   std::vector<ReportBlock> report_blocks;
755 
756   std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
757   for (; it != rtcp_report_blocks.end(); ++it) {
758     ReportBlock report_block;
759     report_block.sender_SSRC = it->sender_ssrc;
760     report_block.source_SSRC = it->source_ssrc;
761     report_block.fraction_lost = it->fraction_lost;
762     report_block.cumulative_num_packets_lost = it->packets_lost;
763     report_block.extended_highest_sequence_number =
764         it->extended_highest_sequence_number;
765     report_block.interarrival_jitter = it->jitter;
766     report_block.last_SR_timestamp = it->last_sender_report_timestamp;
767     report_block.delay_since_last_SR = it->delay_since_last_sender_report;
768     report_blocks.push_back(report_block);
769   }
770   return report_blocks;
771 }
772 
GetRTCPStatistics() const773 CallSendStatistics ChannelSend::GetRTCPStatistics() const {
774   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
775   CallSendStatistics stats = {0};
776   stats.rttMs = GetRTT();
777 
778   StreamDataCounters rtp_stats;
779   StreamDataCounters rtx_stats;
780   rtp_rtcp_->GetSendStreamDataCounters(&rtp_stats, &rtx_stats);
781   stats.payload_bytes_sent =
782       rtp_stats.transmitted.payload_bytes + rtx_stats.transmitted.payload_bytes;
783   stats.header_and_padding_bytes_sent =
784       rtp_stats.transmitted.padding_bytes + rtp_stats.transmitted.header_bytes +
785       rtx_stats.transmitted.padding_bytes + rtx_stats.transmitted.header_bytes;
786 
787   // TODO(https://crbug.com/webrtc/10555): RTX retransmissions should show up in
788   // separate outbound-rtp stream objects.
789   stats.retransmitted_bytes_sent = rtp_stats.retransmitted.payload_bytes;
790   stats.packetsSent =
791       rtp_stats.transmitted.packets + rtx_stats.transmitted.packets;
792   stats.retransmitted_packets_sent = rtp_stats.retransmitted.packets;
793   stats.report_block_datas = rtp_rtcp_->GetLatestReportBlockData();
794 
795   return stats;
796 }
797 
ProcessAndEncodeAudio(std::unique_ptr<AudioFrame> audio_frame)798 void ChannelSend::ProcessAndEncodeAudio(
799     std::unique_ptr<AudioFrame> audio_frame) {
800   RTC_DCHECK_RUNS_SERIALIZED(&audio_thread_race_checker_);
801   RTC_DCHECK_GT(audio_frame->samples_per_channel_, 0);
802   RTC_DCHECK_LE(audio_frame->num_channels_, 8);
803 
804   // Profile time between when the audio frame is added to the task queue and
805   // when the task is actually executed.
806   audio_frame->UpdateProfileTimeStamp();
807   encoder_queue_.PostTask(
808       [this, audio_frame = std::move(audio_frame)]() mutable {
809         RTC_DCHECK_RUN_ON(&encoder_queue_);
810         if (!encoder_queue_is_active_) {
811           return;
812         }
813         // Measure time between when the audio frame is added to the task queue
814         // and when the task is actually executed. Goal is to keep track of
815         // unwanted extra latency added by the task queue.
816         RTC_HISTOGRAM_COUNTS_10000("WebRTC.Audio.EncodingTaskQueueLatencyMs",
817                                    audio_frame->ElapsedProfileTimeMs());
818 
819         bool is_muted = InputMute();
820         AudioFrameOperations::Mute(audio_frame.get(), previous_frame_muted_,
821                                    is_muted);
822 
823         if (_includeAudioLevelIndication) {
824           size_t length =
825               audio_frame->samples_per_channel_ * audio_frame->num_channels_;
826           RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
827           if (is_muted && previous_frame_muted_) {
828             rms_level_.AnalyzeMuted(length);
829           } else {
830             rms_level_.Analyze(
831                 rtc::ArrayView<const int16_t>(audio_frame->data(), length));
832           }
833         }
834         previous_frame_muted_ = is_muted;
835 
836         // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
837 
838         // The ACM resamples internally.
839         audio_frame->timestamp_ = _timeStamp;
840         // This call will trigger AudioPacketizationCallback::SendData if
841         // encoding is done and payload is ready for packetization and
842         // transmission. Otherwise, it will return without invoking the
843         // callback.
844         if (audio_coding_->Add10MsData(*audio_frame) < 0) {
845           RTC_DLOG(LS_ERROR) << "ACM::Add10MsData() failed.";
846           return;
847         }
848 
849         _timeStamp += static_cast<uint32_t>(audio_frame->samples_per_channel_);
850       });
851 }
852 
GetANAStatistics() const853 ANAStats ChannelSend::GetANAStatistics() const {
854   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
855   return audio_coding_->GetANAStats();
856 }
857 
GetRtpRtcp() const858 RtpRtcpInterface* ChannelSend::GetRtpRtcp() const {
859   RTC_DCHECK(module_process_thread_checker_.IsCurrent());
860   return rtp_rtcp_.get();
861 }
862 
GetRTT() const863 int64_t ChannelSend::GetRTT() const {
864   std::vector<RTCPReportBlock> report_blocks;
865   rtp_rtcp_->RemoteRTCPStat(&report_blocks);
866 
867   if (report_blocks.empty()) {
868     return 0;
869   }
870 
871   int64_t rtt = 0;
872   int64_t avg_rtt = 0;
873   int64_t max_rtt = 0;
874   int64_t min_rtt = 0;
875   // We don't know in advance the remote ssrc used by the other end's receiver
876   // reports, so use the SSRC of the first report block for calculating the RTT.
877   if (rtp_rtcp_->RTT(report_blocks[0].sender_ssrc, &rtt, &avg_rtt, &min_rtt,
878                      &max_rtt) != 0) {
879     return 0;
880   }
881   return rtt;
882 }
883 
SetFrameEncryptor(rtc::scoped_refptr<FrameEncryptorInterface> frame_encryptor)884 void ChannelSend::SetFrameEncryptor(
885     rtc::scoped_refptr<FrameEncryptorInterface> frame_encryptor) {
886   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
887   encoder_queue_.PostTask([this, frame_encryptor]() mutable {
888     RTC_DCHECK_RUN_ON(&encoder_queue_);
889     frame_encryptor_ = std::move(frame_encryptor);
890   });
891 }
892 
SetEncoderToPacketizerFrameTransformer(rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)893 void ChannelSend::SetEncoderToPacketizerFrameTransformer(
894     rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
895   RTC_DCHECK_RUN_ON(&worker_thread_checker_);
896   if (!frame_transformer)
897     return;
898 
899   encoder_queue_.PostTask(
900       [this, frame_transformer = std::move(frame_transformer)]() mutable {
901         RTC_DCHECK_RUN_ON(&encoder_queue_);
902         InitFrameTransformerDelegate(std::move(frame_transformer));
903       });
904 }
905 
OnReceivedRtt(int64_t rtt_ms)906 void ChannelSend::OnReceivedRtt(int64_t rtt_ms) {
907   // Invoke audio encoders OnReceivedRtt().
908   CallEncoder(
909       [rtt_ms](AudioEncoder* encoder) { encoder->OnReceivedRtt(rtt_ms); });
910 }
911 
InitFrameTransformerDelegate(rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer)912 void ChannelSend::InitFrameTransformerDelegate(
913     rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer) {
914   RTC_DCHECK_RUN_ON(&encoder_queue_);
915   RTC_DCHECK(frame_transformer);
916   RTC_DCHECK(!frame_transformer_delegate_);
917 
918   // Pass a callback to ChannelSend::SendRtpAudio, to be called by the delegate
919   // to send the transformed audio.
920   ChannelSendFrameTransformerDelegate::SendFrameCallback send_audio_callback =
921       [this](AudioFrameType frameType, uint8_t payloadType,
922              uint32_t rtp_timestamp, rtc::ArrayView<const uint8_t> payload,
923              int64_t absolute_capture_timestamp_ms) {
924         RTC_DCHECK_RUN_ON(&encoder_queue_);
925         return SendRtpAudio(frameType, payloadType, rtp_timestamp, payload,
926                             absolute_capture_timestamp_ms);
927       };
928   frame_transformer_delegate_ =
929       new rtc::RefCountedObject<ChannelSendFrameTransformerDelegate>(
930           std::move(send_audio_callback), std::move(frame_transformer),
931           &encoder_queue_);
932   frame_transformer_delegate_->Init();
933 }
934 
935 }  // namespace
936 
CreateChannelSend(Clock * clock,TaskQueueFactory * task_queue_factory,ProcessThread * module_process_thread,Transport * rtp_transport,RtcpRttStats * rtcp_rtt_stats,RtcEventLog * rtc_event_log,FrameEncryptorInterface * frame_encryptor,const webrtc::CryptoOptions & crypto_options,bool extmap_allow_mixed,int rtcp_report_interval_ms,uint32_t ssrc,rtc::scoped_refptr<FrameTransformerInterface> frame_transformer,TransportFeedbackObserver * feedback_observer)937 std::unique_ptr<ChannelSendInterface> CreateChannelSend(
938     Clock* clock,
939     TaskQueueFactory* task_queue_factory,
940     ProcessThread* module_process_thread,
941     Transport* rtp_transport,
942     RtcpRttStats* rtcp_rtt_stats,
943     RtcEventLog* rtc_event_log,
944     FrameEncryptorInterface* frame_encryptor,
945     const webrtc::CryptoOptions& crypto_options,
946     bool extmap_allow_mixed,
947     int rtcp_report_interval_ms,
948     uint32_t ssrc,
949     rtc::scoped_refptr<FrameTransformerInterface> frame_transformer,
950     TransportFeedbackObserver* feedback_observer) {
951   return std::make_unique<ChannelSend>(
952       clock, task_queue_factory, module_process_thread, rtp_transport,
953       rtcp_rtt_stats, rtc_event_log, frame_encryptor, crypto_options,
954       extmap_allow_mixed, rtcp_report_interval_ms, ssrc,
955       std::move(frame_transformer), feedback_observer);
956 }
957 
958 }  // namespace voe
959 }  // namespace webrtc
960