blob: bf7d30ca43d9f20b61b82960d05d967ff487de8b [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(
perkj09e71da2017-05-22 03:26:49 -070079 const webrtc::rtclog::StreamConfig&) override {
80 RTC_NOTREACHED();
ivoc14d5dbe2016-07-04 07:06:55 -070081 }
82
perkjc0876aa2017-05-22 04:08:28 -070083 void LogVideoSendStreamConfig(const webrtc::rtclog::StreamConfig&) override {
84 RTC_NOTREACHED();
ivoc14d5dbe2016-07-04 07:06:55 -070085 }
86
ivoce0928d82016-10-10 05:12:51 -070087 void LogAudioReceiveStreamConfig(
perkjac8f52d2017-05-22 09:36:28 -070088 const webrtc::rtclog::StreamConfig& config) override {
ivoce0928d82016-10-10 05:12:51 -070089 rtc::CritScope lock(&crit_);
90 if (event_log_) {
91 event_log_->LogAudioReceiveStreamConfig(config);
92 }
93 }
94
95 void LogAudioSendStreamConfig(
perkjf4726992017-05-22 10:12:26 -070096 const webrtc::rtclog::StreamConfig& config) override {
ivoce0928d82016-10-10 05:12:51 -070097 rtc::CritScope lock(&crit_);
98 if (event_log_) {
99 event_log_->LogAudioSendStreamConfig(config);
100 }
101 }
102
ivoc14d5dbe2016-07-04 07:06:55 -0700103 void LogRtpHeader(webrtc::PacketDirection direction,
104 webrtc::MediaType media_type,
105 const uint8_t* header,
106 size_t packet_length) override {
philipel32d00102017-02-27 02:18:46 -0800107 LogRtpHeader(direction, media_type, header, packet_length,
108 PacedPacketInfo::kNotAProbe);
109 }
110
111 void LogRtpHeader(webrtc::PacketDirection direction,
112 webrtc::MediaType media_type,
113 const uint8_t* header,
114 size_t packet_length,
115 int probe_cluster_id) override {
ivoc14d5dbe2016-07-04 07:06:55 -0700116 rtc::CritScope lock(&crit_);
117 if (event_log_) {
philipel32d00102017-02-27 02:18:46 -0800118 event_log_->LogRtpHeader(direction, media_type, header, packet_length,
119 probe_cluster_id);
ivoc14d5dbe2016-07-04 07:06:55 -0700120 }
121 }
122
123 void LogRtcpPacket(webrtc::PacketDirection direction,
124 webrtc::MediaType media_type,
125 const uint8_t* packet,
126 size_t length) override {
127 rtc::CritScope lock(&crit_);
128 if (event_log_) {
129 event_log_->LogRtcpPacket(direction, media_type, packet, length);
130 }
131 }
132
133 void LogAudioPlayout(uint32_t ssrc) override {
134 rtc::CritScope lock(&crit_);
135 if (event_log_) {
136 event_log_->LogAudioPlayout(ssrc);
137 }
138 }
139
terelius424e6cf2017-02-20 05:14:41 -0800140 void LogLossBasedBweUpdate(int32_t bitrate_bps,
ivoc14d5dbe2016-07-04 07:06:55 -0700141 uint8_t fraction_loss,
142 int32_t total_packets) override {
143 rtc::CritScope lock(&crit_);
144 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800145 event_log_->LogLossBasedBweUpdate(bitrate_bps, fraction_loss,
146 total_packets);
ivoc14d5dbe2016-07-04 07:06:55 -0700147 }
148 }
149
terelius424e6cf2017-02-20 05:14:41 -0800150 void LogDelayBasedBweUpdate(int32_t bitrate_bps,
terelius0baf55d2017-02-17 03:38:28 -0800151 BandwidthUsage detector_state) override {
152 rtc::CritScope lock(&crit_);
153 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800154 event_log_->LogDelayBasedBweUpdate(bitrate_bps, detector_state);
terelius0baf55d2017-02-17 03:38:28 -0800155 }
156 }
157
minyue4b7c9522017-01-24 04:54:59 -0800158 void LogAudioNetworkAdaptation(
michaeltcde46b72017-04-06 05:59:10 -0700159 const AudioEncoderRuntimeConfig& config) override {
minyue4b7c9522017-01-24 04:54:59 -0800160 rtc::CritScope lock(&crit_);
161 if (event_log_) {
162 event_log_->LogAudioNetworkAdaptation(config);
163 }
164 }
165
philipel32d00102017-02-27 02:18:46 -0800166 void LogProbeClusterCreated(int id,
167 int bitrate_bps,
168 int min_probes,
169 int min_bytes) override {
170 rtc::CritScope lock(&crit_);
171 if (event_log_) {
172 event_log_->LogProbeClusterCreated(id, bitrate_bps, min_probes,
173 min_bytes);
174 }
175 };
176
177 void LogProbeResultSuccess(int id, int bitrate_bps) override {
178 rtc::CritScope lock(&crit_);
179 if (event_log_) {
180 event_log_->LogProbeResultSuccess(id, bitrate_bps);
181 }
182 };
183
184 void LogProbeResultFailure(int id,
185 ProbeFailureReason failure_reason) override {
186 rtc::CritScope lock(&crit_);
187 if (event_log_) {
188 event_log_->LogProbeResultFailure(id, failure_reason);
189 }
190 };
191
ivoc14d5dbe2016-07-04 07:06:55 -0700192 void SetEventLog(RtcEventLog* event_log) {
193 rtc::CritScope lock(&crit_);
194 event_log_ = event_log;
195 }
196
197 private:
198 rtc::CriticalSection crit_;
199 RtcEventLog* event_log_ GUARDED_BY(crit_);
200 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
201};
202
michaelt9332b7d2016-11-30 07:51:13 -0800203class RtcpRttStatsProxy final : public RtcpRttStats {
204 public:
205 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
206
207 void OnRttUpdate(int64_t rtt) override {
208 rtc::CritScope lock(&crit_);
209 if (rtcp_rtt_stats_)
210 rtcp_rtt_stats_->OnRttUpdate(rtt);
211 }
212
213 int64_t LastProcessedRtt() const override {
214 rtc::CritScope lock(&crit_);
215 if (!rtcp_rtt_stats_)
216 return 0;
217 return rtcp_rtt_stats_->LastProcessedRtt();
218 }
219
220 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
221 rtc::CritScope lock(&crit_);
222 rtcp_rtt_stats_ = rtcp_rtt_stats;
223 }
224
225 private:
226 rtc::CriticalSection crit_;
227 RtcpRttStats* rtcp_rtt_stats_ GUARDED_BY(crit_);
228 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
229};
230
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100231class TransportFeedbackProxy : public TransportFeedbackObserver {
232 public:
233 TransportFeedbackProxy() : feedback_observer_(nullptr) {
234 pacer_thread_.DetachFromThread();
235 network_thread_.DetachFromThread();
236 }
237
238 void SetTransportFeedbackObserver(
239 TransportFeedbackObserver* feedback_observer) {
240 RTC_DCHECK(thread_checker_.CalledOnValidThread());
241 rtc::CritScope lock(&crit_);
242 feedback_observer_ = feedback_observer;
243 }
244
245 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700246 void AddPacket(uint32_t ssrc,
247 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100248 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800249 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100250 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
251 rtc::CritScope lock(&crit_);
252 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700253 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100254 }
philipel8aadd502017-02-23 02:56:13 -0800255
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100256 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
257 RTC_DCHECK(network_thread_.CalledOnValidThread());
258 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700259 if (feedback_observer_)
260 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200261 }
elad.alonf9490002017-03-06 05:32:21 -0800262 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200263 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800264 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100265 }
266
267 private:
268 rtc::CriticalSection crit_;
269 rtc::ThreadChecker thread_checker_;
270 rtc::ThreadChecker pacer_thread_;
271 rtc::ThreadChecker network_thread_;
272 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
273};
274
275class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
276 public:
277 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
278 pacer_thread_.DetachFromThread();
279 }
280
281 void SetSequenceNumberAllocator(
282 TransportSequenceNumberAllocator* seq_num_allocator) {
283 RTC_DCHECK(thread_checker_.CalledOnValidThread());
284 rtc::CritScope lock(&crit_);
285 seq_num_allocator_ = seq_num_allocator;
286 }
287
288 // Implements TransportSequenceNumberAllocator.
289 uint16_t AllocateSequenceNumber() override {
290 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
291 rtc::CritScope lock(&crit_);
292 if (!seq_num_allocator_)
293 return 0;
294 return seq_num_allocator_->AllocateSequenceNumber();
295 }
296
297 private:
298 rtc::CriticalSection crit_;
299 rtc::ThreadChecker thread_checker_;
300 rtc::ThreadChecker pacer_thread_;
301 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
302};
303
304class RtpPacketSenderProxy : public RtpPacketSender {
305 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800306 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100307
308 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
309 RTC_DCHECK(thread_checker_.CalledOnValidThread());
310 rtc::CritScope lock(&crit_);
311 rtp_packet_sender_ = rtp_packet_sender;
312 }
313
314 // Implements RtpPacketSender.
315 void InsertPacket(Priority priority,
316 uint32_t ssrc,
317 uint16_t sequence_number,
318 int64_t capture_time_ms,
319 size_t bytes,
320 bool retransmission) override {
321 rtc::CritScope lock(&crit_);
322 if (rtp_packet_sender_) {
323 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
324 capture_time_ms, bytes, retransmission);
325 }
326 }
327
328 private:
329 rtc::ThreadChecker thread_checker_;
330 rtc::CriticalSection crit_;
331 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
332};
333
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000334class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000335 public:
stefan7de8d642017-02-07 07:14:08 -0800336 explicit VoERtcpObserver(Channel* owner)
337 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000338 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000339
stefan7de8d642017-02-07 07:14:08 -0800340 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
341 rtc::CritScope lock(&crit_);
342 bandwidth_observer_ = bandwidth_observer;
343 }
344
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000345 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800346 rtc::CritScope lock(&crit_);
347 if (bandwidth_observer_) {
348 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
349 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000350 }
351
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000352 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
353 int64_t rtt,
354 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800355 {
356 rtc::CritScope lock(&crit_);
357 if (bandwidth_observer_) {
358 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
359 now_ms);
360 }
361 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000362 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
363 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
364 // report for VoiceEngine?
365 if (report_blocks.empty())
366 return;
367
368 int fraction_lost_aggregate = 0;
369 int total_number_of_packets = 0;
370
371 // If receiving multiple report blocks, calculate the weighted average based
372 // on the number of packets a report refers to.
373 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
374 block_it != report_blocks.end(); ++block_it) {
375 // Find the previous extended high sequence number for this remote SSRC,
376 // to calculate the number of RTP packets this report refers to. Ignore if
377 // we haven't seen this SSRC before.
378 std::map<uint32_t, uint32_t>::iterator seq_num_it =
379 extended_max_sequence_number_.find(block_it->sourceSSRC);
380 int number_of_packets = 0;
381 if (seq_num_it != extended_max_sequence_number_.end()) {
382 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
383 }
384 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
385 total_number_of_packets += number_of_packets;
386
387 extended_max_sequence_number_[block_it->sourceSSRC] =
388 block_it->extendedHighSeqNum;
389 }
390 int weighted_fraction_lost = 0;
391 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800392 weighted_fraction_lost =
393 (fraction_lost_aggregate + total_number_of_packets / 2) /
394 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000395 }
elad.alond12a8e12017-03-23 11:04:48 -0700396 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000397 }
398
399 private:
400 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000401 // Maps remote side ssrc to extended highest sequence number received.
402 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800403 rtc::CriticalSection crit_;
404 RtcpBandwidthObserver* bandwidth_observer_ GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000405};
406
henrikaec6fbd22017-03-31 05:43:36 -0700407class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
408 public:
409 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
410 Channel* channel)
411 : audio_frame_(std::move(audio_frame)), channel_(channel) {
412 RTC_DCHECK(channel_);
413 }
414
415 private:
416 bool Run() override {
417 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
418 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
419 return true;
420 }
421
422 std::unique_ptr<AudioFrame> audio_frame_;
423 Channel* const channel_;
424};
425
kwiberg55b97fe2016-01-28 05:22:45 -0800426int32_t Channel::SendData(FrameType frameType,
427 uint8_t payloadType,
428 uint32_t timeStamp,
429 const uint8_t* payloadData,
430 size_t payloadSize,
431 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700432 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800433 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
434 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
435 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
436 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000437
kwiberg55b97fe2016-01-28 05:22:45 -0800438 if (_includeAudioLevelIndication) {
439 // Store current audio level in the RTP/RTCP module.
440 // The level will be used in combination with voice-activity state
441 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800442 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800443 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000444
kwiberg55b97fe2016-01-28 05:22:45 -0800445 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
446 // packetization.
447 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700448 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800449 (FrameType&)frameType, payloadType, timeStamp,
450 // Leaving the time when this frame was
451 // received from the capture device as
452 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700453 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800454 _engineStatisticsPtr->SetLastError(
455 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
456 "Channel::SendData() failed to send data to RTP/RTCP module");
457 return -1;
458 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000459
kwiberg55b97fe2016-01-28 05:22:45 -0800460 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000461}
462
stefan1d8a5062015-10-02 03:39:33 -0700463bool Channel::SendRtp(const uint8_t* data,
464 size_t len,
465 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800466 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
467 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000468
kwiberg55b97fe2016-01-28 05:22:45 -0800469 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000470
kwiberg55b97fe2016-01-28 05:22:45 -0800471 if (_transportPtr == NULL) {
472 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
473 "Channel::SendPacket() failed to send RTP packet due to"
474 " invalid transport object");
475 return false;
476 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000477
kwiberg55b97fe2016-01-28 05:22:45 -0800478 uint8_t* bufferToSendPtr = (uint8_t*)data;
479 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000480
kwiberg55b97fe2016-01-28 05:22:45 -0800481 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
482 std::string transport_name =
483 _externalTransport ? "external transport" : "WebRtc sockets";
484 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
485 "Channel::SendPacket() RTP transmission using %s failed",
486 transport_name.c_str());
487 return false;
488 }
489 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000490}
491
kwiberg55b97fe2016-01-28 05:22:45 -0800492bool Channel::SendRtcp(const uint8_t* data, size_t len) {
493 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
494 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000495
kwiberg55b97fe2016-01-28 05:22:45 -0800496 rtc::CritScope cs(&_callbackCritSect);
497 if (_transportPtr == NULL) {
498 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
499 "Channel::SendRtcp() failed to send RTCP packet"
500 " due to invalid transport object");
501 return false;
502 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000503
kwiberg55b97fe2016-01-28 05:22:45 -0800504 uint8_t* bufferToSendPtr = (uint8_t*)data;
505 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000506
kwiberg55b97fe2016-01-28 05:22:45 -0800507 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
508 if (n < 0) {
509 std::string transport_name =
510 _externalTransport ? "external transport" : "WebRtc sockets";
511 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
512 "Channel::SendRtcp() transmission using %s failed",
513 transport_name.c_str());
514 return false;
515 }
516 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000517}
518
kwiberg55b97fe2016-01-28 05:22:45 -0800519void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
520 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
521 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000522
kwiberg55b97fe2016-01-28 05:22:45 -0800523 // Update ssrc so that NTP for AV sync can be updated.
524 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000525}
526
Peter Boströmac547a62015-09-17 23:03:57 +0200527void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
528 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
529 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
530 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000531}
532
Peter Boströmac547a62015-09-17 23:03:57 +0200533int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000534 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000535 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000536 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800537 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200538 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800539 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
540 "Channel::OnInitializeDecoder(payloadType=%d, "
541 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
542 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000543
kwiberg55b97fe2016-01-28 05:22:45 -0800544 CodecInst receiveCodec = {0};
545 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000546
kwiberg55b97fe2016-01-28 05:22:45 -0800547 receiveCodec.pltype = payloadType;
548 receiveCodec.plfreq = frequency;
549 receiveCodec.channels = channels;
550 receiveCodec.rate = rate;
551 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000552
kwiberg55b97fe2016-01-28 05:22:45 -0800553 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
554 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000555
kwiberg55b97fe2016-01-28 05:22:45 -0800556 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700557 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
558 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800559 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
560 "Channel::OnInitializeDecoder() invalid codec ("
561 "pt=%d, name=%s) received - 1",
562 payloadType, payloadName);
563 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
564 return -1;
565 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000566
kwiberg55b97fe2016-01-28 05:22:45 -0800567 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000568}
569
kwiberg55b97fe2016-01-28 05:22:45 -0800570int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
571 size_t payloadSize,
572 const WebRtcRTPHeader* rtpHeader) {
573 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
574 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
575 ","
576 " payloadType=%u, audioChannel=%" PRIuS ")",
577 payloadSize, rtpHeader->header.payloadType,
578 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000579
kwiberg55b97fe2016-01-28 05:22:45 -0800580 if (!channel_state_.Get().playing) {
581 // Avoid inserting into NetEQ when we are not playing. Count the
582 // packet as discarded.
583 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
584 "received packet is discarded since playing is not"
585 " activated");
niklase@google.com470e71d2011-07-07 08:21:25 +0000586 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800587 }
588
589 // Push the incoming payload (parsed and ready for decoding) into the ACM
590 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
591 0) {
592 _engineStatisticsPtr->SetLastError(
593 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
594 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
595 return -1;
596 }
597
kwiberg55b97fe2016-01-28 05:22:45 -0800598 int64_t round_trip_time = 0;
599 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
600 NULL);
601
602 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
603 if (!nack_list.empty()) {
604 // Can't use nack_list.data() since it's not supported by all
605 // compilers.
606 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
607 }
608 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000609}
610
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000611bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000612 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000613 RTPHeader header;
614 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
615 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
616 "IncomingPacket invalid RTP header");
617 return false;
618 }
619 header.payload_type_frequency =
620 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
621 if (header.payload_type_frequency < 0)
622 return false;
623 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
624}
625
henrik.lundin42dda502016-05-18 05:36:01 -0700626MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
627 int32_t id,
628 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700629 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800630 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700631 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800632 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700633 bool muted;
634 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
635 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800636 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
637 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
638 // In all likelihood, the audio in this frame is garbage. We return an
639 // error so that the audio mixer module doesn't add it to the mix. As
640 // a result, it won't be played out and the actions skipped here are
641 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700642 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800643 }
henrik.lundina89ab962016-05-18 08:52:45 -0700644
645 if (muted) {
646 // TODO(henrik.lundin): We should be able to do better than this. But we
647 // will have to go through all the cases below where the audio samples may
648 // be used, and handle the muted case in some way.
aleloi6321b492016-12-05 01:46:09 -0800649 AudioFrameOperations::Mute(audioFrame);
henrik.lundina89ab962016-05-18 08:52:45 -0700650 }
kwiberg55b97fe2016-01-28 05:22:45 -0800651
kwiberg55b97fe2016-01-28 05:22:45 -0800652 // Convert module ID to internal VoE channel ID
653 audioFrame->id_ = VoEChannelId(audioFrame->id_);
654 // Store speech type for dead-or-alive detection
655 _outputSpeechType = audioFrame->speech_type_;
656
657 ChannelState::State state = channel_state_.Get();
658
kwiberg55b97fe2016-01-28 05:22:45 -0800659 {
660 // Pass the audio buffers to an optional sink callback, before applying
661 // scaling/panning, as that applies to the mix operation.
662 // External recipients of the audio (e.g. via AudioTrack), will do their
663 // own mixing/dynamic processing.
664 rtc::CritScope cs(&_callbackCritSect);
665 if (audio_sink_) {
666 AudioSinkInterface::Data data(
667 &audioFrame->data_[0], audioFrame->samples_per_channel_,
668 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
669 audioFrame->timestamp_);
670 audio_sink_->OnData(data);
671 }
672 }
673
674 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800675 {
676 rtc::CritScope cs(&volume_settings_critsect_);
677 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800678 }
679
680 // Output volume scaling
681 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800682 // TODO(solenberg): Combine with mute state - this can cause clicks!
oprypin67fdb802017-03-09 06:25:06 -0800683 AudioFrameOperations::ScaleWithSat(output_gain, audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800684 }
685
kwiberg55b97fe2016-01-28 05:22:45 -0800686 // Mix decoded PCM output with file if file mixing is enabled
687 if (state.output_file_playing) {
688 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700689 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800690 }
691
kwiberg55b97fe2016-01-28 05:22:45 -0800692 // Record playout if enabled
693 {
694 rtc::CritScope cs(&_fileCritSect);
695
kwiberg5a25d952016-08-17 07:31:12 -0700696 if (_outputFileRecording && output_file_recorder_) {
697 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800698 }
699 }
700
701 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700702 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800703 _outputAudioLevel.ComputeLevel(*audioFrame);
704
705 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
706 // The first frame with a valid rtp timestamp.
707 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
708 }
709
710 if (capture_start_rtp_time_stamp_ >= 0) {
711 // audioFrame.timestamp_ should be valid from now on.
712
713 // Compute elapsed time.
714 int64_t unwrap_timestamp =
715 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
716 audioFrame->elapsed_time_ms_ =
717 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700718 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800719
niklase@google.com470e71d2011-07-07 08:21:25 +0000720 {
kwiberg55b97fe2016-01-28 05:22:45 -0800721 rtc::CritScope lock(&ts_stats_lock_);
722 // Compute ntp time.
723 audioFrame->ntp_time_ms_ =
724 ntp_estimator_.Estimate(audioFrame->timestamp_);
725 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
726 if (audioFrame->ntp_time_ms_ > 0) {
727 // Compute |capture_start_ntp_time_ms_| so that
728 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
729 capture_start_ntp_time_ms_ =
730 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000731 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000732 }
kwiberg55b97fe2016-01-28 05:22:45 -0800733 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000734
henrik.lundin42dda502016-05-18 05:36:01 -0700735 return muted ? MixerParticipant::AudioFrameInfo::kMuted
736 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000737}
738
aleloi6c278492016-10-20 14:24:39 -0700739AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
740 int sample_rate_hz,
741 AudioFrame* audio_frame) {
742 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700743
aleloi6c278492016-10-20 14:24:39 -0700744 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700745
746 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
747 FrameInfo new_audio_frame_info = FrameInfo::kError;
748 switch (frame_info) {
749 case MixerParticipant::AudioFrameInfo::kNormal:
750 new_audio_frame_info = FrameInfo::kNormal;
751 break;
752 case MixerParticipant::AudioFrameInfo::kMuted:
753 new_audio_frame_info = FrameInfo::kMuted;
754 break;
755 case MixerParticipant::AudioFrameInfo::kError:
756 new_audio_frame_info = FrameInfo::kError;
757 break;
758 }
aleloi6c278492016-10-20 14:24:39 -0700759 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700760}
761
kwiberg55b97fe2016-01-28 05:22:45 -0800762int32_t Channel::NeededFrequency(int32_t id) const {
763 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
764 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000765
kwiberg55b97fe2016-01-28 05:22:45 -0800766 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000767
kwiberg55b97fe2016-01-28 05:22:45 -0800768 // Determine highest needed receive frequency
769 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000770
kwiberg55b97fe2016-01-28 05:22:45 -0800771 // Return the bigger of playout and receive frequency in the ACM.
772 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
773 highestNeeded = audio_coding_->PlayoutFrequency();
774 } else {
775 highestNeeded = receiveFrequency;
776 }
777
778 // Special case, if we're playing a file on the playout side
779 // we take that frequency into consideration as well
780 // This is not needed on sending side, since the codec will
781 // limit the spectrum anyway.
782 if (channel_state_.Get().output_file_playing) {
783 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700784 if (output_file_player_) {
785 if (output_file_player_->Frequency() > highestNeeded) {
786 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800787 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000788 }
kwiberg55b97fe2016-01-28 05:22:45 -0800789 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000790
kwiberg55b97fe2016-01-28 05:22:45 -0800791 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000792}
793
henrikaec6fbd22017-03-31 05:43:36 -0700794int32_t Channel::CreateChannel(Channel*& channel,
795 int32_t channelId,
796 uint32_t instanceId,
797 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800798 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
799 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
800 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000801
solenberg88499ec2016-09-07 07:34:41 -0700802 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800803 if (channel == NULL) {
804 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
805 "Channel::CreateChannel() unable to allocate memory for"
806 " channel");
807 return -1;
808 }
809 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000810}
811
kwiberg55b97fe2016-01-28 05:22:45 -0800812void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
813 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
814 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
815 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000816
kwiberg55b97fe2016-01-28 05:22:45 -0800817 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000818}
819
kwiberg55b97fe2016-01-28 05:22:45 -0800820void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
821 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
822 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
823 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000824
kwiberg55b97fe2016-01-28 05:22:45 -0800825 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000826}
827
kwiberg55b97fe2016-01-28 05:22:45 -0800828void Channel::PlayFileEnded(int32_t id) {
829 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
830 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000831
kwiberg55b97fe2016-01-28 05:22:45 -0800832 if (id == _inputFilePlayerId) {
833 channel_state_.SetInputFilePlaying(false);
834 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
835 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000836 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800837 } else if (id == _outputFilePlayerId) {
838 channel_state_.SetOutputFilePlaying(false);
839 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
840 "Channel::PlayFileEnded() => output file player module is"
841 " shutdown");
842 }
843}
844
845void Channel::RecordFileEnded(int32_t id) {
846 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
847 "Channel::RecordFileEnded(id=%d)", id);
848
849 assert(id == _outputFileRecorderId);
850
851 rtc::CritScope cs(&_fileCritSect);
852
853 _outputFileRecording = false;
854 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
855 "Channel::RecordFileEnded() => output file recorder module is"
856 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000857}
858
pbos@webrtc.org92135212013-05-14 08:31:39 +0000859Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000860 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700861 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800862 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100863 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700864 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800865 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100866 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800867 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100868 rtp_receive_statistics_(
869 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
870 rtp_receiver_(
871 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100872 this,
873 this,
874 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700875 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100876 _outputAudioLevel(),
877 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100878 // Avoid conflict with other channels by adding 1024 - 1026,
879 // won't use as much as 1024 channels.
880 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
881 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
882 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
883 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100884 _timeStamp(0), // This is just an offset, RTP module will add it's own
885 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100886 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100887 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100888 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100889 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100890 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
891 capture_start_rtp_time_stamp_(-1),
892 capture_start_ntp_time_ms_(-1),
893 _engineStatisticsPtr(NULL),
894 _outputMixerPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100895 _moduleProcessThreadPtr(NULL),
896 _audioDeviceModulePtr(NULL),
897 _voiceEngineObserverPtr(NULL),
898 _callbackCritSectPtr(NULL),
899 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700900 input_mute_(false),
901 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100902 _outputGain(1.0f),
solenberg8d73f8c2017-03-08 01:52:20 -0800903 _mixFileWithMicrophone(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100904 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800905 transport_overhead_per_packet_(0),
906 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100907 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100908 restored_packet_in_use_(false),
909 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100910 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700911 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800912 feedback_observer_proxy_(new TransportFeedbackProxy()),
913 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700914 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200915 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
916 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700917 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700918 use_twcc_plr_for_ana_(
919 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800920 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
921 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700922 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800923 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700924 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800925 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200926
kwiberg55b97fe2016-01-28 05:22:45 -0800927 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000928
kwiberg55b97fe2016-01-28 05:22:45 -0800929 RtpRtcp::Configuration configuration;
930 configuration.audio = true;
931 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800932 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800933 configuration.receive_statistics = rtp_receive_statistics_.get();
934 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800935 if (pacing_enabled_) {
936 configuration.paced_sender = rtp_packet_sender_proxy_.get();
937 configuration.transport_sequence_number_allocator =
938 seq_num_allocator_proxy_.get();
939 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
940 }
ivoc14d5dbe2016-07-04 07:06:55 -0700941 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800942 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200943 configuration.retransmission_rate_limiter =
944 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000945
kwiberg55b97fe2016-01-28 05:22:45 -0800946 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100947 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000948}
949
kwiberg55b97fe2016-01-28 05:22:45 -0800950Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700951 RTC_DCHECK(!channel_state_.Get().sending);
952 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000953}
954
kwiberg55b97fe2016-01-28 05:22:45 -0800955int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700956 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800957 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
958 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000959
kwiberg55b97fe2016-01-28 05:22:45 -0800960 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000961
kwiberg55b97fe2016-01-28 05:22:45 -0800962 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000963
kwiberg55b97fe2016-01-28 05:22:45 -0800964 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
965 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
966 "Channel::Init() must call SetEngineInformation() first");
967 return -1;
968 }
969
970 // --- Add modules to process thread (for periodic schedulation)
971
tommidea489f2017-03-03 03:20:24 -0800972 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800973
974 // --- ACM initialization
975
976 if (audio_coding_->InitializeReceiver() == -1) {
977 _engineStatisticsPtr->SetLastError(
978 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
979 "Channel::Init() unable to initialize the ACM - 1");
980 return -1;
981 }
982
983 // --- RTP/RTCP module initialization
984
985 // Ensure that RTCP is enabled by default for the created channel.
986 // Note that, the module will keep generating RTCP until it is explicitly
987 // disabled by the user.
988 // After StopListen (when no sockets exists), RTCP packets will no longer
989 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700990 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800991 // RTCP is enabled by default.
992 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
993 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800994 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800995 _engineStatisticsPtr->SetLastError(
996 VE_CANNOT_INIT_CHANNEL, kTraceError,
997 "Channel::Init() callbacks not registered");
998 return -1;
999 }
1000
kwiberg1c07c702017-03-27 07:15:49 -07001001 // Register a default set of send codecs.
1002 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -08001003 for (int idx = 0; idx < nSupportedCodecs; idx++) {
kwiberg1c07c702017-03-27 07:15:49 -07001004 CodecInst codec;
1005 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
1006
1007 // Ensure that PCMU is used as default send codec.
1008 if (STR_CASE_CMP(codec.plname, "PCMU") == 0 && codec.channels == 1) {
1009 SetSendCodec(codec);
1010 }
1011
1012 // Register default PT for 'telephone-event'
1013 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
1014 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1) {
1015 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1016 "Channel::Init() failed to register outband "
1017 "'telephone-event' (%d/%d) correctly",
1018 codec.pltype, codec.plfreq);
1019 }
1020 }
1021
1022 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
1023 if (!codec_manager_.RegisterEncoder(codec) ||
1024 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
1025 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
1026 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1027 "Channel::Init() failed to register CN (%d/%d) "
1028 "correctly - 1",
1029 codec.pltype, codec.plfreq);
1030 }
1031 }
1032 }
1033
1034 return 0;
1035}
1036
1037void Channel::RegisterLegacyReceiveCodecs() {
1038 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1039 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1040 CodecInst codec;
1041 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
1042
kwiberg55b97fe2016-01-28 05:22:45 -08001043 // Open up the RTP/RTCP receiver for all supported codecs
kwiberg1c07c702017-03-27 07:15:49 -07001044 if (rtp_receiver_->RegisterReceivePayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001045 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1046 "Channel::Init() unable to register %s "
1047 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1048 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1049 codec.rate);
1050 } else {
1051 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1052 "Channel::Init() %s (%d/%d/%" PRIuS
1053 "/%d) has been "
1054 "added to the RTP/RTCP receiver",
1055 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1056 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001057 }
1058
kwiberg1c07c702017-03-27 07:15:49 -07001059 // Register default PT for 'telephone-event'
1060 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
1061 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
kwibergda2bf4e2016-10-24 13:47:09 -07001062 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001063 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
kwiberg1c07c702017-03-27 07:15:49 -07001064 "Channel::Init() failed to register inband "
kwiberg55b97fe2016-01-28 05:22:45 -08001065 "'telephone-event' (%d/%d) correctly",
1066 codec.pltype, codec.plfreq);
1067 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001068 }
1069
kwiberg1c07c702017-03-27 07:15:49 -07001070 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
1071 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1072 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001073 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1074 "Channel::Init() failed to register CN (%d/%d) "
1075 "correctly - 1",
1076 codec.pltype, codec.plfreq);
1077 }
1078 }
kwiberg55b97fe2016-01-28 05:22:45 -08001079 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001080}
1081
tommi0a2391f2017-03-21 02:31:51 -07001082void Channel::Terminate() {
1083 RTC_DCHECK(construction_thread_.CalledOnValidThread());
1084 // Must be called on the same thread as Init().
1085 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
1086 "Channel::Terminate");
1087
1088 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
1089
1090 StopSend();
1091 StopPlayout();
1092
1093 {
1094 rtc::CritScope cs(&_fileCritSect);
1095 if (input_file_player_) {
1096 input_file_player_->RegisterModuleFileCallback(NULL);
1097 input_file_player_->StopPlayingFile();
1098 }
1099 if (output_file_player_) {
1100 output_file_player_->RegisterModuleFileCallback(NULL);
1101 output_file_player_->StopPlayingFile();
1102 }
1103 if (output_file_recorder_) {
1104 output_file_recorder_->RegisterModuleFileCallback(NULL);
1105 output_file_recorder_->StopRecording();
1106 }
1107 }
1108
1109 // The order to safely shutdown modules in a channel is:
1110 // 1. De-register callbacks in modules
1111 // 2. De-register modules in process thread
1112 // 3. Destroy modules
1113 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1114 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1115 "Terminate() failed to de-register transport callback"
1116 " (Audio coding module)");
1117 }
1118
1119 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1120 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1121 "Terminate() failed to de-register VAD callback"
1122 " (Audio coding module)");
1123 }
1124
1125 // De-register modules in process thread
1126 if (_moduleProcessThreadPtr)
1127 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
1128
1129 // End of modules shutdown
1130}
1131
kwiberg55b97fe2016-01-28 05:22:45 -08001132int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1133 OutputMixer& outputMixer,
kwiberg55b97fe2016-01-28 05:22:45 -08001134 ProcessThread& moduleProcessThread,
1135 AudioDeviceModule& audioDeviceModule,
1136 VoiceEngineObserver* voiceEngineObserver,
henrikaec6fbd22017-03-31 05:43:36 -07001137 rtc::CriticalSection* callbackCritSect,
1138 rtc::TaskQueue* encoder_queue) {
1139 RTC_DCHECK(encoder_queue);
1140 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -08001141 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1142 "Channel::SetEngineInformation()");
1143 _engineStatisticsPtr = &engineStatistics;
1144 _outputMixerPtr = &outputMixer;
kwiberg55b97fe2016-01-28 05:22:45 -08001145 _moduleProcessThreadPtr = &moduleProcessThread;
1146 _audioDeviceModulePtr = &audioDeviceModule;
1147 _voiceEngineObserverPtr = voiceEngineObserver;
1148 _callbackCritSectPtr = callbackCritSect;
henrikaec6fbd22017-03-31 05:43:36 -07001149 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -08001150 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001151}
1152
kwibergb7f89d62016-02-17 10:04:18 -08001153void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001154 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001155 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001156}
1157
ossu29b1a8d2016-06-13 07:34:51 -07001158const rtc::scoped_refptr<AudioDecoderFactory>&
1159Channel::GetAudioDecoderFactory() const {
1160 return decoder_factory_;
1161}
1162
kwiberg55b97fe2016-01-28 05:22:45 -08001163int32_t Channel::StartPlayout() {
1164 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1165 "Channel::StartPlayout()");
1166 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001167 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001168 }
1169
solenberge374e012017-02-14 04:55:00 -08001170 // Add participant as candidates for mixing.
1171 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1172 _engineStatisticsPtr->SetLastError(
1173 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1174 "StartPlayout() failed to add participant to mixer");
1175 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001176 }
1177
1178 channel_state_.SetPlaying(true);
1179 if (RegisterFilePlayingToMixer() != 0)
1180 return -1;
1181
1182 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001183}
1184
kwiberg55b97fe2016-01-28 05:22:45 -08001185int32_t Channel::StopPlayout() {
1186 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1187 "Channel::StopPlayout()");
1188 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001189 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001190 }
1191
solenberge374e012017-02-14 04:55:00 -08001192 // Remove participant as candidates for mixing
1193 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1194 _engineStatisticsPtr->SetLastError(
1195 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1196 "StopPlayout() failed to remove participant from mixer");
1197 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001198 }
1199
1200 channel_state_.SetPlaying(false);
1201 _outputAudioLevel.Clear();
1202
1203 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001204}
1205
kwiberg55b97fe2016-01-28 05:22:45 -08001206int32_t Channel::StartSend() {
1207 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1208 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -08001209 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001210 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001211 }
1212 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -07001213 {
1214 // It is now OK to start posting tasks to the encoder task queue.
1215 rtc::CritScope cs(&encoder_queue_lock_);
1216 encoder_queue_is_active_ = true;
1217 }
solenberg08b19df2017-02-15 00:42:31 -08001218 // Resume the previous sequence number which was reset by StopSend(). This
1219 // needs to be done before |sending| is set to true on the RTP/RTCP module.
1220 if (send_sequence_number_) {
1221 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
1222 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001223 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001224 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1225 _engineStatisticsPtr->SetLastError(
1226 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1227 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001228 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001229 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001230 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001231 return -1;
1232 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001233
kwiberg55b97fe2016-01-28 05:22:45 -08001234 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001235}
1236
henrikaec6fbd22017-03-31 05:43:36 -07001237void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -08001238 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1239 "Channel::StopSend()");
1240 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -07001241 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001242 }
1243 channel_state_.SetSending(false);
1244
henrikaec6fbd22017-03-31 05:43:36 -07001245 // Post a task to the encoder thread which sets an event when the task is
1246 // executed. We know that no more encoding tasks will be added to the task
1247 // queue for this channel since sending is now deactivated. It means that,
1248 // if we wait for the event to bet set, we know that no more pending tasks
1249 // exists and it is therfore guaranteed that the task queue will never try
1250 // to acccess and invalid channel object.
1251 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -07001252
henrikaec6fbd22017-03-31 05:43:36 -07001253 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -07001254 {
1255 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
1256 // than this final "flush task" to be posted on the queue.
1257 rtc::CritScope cs(&encoder_queue_lock_);
1258 encoder_queue_is_active_ = false;
1259 encoder_queue_->PostTask([&flush]() { flush.Set(); });
1260 }
henrikaec6fbd22017-03-31 05:43:36 -07001261 flush.Wait(rtc::Event::kForever);
1262
kwiberg55b97fe2016-01-28 05:22:45 -08001263 // Store the sequence number to be able to pick up the same sequence for
1264 // the next StartSend(). This is needed for restarting device, otherwise
1265 // it might cause libSRTP to complain about packets being replayed.
1266 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1267 // CL is landed. See issue
1268 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1269 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1270
1271 // Reset sending SSRC and sequence number and triggers direct transmission
1272 // of RTCP BYE
1273 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1274 _engineStatisticsPtr->SetLastError(
1275 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1276 "StartSend() RTP/RTCP failed to stop sending");
1277 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001278 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001279}
1280
ossu1ffbd6c2017-04-06 12:05:04 -07001281bool Channel::SetEncoder(int payload_type,
1282 std::unique_ptr<AudioEncoder> encoder) {
1283 RTC_DCHECK_GE(payload_type, 0);
1284 RTC_DCHECK_LE(payload_type, 127);
1285 // TODO(ossu): Make a CodecInst up for now. It seems like very little of this
1286 // information is actually used, possibly only payload type and clock rate.
1287 CodecInst lies;
1288 lies.pltype = payload_type;
1289 strncpy(lies.plname, "audio", sizeof(lies.plname));
1290 lies.plname[sizeof(lies.plname) - 1] = 0;
1291 // Seems unclear if it should be clock rate or sample rate. CodecInst
1292 // supposedly carries the sample rate, but only clock rate seems sensible to
1293 // send to the RTP/RTCP module.
1294 lies.plfreq = encoder->RtpTimestampRateHz();
1295 lies.pacsize = 0;
1296 lies.channels = encoder->NumChannels();
1297 lies.rate = 0;
1298
1299 if (_rtpRtcpModule->RegisterSendPayload(lies) != 0) {
1300 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
1301 if (_rtpRtcpModule->RegisterSendPayload(lies) != 0) {
1302 WEBRTC_TRACE(
1303 kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1304 "SetEncoder() failed to register codec to RTP/RTCP module");
1305 return false;
1306 }
1307 }
1308
1309 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -07001310 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -07001311 return true;
1312}
1313
ossu20a4b3f2017-04-27 02:08:52 -07001314void Channel::ModifyEncoder(
1315 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
1316 audio_coding_->ModifyEncoder(modifier);
1317}
1318
kwiberg55b97fe2016-01-28 05:22:45 -08001319int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1320 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1321 "Channel::RegisterVoiceEngineObserver()");
1322 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001323
kwiberg55b97fe2016-01-28 05:22:45 -08001324 if (_voiceEngineObserverPtr) {
1325 _engineStatisticsPtr->SetLastError(
1326 VE_INVALID_OPERATION, kTraceError,
1327 "RegisterVoiceEngineObserver() observer already enabled");
1328 return -1;
1329 }
1330 _voiceEngineObserverPtr = &observer;
1331 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001332}
1333
kwiberg55b97fe2016-01-28 05:22:45 -08001334int32_t Channel::DeRegisterVoiceEngineObserver() {
1335 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1336 "Channel::DeRegisterVoiceEngineObserver()");
1337 rtc::CritScope cs(&_callbackCritSect);
1338
1339 if (!_voiceEngineObserverPtr) {
1340 _engineStatisticsPtr->SetLastError(
1341 VE_INVALID_OPERATION, kTraceWarning,
1342 "DeRegisterVoiceEngineObserver() observer already disabled");
1343 return 0;
1344 }
1345 _voiceEngineObserverPtr = NULL;
1346 return 0;
1347}
1348
1349int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu20a4b3f2017-04-27 02:08:52 -07001350 {
1351 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1352 if (send_codec) {
1353 codec = *send_codec;
1354 return 0;
1355 }
1356 }
1357 rtc::Optional<CodecInst> acm_send_codec = audio_coding_->SendCodec();
1358 if (acm_send_codec) {
1359 codec = *acm_send_codec;
kwiberg1fd4a4a2015-11-03 11:20:50 -08001360 return 0;
1361 }
1362 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001363}
1364
kwiberg55b97fe2016-01-28 05:22:45 -08001365int32_t Channel::GetRecCodec(CodecInst& codec) {
1366 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001367}
1368
kwiberg55b97fe2016-01-28 05:22:45 -08001369int32_t Channel::SetSendCodec(const CodecInst& codec) {
1370 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1371 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001372
kwibergc8d071e2016-04-06 12:22:38 -07001373 if (!codec_manager_.RegisterEncoder(codec) ||
1374 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001375 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1376 "SetSendCodec() failed to register codec to ACM");
1377 return -1;
1378 }
1379
1380 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1381 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1382 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1383 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1384 "SetSendCodec() failed to register codec to"
1385 " RTP/RTCP module");
1386 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001387 }
kwiberg55b97fe2016-01-28 05:22:45 -08001388 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001389
kwiberg55b97fe2016-01-28 05:22:45 -08001390 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001391}
1392
minyue78b4d562016-11-30 04:47:39 -08001393void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001394 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1395 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001396 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001397 if (*encoder) {
1398 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001399 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001400 }
1401 });
michaelt566d8202017-01-12 10:17:38 -08001402 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001403}
1404
elad.alond12a8e12017-03-23 11:04:48 -07001405void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1406 if (!use_twcc_plr_for_ana_)
1407 return;
minyue7e304322016-10-12 05:00:55 -07001408 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001409 if (*encoder) {
1410 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1411 }
1412 });
1413}
1414
elad.alondadb4dc2017-03-23 15:29:50 -07001415void Channel::OnRecoverableUplinkPacketLossRate(
1416 float recoverable_packet_loss_rate) {
1417 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1418 if (*encoder) {
1419 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1420 recoverable_packet_loss_rate);
1421 }
1422 });
1423}
1424
elad.alond12a8e12017-03-23 11:04:48 -07001425void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1426 if (use_twcc_plr_for_ana_)
1427 return;
1428 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1429 if (*encoder) {
1430 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1431 }
minyue7e304322016-10-12 05:00:55 -07001432 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001433}
1434
kwiberg55b97fe2016-01-28 05:22:45 -08001435int32_t Channel::SetVADStatus(bool enableVAD,
1436 ACMVADMode mode,
1437 bool disableDTX) {
1438 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1439 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001440 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1441 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1442 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001443 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1444 kTraceError,
1445 "SetVADStatus() failed to set VAD");
1446 return -1;
1447 }
1448 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001449}
1450
kwiberg55b97fe2016-01-28 05:22:45 -08001451int32_t Channel::GetVADStatus(bool& enabledVAD,
1452 ACMVADMode& mode,
1453 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001454 const auto* params = codec_manager_.GetStackParams();
1455 enabledVAD = params->use_cng;
1456 mode = params->vad_mode;
1457 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001458 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001459}
1460
kwiberg1c07c702017-03-27 07:15:49 -07001461void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1462 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1463 audio_coding_->SetReceiveCodecs(codecs);
1464}
1465
kwiberg55b97fe2016-01-28 05:22:45 -08001466int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
kwibergd32bf752017-01-19 07:03:59 -08001467 return SetRecPayloadType(codec.pltype, CodecInstToSdp(codec));
1468}
1469
1470int32_t Channel::SetRecPayloadType(int payload_type,
1471 const SdpAudioFormat& format) {
kwiberg55b97fe2016-01-28 05:22:45 -08001472 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1473 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001474
kwiberg55b97fe2016-01-28 05:22:45 -08001475 if (channel_state_.Get().playing) {
1476 _engineStatisticsPtr->SetLastError(
1477 VE_ALREADY_PLAYING, kTraceError,
1478 "SetRecPayloadType() unable to set PT while playing");
1479 return -1;
1480 }
kwiberg55b97fe2016-01-28 05:22:45 -08001481
kwiberg09f090c2017-03-01 01:57:11 -08001482 const CodecInst codec = SdpToCodecInst(payload_type, format);
kwibergd32bf752017-01-19 07:03:59 -08001483
1484 if (payload_type == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001485 // De-register the selected codec (RTP/RTCP module and ACM)
1486
1487 int8_t pltype(-1);
1488 CodecInst rxCodec = codec;
1489
1490 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001491 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001492 rxCodec.pltype = pltype;
1493
1494 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1495 _engineStatisticsPtr->SetLastError(
1496 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1497 "SetRecPayloadType() RTP/RTCP-module deregistration "
1498 "failed");
1499 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001500 }
kwiberg55b97fe2016-01-28 05:22:45 -08001501 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1502 _engineStatisticsPtr->SetLastError(
1503 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1504 "SetRecPayloadType() ACM deregistration failed - 1");
1505 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001506 }
kwiberg55b97fe2016-01-28 05:22:45 -08001507 return 0;
1508 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001509
magjed56124bd2016-11-24 09:34:46 -08001510 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001511 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001512 // TODO(kwiberg): Retrying is probably not necessary, since
1513 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001514 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001515 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001516 _engineStatisticsPtr->SetLastError(
1517 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1518 "SetRecPayloadType() RTP/RTCP-module registration failed");
1519 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001520 }
kwiberg55b97fe2016-01-28 05:22:45 -08001521 }
kwibergd32bf752017-01-19 07:03:59 -08001522 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
1523 audio_coding_->UnregisterReceiveCodec(payload_type);
1524 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001525 _engineStatisticsPtr->SetLastError(
1526 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1527 "SetRecPayloadType() ACM registration failed - 1");
1528 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001529 }
kwiberg55b97fe2016-01-28 05:22:45 -08001530 }
1531 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001532}
1533
kwiberg55b97fe2016-01-28 05:22:45 -08001534int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1535 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001536 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001537 _engineStatisticsPtr->SetLastError(
1538 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1539 "GetRecPayloadType() failed to retrieve RX payload type");
1540 return -1;
1541 }
1542 codec.pltype = payloadType;
1543 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001544}
1545
kwiberg55b97fe2016-01-28 05:22:45 -08001546int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1547 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1548 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001549
kwiberg55b97fe2016-01-28 05:22:45 -08001550 CodecInst codec;
1551 int32_t samplingFreqHz(-1);
1552 const size_t kMono = 1;
1553 if (frequency == kFreq32000Hz)
1554 samplingFreqHz = 32000;
1555 else if (frequency == kFreq16000Hz)
1556 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001557
kwiberg55b97fe2016-01-28 05:22:45 -08001558 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1559 _engineStatisticsPtr->SetLastError(
1560 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1561 "SetSendCNPayloadType() failed to retrieve default CN codec "
1562 "settings");
1563 return -1;
1564 }
1565
1566 // Modify the payload type (must be set to dynamic range)
1567 codec.pltype = type;
1568
kwibergc8d071e2016-04-06 12:22:38 -07001569 if (!codec_manager_.RegisterEncoder(codec) ||
1570 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001571 _engineStatisticsPtr->SetLastError(
1572 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1573 "SetSendCNPayloadType() failed to register CN to ACM");
1574 return -1;
1575 }
1576
1577 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1578 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1579 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1580 _engineStatisticsPtr->SetLastError(
1581 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1582 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1583 "module");
1584 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001585 }
kwiberg55b97fe2016-01-28 05:22:45 -08001586 }
1587 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001588}
1589
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001590int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001591 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001592 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001593
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001594 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001595 _engineStatisticsPtr->SetLastError(
1596 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001597 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001598 return -1;
1599 }
1600 return 0;
1601}
1602
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001603int Channel::SetOpusDtx(bool enable_dtx) {
1604 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1605 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001606 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001607 : audio_coding_->DisableOpusDtx();
1608 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001609 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1610 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001611 return -1;
1612 }
1613 return 0;
1614}
1615
ivoc85228d62016-07-27 04:53:47 -07001616int Channel::GetOpusDtx(bool* enabled) {
1617 int success = -1;
1618 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1619 if (encoder) {
1620 *enabled = encoder->GetDtx();
1621 success = 0;
1622 }
1623 });
1624 return success;
1625}
1626
minyue7e304322016-10-12 05:00:55 -07001627bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1628 bool success = false;
1629 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1630 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001631 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1632 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001633 }
1634 });
1635 return success;
1636}
1637
1638void Channel::DisableAudioNetworkAdaptor() {
1639 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1640 if (*encoder)
1641 (*encoder)->DisableAudioNetworkAdaptor();
1642 });
1643}
1644
1645void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1646 int max_frame_length_ms) {
1647 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1648 if (*encoder) {
1649 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1650 max_frame_length_ms);
1651 }
1652 });
1653}
1654
mflodman3d7db262016-04-29 00:57:13 -07001655int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001656 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001657 "Channel::RegisterExternalTransport()");
1658
kwiberg55b97fe2016-01-28 05:22:45 -08001659 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001660 if (_externalTransport) {
1661 _engineStatisticsPtr->SetLastError(
1662 VE_INVALID_OPERATION, kTraceError,
1663 "RegisterExternalTransport() external transport already enabled");
1664 return -1;
1665 }
1666 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001667 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001668 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001669}
1670
kwiberg55b97fe2016-01-28 05:22:45 -08001671int32_t Channel::DeRegisterExternalTransport() {
1672 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1673 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001674
kwiberg55b97fe2016-01-28 05:22:45 -08001675 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001676 if (_transportPtr) {
1677 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1678 "DeRegisterExternalTransport() all transport is disabled");
1679 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001680 _engineStatisticsPtr->SetLastError(
1681 VE_INVALID_OPERATION, kTraceWarning,
1682 "DeRegisterExternalTransport() external transport already "
1683 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001684 }
1685 _externalTransport = false;
1686 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001687 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001688}
1689
nisse657bab22017-02-21 06:28:10 -08001690// TODO(nisse): Delete this method together with ReceivedRTPPacket.
1691// It's a temporary hack to support both ReceivedRTPPacket and
1692// OnRtpPacket interfaces without too much code duplication.
1693bool Channel::OnRtpPacketWithHeader(const uint8_t* received_packet,
1694 size_t length,
1695 RTPHeader *header) {
1696 // Store playout timestamp for the received RTP packet
1697 UpdatePlayoutTimestamp(false);
1698
1699 header->payload_type_frequency =
1700 rtp_payload_registry_->GetPayloadTypeFrequency(header->payloadType);
1701 if (header->payload_type_frequency < 0)
1702 return false;
1703 bool in_order = IsPacketInOrder(*header);
1704 rtp_receive_statistics_->IncomingPacket(
1705 *header, length, IsPacketRetransmitted(*header, in_order));
1706 rtp_payload_registry_->SetIncomingPayloadType(*header);
1707
1708 return ReceivePacket(received_packet, length, *header, in_order);
1709}
1710
mflodman3d7db262016-04-29 00:57:13 -07001711int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001712 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001713 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001714 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001715 "Channel::ReceivedRTPPacket()");
1716
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001717 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001718 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1719 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1720 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001721 return -1;
1722 }
nisse657bab22017-02-21 06:28:10 -08001723 return OnRtpPacketWithHeader(received_packet, length, &header) ? 0 : -1;
1724}
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001725
nisse657bab22017-02-21 06:28:10 -08001726void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1727 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
1728 "Channel::ReceivedRTPPacket()");
1729
1730 RTPHeader header;
1731 packet.GetHeader(&header);
1732 OnRtpPacketWithHeader(packet.data(), packet.size(), &header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001733}
1734
1735bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001736 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001737 const RTPHeader& header,
1738 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001739 if (rtp_payload_registry_->IsRtx(header)) {
1740 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001741 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001742 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001743 assert(packet_length >= header.headerLength);
1744 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001745 PayloadUnion payload_specific;
1746 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001747 &payload_specific)) {
1748 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001749 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001750 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1751 payload_specific, in_order);
1752}
1753
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001754bool Channel::HandleRtxPacket(const uint8_t* packet,
1755 size_t packet_length,
1756 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001757 if (!rtp_payload_registry_->IsRtx(header))
1758 return false;
1759
1760 // Remove the RTX header and parse the original RTP header.
1761 if (packet_length < header.headerLength)
1762 return false;
1763 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1764 return false;
1765 if (restored_packet_in_use_) {
1766 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1767 "Multiple RTX headers detected, dropping packet");
1768 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001769 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001770 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001771 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1772 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001773 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1774 "Incoming RTX packet: invalid RTP header");
1775 return false;
1776 }
1777 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001778 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001779 restored_packet_in_use_ = false;
1780 return ret;
1781}
1782
1783bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1784 StreamStatistician* statistician =
1785 rtp_receive_statistics_->GetStatistician(header.ssrc);
1786 if (!statistician)
1787 return false;
1788 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001789}
1790
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001791bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1792 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001793 // Retransmissions are handled separately if RTX is enabled.
1794 if (rtp_payload_registry_->RtxEnabled())
1795 return false;
1796 StreamStatistician* statistician =
1797 rtp_receive_statistics_->GetStatistician(header.ssrc);
1798 if (!statistician)
1799 return false;
1800 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001801 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001802 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001803 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001804}
1805
mflodman3d7db262016-04-29 00:57:13 -07001806int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001807 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001808 "Channel::ReceivedRTCPPacket()");
1809 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001810 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001811
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001812 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001813 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001814 _engineStatisticsPtr->SetLastError(
1815 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1816 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1817 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001818
Minyue2013aec2015-05-13 14:14:42 +02001819 int64_t rtt = GetRTT(true);
1820 if (rtt == 0) {
1821 // Waiting for valid RTT.
1822 return 0;
1823 }
Erik Språng737336d2016-07-29 12:59:36 +02001824
1825 int64_t nack_window_ms = rtt;
1826 if (nack_window_ms < kMinRetransmissionWindowMs) {
1827 nack_window_ms = kMinRetransmissionWindowMs;
1828 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1829 nack_window_ms = kMaxRetransmissionWindowMs;
1830 }
1831 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1832
minyue7e304322016-10-12 05:00:55 -07001833 // Invoke audio encoders OnReceivedRtt().
1834 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1835 if (*encoder)
1836 (*encoder)->OnReceivedRtt(rtt);
1837 });
1838
Minyue2013aec2015-05-13 14:14:42 +02001839 uint32_t ntp_secs = 0;
1840 uint32_t ntp_frac = 0;
1841 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001842 if (0 !=
1843 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1844 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001845 // Waiting for RTCP.
1846 return 0;
1847 }
1848
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001849 {
tommi31fc21f2016-01-21 10:37:37 -08001850 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001851 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001852 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001853 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001854}
1855
niklase@google.com470e71d2011-07-07 08:21:25 +00001856int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001857 bool loop,
1858 FileFormats format,
1859 int startPosition,
1860 float volumeScaling,
1861 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001862 const CodecInst* codecInst) {
1863 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1864 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1865 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1866 "stopPosition=%d)",
1867 fileName, loop, format, volumeScaling, startPosition,
1868 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001869
kwiberg55b97fe2016-01-28 05:22:45 -08001870 if (channel_state_.Get().output_file_playing) {
1871 _engineStatisticsPtr->SetLastError(
1872 VE_ALREADY_PLAYING, kTraceError,
1873 "StartPlayingFileLocally() is already playing");
1874 return -1;
1875 }
1876
1877 {
1878 rtc::CritScope cs(&_fileCritSect);
1879
kwiberg5a25d952016-08-17 07:31:12 -07001880 if (output_file_player_) {
1881 output_file_player_->RegisterModuleFileCallback(NULL);
1882 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001883 }
1884
kwiberg5b356f42016-09-08 04:32:33 -07001885 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001886 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001887
kwiberg5a25d952016-08-17 07:31:12 -07001888 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001889 _engineStatisticsPtr->SetLastError(
1890 VE_INVALID_ARGUMENT, kTraceError,
1891 "StartPlayingFileLocally() filePlayer format is not correct");
1892 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001893 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001894
kwiberg55b97fe2016-01-28 05:22:45 -08001895 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001896
kwiberg5a25d952016-08-17 07:31:12 -07001897 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001898 fileName, loop, startPosition, volumeScaling, notificationTime,
1899 stopPosition, (const CodecInst*)codecInst) != 0) {
1900 _engineStatisticsPtr->SetLastError(
1901 VE_BAD_FILE, kTraceError,
1902 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001903 output_file_player_->StopPlayingFile();
1904 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001905 return -1;
1906 }
kwiberg5a25d952016-08-17 07:31:12 -07001907 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001908 channel_state_.SetOutputFilePlaying(true);
1909 }
1910
1911 if (RegisterFilePlayingToMixer() != 0)
1912 return -1;
1913
1914 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001915}
1916
1917int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001918 FileFormats format,
1919 int startPosition,
1920 float volumeScaling,
1921 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001922 const CodecInst* codecInst) {
1923 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1924 "Channel::StartPlayingFileLocally(format=%d,"
1925 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1926 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001927
kwiberg55b97fe2016-01-28 05:22:45 -08001928 if (stream == NULL) {
1929 _engineStatisticsPtr->SetLastError(
1930 VE_BAD_FILE, kTraceError,
1931 "StartPlayingFileLocally() NULL as input stream");
1932 return -1;
1933 }
1934
1935 if (channel_state_.Get().output_file_playing) {
1936 _engineStatisticsPtr->SetLastError(
1937 VE_ALREADY_PLAYING, kTraceError,
1938 "StartPlayingFileLocally() is already playing");
1939 return -1;
1940 }
1941
1942 {
1943 rtc::CritScope cs(&_fileCritSect);
1944
1945 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001946 if (output_file_player_) {
1947 output_file_player_->RegisterModuleFileCallback(NULL);
1948 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001949 }
1950
kwiberg55b97fe2016-01-28 05:22:45 -08001951 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001952 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001953 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001954
kwiberg5a25d952016-08-17 07:31:12 -07001955 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001956 _engineStatisticsPtr->SetLastError(
1957 VE_INVALID_ARGUMENT, kTraceError,
1958 "StartPlayingFileLocally() filePlayer format isnot correct");
1959 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001960 }
1961
kwiberg55b97fe2016-01-28 05:22:45 -08001962 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001963
kwiberg4ec01d92016-08-22 08:43:54 -07001964 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001965 volumeScaling, notificationTime,
1966 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001967 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1968 "StartPlayingFile() failed to "
1969 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001970 output_file_player_->StopPlayingFile();
1971 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001972 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001973 }
kwiberg5a25d952016-08-17 07:31:12 -07001974 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001975 channel_state_.SetOutputFilePlaying(true);
1976 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001977
kwiberg55b97fe2016-01-28 05:22:45 -08001978 if (RegisterFilePlayingToMixer() != 0)
1979 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001980
kwiberg55b97fe2016-01-28 05:22:45 -08001981 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001982}
1983
kwiberg55b97fe2016-01-28 05:22:45 -08001984int Channel::StopPlayingFileLocally() {
1985 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1986 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001987
kwiberg55b97fe2016-01-28 05:22:45 -08001988 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001989 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001990 }
1991
1992 {
1993 rtc::CritScope cs(&_fileCritSect);
1994
kwiberg5a25d952016-08-17 07:31:12 -07001995 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001996 _engineStatisticsPtr->SetLastError(
1997 VE_STOP_RECORDING_FAILED, kTraceError,
1998 "StopPlayingFile() could not stop playing");
1999 return -1;
2000 }
kwiberg5a25d952016-08-17 07:31:12 -07002001 output_file_player_->RegisterModuleFileCallback(NULL);
2002 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002003 channel_state_.SetOutputFilePlaying(false);
2004 }
2005 // _fileCritSect cannot be taken while calling
2006 // SetAnonymousMixibilityStatus. Refer to comments in
2007 // StartPlayingFileLocally(const char* ...) for more details.
2008 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
2009 _engineStatisticsPtr->SetLastError(
2010 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
2011 "StopPlayingFile() failed to stop participant from playing as"
2012 "file in the mixer");
2013 return -1;
2014 }
2015
2016 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002017}
2018
kwiberg55b97fe2016-01-28 05:22:45 -08002019int Channel::IsPlayingFileLocally() const {
2020 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002021}
2022
kwiberg55b97fe2016-01-28 05:22:45 -08002023int Channel::RegisterFilePlayingToMixer() {
2024 // Return success for not registering for file playing to mixer if:
2025 // 1. playing file before playout is started on that channel.
2026 // 2. starting playout without file playing on that channel.
2027 if (!channel_state_.Get().playing ||
2028 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00002029 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002030 }
2031
2032 // |_fileCritSect| cannot be taken while calling
2033 // SetAnonymousMixabilityStatus() since as soon as the participant is added
2034 // frames can be pulled by the mixer. Since the frames are generated from
2035 // the file, _fileCritSect will be taken. This would result in a deadlock.
2036 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
2037 channel_state_.SetOutputFilePlaying(false);
2038 rtc::CritScope cs(&_fileCritSect);
2039 _engineStatisticsPtr->SetLastError(
2040 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
2041 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07002042 output_file_player_->StopPlayingFile();
2043 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002044 return -1;
2045 }
2046
2047 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00002048}
2049
niklase@google.com470e71d2011-07-07 08:21:25 +00002050int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002051 bool loop,
2052 FileFormats format,
2053 int startPosition,
2054 float volumeScaling,
2055 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002056 const CodecInst* codecInst) {
2057 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2058 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
2059 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
2060 "stopPosition=%d)",
2061 fileName, loop, format, volumeScaling, startPosition,
2062 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002063
kwiberg55b97fe2016-01-28 05:22:45 -08002064 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002065
kwiberg55b97fe2016-01-28 05:22:45 -08002066 if (channel_state_.Get().input_file_playing) {
2067 _engineStatisticsPtr->SetLastError(
2068 VE_ALREADY_PLAYING, kTraceWarning,
2069 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002070 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002071 }
2072
2073 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002074 if (input_file_player_) {
2075 input_file_player_->RegisterModuleFileCallback(NULL);
2076 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002077 }
2078
2079 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002080 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002081 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002082
kwiberg5a25d952016-08-17 07:31:12 -07002083 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002084 _engineStatisticsPtr->SetLastError(
2085 VE_INVALID_ARGUMENT, kTraceError,
2086 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
2087 return -1;
2088 }
2089
2090 const uint32_t notificationTime(0);
2091
kwiberg5a25d952016-08-17 07:31:12 -07002092 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002093 fileName, loop, startPosition, volumeScaling, notificationTime,
2094 stopPosition, (const CodecInst*)codecInst) != 0) {
2095 _engineStatisticsPtr->SetLastError(
2096 VE_BAD_FILE, kTraceError,
2097 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002098 input_file_player_->StopPlayingFile();
2099 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002100 return -1;
2101 }
kwiberg5a25d952016-08-17 07:31:12 -07002102 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002103 channel_state_.SetInputFilePlaying(true);
2104
2105 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002106}
2107
2108int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002109 FileFormats format,
2110 int startPosition,
2111 float volumeScaling,
2112 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002113 const CodecInst* codecInst) {
2114 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2115 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2116 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2117 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002118
kwiberg55b97fe2016-01-28 05:22:45 -08002119 if (stream == NULL) {
2120 _engineStatisticsPtr->SetLastError(
2121 VE_BAD_FILE, kTraceError,
2122 "StartPlayingFileAsMicrophone NULL as input stream");
2123 return -1;
2124 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002125
kwiberg55b97fe2016-01-28 05:22:45 -08002126 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002127
kwiberg55b97fe2016-01-28 05:22:45 -08002128 if (channel_state_.Get().input_file_playing) {
2129 _engineStatisticsPtr->SetLastError(
2130 VE_ALREADY_PLAYING, kTraceWarning,
2131 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002132 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002133 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002134
kwiberg55b97fe2016-01-28 05:22:45 -08002135 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002136 if (input_file_player_) {
2137 input_file_player_->RegisterModuleFileCallback(NULL);
2138 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002139 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002140
kwiberg55b97fe2016-01-28 05:22:45 -08002141 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002142 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002143 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002144
kwiberg5a25d952016-08-17 07:31:12 -07002145 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002146 _engineStatisticsPtr->SetLastError(
2147 VE_INVALID_ARGUMENT, kTraceError,
2148 "StartPlayingInputFile() filePlayer format isnot correct");
2149 return -1;
2150 }
2151
2152 const uint32_t notificationTime(0);
2153
kwiberg4ec01d92016-08-22 08:43:54 -07002154 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2155 notificationTime, stopPosition,
2156 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002157 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2158 "StartPlayingFile() failed to start "
2159 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002160 input_file_player_->StopPlayingFile();
2161 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002162 return -1;
2163 }
2164
kwiberg5a25d952016-08-17 07:31:12 -07002165 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002166 channel_state_.SetInputFilePlaying(true);
2167
2168 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002169}
2170
kwiberg55b97fe2016-01-28 05:22:45 -08002171int Channel::StopPlayingFileAsMicrophone() {
2172 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2173 "Channel::StopPlayingFileAsMicrophone()");
2174
2175 rtc::CritScope cs(&_fileCritSect);
2176
2177 if (!channel_state_.Get().input_file_playing) {
2178 return 0;
2179 }
2180
kwiberg5a25d952016-08-17 07:31:12 -07002181 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002182 _engineStatisticsPtr->SetLastError(
2183 VE_STOP_RECORDING_FAILED, kTraceError,
2184 "StopPlayingFile() could not stop playing");
2185 return -1;
2186 }
kwiberg5a25d952016-08-17 07:31:12 -07002187 input_file_player_->RegisterModuleFileCallback(NULL);
2188 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002189 channel_state_.SetInputFilePlaying(false);
2190
2191 return 0;
2192}
2193
2194int Channel::IsPlayingFileAsMicrophone() const {
2195 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002196}
2197
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002198int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002199 const CodecInst* codecInst) {
2200 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2201 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002202
kwiberg55b97fe2016-01-28 05:22:45 -08002203 if (_outputFileRecording) {
2204 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2205 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002206 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002207 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002208
kwiberg55b97fe2016-01-28 05:22:45 -08002209 FileFormats format;
2210 const uint32_t notificationTime(0); // Not supported in VoE
2211 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002212
kwiberg55b97fe2016-01-28 05:22:45 -08002213 if ((codecInst != NULL) &&
2214 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2215 _engineStatisticsPtr->SetLastError(
2216 VE_BAD_ARGUMENT, kTraceError,
2217 "StartRecordingPlayout() invalid compression");
2218 return (-1);
2219 }
2220 if (codecInst == NULL) {
2221 format = kFileFormatPcm16kHzFile;
2222 codecInst = &dummyCodec;
2223 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2224 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2225 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2226 format = kFileFormatWavFile;
2227 } else {
2228 format = kFileFormatCompressedFile;
2229 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002230
kwiberg55b97fe2016-01-28 05:22:45 -08002231 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002232
kwiberg55b97fe2016-01-28 05:22:45 -08002233 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002234 if (output_file_recorder_) {
2235 output_file_recorder_->RegisterModuleFileCallback(NULL);
2236 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002237 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002238
kwiberg5a25d952016-08-17 07:31:12 -07002239 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002240 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002241 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002242 _engineStatisticsPtr->SetLastError(
2243 VE_INVALID_ARGUMENT, kTraceError,
2244 "StartRecordingPlayout() fileRecorder format isnot correct");
2245 return -1;
2246 }
2247
kwiberg5a25d952016-08-17 07:31:12 -07002248 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002249 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2250 _engineStatisticsPtr->SetLastError(
2251 VE_BAD_FILE, kTraceError,
2252 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002253 output_file_recorder_->StopRecording();
2254 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002255 return -1;
2256 }
kwiberg5a25d952016-08-17 07:31:12 -07002257 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002258 _outputFileRecording = true;
2259
2260 return 0;
2261}
2262
2263int Channel::StartRecordingPlayout(OutStream* stream,
2264 const CodecInst* codecInst) {
2265 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2266 "Channel::StartRecordingPlayout()");
2267
2268 if (_outputFileRecording) {
2269 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2270 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002271 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002272 }
2273
2274 FileFormats format;
2275 const uint32_t notificationTime(0); // Not supported in VoE
2276 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2277
2278 if (codecInst != NULL && codecInst->channels != 1) {
2279 _engineStatisticsPtr->SetLastError(
2280 VE_BAD_ARGUMENT, kTraceError,
2281 "StartRecordingPlayout() invalid compression");
2282 return (-1);
2283 }
2284 if (codecInst == NULL) {
2285 format = kFileFormatPcm16kHzFile;
2286 codecInst = &dummyCodec;
2287 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2288 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2289 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2290 format = kFileFormatWavFile;
2291 } else {
2292 format = kFileFormatCompressedFile;
2293 }
2294
2295 rtc::CritScope cs(&_fileCritSect);
2296
2297 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002298 if (output_file_recorder_) {
2299 output_file_recorder_->RegisterModuleFileCallback(NULL);
2300 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002301 }
2302
kwiberg5a25d952016-08-17 07:31:12 -07002303 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002304 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002305 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002306 _engineStatisticsPtr->SetLastError(
2307 VE_INVALID_ARGUMENT, kTraceError,
2308 "StartRecordingPlayout() fileRecorder format isnot correct");
2309 return -1;
2310 }
2311
kwiberg4ec01d92016-08-22 08:43:54 -07002312 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002313 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002314 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2315 "StartRecordingPlayout() failed to "
2316 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002317 output_file_recorder_->StopRecording();
2318 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002319 return -1;
2320 }
2321
kwiberg5a25d952016-08-17 07:31:12 -07002322 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002323 _outputFileRecording = true;
2324
2325 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002326}
2327
kwiberg55b97fe2016-01-28 05:22:45 -08002328int Channel::StopRecordingPlayout() {
2329 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2330 "Channel::StopRecordingPlayout()");
2331
2332 if (!_outputFileRecording) {
2333 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2334 "StopRecordingPlayout() isnot recording");
2335 return -1;
2336 }
2337
2338 rtc::CritScope cs(&_fileCritSect);
2339
kwiberg5a25d952016-08-17 07:31:12 -07002340 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002341 _engineStatisticsPtr->SetLastError(
2342 VE_STOP_RECORDING_FAILED, kTraceError,
2343 "StopRecording() could not stop recording");
2344 return (-1);
2345 }
kwiberg5a25d952016-08-17 07:31:12 -07002346 output_file_recorder_->RegisterModuleFileCallback(NULL);
2347 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002348 _outputFileRecording = false;
2349
2350 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002351}
2352
kwiberg55b97fe2016-01-28 05:22:45 -08002353void Channel::SetMixWithMicStatus(bool mix) {
2354 rtc::CritScope cs(&_fileCritSect);
2355 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002356}
2357
solenberg8d73f8c2017-03-08 01:52:20 -08002358int Channel::GetSpeechOutputLevel() const {
2359 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002360}
2361
solenberg8d73f8c2017-03-08 01:52:20 -08002362int Channel::GetSpeechOutputLevelFullRange() const {
2363 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08002364}
2365
solenberg8d73f8c2017-03-08 01:52:20 -08002366void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002367 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002368 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002369}
2370
solenberg1c2af8e2016-03-24 10:36:00 -07002371bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002372 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002373 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002374}
2375
solenberg8d73f8c2017-03-08 01:52:20 -08002376void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08002377 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08002378 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00002379}
2380
solenberg8842c3e2016-03-11 03:06:41 -08002381int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002382 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002383 "Channel::SendTelephoneEventOutband(...)");
2384 RTC_DCHECK_LE(0, event);
2385 RTC_DCHECK_GE(255, event);
2386 RTC_DCHECK_LE(0, duration_ms);
2387 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002388 if (!Sending()) {
2389 return -1;
2390 }
solenberg8842c3e2016-03-11 03:06:41 -08002391 if (_rtpRtcpModule->SendTelephoneEventOutband(
2392 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002393 _engineStatisticsPtr->SetLastError(
2394 VE_SEND_DTMF_FAILED, kTraceWarning,
2395 "SendTelephoneEventOutband() failed to send event");
2396 return -1;
2397 }
2398 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002399}
2400
solenbergffbbcac2016-11-17 05:25:37 -08002401int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2402 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002403 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002404 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002405 RTC_DCHECK_LE(0, payload_type);
2406 RTC_DCHECK_GE(127, payload_type);
2407 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002408 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002409 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002410 memcpy(codec.plname, "telephone-event", 16);
2411 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2412 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2413 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2414 _engineStatisticsPtr->SetLastError(
2415 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2416 "SetSendTelephoneEventPayloadType() failed to register send"
2417 "payload type");
2418 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002419 }
kwiberg55b97fe2016-01-28 05:22:45 -08002420 }
kwiberg55b97fe2016-01-28 05:22:45 -08002421 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002422}
2423
kwiberg55b97fe2016-01-28 05:22:45 -08002424int Channel::SetLocalSSRC(unsigned int ssrc) {
2425 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2426 "Channel::SetLocalSSRC()");
2427 if (channel_state_.Get().sending) {
2428 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2429 "SetLocalSSRC() already sending");
2430 return -1;
2431 }
2432 _rtpRtcpModule->SetSSRC(ssrc);
2433 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002434}
2435
kwiberg55b97fe2016-01-28 05:22:45 -08002436int Channel::GetLocalSSRC(unsigned int& ssrc) {
2437 ssrc = _rtpRtcpModule->SSRC();
2438 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002439}
2440
kwiberg55b97fe2016-01-28 05:22:45 -08002441int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2442 ssrc = rtp_receiver_->SSRC();
2443 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002444}
2445
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002446int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002447 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002448 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002449}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002450
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002451int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2452 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002453 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2454 if (enable &&
2455 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2456 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002457 return -1;
2458 }
2459 return 0;
2460}
2461
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002462void Channel::EnableSendTransportSequenceNumber(int id) {
2463 int ret =
2464 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2465 RTC_DCHECK_EQ(0, ret);
2466}
2467
stefan3313ec92016-01-21 06:32:43 -08002468void Channel::EnableReceiveTransportSequenceNumber(int id) {
2469 rtp_header_parser_->DeregisterRtpHeaderExtension(
2470 kRtpExtensionTransportSequenceNumber);
2471 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2472 kRtpExtensionTransportSequenceNumber, id);
2473 RTC_DCHECK(ret);
2474}
2475
stefanbba9dec2016-02-01 04:39:55 -08002476void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07002477 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08002478 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07002479 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
2480 TransportFeedbackObserver* transport_feedback_observer =
2481 transport->transport_feedback_observer();
2482 PacketRouter* packet_router = transport->packet_router();
2483
stefanbba9dec2016-02-01 04:39:55 -08002484 RTC_DCHECK(rtp_packet_sender);
2485 RTC_DCHECK(transport_feedback_observer);
2486 RTC_DCHECK(packet_router && !packet_router_);
stefan7de8d642017-02-07 07:14:08 -08002487 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08002488 feedback_observer_proxy_->SetTransportFeedbackObserver(
2489 transport_feedback_observer);
2490 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2491 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2492 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
nissefdbfdc92017-03-31 05:44:52 -07002493 packet_router->AddSendRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002494 packet_router_ = packet_router;
2495}
2496
stefanbba9dec2016-02-01 04:39:55 -08002497void Channel::RegisterReceiverCongestionControlObjects(
2498 PacketRouter* packet_router) {
2499 RTC_DCHECK(packet_router && !packet_router_);
nissefdbfdc92017-03-31 05:44:52 -07002500 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002501 packet_router_ = packet_router;
2502}
2503
nissefdbfdc92017-03-31 05:44:52 -07002504void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08002505 RTC_DCHECK(packet_router_);
2506 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08002507 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08002508 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2509 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07002510 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002511 packet_router_ = nullptr;
2512 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2513}
2514
nissefdbfdc92017-03-31 05:44:52 -07002515void Channel::ResetReceiverCongestionControlObjects() {
2516 RTC_DCHECK(packet_router_);
2517 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
2518 packet_router_ = nullptr;
2519}
2520
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002521void Channel::SetRTCPStatus(bool enable) {
2522 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2523 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002524 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002525}
2526
kwiberg55b97fe2016-01-28 05:22:45 -08002527int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002528 RtcpMode method = _rtpRtcpModule->RTCP();
2529 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002530 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002531}
2532
kwiberg55b97fe2016-01-28 05:22:45 -08002533int Channel::SetRTCP_CNAME(const char cName[256]) {
2534 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2535 "Channel::SetRTCP_CNAME()");
2536 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2537 _engineStatisticsPtr->SetLastError(
2538 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2539 "SetRTCP_CNAME() failed to set RTCP CNAME");
2540 return -1;
2541 }
2542 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002543}
2544
kwiberg55b97fe2016-01-28 05:22:45 -08002545int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2546 if (cName == NULL) {
2547 _engineStatisticsPtr->SetLastError(
2548 VE_INVALID_ARGUMENT, kTraceError,
2549 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2550 return -1;
2551 }
2552 char cname[RTCP_CNAME_SIZE];
2553 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2554 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2555 _engineStatisticsPtr->SetLastError(
2556 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2557 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2558 return -1;
2559 }
2560 strcpy(cName, cname);
2561 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002562}
2563
kwiberg55b97fe2016-01-28 05:22:45 -08002564int Channel::SendApplicationDefinedRTCPPacket(
2565 unsigned char subType,
2566 unsigned int name,
2567 const char* data,
2568 unsigned short dataLengthInBytes) {
2569 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2570 "Channel::SendApplicationDefinedRTCPPacket()");
2571 if (!channel_state_.Get().sending) {
2572 _engineStatisticsPtr->SetLastError(
2573 VE_NOT_SENDING, kTraceError,
2574 "SendApplicationDefinedRTCPPacket() not sending");
2575 return -1;
2576 }
2577 if (NULL == data) {
2578 _engineStatisticsPtr->SetLastError(
2579 VE_INVALID_ARGUMENT, kTraceError,
2580 "SendApplicationDefinedRTCPPacket() invalid data value");
2581 return -1;
2582 }
2583 if (dataLengthInBytes % 4 != 0) {
2584 _engineStatisticsPtr->SetLastError(
2585 VE_INVALID_ARGUMENT, kTraceError,
2586 "SendApplicationDefinedRTCPPacket() invalid length value");
2587 return -1;
2588 }
2589 RtcpMode status = _rtpRtcpModule->RTCP();
2590 if (status == RtcpMode::kOff) {
2591 _engineStatisticsPtr->SetLastError(
2592 VE_RTCP_ERROR, kTraceError,
2593 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2594 return -1;
2595 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002596
kwiberg55b97fe2016-01-28 05:22:45 -08002597 // Create and schedule the RTCP APP packet for transmission
2598 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2599 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2600 _engineStatisticsPtr->SetLastError(
2601 VE_SEND_ERROR, kTraceError,
2602 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2603 return -1;
2604 }
2605 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002606}
2607
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002608int Channel::GetRemoteRTCPReportBlocks(
2609 std::vector<ReportBlock>* report_blocks) {
2610 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002611 _engineStatisticsPtr->SetLastError(
2612 VE_INVALID_ARGUMENT, kTraceError,
2613 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002614 return -1;
2615 }
2616
2617 // Get the report blocks from the latest received RTCP Sender or Receiver
2618 // Report. Each element in the vector contains the sender's SSRC and a
2619 // report block according to RFC 3550.
2620 std::vector<RTCPReportBlock> rtcp_report_blocks;
2621 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002622 return -1;
2623 }
2624
2625 if (rtcp_report_blocks.empty())
2626 return 0;
2627
2628 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2629 for (; it != rtcp_report_blocks.end(); ++it) {
2630 ReportBlock report_block;
2631 report_block.sender_SSRC = it->remoteSSRC;
2632 report_block.source_SSRC = it->sourceSSRC;
2633 report_block.fraction_lost = it->fractionLost;
2634 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2635 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2636 report_block.interarrival_jitter = it->jitter;
2637 report_block.last_SR_timestamp = it->lastSR;
2638 report_block.delay_since_last_SR = it->delaySinceLastSR;
2639 report_blocks->push_back(report_block);
2640 }
2641 return 0;
2642}
2643
kwiberg55b97fe2016-01-28 05:22:45 -08002644int Channel::GetRTPStatistics(CallStatistics& stats) {
2645 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002646
kwiberg55b97fe2016-01-28 05:22:45 -08002647 // The jitter statistics is updated for each received RTP packet and is
2648 // based on received packets.
2649 RtcpStatistics statistics;
2650 StreamStatistician* statistician =
2651 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002652 if (statistician) {
2653 statistician->GetStatistics(&statistics,
2654 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002655 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002656
kwiberg55b97fe2016-01-28 05:22:45 -08002657 stats.fractionLost = statistics.fraction_lost;
2658 stats.cumulativeLost = statistics.cumulative_lost;
2659 stats.extendedMax = statistics.extended_max_sequence_number;
2660 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002661
kwiberg55b97fe2016-01-28 05:22:45 -08002662 // --- RTT
2663 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002664
kwiberg55b97fe2016-01-28 05:22:45 -08002665 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002666
kwiberg55b97fe2016-01-28 05:22:45 -08002667 size_t bytesSent(0);
2668 uint32_t packetsSent(0);
2669 size_t bytesReceived(0);
2670 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002671
kwiberg55b97fe2016-01-28 05:22:45 -08002672 if (statistician) {
2673 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2674 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002675
kwiberg55b97fe2016-01-28 05:22:45 -08002676 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2677 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2678 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2679 " output will not be complete");
2680 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002681
kwiberg55b97fe2016-01-28 05:22:45 -08002682 stats.bytesSent = bytesSent;
2683 stats.packetsSent = packetsSent;
2684 stats.bytesReceived = bytesReceived;
2685 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002686
kwiberg55b97fe2016-01-28 05:22:45 -08002687 // --- Timestamps
2688 {
2689 rtc::CritScope lock(&ts_stats_lock_);
2690 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2691 }
2692 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002693}
2694
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002695int Channel::SetCodecFECStatus(bool enable) {
2696 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2697 "Channel::SetCodecFECStatus()");
2698
kwibergc8d071e2016-04-06 12:22:38 -07002699 if (!codec_manager_.SetCodecFEC(enable) ||
2700 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002701 _engineStatisticsPtr->SetLastError(
2702 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2703 "SetCodecFECStatus() failed to set FEC state");
2704 return -1;
2705 }
2706 return 0;
2707}
2708
2709bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002710 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002711}
2712
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002713void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2714 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002715 // If pacing is enabled we always store packets.
2716 if (!pacing_enabled_)
2717 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002718 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002719 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002720 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002721 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002722 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002723}
2724
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002725// Called when we are missing one or more packets.
2726int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002727 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2728}
2729
henrikaec6fbd22017-03-31 05:43:36 -07002730void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07002731 // Avoid posting any new tasks if sending was already stopped in StopSend().
2732 rtc::CritScope cs(&encoder_queue_lock_);
2733 if (!encoder_queue_is_active_) {
2734 return;
2735 }
henrikaec6fbd22017-03-31 05:43:36 -07002736 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
2737 // TODO(henrika): try to avoid copying by moving ownership of audio frame
2738 // either into pool of frames or into the task itself.
2739 audio_frame->CopyFrom(audio_input);
2740 audio_frame->id_ = ChannelId();
2741 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
2742 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00002743}
2744
henrikaec6fbd22017-03-31 05:43:36 -07002745void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
2746 int sample_rate,
2747 size_t number_of_frames,
2748 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07002749 // Avoid posting as new task if sending was already stopped in StopSend().
2750 rtc::CritScope cs(&encoder_queue_lock_);
2751 if (!encoder_queue_is_active_) {
2752 return;
2753 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002754 CodecInst codec;
2755 GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07002756 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
2757 audio_frame->id_ = ChannelId();
2758 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2759 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002760 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07002761 sample_rate, &input_resampler_, audio_frame.get());
2762 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
2763 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002764}
2765
henrikaec6fbd22017-03-31 05:43:36 -07002766void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
2767 RTC_DCHECK_RUN_ON(encoder_queue_);
2768 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
2769 RTC_DCHECK_LE(audio_input->num_channels_, 2);
2770 RTC_DCHECK_EQ(audio_input->id_, ChannelId());
kwiberg55b97fe2016-01-28 05:22:45 -08002771
2772 if (channel_state_.Get().input_file_playing) {
henrikaec6fbd22017-03-31 05:43:36 -07002773 MixOrReplaceAudioWithFile(audio_input);
kwiberg55b97fe2016-01-28 05:22:45 -08002774 }
2775
henrikaec6fbd22017-03-31 05:43:36 -07002776 bool is_muted = InputMute();
2777 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002778
kwiberg55b97fe2016-01-28 05:22:45 -08002779 if (_includeAudioLevelIndication) {
2780 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07002781 audio_input->samples_per_channel_ * audio_input->num_channels_;
2782 RTC_CHECK_LE(length, sizeof(audio_input->data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002783 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002784 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002785 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002786 rms_level_.Analyze(
henrikaec6fbd22017-03-31 05:43:36 -07002787 rtc::ArrayView<const int16_t>(audio_input->data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002788 }
kwiberg55b97fe2016-01-28 05:22:45 -08002789 }
solenberg1c2af8e2016-03-24 10:36:00 -07002790 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002791
henrikaec6fbd22017-03-31 05:43:36 -07002792 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002793
kwiberg55b97fe2016-01-28 05:22:45 -08002794 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07002795 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08002796 // This call will trigger AudioPacketizationCallback::SendData if encoding
2797 // is done and payload is ready for packetization and transmission.
2798 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07002799 if (audio_coding_->Add10MsData(*audio_input) < 0) {
2800 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
2801 return;
kwiberg55b97fe2016-01-28 05:22:45 -08002802 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002803
henrikaec6fbd22017-03-31 05:43:36 -07002804 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00002805}
2806
solenberg7602aab2016-11-14 11:30:07 -08002807void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2808 RTC_DCHECK(!channel.channel() ||
2809 channel.channel()->ChannelId() != _channelId);
2810 rtc::CritScope lock(&assoc_send_channel_lock_);
2811 associate_send_channel_ = channel;
2812}
2813
Minyue2013aec2015-05-13 14:14:42 +02002814void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002815 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002816 Channel* channel = associate_send_channel_.channel();
2817 if (channel && channel->ChannelId() == channel_id) {
2818 // If this channel is associated with a send channel of the specified
2819 // Channel ID, disassociate with it.
2820 ChannelOwner ref(NULL);
2821 associate_send_channel_ = ref;
2822 }
2823}
2824
ivoc14d5dbe2016-07-04 07:06:55 -07002825void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2826 event_log_proxy_->SetEventLog(event_log);
2827}
2828
michaelt9332b7d2016-11-30 07:51:13 -08002829void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2830 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2831}
2832
nisse284542b2017-01-10 08:58:32 -08002833void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08002834 size_t overhead_per_packet =
2835 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08002836 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2837 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08002838 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08002839 }
2840 });
2841}
2842
2843void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002844 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002845 transport_overhead_per_packet_ = transport_overhead_per_packet;
2846 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08002847}
2848
hbos3fd31fe2017-02-28 05:43:16 -08002849// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08002850void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002851 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002852 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
2853 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08002854}
2855
kwiberg55b97fe2016-01-28 05:22:45 -08002856int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2857 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002858}
2859
wu@webrtc.org24301a62013-12-13 19:17:43 +00002860void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2861 audio_coding_->GetDecodingCallStatistics(stats);
2862}
2863
solenberg358057b2015-11-27 10:46:42 -08002864uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08002865 rtc::CritScope lock(&video_sync_lock_);
2866 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07002867}
2868
kwiberg55b97fe2016-01-28 05:22:45 -08002869int Channel::SetMinimumPlayoutDelay(int delayMs) {
2870 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2871 "Channel::SetMinimumPlayoutDelay()");
2872 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
2873 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
2874 _engineStatisticsPtr->SetLastError(
2875 VE_INVALID_ARGUMENT, kTraceError,
2876 "SetMinimumPlayoutDelay() invalid min delay");
2877 return -1;
2878 }
2879 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
2880 _engineStatisticsPtr->SetLastError(
2881 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2882 "SetMinimumPlayoutDelay() failed to set min playout delay");
2883 return -1;
2884 }
2885 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002886}
2887
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002888int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07002889 uint32_t playout_timestamp_rtp = 0;
2890 {
tommi31fc21f2016-01-21 10:37:37 -08002891 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07002892 playout_timestamp_rtp = playout_timestamp_rtp_;
2893 }
kwiberg55b97fe2016-01-28 05:22:45 -08002894 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002895 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07002896 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002897 "GetPlayoutTimestamp() failed to retrieve timestamp");
2898 return -1;
2899 }
deadbeef74375882015-08-13 12:09:10 -07002900 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002901 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002902}
2903
kwiberg55b97fe2016-01-28 05:22:45 -08002904int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
2905 RtpReceiver** rtp_receiver) const {
2906 *rtpRtcpModule = _rtpRtcpModule.get();
2907 *rtp_receiver = rtp_receiver_.get();
2908 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002909}
2910
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00002911// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
2912// a shared helper.
henrikaec6fbd22017-03-31 05:43:36 -07002913int32_t Channel::MixOrReplaceAudioWithFile(AudioFrame* audio_input) {
2914 RTC_DCHECK_RUN_ON(encoder_queue_);
kwibergb7f89d62016-02-17 10:04:18 -08002915 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08002916 size_t fileSamples(0);
henrikaec6fbd22017-03-31 05:43:36 -07002917 const int mixingFrequency = audio_input->sample_rate_hz_;
kwiberg55b97fe2016-01-28 05:22:45 -08002918 {
2919 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002920
kwiberg5a25d952016-08-17 07:31:12 -07002921 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002922 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2923 "Channel::MixOrReplaceAudioWithFile() fileplayer"
2924 " doesnt exist");
2925 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002926 }
2927
kwiberg4ec01d92016-08-22 08:43:54 -07002928 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07002929 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002930 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2931 "Channel::MixOrReplaceAudioWithFile() file mixing "
2932 "failed");
2933 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002934 }
kwiberg55b97fe2016-01-28 05:22:45 -08002935 if (fileSamples == 0) {
2936 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2937 "Channel::MixOrReplaceAudioWithFile() file is ended");
2938 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002939 }
kwiberg55b97fe2016-01-28 05:22:45 -08002940 }
2941
henrikaec6fbd22017-03-31 05:43:36 -07002942 RTC_DCHECK_EQ(audio_input->samples_per_channel_, fileSamples);
kwiberg55b97fe2016-01-28 05:22:45 -08002943
2944 if (_mixFileWithMicrophone) {
2945 // Currently file stream is always mono.
2946 // TODO(xians): Change the code when FilePlayer supports real stereo.
henrikaec6fbd22017-03-31 05:43:36 -07002947 MixWithSat(audio_input->data_, audio_input->num_channels_, fileBuffer.get(),
kwiberg55b97fe2016-01-28 05:22:45 -08002948 1, fileSamples);
2949 } else {
2950 // Replace ACM audio with file.
2951 // Currently file stream is always mono.
2952 // TODO(xians): Change the code when FilePlayer supports real stereo.
henrikaec6fbd22017-03-31 05:43:36 -07002953 audio_input->UpdateFrame(
kwiberg55b97fe2016-01-28 05:22:45 -08002954 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
2955 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
2956 }
2957 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002958}
2959
kwiberg55b97fe2016-01-28 05:22:45 -08002960int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
2961 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00002962
kwibergb7f89d62016-02-17 10:04:18 -08002963 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08002964 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002965
kwiberg55b97fe2016-01-28 05:22:45 -08002966 {
2967 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002968
kwiberg5a25d952016-08-17 07:31:12 -07002969 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002970 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2971 "Channel::MixAudioWithFile() file mixing failed");
2972 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002973 }
2974
kwiberg55b97fe2016-01-28 05:22:45 -08002975 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07002976 if (output_file_player_->Get10msAudioFromFile(
2977 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002978 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2979 "Channel::MixAudioWithFile() file mixing failed");
2980 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002981 }
kwiberg55b97fe2016-01-28 05:22:45 -08002982 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002983
kwiberg55b97fe2016-01-28 05:22:45 -08002984 if (audioFrame.samples_per_channel_ == fileSamples) {
2985 // Currently file stream is always mono.
2986 // TODO(xians): Change the code when FilePlayer supports real stereo.
2987 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
2988 fileSamples);
2989 } else {
2990 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2991 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
2992 ") != "
2993 "fileSamples(%" PRIuS ")",
2994 audioFrame.samples_per_channel_, fileSamples);
2995 return -1;
2996 }
2997
2998 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002999}
3000
deadbeef74375882015-08-13 12:09:10 -07003001void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003002 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003003
henrik.lundin96bd5022016-04-06 04:13:56 -07003004 if (!jitter_buffer_playout_timestamp_) {
3005 // This can happen if this channel has not received any RTP packets. In
3006 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003007 return;
3008 }
3009
3010 uint16_t delay_ms = 0;
3011 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003012 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003013 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3014 " delay from the ADM");
3015 _engineStatisticsPtr->SetLastError(
3016 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3017 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3018 return;
3019 }
3020
henrik.lundin96bd5022016-04-06 04:13:56 -07003021 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3022 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003023
3024 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07003025 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003026
kwiberg55b97fe2016-01-28 05:22:45 -08003027 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003028 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003029 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003030
3031 {
tommi31fc21f2016-01-21 10:37:37 -08003032 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08003033 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003034 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003035 }
3036 playout_delay_ms_ = delay_ms;
3037 }
3038}
3039
kwiberg55b97fe2016-01-28 05:22:45 -08003040void Channel::RegisterReceiveCodecsToRTPModule() {
3041 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3042 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003043
kwiberg55b97fe2016-01-28 05:22:45 -08003044 CodecInst codec;
3045 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003046
kwiberg55b97fe2016-01-28 05:22:45 -08003047 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3048 // Open up the RTP/RTCP receiver for all supported codecs
3049 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08003050 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08003051 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3052 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3053 " to register %s (%d/%d/%" PRIuS
3054 "/%d) to RTP/RTCP "
3055 "receiver",
3056 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3057 codec.rate);
3058 } else {
3059 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3060 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3061 "(%d/%d/%" PRIuS
3062 "/%d) has been added to the RTP/RTCP "
3063 "receiver",
3064 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3065 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003066 }
kwiberg55b97fe2016-01-28 05:22:45 -08003067 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003068}
3069
kwiberg55b97fe2016-01-28 05:22:45 -08003070int Channel::SetSendRtpHeaderExtension(bool enable,
3071 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003072 unsigned char id) {
3073 int error = 0;
3074 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3075 if (enable) {
3076 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3077 }
3078 return error;
3079}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003080
ossue280cde2016-10-12 11:04:10 -07003081int Channel::GetRtpTimestampRateHz() const {
3082 const auto format = audio_coding_->ReceiveFormat();
3083 // Default to the playout frequency if we've not gotten any packets yet.
3084 // TODO(ossu): Zero clockrate can only happen if we've added an external
3085 // decoder for a format we don't support internally. Remove once that way of
3086 // adding decoders is gone!
3087 return (format && format->clockrate_hz != 0)
3088 ? format->clockrate_hz
3089 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00003090}
3091
Minyue2013aec2015-05-13 14:14:42 +02003092int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003093 RtcpMode method = _rtpRtcpModule->RTCP();
3094 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003095 return 0;
3096 }
3097 std::vector<RTCPReportBlock> report_blocks;
3098 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003099
3100 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003101 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003102 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003103 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003104 Channel* channel = associate_send_channel_.channel();
3105 // Tries to get RTT from an associated channel. This is important for
3106 // receive-only channels.
3107 if (channel) {
3108 // To prevent infinite recursion and deadlock, calling GetRTT of
3109 // associate channel should always use "false" for argument:
3110 // |allow_associate_channel|.
3111 rtt = channel->GetRTT(false);
3112 }
3113 }
3114 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003115 }
3116
3117 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3118 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3119 for (; it != report_blocks.end(); ++it) {
3120 if (it->remoteSSRC == remoteSSRC)
3121 break;
3122 }
3123 if (it == report_blocks.end()) {
3124 // We have not received packets with SSRC matching the report blocks.
3125 // To calculate RTT we try with the SSRC of the first report block.
3126 // This is very important for send-only channels where we don't know
3127 // the SSRC of the other end.
3128 remoteSSRC = report_blocks[0].remoteSSRC;
3129 }
Minyue2013aec2015-05-13 14:14:42 +02003130
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003131 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003132 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003133 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003134 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3135 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003136 return 0;
3137 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003138 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003139}
3140
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003141} // namespace voe
3142} // namespace webrtc