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