blob: 6f01725392fadd98b342c5b71664c0c828a7eea9 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
henrika@webrtc.org2919e952012-01-31 08:45:03 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
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
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000011#include "webrtc/voice_engine/channel.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Henrik Lundin64dad832015-05-11 12:44:23 +020013#include <algorithm>
Tommif888bb52015-12-12 01:37:01 +010014#include <utility>
Henrik Lundin64dad832015-05-11 12:44:23 +020015
aleloi6321b492016-12-05 01:46:09 -080016#include "webrtc/audio/utility/audio_frame_operations.h"
henrik.lundin50499422016-11-29 04:26:24 -080017#include "webrtc/base/array_view.h"
Ivo Creusenae856f22015-09-17 16:30:16 +020018#include "webrtc/base/checks.h"
tommi31fc21f2016-01-21 10:37:37 -080019#include "webrtc/base/criticalsection.h"
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +000020#include "webrtc/base/format_macros.h"
tommidea489f2017-03-03 03:20:24 -080021#include "webrtc/base/location.h"
pbosad856222015-11-27 09:48:36 -080022#include "webrtc/base/logging.h"
Erik Språng737336d2016-07-29 12:59:36 +020023#include "webrtc/base/rate_limiter.h"
henrikaec6fbd22017-03-31 05:43:36 -070024#include "webrtc/base/task_queue.h"
25#include "webrtc/base/thread_checker.h"
wu@webrtc.org94454b72014-06-05 20:34:08 +000026#include "webrtc/base/timeutils.h"
nissecae45d02017-04-24 05:53:20 -070027#include "webrtc/call/rtp_transport_controller_send_interface.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020028#include "webrtc/config.h"
skvladcc91d282016-10-03 18:31:22 -070029#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kwibergda2bf4e2016-10-24 13:47:09 -070030#include "webrtc/modules/audio_coding/codecs/audio_format_conversion.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000031#include "webrtc/modules/audio_device/include/audio_device.h"
32#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010033#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010034#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010035#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
36#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
37#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
nisse657bab22017-02-21 06:28:10 -080038#include "webrtc/modules/rtp_rtcp/source/rtp_packet_received.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000039#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010040#include "webrtc/modules/utility/include/process_thread.h"
elad.alon28770482017-03-28 05:03:55 -070041#include "webrtc/system_wrappers/include/field_trial.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010042#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000043#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
44#include "webrtc/voice_engine/output_mixer.h"
45#include "webrtc/voice_engine/statistics.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000046#include "webrtc/voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000047
andrew@webrtc.org50419b02012-11-14 19:07:54 +000048namespace webrtc {
49namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000050
kwibergc8d071e2016-04-06 12:22:38 -070051namespace {
52
Erik Språng737336d2016-07-29 12:59:36 +020053constexpr int64_t kMaxRetransmissionWindowMs = 1000;
54constexpr int64_t kMinRetransmissionWindowMs = 30;
55
kwibergc8d071e2016-04-06 12:22:38 -070056} // namespace
57
solenberg8842c3e2016-03-11 03:06:41 -080058const int kTelephoneEventAttenuationdB = 10;
59
ivoc14d5dbe2016-07-04 07:06:55 -070060class RtcEventLogProxy final : public webrtc::RtcEventLog {
61 public:
62 RtcEventLogProxy() : event_log_(nullptr) {}
63
64 bool StartLogging(const std::string& file_name,
65 int64_t max_size_bytes) override {
66 RTC_NOTREACHED();
67 return false;
68 }
69
70 bool StartLogging(rtc::PlatformFile log_file,
71 int64_t max_size_bytes) override {
72 RTC_NOTREACHED();
73 return false;
74 }
75
76 void StopLogging() override { RTC_NOTREACHED(); }
77
78 void LogVideoReceiveStreamConfig(
79 const webrtc::VideoReceiveStream::Config& config) override {
80 rtc::CritScope lock(&crit_);
81 if (event_log_) {
82 event_log_->LogVideoReceiveStreamConfig(config);
83 }
84 }
85
86 void LogVideoSendStreamConfig(
87 const webrtc::VideoSendStream::Config& config) override {
88 rtc::CritScope lock(&crit_);
89 if (event_log_) {
90 event_log_->LogVideoSendStreamConfig(config);
91 }
92 }
93
ivoce0928d82016-10-10 05:12:51 -070094 void LogAudioReceiveStreamConfig(
95 const webrtc::AudioReceiveStream::Config& config) override {
96 rtc::CritScope lock(&crit_);
97 if (event_log_) {
98 event_log_->LogAudioReceiveStreamConfig(config);
99 }
100 }
101
102 void LogAudioSendStreamConfig(
103 const webrtc::AudioSendStream::Config& config) override {
104 rtc::CritScope lock(&crit_);
105 if (event_log_) {
106 event_log_->LogAudioSendStreamConfig(config);
107 }
108 }
109
ivoc14d5dbe2016-07-04 07:06:55 -0700110 void LogRtpHeader(webrtc::PacketDirection direction,
111 webrtc::MediaType media_type,
112 const uint8_t* header,
113 size_t packet_length) override {
philipel32d00102017-02-27 02:18:46 -0800114 LogRtpHeader(direction, media_type, header, packet_length,
115 PacedPacketInfo::kNotAProbe);
116 }
117
118 void LogRtpHeader(webrtc::PacketDirection direction,
119 webrtc::MediaType media_type,
120 const uint8_t* header,
121 size_t packet_length,
122 int probe_cluster_id) override {
ivoc14d5dbe2016-07-04 07:06:55 -0700123 rtc::CritScope lock(&crit_);
124 if (event_log_) {
philipel32d00102017-02-27 02:18:46 -0800125 event_log_->LogRtpHeader(direction, media_type, header, packet_length,
126 probe_cluster_id);
ivoc14d5dbe2016-07-04 07:06:55 -0700127 }
128 }
129
130 void LogRtcpPacket(webrtc::PacketDirection direction,
131 webrtc::MediaType media_type,
132 const uint8_t* packet,
133 size_t length) override {
134 rtc::CritScope lock(&crit_);
135 if (event_log_) {
136 event_log_->LogRtcpPacket(direction, media_type, packet, length);
137 }
138 }
139
140 void LogAudioPlayout(uint32_t ssrc) override {
141 rtc::CritScope lock(&crit_);
142 if (event_log_) {
143 event_log_->LogAudioPlayout(ssrc);
144 }
145 }
146
terelius424e6cf2017-02-20 05:14:41 -0800147 void LogLossBasedBweUpdate(int32_t bitrate_bps,
ivoc14d5dbe2016-07-04 07:06:55 -0700148 uint8_t fraction_loss,
149 int32_t total_packets) override {
150 rtc::CritScope lock(&crit_);
151 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800152 event_log_->LogLossBasedBweUpdate(bitrate_bps, fraction_loss,
153 total_packets);
ivoc14d5dbe2016-07-04 07:06:55 -0700154 }
155 }
156
terelius424e6cf2017-02-20 05:14:41 -0800157 void LogDelayBasedBweUpdate(int32_t bitrate_bps,
terelius0baf55d2017-02-17 03:38:28 -0800158 BandwidthUsage detector_state) override {
159 rtc::CritScope lock(&crit_);
160 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800161 event_log_->LogDelayBasedBweUpdate(bitrate_bps, detector_state);
terelius0baf55d2017-02-17 03:38:28 -0800162 }
163 }
164
minyue4b7c9522017-01-24 04:54:59 -0800165 void LogAudioNetworkAdaptation(
michaeltcde46b72017-04-06 05:59:10 -0700166 const AudioEncoderRuntimeConfig& config) override {
minyue4b7c9522017-01-24 04:54:59 -0800167 rtc::CritScope lock(&crit_);
168 if (event_log_) {
169 event_log_->LogAudioNetworkAdaptation(config);
170 }
171 }
172
philipel32d00102017-02-27 02:18:46 -0800173 void LogProbeClusterCreated(int id,
174 int bitrate_bps,
175 int min_probes,
176 int min_bytes) override {
177 rtc::CritScope lock(&crit_);
178 if (event_log_) {
179 event_log_->LogProbeClusterCreated(id, bitrate_bps, min_probes,
180 min_bytes);
181 }
182 };
183
184 void LogProbeResultSuccess(int id, int bitrate_bps) override {
185 rtc::CritScope lock(&crit_);
186 if (event_log_) {
187 event_log_->LogProbeResultSuccess(id, bitrate_bps);
188 }
189 };
190
191 void LogProbeResultFailure(int id,
192 ProbeFailureReason failure_reason) override {
193 rtc::CritScope lock(&crit_);
194 if (event_log_) {
195 event_log_->LogProbeResultFailure(id, failure_reason);
196 }
197 };
198
ivoc14d5dbe2016-07-04 07:06:55 -0700199 void SetEventLog(RtcEventLog* event_log) {
200 rtc::CritScope lock(&crit_);
201 event_log_ = event_log;
202 }
203
204 private:
205 rtc::CriticalSection crit_;
206 RtcEventLog* event_log_ GUARDED_BY(crit_);
207 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
208};
209
michaelt9332b7d2016-11-30 07:51:13 -0800210class RtcpRttStatsProxy final : public RtcpRttStats {
211 public:
212 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
213
214 void OnRttUpdate(int64_t rtt) override {
215 rtc::CritScope lock(&crit_);
216 if (rtcp_rtt_stats_)
217 rtcp_rtt_stats_->OnRttUpdate(rtt);
218 }
219
220 int64_t LastProcessedRtt() const override {
221 rtc::CritScope lock(&crit_);
222 if (!rtcp_rtt_stats_)
223 return 0;
224 return rtcp_rtt_stats_->LastProcessedRtt();
225 }
226
227 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
228 rtc::CritScope lock(&crit_);
229 rtcp_rtt_stats_ = rtcp_rtt_stats;
230 }
231
232 private:
233 rtc::CriticalSection crit_;
234 RtcpRttStats* rtcp_rtt_stats_ GUARDED_BY(crit_);
235 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
236};
237
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100238class TransportFeedbackProxy : public TransportFeedbackObserver {
239 public:
240 TransportFeedbackProxy() : feedback_observer_(nullptr) {
241 pacer_thread_.DetachFromThread();
242 network_thread_.DetachFromThread();
243 }
244
245 void SetTransportFeedbackObserver(
246 TransportFeedbackObserver* feedback_observer) {
247 RTC_DCHECK(thread_checker_.CalledOnValidThread());
248 rtc::CritScope lock(&crit_);
249 feedback_observer_ = feedback_observer;
250 }
251
252 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700253 void AddPacket(uint32_t ssrc,
254 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100255 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800256 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100257 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
258 rtc::CritScope lock(&crit_);
259 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700260 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100261 }
philipel8aadd502017-02-23 02:56:13 -0800262
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100263 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
264 RTC_DCHECK(network_thread_.CalledOnValidThread());
265 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700266 if (feedback_observer_)
267 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200268 }
elad.alonf9490002017-03-06 05:32:21 -0800269 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200270 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800271 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100272 }
273
274 private:
275 rtc::CriticalSection crit_;
276 rtc::ThreadChecker thread_checker_;
277 rtc::ThreadChecker pacer_thread_;
278 rtc::ThreadChecker network_thread_;
279 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
280};
281
282class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
283 public:
284 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
285 pacer_thread_.DetachFromThread();
286 }
287
288 void SetSequenceNumberAllocator(
289 TransportSequenceNumberAllocator* seq_num_allocator) {
290 RTC_DCHECK(thread_checker_.CalledOnValidThread());
291 rtc::CritScope lock(&crit_);
292 seq_num_allocator_ = seq_num_allocator;
293 }
294
295 // Implements TransportSequenceNumberAllocator.
296 uint16_t AllocateSequenceNumber() override {
297 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
298 rtc::CritScope lock(&crit_);
299 if (!seq_num_allocator_)
300 return 0;
301 return seq_num_allocator_->AllocateSequenceNumber();
302 }
303
304 private:
305 rtc::CriticalSection crit_;
306 rtc::ThreadChecker thread_checker_;
307 rtc::ThreadChecker pacer_thread_;
308 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
309};
310
311class RtpPacketSenderProxy : public RtpPacketSender {
312 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800313 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100314
315 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
316 RTC_DCHECK(thread_checker_.CalledOnValidThread());
317 rtc::CritScope lock(&crit_);
318 rtp_packet_sender_ = rtp_packet_sender;
319 }
320
321 // Implements RtpPacketSender.
322 void InsertPacket(Priority priority,
323 uint32_t ssrc,
324 uint16_t sequence_number,
325 int64_t capture_time_ms,
326 size_t bytes,
327 bool retransmission) override {
328 rtc::CritScope lock(&crit_);
329 if (rtp_packet_sender_) {
330 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
331 capture_time_ms, bytes, retransmission);
332 }
333 }
334
335 private:
336 rtc::ThreadChecker thread_checker_;
337 rtc::CriticalSection crit_;
338 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
339};
340
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000341class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000342 public:
stefan7de8d642017-02-07 07:14:08 -0800343 explicit VoERtcpObserver(Channel* owner)
344 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000345 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000346
stefan7de8d642017-02-07 07:14:08 -0800347 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
348 rtc::CritScope lock(&crit_);
349 bandwidth_observer_ = bandwidth_observer;
350 }
351
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000352 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800353 rtc::CritScope lock(&crit_);
354 if (bandwidth_observer_) {
355 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
356 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000357 }
358
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000359 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
360 int64_t rtt,
361 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800362 {
363 rtc::CritScope lock(&crit_);
364 if (bandwidth_observer_) {
365 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
366 now_ms);
367 }
368 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000369 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
370 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
371 // report for VoiceEngine?
372 if (report_blocks.empty())
373 return;
374
375 int fraction_lost_aggregate = 0;
376 int total_number_of_packets = 0;
377
378 // If receiving multiple report blocks, calculate the weighted average based
379 // on the number of packets a report refers to.
380 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
381 block_it != report_blocks.end(); ++block_it) {
382 // Find the previous extended high sequence number for this remote SSRC,
383 // to calculate the number of RTP packets this report refers to. Ignore if
384 // we haven't seen this SSRC before.
385 std::map<uint32_t, uint32_t>::iterator seq_num_it =
386 extended_max_sequence_number_.find(block_it->sourceSSRC);
387 int number_of_packets = 0;
388 if (seq_num_it != extended_max_sequence_number_.end()) {
389 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
390 }
391 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
392 total_number_of_packets += number_of_packets;
393
394 extended_max_sequence_number_[block_it->sourceSSRC] =
395 block_it->extendedHighSeqNum;
396 }
397 int weighted_fraction_lost = 0;
398 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800399 weighted_fraction_lost =
400 (fraction_lost_aggregate + total_number_of_packets / 2) /
401 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000402 }
elad.alond12a8e12017-03-23 11:04:48 -0700403 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000404 }
405
406 private:
407 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000408 // Maps remote side ssrc to extended highest sequence number received.
409 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800410 rtc::CriticalSection crit_;
411 RtcpBandwidthObserver* bandwidth_observer_ GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000412};
413
henrikaec6fbd22017-03-31 05:43:36 -0700414class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
415 public:
416 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
417 Channel* channel)
418 : audio_frame_(std::move(audio_frame)), channel_(channel) {
419 RTC_DCHECK(channel_);
420 }
421
422 private:
423 bool Run() override {
424 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
425 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
426 return true;
427 }
428
429 std::unique_ptr<AudioFrame> audio_frame_;
430 Channel* const channel_;
431};
432
kwiberg55b97fe2016-01-28 05:22:45 -0800433int32_t Channel::SendData(FrameType frameType,
434 uint8_t payloadType,
435 uint32_t timeStamp,
436 const uint8_t* payloadData,
437 size_t payloadSize,
438 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700439 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800440 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
441 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
442 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
443 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000444
kwiberg55b97fe2016-01-28 05:22:45 -0800445 if (_includeAudioLevelIndication) {
446 // Store current audio level in the RTP/RTCP module.
447 // The level will be used in combination with voice-activity state
448 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800449 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800450 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000451
kwiberg55b97fe2016-01-28 05:22:45 -0800452 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
453 // packetization.
454 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700455 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800456 (FrameType&)frameType, payloadType, timeStamp,
457 // Leaving the time when this frame was
458 // received from the capture device as
459 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700460 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800461 _engineStatisticsPtr->SetLastError(
462 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
463 "Channel::SendData() failed to send data to RTP/RTCP module");
464 return -1;
465 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000466
kwiberg55b97fe2016-01-28 05:22:45 -0800467 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000468}
469
stefan1d8a5062015-10-02 03:39:33 -0700470bool Channel::SendRtp(const uint8_t* data,
471 size_t len,
472 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800473 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
474 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000475
kwiberg55b97fe2016-01-28 05:22:45 -0800476 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000477
kwiberg55b97fe2016-01-28 05:22:45 -0800478 if (_transportPtr == NULL) {
479 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
480 "Channel::SendPacket() failed to send RTP packet due to"
481 " invalid transport object");
482 return false;
483 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000484
kwiberg55b97fe2016-01-28 05:22:45 -0800485 uint8_t* bufferToSendPtr = (uint8_t*)data;
486 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000487
kwiberg55b97fe2016-01-28 05:22:45 -0800488 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
489 std::string transport_name =
490 _externalTransport ? "external transport" : "WebRtc sockets";
491 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
492 "Channel::SendPacket() RTP transmission using %s failed",
493 transport_name.c_str());
494 return false;
495 }
496 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000497}
498
kwiberg55b97fe2016-01-28 05:22:45 -0800499bool Channel::SendRtcp(const uint8_t* data, size_t len) {
500 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
501 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000502
kwiberg55b97fe2016-01-28 05:22:45 -0800503 rtc::CritScope cs(&_callbackCritSect);
504 if (_transportPtr == NULL) {
505 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
506 "Channel::SendRtcp() failed to send RTCP packet"
507 " due to invalid transport object");
508 return false;
509 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000510
kwiberg55b97fe2016-01-28 05:22:45 -0800511 uint8_t* bufferToSendPtr = (uint8_t*)data;
512 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000513
kwiberg55b97fe2016-01-28 05:22:45 -0800514 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
515 if (n < 0) {
516 std::string transport_name =
517 _externalTransport ? "external transport" : "WebRtc sockets";
518 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
519 "Channel::SendRtcp() transmission using %s failed",
520 transport_name.c_str());
521 return false;
522 }
523 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000524}
525
kwiberg55b97fe2016-01-28 05:22:45 -0800526void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
527 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
528 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000529
kwiberg55b97fe2016-01-28 05:22:45 -0800530 // Update ssrc so that NTP for AV sync can be updated.
531 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000532}
533
Peter Boströmac547a62015-09-17 23:03:57 +0200534void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
535 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
536 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
537 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000538}
539
Peter Boströmac547a62015-09-17 23:03:57 +0200540int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000541 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000542 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000543 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800544 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200545 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800546 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
547 "Channel::OnInitializeDecoder(payloadType=%d, "
548 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
549 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000550
kwiberg55b97fe2016-01-28 05:22:45 -0800551 CodecInst receiveCodec = {0};
552 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000553
kwiberg55b97fe2016-01-28 05:22:45 -0800554 receiveCodec.pltype = payloadType;
555 receiveCodec.plfreq = frequency;
556 receiveCodec.channels = channels;
557 receiveCodec.rate = rate;
558 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000559
kwiberg55b97fe2016-01-28 05:22:45 -0800560 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
561 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000562
kwiberg55b97fe2016-01-28 05:22:45 -0800563 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700564 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
565 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800566 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
567 "Channel::OnInitializeDecoder() invalid codec ("
568 "pt=%d, name=%s) received - 1",
569 payloadType, payloadName);
570 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
571 return -1;
572 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000573
kwiberg55b97fe2016-01-28 05:22:45 -0800574 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000575}
576
kwiberg55b97fe2016-01-28 05:22:45 -0800577int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
578 size_t payloadSize,
579 const WebRtcRTPHeader* rtpHeader) {
580 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
581 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
582 ","
583 " payloadType=%u, audioChannel=%" PRIuS ")",
584 payloadSize, rtpHeader->header.payloadType,
585 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000586
kwiberg55b97fe2016-01-28 05:22:45 -0800587 if (!channel_state_.Get().playing) {
588 // Avoid inserting into NetEQ when we are not playing. Count the
589 // packet as discarded.
590 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
591 "received packet is discarded since playing is not"
592 " activated");
niklase@google.com470e71d2011-07-07 08:21:25 +0000593 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800594 }
595
596 // Push the incoming payload (parsed and ready for decoding) into the ACM
597 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
598 0) {
599 _engineStatisticsPtr->SetLastError(
600 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
601 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
602 return -1;
603 }
604
kwiberg55b97fe2016-01-28 05:22:45 -0800605 int64_t round_trip_time = 0;
606 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
607 NULL);
608
609 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
610 if (!nack_list.empty()) {
611 // Can't use nack_list.data() since it's not supported by all
612 // compilers.
613 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
614 }
615 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000616}
617
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000618bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000619 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000620 RTPHeader header;
621 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
622 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
623 "IncomingPacket invalid RTP header");
624 return false;
625 }
626 header.payload_type_frequency =
627 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
628 if (header.payload_type_frequency < 0)
629 return false;
630 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
631}
632
henrik.lundin42dda502016-05-18 05:36:01 -0700633MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
634 int32_t id,
635 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700636 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800637 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700638 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800639 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700640 bool muted;
641 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
642 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800643 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
644 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
645 // In all likelihood, the audio in this frame is garbage. We return an
646 // error so that the audio mixer module doesn't add it to the mix. As
647 // a result, it won't be played out and the actions skipped here are
648 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700649 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800650 }
henrik.lundina89ab962016-05-18 08:52:45 -0700651
652 if (muted) {
653 // TODO(henrik.lundin): We should be able to do better than this. But we
654 // will have to go through all the cases below where the audio samples may
655 // be used, and handle the muted case in some way.
aleloi6321b492016-12-05 01:46:09 -0800656 AudioFrameOperations::Mute(audioFrame);
henrik.lundina89ab962016-05-18 08:52:45 -0700657 }
kwiberg55b97fe2016-01-28 05:22:45 -0800658
kwiberg55b97fe2016-01-28 05:22:45 -0800659 // Convert module ID to internal VoE channel ID
660 audioFrame->id_ = VoEChannelId(audioFrame->id_);
661 // Store speech type for dead-or-alive detection
662 _outputSpeechType = audioFrame->speech_type_;
663
664 ChannelState::State state = channel_state_.Get();
665
kwiberg55b97fe2016-01-28 05:22:45 -0800666 {
667 // Pass the audio buffers to an optional sink callback, before applying
668 // scaling/panning, as that applies to the mix operation.
669 // External recipients of the audio (e.g. via AudioTrack), will do their
670 // own mixing/dynamic processing.
671 rtc::CritScope cs(&_callbackCritSect);
672 if (audio_sink_) {
673 AudioSinkInterface::Data data(
674 &audioFrame->data_[0], audioFrame->samples_per_channel_,
675 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
676 audioFrame->timestamp_);
677 audio_sink_->OnData(data);
678 }
679 }
680
681 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800682 {
683 rtc::CritScope cs(&volume_settings_critsect_);
684 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800685 }
686
687 // Output volume scaling
688 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800689 // TODO(solenberg): Combine with mute state - this can cause clicks!
oprypin67fdb802017-03-09 06:25:06 -0800690 AudioFrameOperations::ScaleWithSat(output_gain, audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800691 }
692
kwiberg55b97fe2016-01-28 05:22:45 -0800693 // Mix decoded PCM output with file if file mixing is enabled
694 if (state.output_file_playing) {
695 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700696 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800697 }
698
kwiberg55b97fe2016-01-28 05:22:45 -0800699 // Record playout if enabled
700 {
701 rtc::CritScope cs(&_fileCritSect);
702
kwiberg5a25d952016-08-17 07:31:12 -0700703 if (_outputFileRecording && output_file_recorder_) {
704 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800705 }
706 }
707
708 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700709 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800710 _outputAudioLevel.ComputeLevel(*audioFrame);
711
712 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
713 // The first frame with a valid rtp timestamp.
714 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
715 }
716
717 if (capture_start_rtp_time_stamp_ >= 0) {
718 // audioFrame.timestamp_ should be valid from now on.
719
720 // Compute elapsed time.
721 int64_t unwrap_timestamp =
722 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
723 audioFrame->elapsed_time_ms_ =
724 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700725 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800726
niklase@google.com470e71d2011-07-07 08:21:25 +0000727 {
kwiberg55b97fe2016-01-28 05:22:45 -0800728 rtc::CritScope lock(&ts_stats_lock_);
729 // Compute ntp time.
730 audioFrame->ntp_time_ms_ =
731 ntp_estimator_.Estimate(audioFrame->timestamp_);
732 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
733 if (audioFrame->ntp_time_ms_ > 0) {
734 // Compute |capture_start_ntp_time_ms_| so that
735 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
736 capture_start_ntp_time_ms_ =
737 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000738 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000739 }
kwiberg55b97fe2016-01-28 05:22:45 -0800740 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000741
henrik.lundin42dda502016-05-18 05:36:01 -0700742 return muted ? MixerParticipant::AudioFrameInfo::kMuted
743 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000744}
745
aleloi6c278492016-10-20 14:24:39 -0700746AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
747 int sample_rate_hz,
748 AudioFrame* audio_frame) {
749 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700750
aleloi6c278492016-10-20 14:24:39 -0700751 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700752
753 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
754 FrameInfo new_audio_frame_info = FrameInfo::kError;
755 switch (frame_info) {
756 case MixerParticipant::AudioFrameInfo::kNormal:
757 new_audio_frame_info = FrameInfo::kNormal;
758 break;
759 case MixerParticipant::AudioFrameInfo::kMuted:
760 new_audio_frame_info = FrameInfo::kMuted;
761 break;
762 case MixerParticipant::AudioFrameInfo::kError:
763 new_audio_frame_info = FrameInfo::kError;
764 break;
765 }
aleloi6c278492016-10-20 14:24:39 -0700766 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700767}
768
kwiberg55b97fe2016-01-28 05:22:45 -0800769int32_t Channel::NeededFrequency(int32_t id) const {
770 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
771 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000772
kwiberg55b97fe2016-01-28 05:22:45 -0800773 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000774
kwiberg55b97fe2016-01-28 05:22:45 -0800775 // Determine highest needed receive frequency
776 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000777
kwiberg55b97fe2016-01-28 05:22:45 -0800778 // Return the bigger of playout and receive frequency in the ACM.
779 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
780 highestNeeded = audio_coding_->PlayoutFrequency();
781 } else {
782 highestNeeded = receiveFrequency;
783 }
784
785 // Special case, if we're playing a file on the playout side
786 // we take that frequency into consideration as well
787 // This is not needed on sending side, since the codec will
788 // limit the spectrum anyway.
789 if (channel_state_.Get().output_file_playing) {
790 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700791 if (output_file_player_) {
792 if (output_file_player_->Frequency() > highestNeeded) {
793 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800794 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000795 }
kwiberg55b97fe2016-01-28 05:22:45 -0800796 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000797
kwiberg55b97fe2016-01-28 05:22:45 -0800798 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000799}
800
henrikaec6fbd22017-03-31 05:43:36 -0700801int32_t Channel::CreateChannel(Channel*& channel,
802 int32_t channelId,
803 uint32_t instanceId,
804 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800805 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
806 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
807 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000808
solenberg88499ec2016-09-07 07:34:41 -0700809 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800810 if (channel == NULL) {
811 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
812 "Channel::CreateChannel() unable to allocate memory for"
813 " channel");
814 return -1;
815 }
816 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000817}
818
kwiberg55b97fe2016-01-28 05:22:45 -0800819void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
820 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
821 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
822 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000823
kwiberg55b97fe2016-01-28 05:22:45 -0800824 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000825}
826
kwiberg55b97fe2016-01-28 05:22:45 -0800827void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
828 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
829 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
830 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000831
kwiberg55b97fe2016-01-28 05:22:45 -0800832 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000833}
834
kwiberg55b97fe2016-01-28 05:22:45 -0800835void Channel::PlayFileEnded(int32_t id) {
836 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
837 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000838
kwiberg55b97fe2016-01-28 05:22:45 -0800839 if (id == _inputFilePlayerId) {
840 channel_state_.SetInputFilePlaying(false);
841 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
842 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000843 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800844 } else if (id == _outputFilePlayerId) {
845 channel_state_.SetOutputFilePlaying(false);
846 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
847 "Channel::PlayFileEnded() => output file player module is"
848 " shutdown");
849 }
850}
851
852void Channel::RecordFileEnded(int32_t id) {
853 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
854 "Channel::RecordFileEnded(id=%d)", id);
855
856 assert(id == _outputFileRecorderId);
857
858 rtc::CritScope cs(&_fileCritSect);
859
860 _outputFileRecording = false;
861 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
862 "Channel::RecordFileEnded() => output file recorder module is"
863 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000864}
865
pbos@webrtc.org92135212013-05-14 08:31:39 +0000866Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000867 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700868 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800869 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100870 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700871 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800872 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100873 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800874 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100875 rtp_receive_statistics_(
876 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
877 rtp_receiver_(
878 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100879 this,
880 this,
881 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700882 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100883 _outputAudioLevel(),
884 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100885 // Avoid conflict with other channels by adding 1024 - 1026,
886 // won't use as much as 1024 channels.
887 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
888 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
889 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
890 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100891 _timeStamp(0), // This is just an offset, RTP module will add it's own
892 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100893 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100894 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100895 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100896 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100897 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
898 capture_start_rtp_time_stamp_(-1),
899 capture_start_ntp_time_ms_(-1),
900 _engineStatisticsPtr(NULL),
901 _outputMixerPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100902 _moduleProcessThreadPtr(NULL),
903 _audioDeviceModulePtr(NULL),
904 _voiceEngineObserverPtr(NULL),
905 _callbackCritSectPtr(NULL),
906 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700907 input_mute_(false),
908 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100909 _outputGain(1.0f),
solenberg8d73f8c2017-03-08 01:52:20 -0800910 _mixFileWithMicrophone(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100911 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800912 transport_overhead_per_packet_(0),
913 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100914 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100915 restored_packet_in_use_(false),
916 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100917 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700918 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800919 feedback_observer_proxy_(new TransportFeedbackProxy()),
920 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700921 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200922 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
923 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700924 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700925 use_twcc_plr_for_ana_(
926 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800927 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
928 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700929 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800930 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700931 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800932 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200933
kwiberg55b97fe2016-01-28 05:22:45 -0800934 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000935
kwiberg55b97fe2016-01-28 05:22:45 -0800936 RtpRtcp::Configuration configuration;
937 configuration.audio = true;
938 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800939 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800940 configuration.receive_statistics = rtp_receive_statistics_.get();
941 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800942 if (pacing_enabled_) {
943 configuration.paced_sender = rtp_packet_sender_proxy_.get();
944 configuration.transport_sequence_number_allocator =
945 seq_num_allocator_proxy_.get();
946 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
947 }
ivoc14d5dbe2016-07-04 07:06:55 -0700948 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800949 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200950 configuration.retransmission_rate_limiter =
951 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000952
kwiberg55b97fe2016-01-28 05:22:45 -0800953 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100954 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000955}
956
kwiberg55b97fe2016-01-28 05:22:45 -0800957Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700958 RTC_DCHECK(!channel_state_.Get().sending);
959 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000960}
961
kwiberg55b97fe2016-01-28 05:22:45 -0800962int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700963 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800964 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
965 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000966
kwiberg55b97fe2016-01-28 05:22:45 -0800967 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000968
kwiberg55b97fe2016-01-28 05:22:45 -0800969 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000970
kwiberg55b97fe2016-01-28 05:22:45 -0800971 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
972 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
973 "Channel::Init() must call SetEngineInformation() first");
974 return -1;
975 }
976
977 // --- Add modules to process thread (for periodic schedulation)
978
tommidea489f2017-03-03 03:20:24 -0800979 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800980
981 // --- ACM initialization
982
983 if (audio_coding_->InitializeReceiver() == -1) {
984 _engineStatisticsPtr->SetLastError(
985 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
986 "Channel::Init() unable to initialize the ACM - 1");
987 return -1;
988 }
989
990 // --- RTP/RTCP module initialization
991
992 // Ensure that RTCP is enabled by default for the created channel.
993 // Note that, the module will keep generating RTCP until it is explicitly
994 // disabled by the user.
995 // After StopListen (when no sockets exists), RTCP packets will no longer
996 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700997 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800998 // RTCP is enabled by default.
999 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
1000 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -08001001 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001002 _engineStatisticsPtr->SetLastError(
1003 VE_CANNOT_INIT_CHANNEL, kTraceError,
1004 "Channel::Init() callbacks not registered");
1005 return -1;
1006 }
1007
kwiberg1c07c702017-03-27 07:15:49 -07001008 // Register a default set of send codecs.
1009 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -08001010 for (int idx = 0; idx < nSupportedCodecs; idx++) {
kwiberg1c07c702017-03-27 07:15:49 -07001011 CodecInst codec;
1012 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
1013
1014 // Ensure that PCMU is used as default send codec.
1015 if (STR_CASE_CMP(codec.plname, "PCMU") == 0 && codec.channels == 1) {
1016 SetSendCodec(codec);
1017 }
1018
1019 // Register default PT for 'telephone-event'
1020 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
1021 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1) {
1022 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1023 "Channel::Init() failed to register outband "
1024 "'telephone-event' (%d/%d) correctly",
1025 codec.pltype, codec.plfreq);
1026 }
1027 }
1028
1029 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
1030 if (!codec_manager_.RegisterEncoder(codec) ||
1031 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
1032 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
1033 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1034 "Channel::Init() failed to register CN (%d/%d) "
1035 "correctly - 1",
1036 codec.pltype, codec.plfreq);
1037 }
1038 }
1039 }
1040
1041 return 0;
1042}
1043
1044void Channel::RegisterLegacyReceiveCodecs() {
1045 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1046 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1047 CodecInst codec;
1048 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
1049
kwiberg55b97fe2016-01-28 05:22:45 -08001050 // Open up the RTP/RTCP receiver for all supported codecs
kwiberg1c07c702017-03-27 07:15:49 -07001051 if (rtp_receiver_->RegisterReceivePayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001052 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1053 "Channel::Init() unable to register %s "
1054 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1055 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1056 codec.rate);
1057 } else {
1058 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1059 "Channel::Init() %s (%d/%d/%" PRIuS
1060 "/%d) has been "
1061 "added to the RTP/RTCP receiver",
1062 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1063 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001064 }
1065
kwiberg1c07c702017-03-27 07:15:49 -07001066 // Register default PT for 'telephone-event'
1067 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
1068 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
kwibergda2bf4e2016-10-24 13:47:09 -07001069 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001070 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
kwiberg1c07c702017-03-27 07:15:49 -07001071 "Channel::Init() failed to register inband "
kwiberg55b97fe2016-01-28 05:22:45 -08001072 "'telephone-event' (%d/%d) correctly",
1073 codec.pltype, codec.plfreq);
1074 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001075 }
1076
kwiberg1c07c702017-03-27 07:15:49 -07001077 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
1078 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1079 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001080 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1081 "Channel::Init() failed to register CN (%d/%d) "
1082 "correctly - 1",
1083 codec.pltype, codec.plfreq);
1084 }
1085 }
kwiberg55b97fe2016-01-28 05:22:45 -08001086 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001087}
1088
tommi0a2391f2017-03-21 02:31:51 -07001089void Channel::Terminate() {
1090 RTC_DCHECK(construction_thread_.CalledOnValidThread());
1091 // Must be called on the same thread as Init().
1092 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
1093 "Channel::Terminate");
1094
1095 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
1096
1097 StopSend();
1098 StopPlayout();
1099
1100 {
1101 rtc::CritScope cs(&_fileCritSect);
1102 if (input_file_player_) {
1103 input_file_player_->RegisterModuleFileCallback(NULL);
1104 input_file_player_->StopPlayingFile();
1105 }
1106 if (output_file_player_) {
1107 output_file_player_->RegisterModuleFileCallback(NULL);
1108 output_file_player_->StopPlayingFile();
1109 }
1110 if (output_file_recorder_) {
1111 output_file_recorder_->RegisterModuleFileCallback(NULL);
1112 output_file_recorder_->StopRecording();
1113 }
1114 }
1115
1116 // The order to safely shutdown modules in a channel is:
1117 // 1. De-register callbacks in modules
1118 // 2. De-register modules in process thread
1119 // 3. Destroy modules
1120 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1121 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1122 "Terminate() failed to de-register transport callback"
1123 " (Audio coding module)");
1124 }
1125
1126 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1127 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1128 "Terminate() failed to de-register VAD callback"
1129 " (Audio coding module)");
1130 }
1131
1132 // De-register modules in process thread
1133 if (_moduleProcessThreadPtr)
1134 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
1135
1136 // End of modules shutdown
1137}
1138
kwiberg55b97fe2016-01-28 05:22:45 -08001139int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1140 OutputMixer& outputMixer,
kwiberg55b97fe2016-01-28 05:22:45 -08001141 ProcessThread& moduleProcessThread,
1142 AudioDeviceModule& audioDeviceModule,
1143 VoiceEngineObserver* voiceEngineObserver,
henrikaec6fbd22017-03-31 05:43:36 -07001144 rtc::CriticalSection* callbackCritSect,
1145 rtc::TaskQueue* encoder_queue) {
1146 RTC_DCHECK(encoder_queue);
1147 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -08001148 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1149 "Channel::SetEngineInformation()");
1150 _engineStatisticsPtr = &engineStatistics;
1151 _outputMixerPtr = &outputMixer;
kwiberg55b97fe2016-01-28 05:22:45 -08001152 _moduleProcessThreadPtr = &moduleProcessThread;
1153 _audioDeviceModulePtr = &audioDeviceModule;
1154 _voiceEngineObserverPtr = voiceEngineObserver;
1155 _callbackCritSectPtr = callbackCritSect;
henrikaec6fbd22017-03-31 05:43:36 -07001156 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -08001157 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001158}
1159
kwibergb7f89d62016-02-17 10:04:18 -08001160void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001161 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001162 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001163}
1164
ossu29b1a8d2016-06-13 07:34:51 -07001165const rtc::scoped_refptr<AudioDecoderFactory>&
1166Channel::GetAudioDecoderFactory() const {
1167 return decoder_factory_;
1168}
1169
kwiberg55b97fe2016-01-28 05:22:45 -08001170int32_t Channel::StartPlayout() {
1171 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1172 "Channel::StartPlayout()");
1173 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001174 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001175 }
1176
solenberge374e012017-02-14 04:55:00 -08001177 // Add participant as candidates for mixing.
1178 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1179 _engineStatisticsPtr->SetLastError(
1180 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1181 "StartPlayout() failed to add participant to mixer");
1182 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001183 }
1184
1185 channel_state_.SetPlaying(true);
1186 if (RegisterFilePlayingToMixer() != 0)
1187 return -1;
1188
1189 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001190}
1191
kwiberg55b97fe2016-01-28 05:22:45 -08001192int32_t Channel::StopPlayout() {
1193 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1194 "Channel::StopPlayout()");
1195 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001196 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001197 }
1198
solenberge374e012017-02-14 04:55:00 -08001199 // Remove participant as candidates for mixing
1200 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1201 _engineStatisticsPtr->SetLastError(
1202 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1203 "StopPlayout() failed to remove participant from mixer");
1204 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001205 }
1206
1207 channel_state_.SetPlaying(false);
1208 _outputAudioLevel.Clear();
1209
1210 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001211}
1212
kwiberg55b97fe2016-01-28 05:22:45 -08001213int32_t Channel::StartSend() {
1214 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1215 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -08001216 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001217 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001218 }
1219 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -07001220 {
1221 // It is now OK to start posting tasks to the encoder task queue.
1222 rtc::CritScope cs(&encoder_queue_lock_);
1223 encoder_queue_is_active_ = true;
1224 }
solenberg08b19df2017-02-15 00:42:31 -08001225 // Resume the previous sequence number which was reset by StopSend(). This
1226 // needs to be done before |sending| is set to true on the RTP/RTCP module.
1227 if (send_sequence_number_) {
1228 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
1229 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001230 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001231 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1232 _engineStatisticsPtr->SetLastError(
1233 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1234 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001235 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001236 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001237 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001238 return -1;
1239 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001240
kwiberg55b97fe2016-01-28 05:22:45 -08001241 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001242}
1243
henrikaec6fbd22017-03-31 05:43:36 -07001244void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -08001245 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1246 "Channel::StopSend()");
1247 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -07001248 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001249 }
1250 channel_state_.SetSending(false);
1251
henrikaec6fbd22017-03-31 05:43:36 -07001252 // Post a task to the encoder thread which sets an event when the task is
1253 // executed. We know that no more encoding tasks will be added to the task
1254 // queue for this channel since sending is now deactivated. It means that,
1255 // if we wait for the event to bet set, we know that no more pending tasks
1256 // exists and it is therfore guaranteed that the task queue will never try
1257 // to acccess and invalid channel object.
1258 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -07001259
henrikaec6fbd22017-03-31 05:43:36 -07001260 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -07001261 {
1262 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
1263 // than this final "flush task" to be posted on the queue.
1264 rtc::CritScope cs(&encoder_queue_lock_);
1265 encoder_queue_is_active_ = false;
1266 encoder_queue_->PostTask([&flush]() { flush.Set(); });
1267 }
henrikaec6fbd22017-03-31 05:43:36 -07001268 flush.Wait(rtc::Event::kForever);
1269
kwiberg55b97fe2016-01-28 05:22:45 -08001270 // Store the sequence number to be able to pick up the same sequence for
1271 // the next StartSend(). This is needed for restarting device, otherwise
1272 // it might cause libSRTP to complain about packets being replayed.
1273 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1274 // CL is landed. See issue
1275 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1276 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1277
1278 // Reset sending SSRC and sequence number and triggers direct transmission
1279 // of RTCP BYE
1280 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1281 _engineStatisticsPtr->SetLastError(
1282 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1283 "StartSend() RTP/RTCP failed to stop sending");
1284 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001285 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001286}
1287
ossu1ffbd6c2017-04-06 12:05:04 -07001288bool Channel::SetEncoder(int payload_type,
1289 std::unique_ptr<AudioEncoder> encoder) {
1290 RTC_DCHECK_GE(payload_type, 0);
1291 RTC_DCHECK_LE(payload_type, 127);
1292 // TODO(ossu): Make a CodecInst up for now. It seems like very little of this
1293 // information is actually used, possibly only payload type and clock rate.
1294 CodecInst lies;
1295 lies.pltype = payload_type;
1296 strncpy(lies.plname, "audio", sizeof(lies.plname));
1297 lies.plname[sizeof(lies.plname) - 1] = 0;
1298 // Seems unclear if it should be clock rate or sample rate. CodecInst
1299 // supposedly carries the sample rate, but only clock rate seems sensible to
1300 // send to the RTP/RTCP module.
1301 lies.plfreq = encoder->RtpTimestampRateHz();
1302 lies.pacsize = 0;
1303 lies.channels = encoder->NumChannels();
1304 lies.rate = 0;
1305
1306 if (_rtpRtcpModule->RegisterSendPayload(lies) != 0) {
1307 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
1308 if (_rtpRtcpModule->RegisterSendPayload(lies) != 0) {
1309 WEBRTC_TRACE(
1310 kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1311 "SetEncoder() failed to register codec to RTP/RTCP module");
1312 return false;
1313 }
1314 }
1315
1316 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -07001317 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -07001318 return true;
1319}
1320
ossu20a4b3f2017-04-27 02:08:52 -07001321void Channel::ModifyEncoder(
1322 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
1323 audio_coding_->ModifyEncoder(modifier);
1324}
1325
kwiberg55b97fe2016-01-28 05:22:45 -08001326int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1327 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1328 "Channel::RegisterVoiceEngineObserver()");
1329 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001330
kwiberg55b97fe2016-01-28 05:22:45 -08001331 if (_voiceEngineObserverPtr) {
1332 _engineStatisticsPtr->SetLastError(
1333 VE_INVALID_OPERATION, kTraceError,
1334 "RegisterVoiceEngineObserver() observer already enabled");
1335 return -1;
1336 }
1337 _voiceEngineObserverPtr = &observer;
1338 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001339}
1340
kwiberg55b97fe2016-01-28 05:22:45 -08001341int32_t Channel::DeRegisterVoiceEngineObserver() {
1342 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1343 "Channel::DeRegisterVoiceEngineObserver()");
1344 rtc::CritScope cs(&_callbackCritSect);
1345
1346 if (!_voiceEngineObserverPtr) {
1347 _engineStatisticsPtr->SetLastError(
1348 VE_INVALID_OPERATION, kTraceWarning,
1349 "DeRegisterVoiceEngineObserver() observer already disabled");
1350 return 0;
1351 }
1352 _voiceEngineObserverPtr = NULL;
1353 return 0;
1354}
1355
1356int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu20a4b3f2017-04-27 02:08:52 -07001357 {
1358 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1359 if (send_codec) {
1360 codec = *send_codec;
1361 return 0;
1362 }
1363 }
1364 rtc::Optional<CodecInst> acm_send_codec = audio_coding_->SendCodec();
1365 if (acm_send_codec) {
1366 codec = *acm_send_codec;
kwiberg1fd4a4a2015-11-03 11:20:50 -08001367 return 0;
1368 }
1369 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001370}
1371
kwiberg55b97fe2016-01-28 05:22:45 -08001372int32_t Channel::GetRecCodec(CodecInst& codec) {
1373 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001374}
1375
kwiberg55b97fe2016-01-28 05:22:45 -08001376int32_t Channel::SetSendCodec(const CodecInst& codec) {
1377 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1378 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001379
kwibergc8d071e2016-04-06 12:22:38 -07001380 if (!codec_manager_.RegisterEncoder(codec) ||
1381 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001382 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1383 "SetSendCodec() failed to register codec to ACM");
1384 return -1;
1385 }
1386
1387 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1388 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1389 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1390 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1391 "SetSendCodec() failed to register codec to"
1392 " RTP/RTCP module");
1393 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001394 }
kwiberg55b97fe2016-01-28 05:22:45 -08001395 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001396
kwiberg55b97fe2016-01-28 05:22:45 -08001397 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001398}
1399
minyue78b4d562016-11-30 04:47:39 -08001400void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001401 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1402 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001403 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001404 if (*encoder) {
1405 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001406 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001407 }
1408 });
michaelt566d8202017-01-12 10:17:38 -08001409 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001410}
1411
elad.alond12a8e12017-03-23 11:04:48 -07001412void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1413 if (!use_twcc_plr_for_ana_)
1414 return;
minyue7e304322016-10-12 05:00:55 -07001415 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001416 if (*encoder) {
1417 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1418 }
1419 });
1420}
1421
elad.alondadb4dc2017-03-23 15:29:50 -07001422void Channel::OnRecoverableUplinkPacketLossRate(
1423 float recoverable_packet_loss_rate) {
1424 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1425 if (*encoder) {
1426 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1427 recoverable_packet_loss_rate);
1428 }
1429 });
1430}
1431
elad.alond12a8e12017-03-23 11:04:48 -07001432void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1433 if (use_twcc_plr_for_ana_)
1434 return;
1435 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1436 if (*encoder) {
1437 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1438 }
minyue7e304322016-10-12 05:00:55 -07001439 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001440}
1441
kwiberg55b97fe2016-01-28 05:22:45 -08001442int32_t Channel::SetVADStatus(bool enableVAD,
1443 ACMVADMode mode,
1444 bool disableDTX) {
1445 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1446 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001447 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1448 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1449 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001450 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1451 kTraceError,
1452 "SetVADStatus() failed to set VAD");
1453 return -1;
1454 }
1455 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001456}
1457
kwiberg55b97fe2016-01-28 05:22:45 -08001458int32_t Channel::GetVADStatus(bool& enabledVAD,
1459 ACMVADMode& mode,
1460 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001461 const auto* params = codec_manager_.GetStackParams();
1462 enabledVAD = params->use_cng;
1463 mode = params->vad_mode;
1464 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001465 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001466}
1467
kwiberg1c07c702017-03-27 07:15:49 -07001468void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1469 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1470 audio_coding_->SetReceiveCodecs(codecs);
1471}
1472
kwiberg55b97fe2016-01-28 05:22:45 -08001473int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
kwibergd32bf752017-01-19 07:03:59 -08001474 return SetRecPayloadType(codec.pltype, CodecInstToSdp(codec));
1475}
1476
1477int32_t Channel::SetRecPayloadType(int payload_type,
1478 const SdpAudioFormat& format) {
kwiberg55b97fe2016-01-28 05:22:45 -08001479 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1480 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001481
kwiberg55b97fe2016-01-28 05:22:45 -08001482 if (channel_state_.Get().playing) {
1483 _engineStatisticsPtr->SetLastError(
1484 VE_ALREADY_PLAYING, kTraceError,
1485 "SetRecPayloadType() unable to set PT while playing");
1486 return -1;
1487 }
kwiberg55b97fe2016-01-28 05:22:45 -08001488
kwiberg09f090c2017-03-01 01:57:11 -08001489 const CodecInst codec = SdpToCodecInst(payload_type, format);
kwibergd32bf752017-01-19 07:03:59 -08001490
1491 if (payload_type == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001492 // De-register the selected codec (RTP/RTCP module and ACM)
1493
1494 int8_t pltype(-1);
1495 CodecInst rxCodec = codec;
1496
1497 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001498 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001499 rxCodec.pltype = pltype;
1500
1501 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1502 _engineStatisticsPtr->SetLastError(
1503 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1504 "SetRecPayloadType() RTP/RTCP-module deregistration "
1505 "failed");
1506 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001507 }
kwiberg55b97fe2016-01-28 05:22:45 -08001508 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1509 _engineStatisticsPtr->SetLastError(
1510 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1511 "SetRecPayloadType() ACM deregistration failed - 1");
1512 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001513 }
kwiberg55b97fe2016-01-28 05:22:45 -08001514 return 0;
1515 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001516
magjed56124bd2016-11-24 09:34:46 -08001517 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001518 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001519 // TODO(kwiberg): Retrying is probably not necessary, since
1520 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001521 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001522 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001523 _engineStatisticsPtr->SetLastError(
1524 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1525 "SetRecPayloadType() RTP/RTCP-module registration failed");
1526 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001527 }
kwiberg55b97fe2016-01-28 05:22:45 -08001528 }
kwibergd32bf752017-01-19 07:03:59 -08001529 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
1530 audio_coding_->UnregisterReceiveCodec(payload_type);
1531 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001532 _engineStatisticsPtr->SetLastError(
1533 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1534 "SetRecPayloadType() ACM registration failed - 1");
1535 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001536 }
kwiberg55b97fe2016-01-28 05:22:45 -08001537 }
1538 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001539}
1540
kwiberg55b97fe2016-01-28 05:22:45 -08001541int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1542 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001543 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001544 _engineStatisticsPtr->SetLastError(
1545 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1546 "GetRecPayloadType() failed to retrieve RX payload type");
1547 return -1;
1548 }
1549 codec.pltype = payloadType;
1550 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001551}
1552
kwiberg55b97fe2016-01-28 05:22:45 -08001553int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1554 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1555 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001556
kwiberg55b97fe2016-01-28 05:22:45 -08001557 CodecInst codec;
1558 int32_t samplingFreqHz(-1);
1559 const size_t kMono = 1;
1560 if (frequency == kFreq32000Hz)
1561 samplingFreqHz = 32000;
1562 else if (frequency == kFreq16000Hz)
1563 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001564
kwiberg55b97fe2016-01-28 05:22:45 -08001565 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1566 _engineStatisticsPtr->SetLastError(
1567 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1568 "SetSendCNPayloadType() failed to retrieve default CN codec "
1569 "settings");
1570 return -1;
1571 }
1572
1573 // Modify the payload type (must be set to dynamic range)
1574 codec.pltype = type;
1575
kwibergc8d071e2016-04-06 12:22:38 -07001576 if (!codec_manager_.RegisterEncoder(codec) ||
1577 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001578 _engineStatisticsPtr->SetLastError(
1579 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1580 "SetSendCNPayloadType() failed to register CN to ACM");
1581 return -1;
1582 }
1583
1584 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1585 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1586 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1587 _engineStatisticsPtr->SetLastError(
1588 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1589 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1590 "module");
1591 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001592 }
kwiberg55b97fe2016-01-28 05:22:45 -08001593 }
1594 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001595}
1596
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001597int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001598 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001599 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001600
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001601 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001602 _engineStatisticsPtr->SetLastError(
1603 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001604 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001605 return -1;
1606 }
1607 return 0;
1608}
1609
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001610int Channel::SetOpusDtx(bool enable_dtx) {
1611 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1612 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001613 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001614 : audio_coding_->DisableOpusDtx();
1615 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001616 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1617 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001618 return -1;
1619 }
1620 return 0;
1621}
1622
ivoc85228d62016-07-27 04:53:47 -07001623int Channel::GetOpusDtx(bool* enabled) {
1624 int success = -1;
1625 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1626 if (encoder) {
1627 *enabled = encoder->GetDtx();
1628 success = 0;
1629 }
1630 });
1631 return success;
1632}
1633
minyue7e304322016-10-12 05:00:55 -07001634bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1635 bool success = false;
1636 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1637 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001638 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1639 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001640 }
1641 });
1642 return success;
1643}
1644
1645void Channel::DisableAudioNetworkAdaptor() {
1646 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1647 if (*encoder)
1648 (*encoder)->DisableAudioNetworkAdaptor();
1649 });
1650}
1651
1652void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1653 int max_frame_length_ms) {
1654 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1655 if (*encoder) {
1656 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1657 max_frame_length_ms);
1658 }
1659 });
1660}
1661
mflodman3d7db262016-04-29 00:57:13 -07001662int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001663 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001664 "Channel::RegisterExternalTransport()");
1665
kwiberg55b97fe2016-01-28 05:22:45 -08001666 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001667 if (_externalTransport) {
1668 _engineStatisticsPtr->SetLastError(
1669 VE_INVALID_OPERATION, kTraceError,
1670 "RegisterExternalTransport() external transport already enabled");
1671 return -1;
1672 }
1673 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001674 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001675 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001676}
1677
kwiberg55b97fe2016-01-28 05:22:45 -08001678int32_t Channel::DeRegisterExternalTransport() {
1679 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1680 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001681
kwiberg55b97fe2016-01-28 05:22:45 -08001682 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001683 if (_transportPtr) {
1684 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1685 "DeRegisterExternalTransport() all transport is disabled");
1686 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001687 _engineStatisticsPtr->SetLastError(
1688 VE_INVALID_OPERATION, kTraceWarning,
1689 "DeRegisterExternalTransport() external transport already "
1690 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001691 }
1692 _externalTransport = false;
1693 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001694 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001695}
1696
nisse657bab22017-02-21 06:28:10 -08001697// TODO(nisse): Delete this method together with ReceivedRTPPacket.
1698// It's a temporary hack to support both ReceivedRTPPacket and
1699// OnRtpPacket interfaces without too much code duplication.
1700bool Channel::OnRtpPacketWithHeader(const uint8_t* received_packet,
1701 size_t length,
1702 RTPHeader *header) {
1703 // Store playout timestamp for the received RTP packet
1704 UpdatePlayoutTimestamp(false);
1705
1706 header->payload_type_frequency =
1707 rtp_payload_registry_->GetPayloadTypeFrequency(header->payloadType);
1708 if (header->payload_type_frequency < 0)
1709 return false;
1710 bool in_order = IsPacketInOrder(*header);
1711 rtp_receive_statistics_->IncomingPacket(
1712 *header, length, IsPacketRetransmitted(*header, in_order));
1713 rtp_payload_registry_->SetIncomingPayloadType(*header);
1714
1715 return ReceivePacket(received_packet, length, *header, in_order);
1716}
1717
mflodman3d7db262016-04-29 00:57:13 -07001718int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001719 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001720 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001721 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001722 "Channel::ReceivedRTPPacket()");
1723
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001724 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001725 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1726 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1727 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001728 return -1;
1729 }
nisse657bab22017-02-21 06:28:10 -08001730 return OnRtpPacketWithHeader(received_packet, length, &header) ? 0 : -1;
1731}
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001732
nisse657bab22017-02-21 06:28:10 -08001733void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1734 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
1735 "Channel::ReceivedRTPPacket()");
1736
1737 RTPHeader header;
1738 packet.GetHeader(&header);
1739 OnRtpPacketWithHeader(packet.data(), packet.size(), &header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001740}
1741
1742bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001743 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001744 const RTPHeader& header,
1745 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001746 if (rtp_payload_registry_->IsRtx(header)) {
1747 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001748 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001749 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001750 assert(packet_length >= header.headerLength);
1751 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001752 PayloadUnion payload_specific;
1753 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001754 &payload_specific)) {
1755 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001756 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001757 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1758 payload_specific, in_order);
1759}
1760
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001761bool Channel::HandleRtxPacket(const uint8_t* packet,
1762 size_t packet_length,
1763 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001764 if (!rtp_payload_registry_->IsRtx(header))
1765 return false;
1766
1767 // Remove the RTX header and parse the original RTP header.
1768 if (packet_length < header.headerLength)
1769 return false;
1770 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1771 return false;
1772 if (restored_packet_in_use_) {
1773 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1774 "Multiple RTX headers detected, dropping packet");
1775 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001776 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001777 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001778 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1779 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001780 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1781 "Incoming RTX packet: invalid RTP header");
1782 return false;
1783 }
1784 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001785 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001786 restored_packet_in_use_ = false;
1787 return ret;
1788}
1789
1790bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1791 StreamStatistician* statistician =
1792 rtp_receive_statistics_->GetStatistician(header.ssrc);
1793 if (!statistician)
1794 return false;
1795 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001796}
1797
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001798bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1799 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001800 // Retransmissions are handled separately if RTX is enabled.
1801 if (rtp_payload_registry_->RtxEnabled())
1802 return false;
1803 StreamStatistician* statistician =
1804 rtp_receive_statistics_->GetStatistician(header.ssrc);
1805 if (!statistician)
1806 return false;
1807 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001808 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001809 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001810 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001811}
1812
mflodman3d7db262016-04-29 00:57:13 -07001813int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001814 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001815 "Channel::ReceivedRTCPPacket()");
1816 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001817 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001818
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001819 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001820 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001821 _engineStatisticsPtr->SetLastError(
1822 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1823 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1824 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001825
Minyue2013aec2015-05-13 14:14:42 +02001826 int64_t rtt = GetRTT(true);
1827 if (rtt == 0) {
1828 // Waiting for valid RTT.
1829 return 0;
1830 }
Erik Språng737336d2016-07-29 12:59:36 +02001831
1832 int64_t nack_window_ms = rtt;
1833 if (nack_window_ms < kMinRetransmissionWindowMs) {
1834 nack_window_ms = kMinRetransmissionWindowMs;
1835 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1836 nack_window_ms = kMaxRetransmissionWindowMs;
1837 }
1838 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1839
minyue7e304322016-10-12 05:00:55 -07001840 // Invoke audio encoders OnReceivedRtt().
1841 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1842 if (*encoder)
1843 (*encoder)->OnReceivedRtt(rtt);
1844 });
1845
Minyue2013aec2015-05-13 14:14:42 +02001846 uint32_t ntp_secs = 0;
1847 uint32_t ntp_frac = 0;
1848 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001849 if (0 !=
1850 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1851 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001852 // Waiting for RTCP.
1853 return 0;
1854 }
1855
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001856 {
tommi31fc21f2016-01-21 10:37:37 -08001857 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001858 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001859 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001860 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001861}
1862
niklase@google.com470e71d2011-07-07 08:21:25 +00001863int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001864 bool loop,
1865 FileFormats format,
1866 int startPosition,
1867 float volumeScaling,
1868 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001869 const CodecInst* codecInst) {
1870 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1871 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1872 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1873 "stopPosition=%d)",
1874 fileName, loop, format, volumeScaling, startPosition,
1875 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001876
kwiberg55b97fe2016-01-28 05:22:45 -08001877 if (channel_state_.Get().output_file_playing) {
1878 _engineStatisticsPtr->SetLastError(
1879 VE_ALREADY_PLAYING, kTraceError,
1880 "StartPlayingFileLocally() is already playing");
1881 return -1;
1882 }
1883
1884 {
1885 rtc::CritScope cs(&_fileCritSect);
1886
kwiberg5a25d952016-08-17 07:31:12 -07001887 if (output_file_player_) {
1888 output_file_player_->RegisterModuleFileCallback(NULL);
1889 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001890 }
1891
kwiberg5b356f42016-09-08 04:32:33 -07001892 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001893 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001894
kwiberg5a25d952016-08-17 07:31:12 -07001895 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001896 _engineStatisticsPtr->SetLastError(
1897 VE_INVALID_ARGUMENT, kTraceError,
1898 "StartPlayingFileLocally() filePlayer format is not correct");
1899 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001900 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001901
kwiberg55b97fe2016-01-28 05:22:45 -08001902 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001903
kwiberg5a25d952016-08-17 07:31:12 -07001904 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001905 fileName, loop, startPosition, volumeScaling, notificationTime,
1906 stopPosition, (const CodecInst*)codecInst) != 0) {
1907 _engineStatisticsPtr->SetLastError(
1908 VE_BAD_FILE, kTraceError,
1909 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001910 output_file_player_->StopPlayingFile();
1911 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001912 return -1;
1913 }
kwiberg5a25d952016-08-17 07:31:12 -07001914 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001915 channel_state_.SetOutputFilePlaying(true);
1916 }
1917
1918 if (RegisterFilePlayingToMixer() != 0)
1919 return -1;
1920
1921 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001922}
1923
1924int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001925 FileFormats format,
1926 int startPosition,
1927 float volumeScaling,
1928 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001929 const CodecInst* codecInst) {
1930 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1931 "Channel::StartPlayingFileLocally(format=%d,"
1932 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1933 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001934
kwiberg55b97fe2016-01-28 05:22:45 -08001935 if (stream == NULL) {
1936 _engineStatisticsPtr->SetLastError(
1937 VE_BAD_FILE, kTraceError,
1938 "StartPlayingFileLocally() NULL as input stream");
1939 return -1;
1940 }
1941
1942 if (channel_state_.Get().output_file_playing) {
1943 _engineStatisticsPtr->SetLastError(
1944 VE_ALREADY_PLAYING, kTraceError,
1945 "StartPlayingFileLocally() is already playing");
1946 return -1;
1947 }
1948
1949 {
1950 rtc::CritScope cs(&_fileCritSect);
1951
1952 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001953 if (output_file_player_) {
1954 output_file_player_->RegisterModuleFileCallback(NULL);
1955 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001956 }
1957
kwiberg55b97fe2016-01-28 05:22:45 -08001958 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001959 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001960 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001961
kwiberg5a25d952016-08-17 07:31:12 -07001962 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001963 _engineStatisticsPtr->SetLastError(
1964 VE_INVALID_ARGUMENT, kTraceError,
1965 "StartPlayingFileLocally() filePlayer format isnot correct");
1966 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001967 }
1968
kwiberg55b97fe2016-01-28 05:22:45 -08001969 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001970
kwiberg4ec01d92016-08-22 08:43:54 -07001971 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001972 volumeScaling, notificationTime,
1973 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001974 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1975 "StartPlayingFile() failed to "
1976 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001977 output_file_player_->StopPlayingFile();
1978 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001979 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001980 }
kwiberg5a25d952016-08-17 07:31:12 -07001981 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001982 channel_state_.SetOutputFilePlaying(true);
1983 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001984
kwiberg55b97fe2016-01-28 05:22:45 -08001985 if (RegisterFilePlayingToMixer() != 0)
1986 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001987
kwiberg55b97fe2016-01-28 05:22:45 -08001988 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001989}
1990
kwiberg55b97fe2016-01-28 05:22:45 -08001991int Channel::StopPlayingFileLocally() {
1992 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1993 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001994
kwiberg55b97fe2016-01-28 05:22:45 -08001995 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001996 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001997 }
1998
1999 {
2000 rtc::CritScope cs(&_fileCritSect);
2001
kwiberg5a25d952016-08-17 07:31:12 -07002002 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002003 _engineStatisticsPtr->SetLastError(
2004 VE_STOP_RECORDING_FAILED, kTraceError,
2005 "StopPlayingFile() could not stop playing");
2006 return -1;
2007 }
kwiberg5a25d952016-08-17 07:31:12 -07002008 output_file_player_->RegisterModuleFileCallback(NULL);
2009 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002010 channel_state_.SetOutputFilePlaying(false);
2011 }
2012 // _fileCritSect cannot be taken while calling
2013 // SetAnonymousMixibilityStatus. Refer to comments in
2014 // StartPlayingFileLocally(const char* ...) for more details.
2015 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
2016 _engineStatisticsPtr->SetLastError(
2017 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
2018 "StopPlayingFile() failed to stop participant from playing as"
2019 "file in the mixer");
2020 return -1;
2021 }
2022
2023 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002024}
2025
kwiberg55b97fe2016-01-28 05:22:45 -08002026int Channel::IsPlayingFileLocally() const {
2027 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002028}
2029
kwiberg55b97fe2016-01-28 05:22:45 -08002030int Channel::RegisterFilePlayingToMixer() {
2031 // Return success for not registering for file playing to mixer if:
2032 // 1. playing file before playout is started on that channel.
2033 // 2. starting playout without file playing on that channel.
2034 if (!channel_state_.Get().playing ||
2035 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00002036 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002037 }
2038
2039 // |_fileCritSect| cannot be taken while calling
2040 // SetAnonymousMixabilityStatus() since as soon as the participant is added
2041 // frames can be pulled by the mixer. Since the frames are generated from
2042 // the file, _fileCritSect will be taken. This would result in a deadlock.
2043 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
2044 channel_state_.SetOutputFilePlaying(false);
2045 rtc::CritScope cs(&_fileCritSect);
2046 _engineStatisticsPtr->SetLastError(
2047 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
2048 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07002049 output_file_player_->StopPlayingFile();
2050 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002051 return -1;
2052 }
2053
2054 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00002055}
2056
niklase@google.com470e71d2011-07-07 08:21:25 +00002057int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002058 bool loop,
2059 FileFormats format,
2060 int startPosition,
2061 float volumeScaling,
2062 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002063 const CodecInst* codecInst) {
2064 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2065 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
2066 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
2067 "stopPosition=%d)",
2068 fileName, loop, format, volumeScaling, startPosition,
2069 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002070
kwiberg55b97fe2016-01-28 05:22:45 -08002071 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002072
kwiberg55b97fe2016-01-28 05:22:45 -08002073 if (channel_state_.Get().input_file_playing) {
2074 _engineStatisticsPtr->SetLastError(
2075 VE_ALREADY_PLAYING, kTraceWarning,
2076 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002077 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002078 }
2079
2080 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002081 if (input_file_player_) {
2082 input_file_player_->RegisterModuleFileCallback(NULL);
2083 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002084 }
2085
2086 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002087 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002088 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002089
kwiberg5a25d952016-08-17 07:31:12 -07002090 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002091 _engineStatisticsPtr->SetLastError(
2092 VE_INVALID_ARGUMENT, kTraceError,
2093 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
2094 return -1;
2095 }
2096
2097 const uint32_t notificationTime(0);
2098
kwiberg5a25d952016-08-17 07:31:12 -07002099 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002100 fileName, loop, startPosition, volumeScaling, notificationTime,
2101 stopPosition, (const CodecInst*)codecInst) != 0) {
2102 _engineStatisticsPtr->SetLastError(
2103 VE_BAD_FILE, kTraceError,
2104 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002105 input_file_player_->StopPlayingFile();
2106 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002107 return -1;
2108 }
kwiberg5a25d952016-08-17 07:31:12 -07002109 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002110 channel_state_.SetInputFilePlaying(true);
2111
2112 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002113}
2114
2115int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002116 FileFormats format,
2117 int startPosition,
2118 float volumeScaling,
2119 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002120 const CodecInst* codecInst) {
2121 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2122 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2123 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2124 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002125
kwiberg55b97fe2016-01-28 05:22:45 -08002126 if (stream == NULL) {
2127 _engineStatisticsPtr->SetLastError(
2128 VE_BAD_FILE, kTraceError,
2129 "StartPlayingFileAsMicrophone NULL as input stream");
2130 return -1;
2131 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002132
kwiberg55b97fe2016-01-28 05:22:45 -08002133 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002134
kwiberg55b97fe2016-01-28 05:22:45 -08002135 if (channel_state_.Get().input_file_playing) {
2136 _engineStatisticsPtr->SetLastError(
2137 VE_ALREADY_PLAYING, kTraceWarning,
2138 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002139 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002140 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002141
kwiberg55b97fe2016-01-28 05:22:45 -08002142 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002143 if (input_file_player_) {
2144 input_file_player_->RegisterModuleFileCallback(NULL);
2145 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002146 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002147
kwiberg55b97fe2016-01-28 05:22:45 -08002148 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002149 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002150 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002151
kwiberg5a25d952016-08-17 07:31:12 -07002152 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002153 _engineStatisticsPtr->SetLastError(
2154 VE_INVALID_ARGUMENT, kTraceError,
2155 "StartPlayingInputFile() filePlayer format isnot correct");
2156 return -1;
2157 }
2158
2159 const uint32_t notificationTime(0);
2160
kwiberg4ec01d92016-08-22 08:43:54 -07002161 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2162 notificationTime, stopPosition,
2163 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002164 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2165 "StartPlayingFile() failed to start "
2166 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002167 input_file_player_->StopPlayingFile();
2168 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002169 return -1;
2170 }
2171
kwiberg5a25d952016-08-17 07:31:12 -07002172 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002173 channel_state_.SetInputFilePlaying(true);
2174
2175 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002176}
2177
kwiberg55b97fe2016-01-28 05:22:45 -08002178int Channel::StopPlayingFileAsMicrophone() {
2179 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2180 "Channel::StopPlayingFileAsMicrophone()");
2181
2182 rtc::CritScope cs(&_fileCritSect);
2183
2184 if (!channel_state_.Get().input_file_playing) {
2185 return 0;
2186 }
2187
kwiberg5a25d952016-08-17 07:31:12 -07002188 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002189 _engineStatisticsPtr->SetLastError(
2190 VE_STOP_RECORDING_FAILED, kTraceError,
2191 "StopPlayingFile() could not stop playing");
2192 return -1;
2193 }
kwiberg5a25d952016-08-17 07:31:12 -07002194 input_file_player_->RegisterModuleFileCallback(NULL);
2195 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002196 channel_state_.SetInputFilePlaying(false);
2197
2198 return 0;
2199}
2200
2201int Channel::IsPlayingFileAsMicrophone() const {
2202 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002203}
2204
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002205int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002206 const CodecInst* codecInst) {
2207 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2208 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002209
kwiberg55b97fe2016-01-28 05:22:45 -08002210 if (_outputFileRecording) {
2211 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2212 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002213 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002214 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002215
kwiberg55b97fe2016-01-28 05:22:45 -08002216 FileFormats format;
2217 const uint32_t notificationTime(0); // Not supported in VoE
2218 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002219
kwiberg55b97fe2016-01-28 05:22:45 -08002220 if ((codecInst != NULL) &&
2221 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2222 _engineStatisticsPtr->SetLastError(
2223 VE_BAD_ARGUMENT, kTraceError,
2224 "StartRecordingPlayout() invalid compression");
2225 return (-1);
2226 }
2227 if (codecInst == NULL) {
2228 format = kFileFormatPcm16kHzFile;
2229 codecInst = &dummyCodec;
2230 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2231 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2232 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2233 format = kFileFormatWavFile;
2234 } else {
2235 format = kFileFormatCompressedFile;
2236 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002237
kwiberg55b97fe2016-01-28 05:22:45 -08002238 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002239
kwiberg55b97fe2016-01-28 05:22:45 -08002240 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002241 if (output_file_recorder_) {
2242 output_file_recorder_->RegisterModuleFileCallback(NULL);
2243 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002244 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002245
kwiberg5a25d952016-08-17 07:31:12 -07002246 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002247 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002248 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002249 _engineStatisticsPtr->SetLastError(
2250 VE_INVALID_ARGUMENT, kTraceError,
2251 "StartRecordingPlayout() fileRecorder format isnot correct");
2252 return -1;
2253 }
2254
kwiberg5a25d952016-08-17 07:31:12 -07002255 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002256 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2257 _engineStatisticsPtr->SetLastError(
2258 VE_BAD_FILE, kTraceError,
2259 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002260 output_file_recorder_->StopRecording();
2261 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002262 return -1;
2263 }
kwiberg5a25d952016-08-17 07:31:12 -07002264 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002265 _outputFileRecording = true;
2266
2267 return 0;
2268}
2269
2270int Channel::StartRecordingPlayout(OutStream* stream,
2271 const CodecInst* codecInst) {
2272 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2273 "Channel::StartRecordingPlayout()");
2274
2275 if (_outputFileRecording) {
2276 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2277 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002278 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002279 }
2280
2281 FileFormats format;
2282 const uint32_t notificationTime(0); // Not supported in VoE
2283 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2284
2285 if (codecInst != NULL && codecInst->channels != 1) {
2286 _engineStatisticsPtr->SetLastError(
2287 VE_BAD_ARGUMENT, kTraceError,
2288 "StartRecordingPlayout() invalid compression");
2289 return (-1);
2290 }
2291 if (codecInst == NULL) {
2292 format = kFileFormatPcm16kHzFile;
2293 codecInst = &dummyCodec;
2294 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2295 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2296 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2297 format = kFileFormatWavFile;
2298 } else {
2299 format = kFileFormatCompressedFile;
2300 }
2301
2302 rtc::CritScope cs(&_fileCritSect);
2303
2304 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002305 if (output_file_recorder_) {
2306 output_file_recorder_->RegisterModuleFileCallback(NULL);
2307 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002308 }
2309
kwiberg5a25d952016-08-17 07:31:12 -07002310 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002311 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002312 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002313 _engineStatisticsPtr->SetLastError(
2314 VE_INVALID_ARGUMENT, kTraceError,
2315 "StartRecordingPlayout() fileRecorder format isnot correct");
2316 return -1;
2317 }
2318
kwiberg4ec01d92016-08-22 08:43:54 -07002319 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002320 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002321 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2322 "StartRecordingPlayout() failed to "
2323 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002324 output_file_recorder_->StopRecording();
2325 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002326 return -1;
2327 }
2328
kwiberg5a25d952016-08-17 07:31:12 -07002329 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002330 _outputFileRecording = true;
2331
2332 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002333}
2334
kwiberg55b97fe2016-01-28 05:22:45 -08002335int Channel::StopRecordingPlayout() {
2336 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2337 "Channel::StopRecordingPlayout()");
2338
2339 if (!_outputFileRecording) {
2340 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2341 "StopRecordingPlayout() isnot recording");
2342 return -1;
2343 }
2344
2345 rtc::CritScope cs(&_fileCritSect);
2346
kwiberg5a25d952016-08-17 07:31:12 -07002347 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002348 _engineStatisticsPtr->SetLastError(
2349 VE_STOP_RECORDING_FAILED, kTraceError,
2350 "StopRecording() could not stop recording");
2351 return (-1);
2352 }
kwiberg5a25d952016-08-17 07:31:12 -07002353 output_file_recorder_->RegisterModuleFileCallback(NULL);
2354 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002355 _outputFileRecording = false;
2356
2357 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002358}
2359
kwiberg55b97fe2016-01-28 05:22:45 -08002360void Channel::SetMixWithMicStatus(bool mix) {
2361 rtc::CritScope cs(&_fileCritSect);
2362 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002363}
2364
solenberg8d73f8c2017-03-08 01:52:20 -08002365int Channel::GetSpeechOutputLevel() const {
2366 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002367}
2368
solenberg8d73f8c2017-03-08 01:52:20 -08002369int Channel::GetSpeechOutputLevelFullRange() const {
2370 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08002371}
2372
solenberg8d73f8c2017-03-08 01:52:20 -08002373void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002374 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002375 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002376}
2377
solenberg1c2af8e2016-03-24 10:36:00 -07002378bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002379 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002380 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002381}
2382
solenberg8d73f8c2017-03-08 01:52:20 -08002383void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08002384 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08002385 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00002386}
2387
solenberg8842c3e2016-03-11 03:06:41 -08002388int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002389 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002390 "Channel::SendTelephoneEventOutband(...)");
2391 RTC_DCHECK_LE(0, event);
2392 RTC_DCHECK_GE(255, event);
2393 RTC_DCHECK_LE(0, duration_ms);
2394 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002395 if (!Sending()) {
2396 return -1;
2397 }
solenberg8842c3e2016-03-11 03:06:41 -08002398 if (_rtpRtcpModule->SendTelephoneEventOutband(
2399 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002400 _engineStatisticsPtr->SetLastError(
2401 VE_SEND_DTMF_FAILED, kTraceWarning,
2402 "SendTelephoneEventOutband() failed to send event");
2403 return -1;
2404 }
2405 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002406}
2407
solenbergffbbcac2016-11-17 05:25:37 -08002408int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2409 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002410 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002411 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002412 RTC_DCHECK_LE(0, payload_type);
2413 RTC_DCHECK_GE(127, payload_type);
2414 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002415 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002416 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002417 memcpy(codec.plname, "telephone-event", 16);
2418 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2419 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2420 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2421 _engineStatisticsPtr->SetLastError(
2422 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2423 "SetSendTelephoneEventPayloadType() failed to register send"
2424 "payload type");
2425 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002426 }
kwiberg55b97fe2016-01-28 05:22:45 -08002427 }
kwiberg55b97fe2016-01-28 05:22:45 -08002428 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002429}
2430
kwiberg55b97fe2016-01-28 05:22:45 -08002431int Channel::SetLocalSSRC(unsigned int ssrc) {
2432 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2433 "Channel::SetLocalSSRC()");
2434 if (channel_state_.Get().sending) {
2435 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2436 "SetLocalSSRC() already sending");
2437 return -1;
2438 }
2439 _rtpRtcpModule->SetSSRC(ssrc);
2440 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002441}
2442
kwiberg55b97fe2016-01-28 05:22:45 -08002443int Channel::GetLocalSSRC(unsigned int& ssrc) {
2444 ssrc = _rtpRtcpModule->SSRC();
2445 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002446}
2447
kwiberg55b97fe2016-01-28 05:22:45 -08002448int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2449 ssrc = rtp_receiver_->SSRC();
2450 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002451}
2452
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002453int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002454 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002455 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002456}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002457
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002458int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2459 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002460 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2461 if (enable &&
2462 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2463 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002464 return -1;
2465 }
2466 return 0;
2467}
2468
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002469void Channel::EnableSendTransportSequenceNumber(int id) {
2470 int ret =
2471 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2472 RTC_DCHECK_EQ(0, ret);
2473}
2474
stefan3313ec92016-01-21 06:32:43 -08002475void Channel::EnableReceiveTransportSequenceNumber(int id) {
2476 rtp_header_parser_->DeregisterRtpHeaderExtension(
2477 kRtpExtensionTransportSequenceNumber);
2478 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2479 kRtpExtensionTransportSequenceNumber, id);
2480 RTC_DCHECK(ret);
2481}
2482
stefanbba9dec2016-02-01 04:39:55 -08002483void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07002484 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08002485 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07002486 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
2487 TransportFeedbackObserver* transport_feedback_observer =
2488 transport->transport_feedback_observer();
2489 PacketRouter* packet_router = transport->packet_router();
2490
stefanbba9dec2016-02-01 04:39:55 -08002491 RTC_DCHECK(rtp_packet_sender);
2492 RTC_DCHECK(transport_feedback_observer);
2493 RTC_DCHECK(packet_router && !packet_router_);
stefan7de8d642017-02-07 07:14:08 -08002494 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08002495 feedback_observer_proxy_->SetTransportFeedbackObserver(
2496 transport_feedback_observer);
2497 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2498 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2499 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
nissefdbfdc92017-03-31 05:44:52 -07002500 packet_router->AddSendRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002501 packet_router_ = packet_router;
2502}
2503
stefanbba9dec2016-02-01 04:39:55 -08002504void Channel::RegisterReceiverCongestionControlObjects(
2505 PacketRouter* packet_router) {
2506 RTC_DCHECK(packet_router && !packet_router_);
nissefdbfdc92017-03-31 05:44:52 -07002507 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002508 packet_router_ = packet_router;
2509}
2510
nissefdbfdc92017-03-31 05:44:52 -07002511void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08002512 RTC_DCHECK(packet_router_);
2513 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08002514 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08002515 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2516 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07002517 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002518 packet_router_ = nullptr;
2519 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2520}
2521
nissefdbfdc92017-03-31 05:44:52 -07002522void Channel::ResetReceiverCongestionControlObjects() {
2523 RTC_DCHECK(packet_router_);
2524 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
2525 packet_router_ = nullptr;
2526}
2527
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002528void Channel::SetRTCPStatus(bool enable) {
2529 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2530 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002531 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002532}
2533
kwiberg55b97fe2016-01-28 05:22:45 -08002534int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002535 RtcpMode method = _rtpRtcpModule->RTCP();
2536 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002537 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002538}
2539
kwiberg55b97fe2016-01-28 05:22:45 -08002540int Channel::SetRTCP_CNAME(const char cName[256]) {
2541 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2542 "Channel::SetRTCP_CNAME()");
2543 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2544 _engineStatisticsPtr->SetLastError(
2545 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2546 "SetRTCP_CNAME() failed to set RTCP CNAME");
2547 return -1;
2548 }
2549 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002550}
2551
kwiberg55b97fe2016-01-28 05:22:45 -08002552int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2553 if (cName == NULL) {
2554 _engineStatisticsPtr->SetLastError(
2555 VE_INVALID_ARGUMENT, kTraceError,
2556 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2557 return -1;
2558 }
2559 char cname[RTCP_CNAME_SIZE];
2560 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2561 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2562 _engineStatisticsPtr->SetLastError(
2563 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2564 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2565 return -1;
2566 }
2567 strcpy(cName, cname);
2568 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002569}
2570
kwiberg55b97fe2016-01-28 05:22:45 -08002571int Channel::SendApplicationDefinedRTCPPacket(
2572 unsigned char subType,
2573 unsigned int name,
2574 const char* data,
2575 unsigned short dataLengthInBytes) {
2576 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2577 "Channel::SendApplicationDefinedRTCPPacket()");
2578 if (!channel_state_.Get().sending) {
2579 _engineStatisticsPtr->SetLastError(
2580 VE_NOT_SENDING, kTraceError,
2581 "SendApplicationDefinedRTCPPacket() not sending");
2582 return -1;
2583 }
2584 if (NULL == data) {
2585 _engineStatisticsPtr->SetLastError(
2586 VE_INVALID_ARGUMENT, kTraceError,
2587 "SendApplicationDefinedRTCPPacket() invalid data value");
2588 return -1;
2589 }
2590 if (dataLengthInBytes % 4 != 0) {
2591 _engineStatisticsPtr->SetLastError(
2592 VE_INVALID_ARGUMENT, kTraceError,
2593 "SendApplicationDefinedRTCPPacket() invalid length value");
2594 return -1;
2595 }
2596 RtcpMode status = _rtpRtcpModule->RTCP();
2597 if (status == RtcpMode::kOff) {
2598 _engineStatisticsPtr->SetLastError(
2599 VE_RTCP_ERROR, kTraceError,
2600 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2601 return -1;
2602 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002603
kwiberg55b97fe2016-01-28 05:22:45 -08002604 // Create and schedule the RTCP APP packet for transmission
2605 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2606 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2607 _engineStatisticsPtr->SetLastError(
2608 VE_SEND_ERROR, kTraceError,
2609 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2610 return -1;
2611 }
2612 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002613}
2614
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002615int Channel::GetRemoteRTCPReportBlocks(
2616 std::vector<ReportBlock>* report_blocks) {
2617 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002618 _engineStatisticsPtr->SetLastError(
2619 VE_INVALID_ARGUMENT, kTraceError,
2620 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002621 return -1;
2622 }
2623
2624 // Get the report blocks from the latest received RTCP Sender or Receiver
2625 // Report. Each element in the vector contains the sender's SSRC and a
2626 // report block according to RFC 3550.
2627 std::vector<RTCPReportBlock> rtcp_report_blocks;
2628 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002629 return -1;
2630 }
2631
2632 if (rtcp_report_blocks.empty())
2633 return 0;
2634
2635 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2636 for (; it != rtcp_report_blocks.end(); ++it) {
2637 ReportBlock report_block;
2638 report_block.sender_SSRC = it->remoteSSRC;
2639 report_block.source_SSRC = it->sourceSSRC;
2640 report_block.fraction_lost = it->fractionLost;
2641 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2642 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2643 report_block.interarrival_jitter = it->jitter;
2644 report_block.last_SR_timestamp = it->lastSR;
2645 report_block.delay_since_last_SR = it->delaySinceLastSR;
2646 report_blocks->push_back(report_block);
2647 }
2648 return 0;
2649}
2650
kwiberg55b97fe2016-01-28 05:22:45 -08002651int Channel::GetRTPStatistics(CallStatistics& stats) {
2652 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002653
kwiberg55b97fe2016-01-28 05:22:45 -08002654 // The jitter statistics is updated for each received RTP packet and is
2655 // based on received packets.
2656 RtcpStatistics statistics;
2657 StreamStatistician* statistician =
2658 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002659 if (statistician) {
2660 statistician->GetStatistics(&statistics,
2661 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002662 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002663
kwiberg55b97fe2016-01-28 05:22:45 -08002664 stats.fractionLost = statistics.fraction_lost;
2665 stats.cumulativeLost = statistics.cumulative_lost;
2666 stats.extendedMax = statistics.extended_max_sequence_number;
2667 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002668
kwiberg55b97fe2016-01-28 05:22:45 -08002669 // --- RTT
2670 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002671
kwiberg55b97fe2016-01-28 05:22:45 -08002672 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002673
kwiberg55b97fe2016-01-28 05:22:45 -08002674 size_t bytesSent(0);
2675 uint32_t packetsSent(0);
2676 size_t bytesReceived(0);
2677 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002678
kwiberg55b97fe2016-01-28 05:22:45 -08002679 if (statistician) {
2680 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2681 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002682
kwiberg55b97fe2016-01-28 05:22:45 -08002683 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2684 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2685 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2686 " output will not be complete");
2687 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002688
kwiberg55b97fe2016-01-28 05:22:45 -08002689 stats.bytesSent = bytesSent;
2690 stats.packetsSent = packetsSent;
2691 stats.bytesReceived = bytesReceived;
2692 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002693
kwiberg55b97fe2016-01-28 05:22:45 -08002694 // --- Timestamps
2695 {
2696 rtc::CritScope lock(&ts_stats_lock_);
2697 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2698 }
2699 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002700}
2701
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002702int Channel::SetCodecFECStatus(bool enable) {
2703 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2704 "Channel::SetCodecFECStatus()");
2705
kwibergc8d071e2016-04-06 12:22:38 -07002706 if (!codec_manager_.SetCodecFEC(enable) ||
2707 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002708 _engineStatisticsPtr->SetLastError(
2709 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2710 "SetCodecFECStatus() failed to set FEC state");
2711 return -1;
2712 }
2713 return 0;
2714}
2715
2716bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002717 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002718}
2719
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002720void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2721 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002722 // If pacing is enabled we always store packets.
2723 if (!pacing_enabled_)
2724 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002725 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002726 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002727 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002728 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002729 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002730}
2731
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002732// Called when we are missing one or more packets.
2733int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002734 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2735}
2736
henrikaec6fbd22017-03-31 05:43:36 -07002737void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07002738 // Avoid posting any new tasks if sending was already stopped in StopSend().
2739 rtc::CritScope cs(&encoder_queue_lock_);
2740 if (!encoder_queue_is_active_) {
2741 return;
2742 }
henrikaec6fbd22017-03-31 05:43:36 -07002743 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
2744 // TODO(henrika): try to avoid copying by moving ownership of audio frame
2745 // either into pool of frames or into the task itself.
2746 audio_frame->CopyFrom(audio_input);
2747 audio_frame->id_ = ChannelId();
2748 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
2749 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00002750}
2751
henrikaec6fbd22017-03-31 05:43:36 -07002752void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
2753 int sample_rate,
2754 size_t number_of_frames,
2755 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07002756 // Avoid posting as new task if sending was already stopped in StopSend().
2757 rtc::CritScope cs(&encoder_queue_lock_);
2758 if (!encoder_queue_is_active_) {
2759 return;
2760 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002761 CodecInst codec;
2762 GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07002763 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
2764 audio_frame->id_ = ChannelId();
2765 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2766 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002767 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07002768 sample_rate, &input_resampler_, audio_frame.get());
2769 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
2770 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002771}
2772
henrikaec6fbd22017-03-31 05:43:36 -07002773void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
2774 RTC_DCHECK_RUN_ON(encoder_queue_);
2775 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
2776 RTC_DCHECK_LE(audio_input->num_channels_, 2);
2777 RTC_DCHECK_EQ(audio_input->id_, ChannelId());
kwiberg55b97fe2016-01-28 05:22:45 -08002778
2779 if (channel_state_.Get().input_file_playing) {
henrikaec6fbd22017-03-31 05:43:36 -07002780 MixOrReplaceAudioWithFile(audio_input);
kwiberg55b97fe2016-01-28 05:22:45 -08002781 }
2782
henrikaec6fbd22017-03-31 05:43:36 -07002783 bool is_muted = InputMute();
2784 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002785
kwiberg55b97fe2016-01-28 05:22:45 -08002786 if (_includeAudioLevelIndication) {
2787 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07002788 audio_input->samples_per_channel_ * audio_input->num_channels_;
2789 RTC_CHECK_LE(length, sizeof(audio_input->data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002790 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002791 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002792 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002793 rms_level_.Analyze(
henrikaec6fbd22017-03-31 05:43:36 -07002794 rtc::ArrayView<const int16_t>(audio_input->data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002795 }
kwiberg55b97fe2016-01-28 05:22:45 -08002796 }
solenberg1c2af8e2016-03-24 10:36:00 -07002797 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002798
henrikaec6fbd22017-03-31 05:43:36 -07002799 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002800
kwiberg55b97fe2016-01-28 05:22:45 -08002801 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07002802 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08002803 // This call will trigger AudioPacketizationCallback::SendData if encoding
2804 // is done and payload is ready for packetization and transmission.
2805 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07002806 if (audio_coding_->Add10MsData(*audio_input) < 0) {
2807 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
2808 return;
kwiberg55b97fe2016-01-28 05:22:45 -08002809 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002810
henrikaec6fbd22017-03-31 05:43:36 -07002811 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00002812}
2813
solenberg7602aab2016-11-14 11:30:07 -08002814void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2815 RTC_DCHECK(!channel.channel() ||
2816 channel.channel()->ChannelId() != _channelId);
2817 rtc::CritScope lock(&assoc_send_channel_lock_);
2818 associate_send_channel_ = channel;
2819}
2820
Minyue2013aec2015-05-13 14:14:42 +02002821void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002822 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002823 Channel* channel = associate_send_channel_.channel();
2824 if (channel && channel->ChannelId() == channel_id) {
2825 // If this channel is associated with a send channel of the specified
2826 // Channel ID, disassociate with it.
2827 ChannelOwner ref(NULL);
2828 associate_send_channel_ = ref;
2829 }
2830}
2831
ivoc14d5dbe2016-07-04 07:06:55 -07002832void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2833 event_log_proxy_->SetEventLog(event_log);
2834}
2835
michaelt9332b7d2016-11-30 07:51:13 -08002836void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2837 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2838}
2839
nisse284542b2017-01-10 08:58:32 -08002840void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08002841 size_t overhead_per_packet =
2842 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08002843 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2844 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08002845 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08002846 }
2847 });
2848}
2849
2850void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002851 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002852 transport_overhead_per_packet_ = transport_overhead_per_packet;
2853 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08002854}
2855
hbos3fd31fe2017-02-28 05:43:16 -08002856// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08002857void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002858 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002859 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
2860 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08002861}
2862
kwiberg55b97fe2016-01-28 05:22:45 -08002863int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2864 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002865}
2866
wu@webrtc.org24301a62013-12-13 19:17:43 +00002867void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2868 audio_coding_->GetDecodingCallStatistics(stats);
2869}
2870
solenberg358057b2015-11-27 10:46:42 -08002871uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08002872 rtc::CritScope lock(&video_sync_lock_);
2873 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07002874}
2875
kwiberg55b97fe2016-01-28 05:22:45 -08002876int Channel::SetMinimumPlayoutDelay(int delayMs) {
2877 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2878 "Channel::SetMinimumPlayoutDelay()");
2879 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
2880 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
2881 _engineStatisticsPtr->SetLastError(
2882 VE_INVALID_ARGUMENT, kTraceError,
2883 "SetMinimumPlayoutDelay() invalid min delay");
2884 return -1;
2885 }
2886 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
2887 _engineStatisticsPtr->SetLastError(
2888 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2889 "SetMinimumPlayoutDelay() failed to set min playout delay");
2890 return -1;
2891 }
2892 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002893}
2894
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002895int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07002896 uint32_t playout_timestamp_rtp = 0;
2897 {
tommi31fc21f2016-01-21 10:37:37 -08002898 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07002899 playout_timestamp_rtp = playout_timestamp_rtp_;
2900 }
kwiberg55b97fe2016-01-28 05:22:45 -08002901 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002902 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07002903 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002904 "GetPlayoutTimestamp() failed to retrieve timestamp");
2905 return -1;
2906 }
deadbeef74375882015-08-13 12:09:10 -07002907 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002908 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002909}
2910
kwiberg55b97fe2016-01-28 05:22:45 -08002911int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
2912 RtpReceiver** rtp_receiver) const {
2913 *rtpRtcpModule = _rtpRtcpModule.get();
2914 *rtp_receiver = rtp_receiver_.get();
2915 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002916}
2917
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00002918// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
2919// a shared helper.
henrikaec6fbd22017-03-31 05:43:36 -07002920int32_t Channel::MixOrReplaceAudioWithFile(AudioFrame* audio_input) {
2921 RTC_DCHECK_RUN_ON(encoder_queue_);
kwibergb7f89d62016-02-17 10:04:18 -08002922 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08002923 size_t fileSamples(0);
henrikaec6fbd22017-03-31 05:43:36 -07002924 const int mixingFrequency = audio_input->sample_rate_hz_;
kwiberg55b97fe2016-01-28 05:22:45 -08002925 {
2926 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002927
kwiberg5a25d952016-08-17 07:31:12 -07002928 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002929 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2930 "Channel::MixOrReplaceAudioWithFile() fileplayer"
2931 " doesnt exist");
2932 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002933 }
2934
kwiberg4ec01d92016-08-22 08:43:54 -07002935 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07002936 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002937 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2938 "Channel::MixOrReplaceAudioWithFile() file mixing "
2939 "failed");
2940 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002941 }
kwiberg55b97fe2016-01-28 05:22:45 -08002942 if (fileSamples == 0) {
2943 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2944 "Channel::MixOrReplaceAudioWithFile() file is ended");
2945 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002946 }
kwiberg55b97fe2016-01-28 05:22:45 -08002947 }
2948
henrikaec6fbd22017-03-31 05:43:36 -07002949 RTC_DCHECK_EQ(audio_input->samples_per_channel_, fileSamples);
kwiberg55b97fe2016-01-28 05:22:45 -08002950
2951 if (_mixFileWithMicrophone) {
2952 // Currently file stream is always mono.
2953 // TODO(xians): Change the code when FilePlayer supports real stereo.
henrikaec6fbd22017-03-31 05:43:36 -07002954 MixWithSat(audio_input->data_, audio_input->num_channels_, fileBuffer.get(),
kwiberg55b97fe2016-01-28 05:22:45 -08002955 1, fileSamples);
2956 } else {
2957 // Replace ACM audio with file.
2958 // Currently file stream is always mono.
2959 // TODO(xians): Change the code when FilePlayer supports real stereo.
henrikaec6fbd22017-03-31 05:43:36 -07002960 audio_input->UpdateFrame(
kwiberg55b97fe2016-01-28 05:22:45 -08002961 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
2962 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
2963 }
2964 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002965}
2966
kwiberg55b97fe2016-01-28 05:22:45 -08002967int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
2968 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00002969
kwibergb7f89d62016-02-17 10:04:18 -08002970 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08002971 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002972
kwiberg55b97fe2016-01-28 05:22:45 -08002973 {
2974 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002975
kwiberg5a25d952016-08-17 07:31:12 -07002976 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002977 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2978 "Channel::MixAudioWithFile() file mixing failed");
2979 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002980 }
2981
kwiberg55b97fe2016-01-28 05:22:45 -08002982 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07002983 if (output_file_player_->Get10msAudioFromFile(
2984 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002985 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2986 "Channel::MixAudioWithFile() file mixing failed");
2987 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002988 }
kwiberg55b97fe2016-01-28 05:22:45 -08002989 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002990
kwiberg55b97fe2016-01-28 05:22:45 -08002991 if (audioFrame.samples_per_channel_ == fileSamples) {
2992 // Currently file stream is always mono.
2993 // TODO(xians): Change the code when FilePlayer supports real stereo.
2994 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
2995 fileSamples);
2996 } else {
2997 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2998 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
2999 ") != "
3000 "fileSamples(%" PRIuS ")",
3001 audioFrame.samples_per_channel_, fileSamples);
3002 return -1;
3003 }
3004
3005 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003006}
3007
deadbeef74375882015-08-13 12:09:10 -07003008void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003009 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003010
henrik.lundin96bd5022016-04-06 04:13:56 -07003011 if (!jitter_buffer_playout_timestamp_) {
3012 // This can happen if this channel has not received any RTP packets. In
3013 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003014 return;
3015 }
3016
3017 uint16_t delay_ms = 0;
3018 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003019 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003020 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3021 " delay from the ADM");
3022 _engineStatisticsPtr->SetLastError(
3023 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3024 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3025 return;
3026 }
3027
henrik.lundin96bd5022016-04-06 04:13:56 -07003028 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3029 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003030
3031 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07003032 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003033
kwiberg55b97fe2016-01-28 05:22:45 -08003034 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003035 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003036 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003037
3038 {
tommi31fc21f2016-01-21 10:37:37 -08003039 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08003040 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003041 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003042 }
3043 playout_delay_ms_ = delay_ms;
3044 }
3045}
3046
kwiberg55b97fe2016-01-28 05:22:45 -08003047void Channel::RegisterReceiveCodecsToRTPModule() {
3048 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3049 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003050
kwiberg55b97fe2016-01-28 05:22:45 -08003051 CodecInst codec;
3052 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003053
kwiberg55b97fe2016-01-28 05:22:45 -08003054 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3055 // Open up the RTP/RTCP receiver for all supported codecs
3056 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08003057 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08003058 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3059 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3060 " to register %s (%d/%d/%" PRIuS
3061 "/%d) to RTP/RTCP "
3062 "receiver",
3063 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3064 codec.rate);
3065 } else {
3066 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3067 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3068 "(%d/%d/%" PRIuS
3069 "/%d) has been added to the RTP/RTCP "
3070 "receiver",
3071 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3072 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003073 }
kwiberg55b97fe2016-01-28 05:22:45 -08003074 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003075}
3076
kwiberg55b97fe2016-01-28 05:22:45 -08003077int Channel::SetSendRtpHeaderExtension(bool enable,
3078 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003079 unsigned char id) {
3080 int error = 0;
3081 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3082 if (enable) {
3083 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3084 }
3085 return error;
3086}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003087
ossue280cde2016-10-12 11:04:10 -07003088int Channel::GetRtpTimestampRateHz() const {
3089 const auto format = audio_coding_->ReceiveFormat();
3090 // Default to the playout frequency if we've not gotten any packets yet.
3091 // TODO(ossu): Zero clockrate can only happen if we've added an external
3092 // decoder for a format we don't support internally. Remove once that way of
3093 // adding decoders is gone!
3094 return (format && format->clockrate_hz != 0)
3095 ? format->clockrate_hz
3096 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00003097}
3098
Minyue2013aec2015-05-13 14:14:42 +02003099int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003100 RtcpMode method = _rtpRtcpModule->RTCP();
3101 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003102 return 0;
3103 }
3104 std::vector<RTCPReportBlock> report_blocks;
3105 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003106
3107 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003108 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003109 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003110 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003111 Channel* channel = associate_send_channel_.channel();
3112 // Tries to get RTT from an associated channel. This is important for
3113 // receive-only channels.
3114 if (channel) {
3115 // To prevent infinite recursion and deadlock, calling GetRTT of
3116 // associate channel should always use "false" for argument:
3117 // |allow_associate_channel|.
3118 rtt = channel->GetRTT(false);
3119 }
3120 }
3121 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003122 }
3123
3124 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3125 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3126 for (; it != report_blocks.end(); ++it) {
3127 if (it->remoteSSRC == remoteSSRC)
3128 break;
3129 }
3130 if (it == report_blocks.end()) {
3131 // We have not received packets with SSRC matching the report blocks.
3132 // To calculate RTT we try with the SSRC of the first report block.
3133 // This is very important for send-only channels where we don't know
3134 // the SSRC of the other end.
3135 remoteSSRC = report_blocks[0].remoteSSRC;
3136 }
Minyue2013aec2015-05-13 14:14:42 +02003137
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003138 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003139 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003140 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003141 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3142 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003143 return 0;
3144 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003145 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003146}
3147
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003148} // namespace voe
3149} // namespace webrtc