blob: a9cf2b26dc8edea51bb8d56b57d13a52275e58b2 [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"
pbosad856222015-11-27 09:48:36 -080021#include "webrtc/base/logging.h"
Erik Språng737336d2016-07-29 12:59:36 +020022#include "webrtc/base/rate_limiter.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010023#include "webrtc/base/thread_checker.h"
wu@webrtc.org94454b72014-06-05 20:34:08 +000024#include "webrtc/base/timeutils.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020025#include "webrtc/config.h"
skvladcc91d282016-10-03 18:31:22 -070026#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kwibergda2bf4e2016-10-24 13:47:09 -070027#include "webrtc/modules/audio_coding/codecs/audio_format_conversion.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000028#include "webrtc/modules/audio_device/include/audio_device.h"
29#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010030#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010031#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010032#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
33#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
34#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000035#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010036#include "webrtc/modules/utility/include/process_thread.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010037#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000038#include "webrtc/voice_engine/include/voe_external_media.h"
39#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
40#include "webrtc/voice_engine/output_mixer.h"
41#include "webrtc/voice_engine/statistics.h"
42#include "webrtc/voice_engine/transmit_mixer.h"
43#include "webrtc/voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000044
andrew@webrtc.org50419b02012-11-14 19:07:54 +000045namespace webrtc {
46namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000047
kwibergc8d071e2016-04-06 12:22:38 -070048namespace {
49
Erik Språng737336d2016-07-29 12:59:36 +020050constexpr int64_t kMaxRetransmissionWindowMs = 1000;
51constexpr int64_t kMinRetransmissionWindowMs = 30;
52
kwibergc8d071e2016-04-06 12:22:38 -070053} // namespace
54
solenberg8842c3e2016-03-11 03:06:41 -080055const int kTelephoneEventAttenuationdB = 10;
56
ivoc14d5dbe2016-07-04 07:06:55 -070057class RtcEventLogProxy final : public webrtc::RtcEventLog {
58 public:
59 RtcEventLogProxy() : event_log_(nullptr) {}
60
61 bool StartLogging(const std::string& file_name,
62 int64_t max_size_bytes) override {
63 RTC_NOTREACHED();
64 return false;
65 }
66
67 bool StartLogging(rtc::PlatformFile log_file,
68 int64_t max_size_bytes) override {
69 RTC_NOTREACHED();
70 return false;
71 }
72
73 void StopLogging() override { RTC_NOTREACHED(); }
74
75 void LogVideoReceiveStreamConfig(
76 const webrtc::VideoReceiveStream::Config& config) override {
77 rtc::CritScope lock(&crit_);
78 if (event_log_) {
79 event_log_->LogVideoReceiveStreamConfig(config);
80 }
81 }
82
83 void LogVideoSendStreamConfig(
84 const webrtc::VideoSendStream::Config& config) override {
85 rtc::CritScope lock(&crit_);
86 if (event_log_) {
87 event_log_->LogVideoSendStreamConfig(config);
88 }
89 }
90
ivoce0928d82016-10-10 05:12:51 -070091 void LogAudioReceiveStreamConfig(
92 const webrtc::AudioReceiveStream::Config& config) override {
93 rtc::CritScope lock(&crit_);
94 if (event_log_) {
95 event_log_->LogAudioReceiveStreamConfig(config);
96 }
97 }
98
99 void LogAudioSendStreamConfig(
100 const webrtc::AudioSendStream::Config& config) override {
101 rtc::CritScope lock(&crit_);
102 if (event_log_) {
103 event_log_->LogAudioSendStreamConfig(config);
104 }
105 }
106
ivoc14d5dbe2016-07-04 07:06:55 -0700107 void LogRtpHeader(webrtc::PacketDirection direction,
108 webrtc::MediaType media_type,
109 const uint8_t* header,
110 size_t packet_length) override {
111 rtc::CritScope lock(&crit_);
112 if (event_log_) {
113 event_log_->LogRtpHeader(direction, media_type, header, packet_length);
114 }
115 }
116
117 void LogRtcpPacket(webrtc::PacketDirection direction,
118 webrtc::MediaType media_type,
119 const uint8_t* packet,
120 size_t length) override {
121 rtc::CritScope lock(&crit_);
122 if (event_log_) {
123 event_log_->LogRtcpPacket(direction, media_type, packet, length);
124 }
125 }
126
127 void LogAudioPlayout(uint32_t ssrc) override {
128 rtc::CritScope lock(&crit_);
129 if (event_log_) {
130 event_log_->LogAudioPlayout(ssrc);
131 }
132 }
133
134 void LogBwePacketLossEvent(int32_t bitrate,
135 uint8_t fraction_loss,
136 int32_t total_packets) override {
137 rtc::CritScope lock(&crit_);
138 if (event_log_) {
139 event_log_->LogBwePacketLossEvent(bitrate, fraction_loss, total_packets);
140 }
141 }
142
minyue4b7c9522017-01-24 04:54:59 -0800143 void LogAudioNetworkAdaptation(
144 const AudioNetworkAdaptor::EncoderRuntimeConfig& config) override {
145 rtc::CritScope lock(&crit_);
146 if (event_log_) {
147 event_log_->LogAudioNetworkAdaptation(config);
148 }
149 }
150
ivoc14d5dbe2016-07-04 07:06:55 -0700151 void SetEventLog(RtcEventLog* event_log) {
152 rtc::CritScope lock(&crit_);
153 event_log_ = event_log;
154 }
155
156 private:
157 rtc::CriticalSection crit_;
158 RtcEventLog* event_log_ GUARDED_BY(crit_);
159 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
160};
161
michaelt9332b7d2016-11-30 07:51:13 -0800162class RtcpRttStatsProxy final : public RtcpRttStats {
163 public:
164 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
165
166 void OnRttUpdate(int64_t rtt) override {
167 rtc::CritScope lock(&crit_);
168 if (rtcp_rtt_stats_)
169 rtcp_rtt_stats_->OnRttUpdate(rtt);
170 }
171
172 int64_t LastProcessedRtt() const override {
173 rtc::CritScope lock(&crit_);
174 if (!rtcp_rtt_stats_)
175 return 0;
176 return rtcp_rtt_stats_->LastProcessedRtt();
177 }
178
179 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
180 rtc::CritScope lock(&crit_);
181 rtcp_rtt_stats_ = rtcp_rtt_stats;
182 }
183
184 private:
185 rtc::CriticalSection crit_;
186 RtcpRttStats* rtcp_rtt_stats_ GUARDED_BY(crit_);
187 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
188};
189
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100190class TransportFeedbackProxy : public TransportFeedbackObserver {
191 public:
192 TransportFeedbackProxy() : feedback_observer_(nullptr) {
193 pacer_thread_.DetachFromThread();
194 network_thread_.DetachFromThread();
195 }
196
197 void SetTransportFeedbackObserver(
198 TransportFeedbackObserver* feedback_observer) {
199 RTC_DCHECK(thread_checker_.CalledOnValidThread());
200 rtc::CritScope lock(&crit_);
201 feedback_observer_ = feedback_observer;
202 }
203
204 // Implements TransportFeedbackObserver.
205 void AddPacket(uint16_t sequence_number,
206 size_t length,
philipela1ed0b32016-06-01 06:31:17 -0700207 int probe_cluster_id) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100208 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
209 rtc::CritScope lock(&crit_);
210 if (feedback_observer_)
pbos2169d8b2016-06-20 11:53:02 -0700211 feedback_observer_->AddPacket(sequence_number, length, probe_cluster_id);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100212 }
213 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
214 RTC_DCHECK(network_thread_.CalledOnValidThread());
215 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700216 if (feedback_observer_)
217 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200218 }
219 std::vector<PacketInfo> GetTransportFeedbackVector() const override {
220 RTC_NOTREACHED();
221 return std::vector<PacketInfo>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100222 }
223
224 private:
225 rtc::CriticalSection crit_;
226 rtc::ThreadChecker thread_checker_;
227 rtc::ThreadChecker pacer_thread_;
228 rtc::ThreadChecker network_thread_;
229 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
230};
231
232class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
233 public:
234 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
235 pacer_thread_.DetachFromThread();
236 }
237
238 void SetSequenceNumberAllocator(
239 TransportSequenceNumberAllocator* seq_num_allocator) {
240 RTC_DCHECK(thread_checker_.CalledOnValidThread());
241 rtc::CritScope lock(&crit_);
242 seq_num_allocator_ = seq_num_allocator;
243 }
244
245 // Implements TransportSequenceNumberAllocator.
246 uint16_t AllocateSequenceNumber() override {
247 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
248 rtc::CritScope lock(&crit_);
249 if (!seq_num_allocator_)
250 return 0;
251 return seq_num_allocator_->AllocateSequenceNumber();
252 }
253
254 private:
255 rtc::CriticalSection crit_;
256 rtc::ThreadChecker thread_checker_;
257 rtc::ThreadChecker pacer_thread_;
258 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
259};
260
261class RtpPacketSenderProxy : public RtpPacketSender {
262 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800263 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100264
265 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
266 RTC_DCHECK(thread_checker_.CalledOnValidThread());
267 rtc::CritScope lock(&crit_);
268 rtp_packet_sender_ = rtp_packet_sender;
269 }
270
271 // Implements RtpPacketSender.
272 void InsertPacket(Priority priority,
273 uint32_t ssrc,
274 uint16_t sequence_number,
275 int64_t capture_time_ms,
276 size_t bytes,
277 bool retransmission) override {
278 rtc::CritScope lock(&crit_);
279 if (rtp_packet_sender_) {
280 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
281 capture_time_ms, bytes, retransmission);
282 }
283 }
284
285 private:
286 rtc::ThreadChecker thread_checker_;
287 rtc::CriticalSection crit_;
288 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
289};
290
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000291// Extend the default RTCP statistics struct with max_jitter, defined as the
292// maximum jitter value seen in an RTCP report block.
293struct ChannelStatistics : public RtcpStatistics {
294 ChannelStatistics() : rtcp(), max_jitter(0) {}
295
296 RtcpStatistics rtcp;
297 uint32_t max_jitter;
298};
299
300// Statistics callback, called at each generation of a new RTCP report block.
301class StatisticsProxy : public RtcpStatisticsCallback {
302 public:
tommi31fc21f2016-01-21 10:37:37 -0800303 StatisticsProxy(uint32_t ssrc) : ssrc_(ssrc) {}
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000304 virtual ~StatisticsProxy() {}
305
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000306 void StatisticsUpdated(const RtcpStatistics& statistics,
307 uint32_t ssrc) override {
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000308 if (ssrc != ssrc_)
309 return;
310
tommi31fc21f2016-01-21 10:37:37 -0800311 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000312 stats_.rtcp = statistics;
313 if (statistics.jitter > stats_.max_jitter) {
314 stats_.max_jitter = statistics.jitter;
315 }
316 }
317
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000318 void CNameChanged(const char* cname, uint32_t ssrc) override {}
pbos@webrtc.orgce4e9a32014-12-18 13:50:16 +0000319
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000320 ChannelStatistics GetStats() {
tommi31fc21f2016-01-21 10:37:37 -0800321 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000322 return stats_;
323 }
324
325 private:
326 // StatisticsUpdated calls are triggered from threads in the RTP module,
327 // while GetStats calls can be triggered from the public voice engine API,
328 // hence synchronization is needed.
tommi31fc21f2016-01-21 10:37:37 -0800329 rtc::CriticalSection stats_lock_;
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000330 const uint32_t ssrc_;
331 ChannelStatistics stats_;
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 }
396 owner_->OnIncomingFractionLoss(weighted_fraction_lost);
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
kwiberg55b97fe2016-01-28 05:22:45 -0800407int32_t Channel::SendData(FrameType frameType,
408 uint8_t payloadType,
409 uint32_t timeStamp,
410 const uint8_t* payloadData,
411 size_t payloadSize,
412 const RTPFragmentationHeader* fragmentation) {
413 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
414 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
415 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
416 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000417
kwiberg55b97fe2016-01-28 05:22:45 -0800418 if (_includeAudioLevelIndication) {
419 // Store current audio level in the RTP/RTCP module.
420 // The level will be used in combination with voice-activity state
421 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800422 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800423 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000424
kwiberg55b97fe2016-01-28 05:22:45 -0800425 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
426 // packetization.
427 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700428 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800429 (FrameType&)frameType, payloadType, timeStamp,
430 // Leaving the time when this frame was
431 // received from the capture device as
432 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700433 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800434 _engineStatisticsPtr->SetLastError(
435 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
436 "Channel::SendData() failed to send data to RTP/RTCP module");
437 return -1;
438 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000439
kwiberg55b97fe2016-01-28 05:22:45 -0800440 _lastLocalTimeStamp = timeStamp;
441 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000442
kwiberg55b97fe2016-01-28 05:22:45 -0800443 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000444}
445
kwiberg55b97fe2016-01-28 05:22:45 -0800446int32_t Channel::InFrameType(FrameType frame_type) {
447 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
448 "Channel::InFrameType(frame_type=%d)", frame_type);
niklase@google.com470e71d2011-07-07 08:21:25 +0000449
kwiberg55b97fe2016-01-28 05:22:45 -0800450 rtc::CritScope cs(&_callbackCritSect);
451 _sendFrameType = (frame_type == kAudioFrameSpeech);
452 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000453}
454
stefan1d8a5062015-10-02 03:39:33 -0700455bool Channel::SendRtp(const uint8_t* data,
456 size_t len,
457 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800458 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
459 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000460
kwiberg55b97fe2016-01-28 05:22:45 -0800461 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000462
kwiberg55b97fe2016-01-28 05:22:45 -0800463 if (_transportPtr == NULL) {
464 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
465 "Channel::SendPacket() failed to send RTP packet due to"
466 " invalid transport object");
467 return false;
468 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000469
kwiberg55b97fe2016-01-28 05:22:45 -0800470 uint8_t* bufferToSendPtr = (uint8_t*)data;
471 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000472
kwiberg55b97fe2016-01-28 05:22:45 -0800473 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
474 std::string transport_name =
475 _externalTransport ? "external transport" : "WebRtc sockets";
476 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
477 "Channel::SendPacket() RTP transmission using %s failed",
478 transport_name.c_str());
479 return false;
480 }
481 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000482}
483
kwiberg55b97fe2016-01-28 05:22:45 -0800484bool Channel::SendRtcp(const uint8_t* data, size_t len) {
485 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
486 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000487
kwiberg55b97fe2016-01-28 05:22:45 -0800488 rtc::CritScope cs(&_callbackCritSect);
489 if (_transportPtr == NULL) {
490 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
491 "Channel::SendRtcp() failed to send RTCP packet"
492 " due to invalid transport object");
493 return false;
494 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000495
kwiberg55b97fe2016-01-28 05:22:45 -0800496 uint8_t* bufferToSendPtr = (uint8_t*)data;
497 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000498
kwiberg55b97fe2016-01-28 05:22:45 -0800499 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
500 if (n < 0) {
501 std::string transport_name =
502 _externalTransport ? "external transport" : "WebRtc sockets";
503 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
504 "Channel::SendRtcp() transmission using %s failed",
505 transport_name.c_str());
506 return false;
507 }
508 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000509}
510
kwiberg55b97fe2016-01-28 05:22:45 -0800511void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
512 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
513 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000514
kwiberg55b97fe2016-01-28 05:22:45 -0800515 // Update ssrc so that NTP for AV sync can be updated.
516 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000517}
518
Peter Boströmac547a62015-09-17 23:03:57 +0200519void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
520 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
521 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
522 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000523}
524
Peter Boströmac547a62015-09-17 23:03:57 +0200525int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000526 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000527 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000528 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800529 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200530 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800531 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
532 "Channel::OnInitializeDecoder(payloadType=%d, "
533 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
534 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000535
kwiberg55b97fe2016-01-28 05:22:45 -0800536 CodecInst receiveCodec = {0};
537 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000538
kwiberg55b97fe2016-01-28 05:22:45 -0800539 receiveCodec.pltype = payloadType;
540 receiveCodec.plfreq = frequency;
541 receiveCodec.channels = channels;
542 receiveCodec.rate = rate;
543 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000544
kwiberg55b97fe2016-01-28 05:22:45 -0800545 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
546 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000547
kwiberg55b97fe2016-01-28 05:22:45 -0800548 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700549 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
550 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800551 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
552 "Channel::OnInitializeDecoder() invalid codec ("
553 "pt=%d, name=%s) received - 1",
554 payloadType, payloadName);
555 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
556 return -1;
557 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000558
kwiberg55b97fe2016-01-28 05:22:45 -0800559 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000560}
561
kwiberg55b97fe2016-01-28 05:22:45 -0800562int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
563 size_t payloadSize,
564 const WebRtcRTPHeader* rtpHeader) {
565 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
566 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
567 ","
568 " payloadType=%u, audioChannel=%" PRIuS ")",
569 payloadSize, rtpHeader->header.payloadType,
570 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000571
kwiberg55b97fe2016-01-28 05:22:45 -0800572 if (!channel_state_.Get().playing) {
573 // Avoid inserting into NetEQ when we are not playing. Count the
574 // packet as discarded.
575 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
576 "received packet is discarded since playing is not"
577 " activated");
578 _numberOfDiscardedPackets++;
niklase@google.com470e71d2011-07-07 08:21:25 +0000579 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800580 }
581
582 // Push the incoming payload (parsed and ready for decoding) into the ACM
583 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
584 0) {
585 _engineStatisticsPtr->SetLastError(
586 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
587 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
588 return -1;
589 }
590
kwiberg55b97fe2016-01-28 05:22:45 -0800591 int64_t round_trip_time = 0;
592 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
593 NULL);
594
595 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
596 if (!nack_list.empty()) {
597 // Can't use nack_list.data() since it's not supported by all
598 // compilers.
599 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
600 }
601 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000602}
603
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000604bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000605 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000606 RTPHeader header;
607 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
608 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
609 "IncomingPacket invalid RTP header");
610 return false;
611 }
612 header.payload_type_frequency =
613 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
614 if (header.payload_type_frequency < 0)
615 return false;
616 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
617}
618
henrik.lundin42dda502016-05-18 05:36:01 -0700619MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
620 int32_t id,
621 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700622 unsigned int ssrc;
623 RTC_CHECK_EQ(GetLocalSSRC(ssrc), 0);
624 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800625 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700626 bool muted;
627 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
628 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800629 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
630 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
631 // In all likelihood, the audio in this frame is garbage. We return an
632 // error so that the audio mixer module doesn't add it to the mix. As
633 // a result, it won't be played out and the actions skipped here are
634 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700635 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800636 }
henrik.lundina89ab962016-05-18 08:52:45 -0700637
638 if (muted) {
639 // TODO(henrik.lundin): We should be able to do better than this. But we
640 // will have to go through all the cases below where the audio samples may
641 // be used, and handle the muted case in some way.
aleloi6321b492016-12-05 01:46:09 -0800642 AudioFrameOperations::Mute(audioFrame);
henrik.lundina89ab962016-05-18 08:52:45 -0700643 }
kwiberg55b97fe2016-01-28 05:22:45 -0800644
kwiberg55b97fe2016-01-28 05:22:45 -0800645 // Convert module ID to internal VoE channel ID
646 audioFrame->id_ = VoEChannelId(audioFrame->id_);
647 // Store speech type for dead-or-alive detection
648 _outputSpeechType = audioFrame->speech_type_;
649
650 ChannelState::State state = channel_state_.Get();
651
kwiberg55b97fe2016-01-28 05:22:45 -0800652 {
653 // Pass the audio buffers to an optional sink callback, before applying
654 // scaling/panning, as that applies to the mix operation.
655 // External recipients of the audio (e.g. via AudioTrack), will do their
656 // own mixing/dynamic processing.
657 rtc::CritScope cs(&_callbackCritSect);
658 if (audio_sink_) {
659 AudioSinkInterface::Data data(
660 &audioFrame->data_[0], audioFrame->samples_per_channel_,
661 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
662 audioFrame->timestamp_);
663 audio_sink_->OnData(data);
664 }
665 }
666
667 float output_gain = 1.0f;
668 float left_pan = 1.0f;
669 float right_pan = 1.0f;
670 {
671 rtc::CritScope cs(&volume_settings_critsect_);
672 output_gain = _outputGain;
673 left_pan = _panLeft;
674 right_pan = _panRight;
675 }
676
677 // Output volume scaling
678 if (output_gain < 0.99f || output_gain > 1.01f) {
679 AudioFrameOperations::ScaleWithSat(output_gain, *audioFrame);
680 }
681
682 // Scale left and/or right channel(s) if stereo and master balance is
683 // active
684
685 if (left_pan != 1.0f || right_pan != 1.0f) {
686 if (audioFrame->num_channels_ == 1) {
687 // Emulate stereo mode since panning is active.
688 // The mono signal is copied to both left and right channels here.
689 AudioFrameOperations::MonoToStereo(audioFrame);
690 }
691 // For true stereo mode (when we are receiving a stereo signal), no
692 // action is needed.
693
694 // Do the panning operation (the audio frame contains stereo at this
695 // stage)
696 AudioFrameOperations::Scale(left_pan, right_pan, *audioFrame);
697 }
698
699 // Mix decoded PCM output with file if file mixing is enabled
700 if (state.output_file_playing) {
701 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700702 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800703 }
704
705 // External media
706 if (_outputExternalMedia) {
707 rtc::CritScope cs(&_callbackCritSect);
708 const bool isStereo = (audioFrame->num_channels_ == 2);
709 if (_outputExternalMediaCallbackPtr) {
710 _outputExternalMediaCallbackPtr->Process(
711 _channelId, kPlaybackPerChannel, (int16_t*)audioFrame->data_,
712 audioFrame->samples_per_channel_, audioFrame->sample_rate_hz_,
713 isStereo);
714 }
715 }
716
717 // Record playout if enabled
718 {
719 rtc::CritScope cs(&_fileCritSect);
720
kwiberg5a25d952016-08-17 07:31:12 -0700721 if (_outputFileRecording && output_file_recorder_) {
722 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800723 }
724 }
725
726 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700727 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800728 _outputAudioLevel.ComputeLevel(*audioFrame);
729
730 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
731 // The first frame with a valid rtp timestamp.
732 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
733 }
734
735 if (capture_start_rtp_time_stamp_ >= 0) {
736 // audioFrame.timestamp_ should be valid from now on.
737
738 // Compute elapsed time.
739 int64_t unwrap_timestamp =
740 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
741 audioFrame->elapsed_time_ms_ =
742 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700743 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800744
niklase@google.com470e71d2011-07-07 08:21:25 +0000745 {
kwiberg55b97fe2016-01-28 05:22:45 -0800746 rtc::CritScope lock(&ts_stats_lock_);
747 // Compute ntp time.
748 audioFrame->ntp_time_ms_ =
749 ntp_estimator_.Estimate(audioFrame->timestamp_);
750 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
751 if (audioFrame->ntp_time_ms_ > 0) {
752 // Compute |capture_start_ntp_time_ms_| so that
753 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
754 capture_start_ntp_time_ms_ =
755 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000756 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000757 }
kwiberg55b97fe2016-01-28 05:22:45 -0800758 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000759
henrik.lundin42dda502016-05-18 05:36:01 -0700760 return muted ? MixerParticipant::AudioFrameInfo::kMuted
761 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000762}
763
aleloi6c278492016-10-20 14:24:39 -0700764AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
765 int sample_rate_hz,
766 AudioFrame* audio_frame) {
767 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700768
aleloi6c278492016-10-20 14:24:39 -0700769 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700770
771 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
772 FrameInfo new_audio_frame_info = FrameInfo::kError;
773 switch (frame_info) {
774 case MixerParticipant::AudioFrameInfo::kNormal:
775 new_audio_frame_info = FrameInfo::kNormal;
776 break;
777 case MixerParticipant::AudioFrameInfo::kMuted:
778 new_audio_frame_info = FrameInfo::kMuted;
779 break;
780 case MixerParticipant::AudioFrameInfo::kError:
781 new_audio_frame_info = FrameInfo::kError;
782 break;
783 }
aleloi6c278492016-10-20 14:24:39 -0700784 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700785}
786
kwiberg55b97fe2016-01-28 05:22:45 -0800787int32_t Channel::NeededFrequency(int32_t id) const {
788 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
789 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000790
kwiberg55b97fe2016-01-28 05:22:45 -0800791 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000792
kwiberg55b97fe2016-01-28 05:22:45 -0800793 // Determine highest needed receive frequency
794 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000795
kwiberg55b97fe2016-01-28 05:22:45 -0800796 // Return the bigger of playout and receive frequency in the ACM.
797 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
798 highestNeeded = audio_coding_->PlayoutFrequency();
799 } else {
800 highestNeeded = receiveFrequency;
801 }
802
803 // Special case, if we're playing a file on the playout side
804 // we take that frequency into consideration as well
805 // This is not needed on sending side, since the codec will
806 // limit the spectrum anyway.
807 if (channel_state_.Get().output_file_playing) {
808 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700809 if (output_file_player_) {
810 if (output_file_player_->Frequency() > highestNeeded) {
811 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800812 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000813 }
kwiberg55b97fe2016-01-28 05:22:45 -0800814 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000815
kwiberg55b97fe2016-01-28 05:22:45 -0800816 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000817}
818
ossu5f7cfa52016-05-30 08:11:28 -0700819int32_t Channel::CreateChannel(
820 Channel*& channel,
821 int32_t channelId,
822 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700823 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800824 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
825 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
826 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000827
solenberg88499ec2016-09-07 07:34:41 -0700828 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800829 if (channel == NULL) {
830 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
831 "Channel::CreateChannel() unable to allocate memory for"
832 " channel");
833 return -1;
834 }
835 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000836}
837
kwiberg55b97fe2016-01-28 05:22:45 -0800838void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
839 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
840 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
841 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000842
kwiberg55b97fe2016-01-28 05:22:45 -0800843 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000844}
845
kwiberg55b97fe2016-01-28 05:22:45 -0800846void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
847 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
848 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
849 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000850
kwiberg55b97fe2016-01-28 05:22:45 -0800851 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000852}
853
kwiberg55b97fe2016-01-28 05:22:45 -0800854void Channel::PlayFileEnded(int32_t id) {
855 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
856 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000857
kwiberg55b97fe2016-01-28 05:22:45 -0800858 if (id == _inputFilePlayerId) {
859 channel_state_.SetInputFilePlaying(false);
860 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
861 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000862 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800863 } else if (id == _outputFilePlayerId) {
864 channel_state_.SetOutputFilePlaying(false);
865 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
866 "Channel::PlayFileEnded() => output file player module is"
867 " shutdown");
868 }
869}
870
871void Channel::RecordFileEnded(int32_t id) {
872 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
873 "Channel::RecordFileEnded(id=%d)", id);
874
875 assert(id == _outputFileRecorderId);
876
877 rtc::CritScope cs(&_fileCritSect);
878
879 _outputFileRecording = false;
880 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
881 "Channel::RecordFileEnded() => output file recorder module is"
882 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000883}
884
pbos@webrtc.org92135212013-05-14 08:31:39 +0000885Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000886 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700887 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800888 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100889 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700890 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800891 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100892 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800893 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100894 rtp_receive_statistics_(
895 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
896 rtp_receiver_(
897 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100898 this,
899 this,
900 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700901 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100902 _outputAudioLevel(),
903 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100904 // Avoid conflict with other channels by adding 1024 - 1026,
905 // won't use as much as 1024 channels.
906 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
907 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
908 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
909 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100910 _outputExternalMedia(false),
911 _inputExternalMediaCallbackPtr(NULL),
912 _outputExternalMediaCallbackPtr(NULL),
913 _timeStamp(0), // This is just an offset, RTP module will add it's own
914 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100915 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100916 playout_timestamp_rtp_(0),
917 playout_timestamp_rtcp_(0),
918 playout_delay_ms_(0),
919 _numberOfDiscardedPackets(0),
920 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100921 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
922 capture_start_rtp_time_stamp_(-1),
923 capture_start_ntp_time_ms_(-1),
924 _engineStatisticsPtr(NULL),
925 _outputMixerPtr(NULL),
926 _transmitMixerPtr(NULL),
927 _moduleProcessThreadPtr(NULL),
928 _audioDeviceModulePtr(NULL),
929 _voiceEngineObserverPtr(NULL),
930 _callbackCritSectPtr(NULL),
931 _transportPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100932 _sendFrameType(0),
933 _externalMixing(false),
934 _mixFileWithMicrophone(false),
solenberg1c2af8e2016-03-24 10:36:00 -0700935 input_mute_(false),
936 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100937 _panLeft(1.0f),
938 _panRight(1.0f),
939 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100940 _lastLocalTimeStamp(0),
941 _lastPayloadType(0),
942 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800943 transport_overhead_per_packet_(0),
944 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100945 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100946 restored_packet_in_use_(false),
947 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100948 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700949 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800950 feedback_observer_proxy_(new TransportFeedbackProxy()),
951 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700952 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200953 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
954 kMaxRetransmissionWindowMs)),
michaelt566d8202017-01-12 10:17:38 -0800955 decoder_factory_(config.acm_config.decoder_factory) {
kwiberg55b97fe2016-01-28 05:22:45 -0800956 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
957 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700958 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800959 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700960 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800961 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200962
kwiberg55b97fe2016-01-28 05:22:45 -0800963 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000964
kwiberg55b97fe2016-01-28 05:22:45 -0800965 RtpRtcp::Configuration configuration;
966 configuration.audio = true;
967 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800968 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800969 configuration.receive_statistics = rtp_receive_statistics_.get();
970 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800971 if (pacing_enabled_) {
972 configuration.paced_sender = rtp_packet_sender_proxy_.get();
973 configuration.transport_sequence_number_allocator =
974 seq_num_allocator_proxy_.get();
975 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
976 }
ivoc14d5dbe2016-07-04 07:06:55 -0700977 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800978 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200979 configuration.retransmission_rate_limiter =
980 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000981
kwiberg55b97fe2016-01-28 05:22:45 -0800982 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100983 _rtpRtcpModule->SetSendingMediaStatus(false);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000984
kwiberg55b97fe2016-01-28 05:22:45 -0800985 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
986 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
987 statistics_proxy_.get());
niklase@google.com470e71d2011-07-07 08:21:25 +0000988}
989
kwiberg55b97fe2016-01-28 05:22:45 -0800990Channel::~Channel() {
991 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
992 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
993 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000994
kwiberg55b97fe2016-01-28 05:22:45 -0800995 if (_outputExternalMedia) {
996 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
997 }
998 if (channel_state_.Get().input_external_media) {
999 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
1000 }
1001 StopSend();
1002 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +00001003
kwiberg55b97fe2016-01-28 05:22:45 -08001004 {
1005 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -07001006 if (input_file_player_) {
1007 input_file_player_->RegisterModuleFileCallback(NULL);
1008 input_file_player_->StopPlayingFile();
niklase@google.com470e71d2011-07-07 08:21:25 +00001009 }
kwiberg5a25d952016-08-17 07:31:12 -07001010 if (output_file_player_) {
1011 output_file_player_->RegisterModuleFileCallback(NULL);
1012 output_file_player_->StopPlayingFile();
kwiberg55b97fe2016-01-28 05:22:45 -08001013 }
kwiberg5a25d952016-08-17 07:31:12 -07001014 if (output_file_recorder_) {
1015 output_file_recorder_->RegisterModuleFileCallback(NULL);
1016 output_file_recorder_->StopRecording();
kwiberg55b97fe2016-01-28 05:22:45 -08001017 }
1018 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001019
kwiberg55b97fe2016-01-28 05:22:45 -08001020 // The order to safely shutdown modules in a channel is:
1021 // 1. De-register callbacks in modules
1022 // 2. De-register modules in process thread
1023 // 3. Destroy modules
1024 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1025 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1026 "~Channel() failed to de-register transport callback"
1027 " (Audio coding module)");
1028 }
1029 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1030 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1031 "~Channel() failed to de-register VAD callback"
1032 " (Audio coding module)");
1033 }
1034 // De-register modules in process thread
1035 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +00001036
kwiberg55b97fe2016-01-28 05:22:45 -08001037 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +00001038}
1039
kwiberg55b97fe2016-01-28 05:22:45 -08001040int32_t Channel::Init() {
1041 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1042 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001043
kwiberg55b97fe2016-01-28 05:22:45 -08001044 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001045
kwiberg55b97fe2016-01-28 05:22:45 -08001046 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +00001047
kwiberg55b97fe2016-01-28 05:22:45 -08001048 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
1049 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1050 "Channel::Init() must call SetEngineInformation() first");
1051 return -1;
1052 }
1053
1054 // --- Add modules to process thread (for periodic schedulation)
1055
1056 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
1057
1058 // --- ACM initialization
1059
1060 if (audio_coding_->InitializeReceiver() == -1) {
1061 _engineStatisticsPtr->SetLastError(
1062 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1063 "Channel::Init() unable to initialize the ACM - 1");
1064 return -1;
1065 }
1066
1067 // --- RTP/RTCP module initialization
1068
1069 // Ensure that RTCP is enabled by default for the created channel.
1070 // Note that, the module will keep generating RTCP until it is explicitly
1071 // disabled by the user.
1072 // After StopListen (when no sockets exists), RTCP packets will no longer
1073 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -07001074 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001075 // RTCP is enabled by default.
1076 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
1077 // --- Register all permanent callbacks
1078 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
1079 (audio_coding_->RegisterVADCallback(this) == -1);
1080
1081 if (fail) {
1082 _engineStatisticsPtr->SetLastError(
1083 VE_CANNOT_INIT_CHANNEL, kTraceError,
1084 "Channel::Init() callbacks not registered");
1085 return -1;
1086 }
1087
1088 // --- Register all supported codecs to the receiving side of the
1089 // RTP/RTCP module
1090
1091 CodecInst codec;
1092 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1093
1094 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1095 // Open up the RTP/RTCP receiver for all supported codecs
1096 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001097 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001098 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1099 "Channel::Init() unable to register %s "
1100 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1101 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1102 codec.rate);
1103 } else {
1104 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1105 "Channel::Init() %s (%d/%d/%" PRIuS
1106 "/%d) has been "
1107 "added to the RTP/RTCP receiver",
1108 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1109 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001110 }
1111
kwiberg55b97fe2016-01-28 05:22:45 -08001112 // Ensure that PCMU is used as default codec on the sending side
1113 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
1114 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +00001115 }
1116
kwiberg55b97fe2016-01-28 05:22:45 -08001117 // Register default PT for outband 'telephone-event'
1118 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -07001119 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
kwibergda2bf4e2016-10-24 13:47:09 -07001120 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1121 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001122 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1123 "Channel::Init() failed to register outband "
1124 "'telephone-event' (%d/%d) correctly",
1125 codec.pltype, codec.plfreq);
1126 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001127 }
1128
kwiberg55b97fe2016-01-28 05:22:45 -08001129 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -07001130 if (!codec_manager_.RegisterEncoder(codec) ||
1131 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
kwibergda2bf4e2016-10-24 13:47:09 -07001132 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1133 CodecInstToSdp(codec)) ||
kwibergc8d071e2016-04-06 12:22:38 -07001134 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001135 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1136 "Channel::Init() failed to register CN (%d/%d) "
1137 "correctly - 1",
1138 codec.pltype, codec.plfreq);
1139 }
1140 }
kwiberg55b97fe2016-01-28 05:22:45 -08001141 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001142
kwiberg55b97fe2016-01-28 05:22:45 -08001143 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001144}
1145
kwiberg55b97fe2016-01-28 05:22:45 -08001146int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1147 OutputMixer& outputMixer,
1148 voe::TransmitMixer& transmitMixer,
1149 ProcessThread& moduleProcessThread,
1150 AudioDeviceModule& audioDeviceModule,
1151 VoiceEngineObserver* voiceEngineObserver,
1152 rtc::CriticalSection* callbackCritSect) {
1153 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1154 "Channel::SetEngineInformation()");
1155 _engineStatisticsPtr = &engineStatistics;
1156 _outputMixerPtr = &outputMixer;
1157 _transmitMixerPtr = &transmitMixer,
1158 _moduleProcessThreadPtr = &moduleProcessThread;
1159 _audioDeviceModulePtr = &audioDeviceModule;
1160 _voiceEngineObserverPtr = voiceEngineObserver;
1161 _callbackCritSectPtr = callbackCritSect;
1162 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001163}
1164
kwiberg55b97fe2016-01-28 05:22:45 -08001165int32_t Channel::UpdateLocalTimeStamp() {
1166 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1167 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001168}
1169
kwibergb7f89d62016-02-17 10:04:18 -08001170void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001171 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001172 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001173}
1174
ossu29b1a8d2016-06-13 07:34:51 -07001175const rtc::scoped_refptr<AudioDecoderFactory>&
1176Channel::GetAudioDecoderFactory() const {
1177 return decoder_factory_;
1178}
1179
kwiberg55b97fe2016-01-28 05:22:45 -08001180int32_t Channel::StartPlayout() {
1181 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1182 "Channel::StartPlayout()");
1183 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001184 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001185 }
1186
1187 if (!_externalMixing) {
1188 // Add participant as candidates for mixing.
1189 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1190 _engineStatisticsPtr->SetLastError(
1191 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1192 "StartPlayout() failed to add participant to mixer");
1193 return -1;
1194 }
1195 }
1196
1197 channel_state_.SetPlaying(true);
1198 if (RegisterFilePlayingToMixer() != 0)
1199 return -1;
1200
1201 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001202}
1203
kwiberg55b97fe2016-01-28 05:22:45 -08001204int32_t Channel::StopPlayout() {
1205 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1206 "Channel::StopPlayout()");
1207 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001208 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001209 }
1210
1211 if (!_externalMixing) {
1212 // Remove participant as candidates for mixing
1213 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1214 _engineStatisticsPtr->SetLastError(
1215 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1216 "StopPlayout() failed to remove participant from mixer");
1217 return -1;
1218 }
1219 }
1220
1221 channel_state_.SetPlaying(false);
1222 _outputAudioLevel.Clear();
1223
1224 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001225}
1226
kwiberg55b97fe2016-01-28 05:22:45 -08001227int32_t Channel::StartSend() {
1228 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1229 "Channel::StartSend()");
1230 // Resume the previous sequence number which was reset by StopSend().
1231 // This needs to be done before |sending| is set to true.
1232 if (send_sequence_number_)
1233 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001234
kwiberg55b97fe2016-01-28 05:22:45 -08001235 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001236 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001237 }
1238 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001239
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001240 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001241 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1242 _engineStatisticsPtr->SetLastError(
1243 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1244 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001245 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001246 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001247 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001248 return -1;
1249 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001250
kwiberg55b97fe2016-01-28 05:22:45 -08001251 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001252}
1253
kwiberg55b97fe2016-01-28 05:22:45 -08001254int32_t Channel::StopSend() {
1255 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1256 "Channel::StopSend()");
1257 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001258 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001259 }
1260 channel_state_.SetSending(false);
1261
1262 // Store the sequence number to be able to pick up the same sequence for
1263 // the next StartSend(). This is needed for restarting device, otherwise
1264 // it might cause libSRTP to complain about packets being replayed.
1265 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1266 // CL is landed. See issue
1267 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1268 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1269
1270 // Reset sending SSRC and sequence number and triggers direct transmission
1271 // of RTCP BYE
1272 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1273 _engineStatisticsPtr->SetLastError(
1274 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1275 "StartSend() RTP/RTCP failed to stop sending");
1276 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001277 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001278
1279 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001280}
1281
solenberge566ac72016-10-31 12:52:33 -07001282void Channel::ResetDiscardedPacketCount() {
kwiberg55b97fe2016-01-28 05:22:45 -08001283 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberge566ac72016-10-31 12:52:33 -07001284 "Channel::ResetDiscardedPacketCount()");
kwiberg55b97fe2016-01-28 05:22:45 -08001285 _numberOfDiscardedPackets = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001286}
1287
kwiberg55b97fe2016-01-28 05:22:45 -08001288int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1289 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1290 "Channel::RegisterVoiceEngineObserver()");
1291 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001292
kwiberg55b97fe2016-01-28 05:22:45 -08001293 if (_voiceEngineObserverPtr) {
1294 _engineStatisticsPtr->SetLastError(
1295 VE_INVALID_OPERATION, kTraceError,
1296 "RegisterVoiceEngineObserver() observer already enabled");
1297 return -1;
1298 }
1299 _voiceEngineObserverPtr = &observer;
1300 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001301}
1302
kwiberg55b97fe2016-01-28 05:22:45 -08001303int32_t Channel::DeRegisterVoiceEngineObserver() {
1304 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1305 "Channel::DeRegisterVoiceEngineObserver()");
1306 rtc::CritScope cs(&_callbackCritSect);
1307
1308 if (!_voiceEngineObserverPtr) {
1309 _engineStatisticsPtr->SetLastError(
1310 VE_INVALID_OPERATION, kTraceWarning,
1311 "DeRegisterVoiceEngineObserver() observer already disabled");
1312 return 0;
1313 }
1314 _voiceEngineObserverPtr = NULL;
1315 return 0;
1316}
1317
1318int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001319 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001320 if (send_codec) {
1321 codec = *send_codec;
1322 return 0;
1323 }
1324 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001325}
1326
kwiberg55b97fe2016-01-28 05:22:45 -08001327int32_t Channel::GetRecCodec(CodecInst& codec) {
1328 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001329}
1330
kwiberg55b97fe2016-01-28 05:22:45 -08001331int32_t Channel::SetSendCodec(const CodecInst& codec) {
1332 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1333 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001334
kwibergc8d071e2016-04-06 12:22:38 -07001335 if (!codec_manager_.RegisterEncoder(codec) ||
1336 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001337 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1338 "SetSendCodec() failed to register codec to ACM");
1339 return -1;
1340 }
1341
1342 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1343 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1344 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1345 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1346 "SetSendCodec() failed to register codec to"
1347 " RTP/RTCP module");
1348 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001349 }
kwiberg55b97fe2016-01-28 05:22:45 -08001350 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001351
kwiberg55b97fe2016-01-28 05:22:45 -08001352 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001353}
1354
minyue78b4d562016-11-30 04:47:39 -08001355void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001356 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1357 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001358 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001359 if (*encoder) {
1360 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001361 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001362 }
1363 });
michaelt566d8202017-01-12 10:17:38 -08001364 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001365}
1366
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001367void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue7e304322016-10-12 05:00:55 -07001368 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1369 if (*encoder)
1370 (*encoder)->OnReceivedUplinkPacketLossFraction(fraction_lost / 255.0f);
1371 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001372}
1373
kwiberg55b97fe2016-01-28 05:22:45 -08001374int32_t Channel::SetVADStatus(bool enableVAD,
1375 ACMVADMode mode,
1376 bool disableDTX) {
1377 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1378 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001379 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1380 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1381 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001382 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1383 kTraceError,
1384 "SetVADStatus() failed to set VAD");
1385 return -1;
1386 }
1387 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001388}
1389
kwiberg55b97fe2016-01-28 05:22:45 -08001390int32_t Channel::GetVADStatus(bool& enabledVAD,
1391 ACMVADMode& mode,
1392 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001393 const auto* params = codec_manager_.GetStackParams();
1394 enabledVAD = params->use_cng;
1395 mode = params->vad_mode;
1396 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001397 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001398}
1399
kwiberg55b97fe2016-01-28 05:22:45 -08001400int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
kwibergd32bf752017-01-19 07:03:59 -08001401 return SetRecPayloadType(codec.pltype, CodecInstToSdp(codec));
1402}
1403
1404int32_t Channel::SetRecPayloadType(int payload_type,
1405 const SdpAudioFormat& format) {
kwiberg55b97fe2016-01-28 05:22:45 -08001406 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1407 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001408
kwiberg55b97fe2016-01-28 05:22:45 -08001409 if (channel_state_.Get().playing) {
1410 _engineStatisticsPtr->SetLastError(
1411 VE_ALREADY_PLAYING, kTraceError,
1412 "SetRecPayloadType() unable to set PT while playing");
1413 return -1;
1414 }
kwiberg55b97fe2016-01-28 05:22:45 -08001415
kwibergd32bf752017-01-19 07:03:59 -08001416 const CodecInst codec = [&] {
1417 CodecInst c = SdpToCodecInst(payload_type, format);
1418
1419 // Bug 6986: Emulate an old bug that caused us to always choose to decode
1420 // Opus in stereo. To be able to remove this, we first need to fix the
1421 // other half of bug 6986, which is about losing the Opus "stereo"
1422 // parameter.
1423 // TODO(kwiberg): Remove this special case, a.k.a. fix bug 6986.
1424 if (STR_CASE_CMP(codec.plname, "opus") == 0) {
1425 c.channels = 2;
1426 }
1427
1428 return c;
1429 }();
1430
1431 if (payload_type == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001432 // De-register the selected codec (RTP/RTCP module and ACM)
1433
1434 int8_t pltype(-1);
1435 CodecInst rxCodec = codec;
1436
1437 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001438 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001439 rxCodec.pltype = pltype;
1440
1441 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1442 _engineStatisticsPtr->SetLastError(
1443 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1444 "SetRecPayloadType() RTP/RTCP-module deregistration "
1445 "failed");
1446 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001447 }
kwiberg55b97fe2016-01-28 05:22:45 -08001448 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1449 _engineStatisticsPtr->SetLastError(
1450 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1451 "SetRecPayloadType() ACM deregistration failed - 1");
1452 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001453 }
kwiberg55b97fe2016-01-28 05:22:45 -08001454 return 0;
1455 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001456
magjed56124bd2016-11-24 09:34:46 -08001457 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001458 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001459 // TODO(kwiberg): Retrying is probably not necessary, since
1460 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001461 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001462 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001463 _engineStatisticsPtr->SetLastError(
1464 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1465 "SetRecPayloadType() RTP/RTCP-module registration failed");
1466 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001467 }
kwiberg55b97fe2016-01-28 05:22:45 -08001468 }
kwibergd32bf752017-01-19 07:03:59 -08001469 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
1470 audio_coding_->UnregisterReceiveCodec(payload_type);
1471 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001472 _engineStatisticsPtr->SetLastError(
1473 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1474 "SetRecPayloadType() ACM registration failed - 1");
1475 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001476 }
kwiberg55b97fe2016-01-28 05:22:45 -08001477 }
1478 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001479}
1480
kwiberg55b97fe2016-01-28 05:22:45 -08001481int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1482 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001483 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001484 _engineStatisticsPtr->SetLastError(
1485 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1486 "GetRecPayloadType() failed to retrieve RX payload type");
1487 return -1;
1488 }
1489 codec.pltype = payloadType;
1490 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001491}
1492
kwiberg55b97fe2016-01-28 05:22:45 -08001493int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1494 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1495 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001496
kwiberg55b97fe2016-01-28 05:22:45 -08001497 CodecInst codec;
1498 int32_t samplingFreqHz(-1);
1499 const size_t kMono = 1;
1500 if (frequency == kFreq32000Hz)
1501 samplingFreqHz = 32000;
1502 else if (frequency == kFreq16000Hz)
1503 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001504
kwiberg55b97fe2016-01-28 05:22:45 -08001505 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1506 _engineStatisticsPtr->SetLastError(
1507 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1508 "SetSendCNPayloadType() failed to retrieve default CN codec "
1509 "settings");
1510 return -1;
1511 }
1512
1513 // Modify the payload type (must be set to dynamic range)
1514 codec.pltype = type;
1515
kwibergc8d071e2016-04-06 12:22:38 -07001516 if (!codec_manager_.RegisterEncoder(codec) ||
1517 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001518 _engineStatisticsPtr->SetLastError(
1519 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1520 "SetSendCNPayloadType() failed to register CN to ACM");
1521 return -1;
1522 }
1523
1524 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1525 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1526 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1527 _engineStatisticsPtr->SetLastError(
1528 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1529 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1530 "module");
1531 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001532 }
kwiberg55b97fe2016-01-28 05:22:45 -08001533 }
1534 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001535}
1536
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001537int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001538 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001539 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001540
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001541 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001542 _engineStatisticsPtr->SetLastError(
1543 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001544 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001545 return -1;
1546 }
1547 return 0;
1548}
1549
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001550int Channel::SetOpusDtx(bool enable_dtx) {
1551 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1552 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001553 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001554 : audio_coding_->DisableOpusDtx();
1555 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001556 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1557 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001558 return -1;
1559 }
1560 return 0;
1561}
1562
ivoc85228d62016-07-27 04:53:47 -07001563int Channel::GetOpusDtx(bool* enabled) {
1564 int success = -1;
1565 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1566 if (encoder) {
1567 *enabled = encoder->GetDtx();
1568 success = 0;
1569 }
1570 });
1571 return success;
1572}
1573
minyue7e304322016-10-12 05:00:55 -07001574bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1575 bool success = false;
1576 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1577 if (*encoder) {
1578 success = (*encoder)->EnableAudioNetworkAdaptor(
michaeltbf279fc2017-01-13 06:02:29 -08001579 config_string, event_log_proxy_.get(), Clock::GetRealTimeClock());
minyue7e304322016-10-12 05:00:55 -07001580 }
1581 });
1582 return success;
1583}
1584
1585void Channel::DisableAudioNetworkAdaptor() {
1586 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1587 if (*encoder)
1588 (*encoder)->DisableAudioNetworkAdaptor();
1589 });
1590}
1591
1592void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1593 int max_frame_length_ms) {
1594 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1595 if (*encoder) {
1596 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1597 max_frame_length_ms);
1598 }
1599 });
1600}
1601
mflodman3d7db262016-04-29 00:57:13 -07001602int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001603 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001604 "Channel::RegisterExternalTransport()");
1605
kwiberg55b97fe2016-01-28 05:22:45 -08001606 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001607 if (_externalTransport) {
1608 _engineStatisticsPtr->SetLastError(
1609 VE_INVALID_OPERATION, kTraceError,
1610 "RegisterExternalTransport() external transport already enabled");
1611 return -1;
1612 }
1613 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001614 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001615 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001616}
1617
kwiberg55b97fe2016-01-28 05:22:45 -08001618int32_t Channel::DeRegisterExternalTransport() {
1619 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1620 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001621
kwiberg55b97fe2016-01-28 05:22:45 -08001622 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001623 if (_transportPtr) {
1624 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1625 "DeRegisterExternalTransport() all transport is disabled");
1626 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001627 _engineStatisticsPtr->SetLastError(
1628 VE_INVALID_OPERATION, kTraceWarning,
1629 "DeRegisterExternalTransport() external transport already "
1630 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001631 }
1632 _externalTransport = false;
1633 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001634 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001635}
1636
mflodman3d7db262016-04-29 00:57:13 -07001637int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001638 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001639 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001640 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001641 "Channel::ReceivedRTPPacket()");
1642
1643 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001644 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001645
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001646 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001647 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1648 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1649 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001650 return -1;
1651 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001652 header.payload_type_frequency =
1653 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001654 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001655 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001656 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001657 rtp_receive_statistics_->IncomingPacket(
1658 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001659 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001660
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001661 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001662}
1663
1664bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001665 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001666 const RTPHeader& header,
1667 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001668 if (rtp_payload_registry_->IsRtx(header)) {
1669 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001670 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001671 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001672 assert(packet_length >= header.headerLength);
1673 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001674 PayloadUnion payload_specific;
1675 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001676 &payload_specific)) {
1677 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001678 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001679 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1680 payload_specific, in_order);
1681}
1682
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001683bool Channel::HandleRtxPacket(const uint8_t* packet,
1684 size_t packet_length,
1685 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001686 if (!rtp_payload_registry_->IsRtx(header))
1687 return false;
1688
1689 // Remove the RTX header and parse the original RTP header.
1690 if (packet_length < header.headerLength)
1691 return false;
1692 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1693 return false;
1694 if (restored_packet_in_use_) {
1695 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1696 "Multiple RTX headers detected, dropping packet");
1697 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001698 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001699 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001700 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1701 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001702 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1703 "Incoming RTX packet: invalid RTP header");
1704 return false;
1705 }
1706 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001707 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001708 restored_packet_in_use_ = false;
1709 return ret;
1710}
1711
1712bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1713 StreamStatistician* statistician =
1714 rtp_receive_statistics_->GetStatistician(header.ssrc);
1715 if (!statistician)
1716 return false;
1717 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001718}
1719
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001720bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1721 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001722 // Retransmissions are handled separately if RTX is enabled.
1723 if (rtp_payload_registry_->RtxEnabled())
1724 return false;
1725 StreamStatistician* statistician =
1726 rtp_receive_statistics_->GetStatistician(header.ssrc);
1727 if (!statistician)
1728 return false;
1729 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001730 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001731 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001732 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001733}
1734
mflodman3d7db262016-04-29 00:57:13 -07001735int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001736 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001737 "Channel::ReceivedRTCPPacket()");
1738 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001739 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001740
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001741 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001742 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001743 _engineStatisticsPtr->SetLastError(
1744 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1745 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1746 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001747
Minyue2013aec2015-05-13 14:14:42 +02001748 int64_t rtt = GetRTT(true);
1749 if (rtt == 0) {
1750 // Waiting for valid RTT.
1751 return 0;
1752 }
Erik Språng737336d2016-07-29 12:59:36 +02001753
1754 int64_t nack_window_ms = rtt;
1755 if (nack_window_ms < kMinRetransmissionWindowMs) {
1756 nack_window_ms = kMinRetransmissionWindowMs;
1757 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1758 nack_window_ms = kMaxRetransmissionWindowMs;
1759 }
1760 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1761
minyue7e304322016-10-12 05:00:55 -07001762 // Invoke audio encoders OnReceivedRtt().
1763 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1764 if (*encoder)
1765 (*encoder)->OnReceivedRtt(rtt);
1766 });
1767
Minyue2013aec2015-05-13 14:14:42 +02001768 uint32_t ntp_secs = 0;
1769 uint32_t ntp_frac = 0;
1770 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001771 if (0 !=
1772 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1773 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001774 // Waiting for RTCP.
1775 return 0;
1776 }
1777
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001778 {
tommi31fc21f2016-01-21 10:37:37 -08001779 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001780 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001781 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001782 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001783}
1784
niklase@google.com470e71d2011-07-07 08:21:25 +00001785int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001786 bool loop,
1787 FileFormats format,
1788 int startPosition,
1789 float volumeScaling,
1790 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001791 const CodecInst* codecInst) {
1792 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1793 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1794 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1795 "stopPosition=%d)",
1796 fileName, loop, format, volumeScaling, startPosition,
1797 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001798
kwiberg55b97fe2016-01-28 05:22:45 -08001799 if (channel_state_.Get().output_file_playing) {
1800 _engineStatisticsPtr->SetLastError(
1801 VE_ALREADY_PLAYING, kTraceError,
1802 "StartPlayingFileLocally() is already playing");
1803 return -1;
1804 }
1805
1806 {
1807 rtc::CritScope cs(&_fileCritSect);
1808
kwiberg5a25d952016-08-17 07:31:12 -07001809 if (output_file_player_) {
1810 output_file_player_->RegisterModuleFileCallback(NULL);
1811 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001812 }
1813
kwiberg5b356f42016-09-08 04:32:33 -07001814 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001815 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001816
kwiberg5a25d952016-08-17 07:31:12 -07001817 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001818 _engineStatisticsPtr->SetLastError(
1819 VE_INVALID_ARGUMENT, kTraceError,
1820 "StartPlayingFileLocally() filePlayer format is not correct");
1821 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001822 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001823
kwiberg55b97fe2016-01-28 05:22:45 -08001824 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001825
kwiberg5a25d952016-08-17 07:31:12 -07001826 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001827 fileName, loop, startPosition, volumeScaling, notificationTime,
1828 stopPosition, (const CodecInst*)codecInst) != 0) {
1829 _engineStatisticsPtr->SetLastError(
1830 VE_BAD_FILE, kTraceError,
1831 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001832 output_file_player_->StopPlayingFile();
1833 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001834 return -1;
1835 }
kwiberg5a25d952016-08-17 07:31:12 -07001836 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001837 channel_state_.SetOutputFilePlaying(true);
1838 }
1839
1840 if (RegisterFilePlayingToMixer() != 0)
1841 return -1;
1842
1843 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001844}
1845
1846int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001847 FileFormats format,
1848 int startPosition,
1849 float volumeScaling,
1850 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001851 const CodecInst* codecInst) {
1852 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1853 "Channel::StartPlayingFileLocally(format=%d,"
1854 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1855 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001856
kwiberg55b97fe2016-01-28 05:22:45 -08001857 if (stream == NULL) {
1858 _engineStatisticsPtr->SetLastError(
1859 VE_BAD_FILE, kTraceError,
1860 "StartPlayingFileLocally() NULL as input stream");
1861 return -1;
1862 }
1863
1864 if (channel_state_.Get().output_file_playing) {
1865 _engineStatisticsPtr->SetLastError(
1866 VE_ALREADY_PLAYING, kTraceError,
1867 "StartPlayingFileLocally() is already playing");
1868 return -1;
1869 }
1870
1871 {
1872 rtc::CritScope cs(&_fileCritSect);
1873
1874 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001875 if (output_file_player_) {
1876 output_file_player_->RegisterModuleFileCallback(NULL);
1877 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001878 }
1879
kwiberg55b97fe2016-01-28 05:22:45 -08001880 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001881 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001882 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001883
kwiberg5a25d952016-08-17 07:31:12 -07001884 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001885 _engineStatisticsPtr->SetLastError(
1886 VE_INVALID_ARGUMENT, kTraceError,
1887 "StartPlayingFileLocally() filePlayer format isnot correct");
1888 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001889 }
1890
kwiberg55b97fe2016-01-28 05:22:45 -08001891 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001892
kwiberg4ec01d92016-08-22 08:43:54 -07001893 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001894 volumeScaling, notificationTime,
1895 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001896 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1897 "StartPlayingFile() failed to "
1898 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001899 output_file_player_->StopPlayingFile();
1900 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001901 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001902 }
kwiberg5a25d952016-08-17 07:31:12 -07001903 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001904 channel_state_.SetOutputFilePlaying(true);
1905 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001906
kwiberg55b97fe2016-01-28 05:22:45 -08001907 if (RegisterFilePlayingToMixer() != 0)
1908 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001909
kwiberg55b97fe2016-01-28 05:22:45 -08001910 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001911}
1912
kwiberg55b97fe2016-01-28 05:22:45 -08001913int Channel::StopPlayingFileLocally() {
1914 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1915 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001916
kwiberg55b97fe2016-01-28 05:22:45 -08001917 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001918 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001919 }
1920
1921 {
1922 rtc::CritScope cs(&_fileCritSect);
1923
kwiberg5a25d952016-08-17 07:31:12 -07001924 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001925 _engineStatisticsPtr->SetLastError(
1926 VE_STOP_RECORDING_FAILED, kTraceError,
1927 "StopPlayingFile() could not stop playing");
1928 return -1;
1929 }
kwiberg5a25d952016-08-17 07:31:12 -07001930 output_file_player_->RegisterModuleFileCallback(NULL);
1931 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001932 channel_state_.SetOutputFilePlaying(false);
1933 }
1934 // _fileCritSect cannot be taken while calling
1935 // SetAnonymousMixibilityStatus. Refer to comments in
1936 // StartPlayingFileLocally(const char* ...) for more details.
1937 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1938 _engineStatisticsPtr->SetLastError(
1939 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1940 "StopPlayingFile() failed to stop participant from playing as"
1941 "file in the mixer");
1942 return -1;
1943 }
1944
1945 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001946}
1947
kwiberg55b97fe2016-01-28 05:22:45 -08001948int Channel::IsPlayingFileLocally() const {
1949 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001950}
1951
kwiberg55b97fe2016-01-28 05:22:45 -08001952int Channel::RegisterFilePlayingToMixer() {
1953 // Return success for not registering for file playing to mixer if:
1954 // 1. playing file before playout is started on that channel.
1955 // 2. starting playout without file playing on that channel.
1956 if (!channel_state_.Get().playing ||
1957 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001958 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001959 }
1960
1961 // |_fileCritSect| cannot be taken while calling
1962 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1963 // frames can be pulled by the mixer. Since the frames are generated from
1964 // the file, _fileCritSect will be taken. This would result in a deadlock.
1965 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1966 channel_state_.SetOutputFilePlaying(false);
1967 rtc::CritScope cs(&_fileCritSect);
1968 _engineStatisticsPtr->SetLastError(
1969 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1970 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07001971 output_file_player_->StopPlayingFile();
1972 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001973 return -1;
1974 }
1975
1976 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001977}
1978
niklase@google.com470e71d2011-07-07 08:21:25 +00001979int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001980 bool loop,
1981 FileFormats format,
1982 int startPosition,
1983 float volumeScaling,
1984 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001985 const CodecInst* codecInst) {
1986 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1987 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1988 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1989 "stopPosition=%d)",
1990 fileName, loop, format, volumeScaling, startPosition,
1991 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001992
kwiberg55b97fe2016-01-28 05:22:45 -08001993 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001994
kwiberg55b97fe2016-01-28 05:22:45 -08001995 if (channel_state_.Get().input_file_playing) {
1996 _engineStatisticsPtr->SetLastError(
1997 VE_ALREADY_PLAYING, kTraceWarning,
1998 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001999 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002000 }
2001
2002 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002003 if (input_file_player_) {
2004 input_file_player_->RegisterModuleFileCallback(NULL);
2005 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002006 }
2007
2008 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002009 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002010 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002011
kwiberg5a25d952016-08-17 07:31:12 -07002012 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002013 _engineStatisticsPtr->SetLastError(
2014 VE_INVALID_ARGUMENT, kTraceError,
2015 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
2016 return -1;
2017 }
2018
2019 const uint32_t notificationTime(0);
2020
kwiberg5a25d952016-08-17 07:31:12 -07002021 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002022 fileName, loop, startPosition, volumeScaling, notificationTime,
2023 stopPosition, (const CodecInst*)codecInst) != 0) {
2024 _engineStatisticsPtr->SetLastError(
2025 VE_BAD_FILE, kTraceError,
2026 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002027 input_file_player_->StopPlayingFile();
2028 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002029 return -1;
2030 }
kwiberg5a25d952016-08-17 07:31:12 -07002031 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002032 channel_state_.SetInputFilePlaying(true);
2033
2034 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002035}
2036
2037int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002038 FileFormats format,
2039 int startPosition,
2040 float volumeScaling,
2041 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002042 const CodecInst* codecInst) {
2043 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2044 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2045 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2046 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002047
kwiberg55b97fe2016-01-28 05:22:45 -08002048 if (stream == NULL) {
2049 _engineStatisticsPtr->SetLastError(
2050 VE_BAD_FILE, kTraceError,
2051 "StartPlayingFileAsMicrophone NULL as input stream");
2052 return -1;
2053 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002054
kwiberg55b97fe2016-01-28 05:22:45 -08002055 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002056
kwiberg55b97fe2016-01-28 05:22:45 -08002057 if (channel_state_.Get().input_file_playing) {
2058 _engineStatisticsPtr->SetLastError(
2059 VE_ALREADY_PLAYING, kTraceWarning,
2060 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002061 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002062 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002063
kwiberg55b97fe2016-01-28 05:22:45 -08002064 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002065 if (input_file_player_) {
2066 input_file_player_->RegisterModuleFileCallback(NULL);
2067 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002068 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002069
kwiberg55b97fe2016-01-28 05:22:45 -08002070 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002071 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002072 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002073
kwiberg5a25d952016-08-17 07:31:12 -07002074 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002075 _engineStatisticsPtr->SetLastError(
2076 VE_INVALID_ARGUMENT, kTraceError,
2077 "StartPlayingInputFile() filePlayer format isnot correct");
2078 return -1;
2079 }
2080
2081 const uint32_t notificationTime(0);
2082
kwiberg4ec01d92016-08-22 08:43:54 -07002083 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2084 notificationTime, stopPosition,
2085 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002086 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2087 "StartPlayingFile() failed to start "
2088 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002089 input_file_player_->StopPlayingFile();
2090 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002091 return -1;
2092 }
2093
kwiberg5a25d952016-08-17 07:31:12 -07002094 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002095 channel_state_.SetInputFilePlaying(true);
2096
2097 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002098}
2099
kwiberg55b97fe2016-01-28 05:22:45 -08002100int Channel::StopPlayingFileAsMicrophone() {
2101 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2102 "Channel::StopPlayingFileAsMicrophone()");
2103
2104 rtc::CritScope cs(&_fileCritSect);
2105
2106 if (!channel_state_.Get().input_file_playing) {
2107 return 0;
2108 }
2109
kwiberg5a25d952016-08-17 07:31:12 -07002110 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002111 _engineStatisticsPtr->SetLastError(
2112 VE_STOP_RECORDING_FAILED, kTraceError,
2113 "StopPlayingFile() could not stop playing");
2114 return -1;
2115 }
kwiberg5a25d952016-08-17 07:31:12 -07002116 input_file_player_->RegisterModuleFileCallback(NULL);
2117 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002118 channel_state_.SetInputFilePlaying(false);
2119
2120 return 0;
2121}
2122
2123int Channel::IsPlayingFileAsMicrophone() const {
2124 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002125}
2126
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002127int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002128 const CodecInst* codecInst) {
2129 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2130 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002131
kwiberg55b97fe2016-01-28 05:22:45 -08002132 if (_outputFileRecording) {
2133 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2134 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002135 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002136 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002137
kwiberg55b97fe2016-01-28 05:22:45 -08002138 FileFormats format;
2139 const uint32_t notificationTime(0); // Not supported in VoE
2140 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002141
kwiberg55b97fe2016-01-28 05:22:45 -08002142 if ((codecInst != NULL) &&
2143 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2144 _engineStatisticsPtr->SetLastError(
2145 VE_BAD_ARGUMENT, kTraceError,
2146 "StartRecordingPlayout() invalid compression");
2147 return (-1);
2148 }
2149 if (codecInst == NULL) {
2150 format = kFileFormatPcm16kHzFile;
2151 codecInst = &dummyCodec;
2152 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2153 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2154 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2155 format = kFileFormatWavFile;
2156 } else {
2157 format = kFileFormatCompressedFile;
2158 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002159
kwiberg55b97fe2016-01-28 05:22:45 -08002160 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002161
kwiberg55b97fe2016-01-28 05:22:45 -08002162 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002163 if (output_file_recorder_) {
2164 output_file_recorder_->RegisterModuleFileCallback(NULL);
2165 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002166 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002167
kwiberg5a25d952016-08-17 07:31:12 -07002168 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002169 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002170 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002171 _engineStatisticsPtr->SetLastError(
2172 VE_INVALID_ARGUMENT, kTraceError,
2173 "StartRecordingPlayout() fileRecorder format isnot correct");
2174 return -1;
2175 }
2176
kwiberg5a25d952016-08-17 07:31:12 -07002177 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002178 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2179 _engineStatisticsPtr->SetLastError(
2180 VE_BAD_FILE, kTraceError,
2181 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002182 output_file_recorder_->StopRecording();
2183 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002184 return -1;
2185 }
kwiberg5a25d952016-08-17 07:31:12 -07002186 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002187 _outputFileRecording = true;
2188
2189 return 0;
2190}
2191
2192int Channel::StartRecordingPlayout(OutStream* stream,
2193 const CodecInst* codecInst) {
2194 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2195 "Channel::StartRecordingPlayout()");
2196
2197 if (_outputFileRecording) {
2198 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2199 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002200 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002201 }
2202
2203 FileFormats format;
2204 const uint32_t notificationTime(0); // Not supported in VoE
2205 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2206
2207 if (codecInst != NULL && codecInst->channels != 1) {
2208 _engineStatisticsPtr->SetLastError(
2209 VE_BAD_ARGUMENT, kTraceError,
2210 "StartRecordingPlayout() invalid compression");
2211 return (-1);
2212 }
2213 if (codecInst == NULL) {
2214 format = kFileFormatPcm16kHzFile;
2215 codecInst = &dummyCodec;
2216 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2217 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2218 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2219 format = kFileFormatWavFile;
2220 } else {
2221 format = kFileFormatCompressedFile;
2222 }
2223
2224 rtc::CritScope cs(&_fileCritSect);
2225
2226 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002227 if (output_file_recorder_) {
2228 output_file_recorder_->RegisterModuleFileCallback(NULL);
2229 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002230 }
2231
kwiberg5a25d952016-08-17 07:31:12 -07002232 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002233 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002234 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002235 _engineStatisticsPtr->SetLastError(
2236 VE_INVALID_ARGUMENT, kTraceError,
2237 "StartRecordingPlayout() fileRecorder format isnot correct");
2238 return -1;
2239 }
2240
kwiberg4ec01d92016-08-22 08:43:54 -07002241 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002242 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002243 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2244 "StartRecordingPlayout() failed to "
2245 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002246 output_file_recorder_->StopRecording();
2247 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002248 return -1;
2249 }
2250
kwiberg5a25d952016-08-17 07:31:12 -07002251 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002252 _outputFileRecording = true;
2253
2254 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002255}
2256
kwiberg55b97fe2016-01-28 05:22:45 -08002257int Channel::StopRecordingPlayout() {
2258 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2259 "Channel::StopRecordingPlayout()");
2260
2261 if (!_outputFileRecording) {
2262 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2263 "StopRecordingPlayout() isnot recording");
2264 return -1;
2265 }
2266
2267 rtc::CritScope cs(&_fileCritSect);
2268
kwiberg5a25d952016-08-17 07:31:12 -07002269 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002270 _engineStatisticsPtr->SetLastError(
2271 VE_STOP_RECORDING_FAILED, kTraceError,
2272 "StopRecording() could not stop recording");
2273 return (-1);
2274 }
kwiberg5a25d952016-08-17 07:31:12 -07002275 output_file_recorder_->RegisterModuleFileCallback(NULL);
2276 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002277 _outputFileRecording = false;
2278
2279 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002280}
2281
kwiberg55b97fe2016-01-28 05:22:45 -08002282void Channel::SetMixWithMicStatus(bool mix) {
2283 rtc::CritScope cs(&_fileCritSect);
2284 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002285}
2286
kwiberg55b97fe2016-01-28 05:22:45 -08002287int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2288 int8_t currentLevel = _outputAudioLevel.Level();
2289 level = static_cast<int32_t>(currentLevel);
2290 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002291}
2292
kwiberg55b97fe2016-01-28 05:22:45 -08002293int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2294 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2295 level = static_cast<int32_t>(currentLevel);
2296 return 0;
2297}
2298
solenberg1c2af8e2016-03-24 10:36:00 -07002299int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002300 rtc::CritScope cs(&volume_settings_critsect_);
2301 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002302 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002303 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002304 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002305}
2306
solenberg1c2af8e2016-03-24 10:36:00 -07002307bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002308 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002309 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002310}
2311
kwiberg55b97fe2016-01-28 05:22:45 -08002312int Channel::SetOutputVolumePan(float left, float right) {
2313 rtc::CritScope cs(&volume_settings_critsect_);
2314 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002315 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002316 _panLeft = left;
2317 _panRight = right;
2318 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002319}
2320
kwiberg55b97fe2016-01-28 05:22:45 -08002321int Channel::GetOutputVolumePan(float& left, float& right) const {
2322 rtc::CritScope cs(&volume_settings_critsect_);
2323 left = _panLeft;
2324 right = _panRight;
2325 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002326}
2327
kwiberg55b97fe2016-01-28 05:22:45 -08002328int Channel::SetChannelOutputVolumeScaling(float scaling) {
2329 rtc::CritScope cs(&volume_settings_critsect_);
2330 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002331 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002332 _outputGain = scaling;
2333 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002334}
2335
kwiberg55b97fe2016-01-28 05:22:45 -08002336int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2337 rtc::CritScope cs(&volume_settings_critsect_);
2338 scaling = _outputGain;
2339 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002340}
2341
solenberg8842c3e2016-03-11 03:06:41 -08002342int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002343 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002344 "Channel::SendTelephoneEventOutband(...)");
2345 RTC_DCHECK_LE(0, event);
2346 RTC_DCHECK_GE(255, event);
2347 RTC_DCHECK_LE(0, duration_ms);
2348 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002349 if (!Sending()) {
2350 return -1;
2351 }
solenberg8842c3e2016-03-11 03:06:41 -08002352 if (_rtpRtcpModule->SendTelephoneEventOutband(
2353 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002354 _engineStatisticsPtr->SetLastError(
2355 VE_SEND_DTMF_FAILED, kTraceWarning,
2356 "SendTelephoneEventOutband() failed to send event");
2357 return -1;
2358 }
2359 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002360}
2361
solenbergffbbcac2016-11-17 05:25:37 -08002362int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2363 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002364 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002365 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002366 RTC_DCHECK_LE(0, payload_type);
2367 RTC_DCHECK_GE(127, payload_type);
2368 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002369 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002370 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002371 memcpy(codec.plname, "telephone-event", 16);
2372 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2373 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2374 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2375 _engineStatisticsPtr->SetLastError(
2376 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2377 "SetSendTelephoneEventPayloadType() failed to register send"
2378 "payload type");
2379 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002380 }
kwiberg55b97fe2016-01-28 05:22:45 -08002381 }
kwiberg55b97fe2016-01-28 05:22:45 -08002382 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002383}
2384
kwiberg55b97fe2016-01-28 05:22:45 -08002385int Channel::VoiceActivityIndicator(int& activity) {
2386 activity = _sendFrameType;
2387 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002388}
2389
kwiberg55b97fe2016-01-28 05:22:45 -08002390int Channel::SetLocalSSRC(unsigned int ssrc) {
2391 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2392 "Channel::SetLocalSSRC()");
2393 if (channel_state_.Get().sending) {
2394 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2395 "SetLocalSSRC() already sending");
2396 return -1;
2397 }
2398 _rtpRtcpModule->SetSSRC(ssrc);
2399 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002400}
2401
kwiberg55b97fe2016-01-28 05:22:45 -08002402int Channel::GetLocalSSRC(unsigned int& ssrc) {
2403 ssrc = _rtpRtcpModule->SSRC();
2404 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002405}
2406
kwiberg55b97fe2016-01-28 05:22:45 -08002407int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2408 ssrc = rtp_receiver_->SSRC();
2409 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002410}
2411
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002412int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002413 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002414 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002415}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002416
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002417int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2418 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002419 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2420 if (enable &&
2421 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2422 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002423 return -1;
2424 }
2425 return 0;
2426}
2427
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002428void Channel::EnableSendTransportSequenceNumber(int id) {
2429 int ret =
2430 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2431 RTC_DCHECK_EQ(0, ret);
2432}
2433
stefan3313ec92016-01-21 06:32:43 -08002434void Channel::EnableReceiveTransportSequenceNumber(int id) {
2435 rtp_header_parser_->DeregisterRtpHeaderExtension(
2436 kRtpExtensionTransportSequenceNumber);
2437 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2438 kRtpExtensionTransportSequenceNumber, id);
2439 RTC_DCHECK(ret);
2440}
2441
stefanbba9dec2016-02-01 04:39:55 -08002442void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002443 RtpPacketSender* rtp_packet_sender,
2444 TransportFeedbackObserver* transport_feedback_observer,
stefan7de8d642017-02-07 07:14:08 -08002445 PacketRouter* packet_router,
2446 RtcpBandwidthObserver* bandwidth_observer) {
stefanbba9dec2016-02-01 04:39:55 -08002447 RTC_DCHECK(rtp_packet_sender);
2448 RTC_DCHECK(transport_feedback_observer);
2449 RTC_DCHECK(packet_router && !packet_router_);
stefan7de8d642017-02-07 07:14:08 -08002450 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08002451 feedback_observer_proxy_->SetTransportFeedbackObserver(
2452 transport_feedback_observer);
2453 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2454 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2455 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002456 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002457 packet_router_ = packet_router;
2458}
2459
stefanbba9dec2016-02-01 04:39:55 -08002460void Channel::RegisterReceiverCongestionControlObjects(
2461 PacketRouter* packet_router) {
2462 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002463 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002464 packet_router_ = packet_router;
2465}
2466
2467void Channel::ResetCongestionControlObjects() {
2468 RTC_DCHECK(packet_router_);
2469 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08002470 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08002471 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2472 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002473 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002474 packet_router_ = nullptr;
2475 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2476}
2477
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002478void Channel::SetRTCPStatus(bool enable) {
2479 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2480 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002481 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002482}
2483
kwiberg55b97fe2016-01-28 05:22:45 -08002484int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002485 RtcpMode method = _rtpRtcpModule->RTCP();
2486 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002487 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002488}
2489
kwiberg55b97fe2016-01-28 05:22:45 -08002490int Channel::SetRTCP_CNAME(const char cName[256]) {
2491 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2492 "Channel::SetRTCP_CNAME()");
2493 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2494 _engineStatisticsPtr->SetLastError(
2495 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2496 "SetRTCP_CNAME() failed to set RTCP CNAME");
2497 return -1;
2498 }
2499 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002500}
2501
kwiberg55b97fe2016-01-28 05:22:45 -08002502int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2503 if (cName == NULL) {
2504 _engineStatisticsPtr->SetLastError(
2505 VE_INVALID_ARGUMENT, kTraceError,
2506 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2507 return -1;
2508 }
2509 char cname[RTCP_CNAME_SIZE];
2510 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2511 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2512 _engineStatisticsPtr->SetLastError(
2513 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2514 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2515 return -1;
2516 }
2517 strcpy(cName, cname);
2518 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002519}
2520
kwiberg55b97fe2016-01-28 05:22:45 -08002521int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2522 unsigned int& NTPLow,
2523 unsigned int& timestamp,
2524 unsigned int& playoutTimestamp,
2525 unsigned int* jitter,
2526 unsigned short* fractionLost) {
2527 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002528
kwiberg55b97fe2016-01-28 05:22:45 -08002529 RTCPSenderInfo senderInfo;
2530 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2531 _engineStatisticsPtr->SetLastError(
2532 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2533 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2534 "side");
2535 return -1;
2536 }
2537
2538 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2539 // and octet count)
2540 NTPHigh = senderInfo.NTPseconds;
2541 NTPLow = senderInfo.NTPfraction;
2542 timestamp = senderInfo.RTPtimeStamp;
2543
2544 // --- Locally derived information
2545
2546 // This value is updated on each incoming RTCP packet (0 when no packet
2547 // has been received)
2548 playoutTimestamp = playout_timestamp_rtcp_;
2549
2550 if (NULL != jitter || NULL != fractionLost) {
2551 // Get all RTCP receiver report blocks that have been received on this
2552 // channel. If we receive RTP packets from a remote source we know the
2553 // remote SSRC and use the report block from him.
2554 // Otherwise use the first report block.
2555 std::vector<RTCPReportBlock> remote_stats;
2556 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2557 remote_stats.empty()) {
2558 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2559 "GetRemoteRTCPData() failed to measure statistics due"
2560 " to lack of received RTP and/or RTCP packets");
2561 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002562 }
2563
kwiberg55b97fe2016-01-28 05:22:45 -08002564 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2565 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2566 for (; it != remote_stats.end(); ++it) {
2567 if (it->remoteSSRC == remoteSSRC)
2568 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002569 }
kwiberg55b97fe2016-01-28 05:22:45 -08002570
2571 if (it == remote_stats.end()) {
2572 // If we have not received any RTCP packets from this SSRC it probably
2573 // means that we have not received any RTP packets.
2574 // Use the first received report block instead.
2575 it = remote_stats.begin();
2576 remoteSSRC = it->remoteSSRC;
2577 }
2578
2579 if (jitter) {
2580 *jitter = it->jitter;
2581 }
2582
2583 if (fractionLost) {
2584 *fractionLost = it->fractionLost;
2585 }
2586 }
2587 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002588}
2589
kwiberg55b97fe2016-01-28 05:22:45 -08002590int Channel::SendApplicationDefinedRTCPPacket(
2591 unsigned char subType,
2592 unsigned int name,
2593 const char* data,
2594 unsigned short dataLengthInBytes) {
2595 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2596 "Channel::SendApplicationDefinedRTCPPacket()");
2597 if (!channel_state_.Get().sending) {
2598 _engineStatisticsPtr->SetLastError(
2599 VE_NOT_SENDING, kTraceError,
2600 "SendApplicationDefinedRTCPPacket() not sending");
2601 return -1;
2602 }
2603 if (NULL == data) {
2604 _engineStatisticsPtr->SetLastError(
2605 VE_INVALID_ARGUMENT, kTraceError,
2606 "SendApplicationDefinedRTCPPacket() invalid data value");
2607 return -1;
2608 }
2609 if (dataLengthInBytes % 4 != 0) {
2610 _engineStatisticsPtr->SetLastError(
2611 VE_INVALID_ARGUMENT, kTraceError,
2612 "SendApplicationDefinedRTCPPacket() invalid length value");
2613 return -1;
2614 }
2615 RtcpMode status = _rtpRtcpModule->RTCP();
2616 if (status == RtcpMode::kOff) {
2617 _engineStatisticsPtr->SetLastError(
2618 VE_RTCP_ERROR, kTraceError,
2619 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2620 return -1;
2621 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002622
kwiberg55b97fe2016-01-28 05:22:45 -08002623 // Create and schedule the RTCP APP packet for transmission
2624 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2625 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2626 _engineStatisticsPtr->SetLastError(
2627 VE_SEND_ERROR, kTraceError,
2628 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2629 return -1;
2630 }
2631 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002632}
2633
kwiberg55b97fe2016-01-28 05:22:45 -08002634int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2635 unsigned int& maxJitterMs,
2636 unsigned int& discardedPackets) {
2637 // The jitter statistics is updated for each received RTP packet and is
2638 // based on received packets.
2639 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2640 // If RTCP is off, there is no timed thread in the RTCP module regularly
2641 // generating new stats, trigger the update manually here instead.
2642 StreamStatistician* statistician =
2643 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2644 if (statistician) {
2645 // Don't use returned statistics, use data from proxy instead so that
2646 // max jitter can be fetched atomically.
2647 RtcpStatistics s;
2648 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002649 }
kwiberg55b97fe2016-01-28 05:22:45 -08002650 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002651
kwiberg55b97fe2016-01-28 05:22:45 -08002652 ChannelStatistics stats = statistics_proxy_->GetStats();
2653 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2654 if (playoutFrequency > 0) {
2655 // Scale RTP statistics given the current playout frequency
2656 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2657 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2658 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002659
kwiberg55b97fe2016-01-28 05:22:45 -08002660 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002661
kwiberg55b97fe2016-01-28 05:22:45 -08002662 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002663}
2664
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002665int Channel::GetRemoteRTCPReportBlocks(
2666 std::vector<ReportBlock>* report_blocks) {
2667 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002668 _engineStatisticsPtr->SetLastError(
2669 VE_INVALID_ARGUMENT, kTraceError,
2670 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002671 return -1;
2672 }
2673
2674 // Get the report blocks from the latest received RTCP Sender or Receiver
2675 // Report. Each element in the vector contains the sender's SSRC and a
2676 // report block according to RFC 3550.
2677 std::vector<RTCPReportBlock> rtcp_report_blocks;
2678 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002679 return -1;
2680 }
2681
2682 if (rtcp_report_blocks.empty())
2683 return 0;
2684
2685 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2686 for (; it != rtcp_report_blocks.end(); ++it) {
2687 ReportBlock report_block;
2688 report_block.sender_SSRC = it->remoteSSRC;
2689 report_block.source_SSRC = it->sourceSSRC;
2690 report_block.fraction_lost = it->fractionLost;
2691 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2692 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2693 report_block.interarrival_jitter = it->jitter;
2694 report_block.last_SR_timestamp = it->lastSR;
2695 report_block.delay_since_last_SR = it->delaySinceLastSR;
2696 report_blocks->push_back(report_block);
2697 }
2698 return 0;
2699}
2700
kwiberg55b97fe2016-01-28 05:22:45 -08002701int Channel::GetRTPStatistics(CallStatistics& stats) {
2702 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002703
kwiberg55b97fe2016-01-28 05:22:45 -08002704 // The jitter statistics is updated for each received RTP packet and is
2705 // based on received packets.
2706 RtcpStatistics statistics;
2707 StreamStatistician* statistician =
2708 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002709 if (statistician) {
2710 statistician->GetStatistics(&statistics,
2711 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002712 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002713
kwiberg55b97fe2016-01-28 05:22:45 -08002714 stats.fractionLost = statistics.fraction_lost;
2715 stats.cumulativeLost = statistics.cumulative_lost;
2716 stats.extendedMax = statistics.extended_max_sequence_number;
2717 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002718
kwiberg55b97fe2016-01-28 05:22:45 -08002719 // --- RTT
2720 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002721
kwiberg55b97fe2016-01-28 05:22:45 -08002722 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002723
kwiberg55b97fe2016-01-28 05:22:45 -08002724 size_t bytesSent(0);
2725 uint32_t packetsSent(0);
2726 size_t bytesReceived(0);
2727 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002728
kwiberg55b97fe2016-01-28 05:22:45 -08002729 if (statistician) {
2730 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2731 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002732
kwiberg55b97fe2016-01-28 05:22:45 -08002733 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2734 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2735 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2736 " output will not be complete");
2737 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002738
kwiberg55b97fe2016-01-28 05:22:45 -08002739 stats.bytesSent = bytesSent;
2740 stats.packetsSent = packetsSent;
2741 stats.bytesReceived = bytesReceived;
2742 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002743
kwiberg55b97fe2016-01-28 05:22:45 -08002744 // --- Timestamps
2745 {
2746 rtc::CritScope lock(&ts_stats_lock_);
2747 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2748 }
2749 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002750}
2751
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002752int Channel::SetCodecFECStatus(bool enable) {
2753 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2754 "Channel::SetCodecFECStatus()");
2755
kwibergc8d071e2016-04-06 12:22:38 -07002756 if (!codec_manager_.SetCodecFEC(enable) ||
2757 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002758 _engineStatisticsPtr->SetLastError(
2759 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2760 "SetCodecFECStatus() failed to set FEC state");
2761 return -1;
2762 }
2763 return 0;
2764}
2765
2766bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002767 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002768}
2769
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002770void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2771 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002772 // If pacing is enabled we always store packets.
2773 if (!pacing_enabled_)
2774 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002775 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002776 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002777 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002778 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002779 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002780}
2781
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002782// Called when we are missing one or more packets.
2783int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002784 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2785}
2786
kwiberg55b97fe2016-01-28 05:22:45 -08002787uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2788 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2789 "Channel::Demultiplex()");
2790 _audioFrame.CopyFrom(audioFrame);
2791 _audioFrame.id_ = _channelId;
2792 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002793}
2794
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002795void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002796 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002797 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002798 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002799 CodecInst codec;
2800 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002801
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002802 // Never upsample or upmix the capture signal here. This should be done at the
2803 // end of the send chain.
2804 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2805 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2806 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2807 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002808}
2809
kwiberg55b97fe2016-01-28 05:22:45 -08002810uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2811 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2812 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002813
kwiberg55b97fe2016-01-28 05:22:45 -08002814 if (_audioFrame.samples_per_channel_ == 0) {
2815 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2816 "Channel::PrepareEncodeAndSend() invalid audio frame");
2817 return 0xFFFFFFFF;
2818 }
2819
2820 if (channel_state_.Get().input_file_playing) {
2821 MixOrReplaceAudioWithFile(mixingFrequency);
2822 }
2823
solenberg1c2af8e2016-03-24 10:36:00 -07002824 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2825 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002826
2827 if (channel_state_.Get().input_external_media) {
2828 rtc::CritScope cs(&_callbackCritSect);
2829 const bool isStereo = (_audioFrame.num_channels_ == 2);
2830 if (_inputExternalMediaCallbackPtr) {
2831 _inputExternalMediaCallbackPtr->Process(
2832 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
2833 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
2834 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00002835 }
kwiberg55b97fe2016-01-28 05:22:45 -08002836 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002837
kwiberg55b97fe2016-01-28 05:22:45 -08002838 if (_includeAudioLevelIndication) {
2839 size_t length =
2840 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02002841 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002842 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002843 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002844 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002845 rms_level_.Analyze(
2846 rtc::ArrayView<const int16_t>(_audioFrame.data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002847 }
kwiberg55b97fe2016-01-28 05:22:45 -08002848 }
solenberg1c2af8e2016-03-24 10:36:00 -07002849 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002850
kwiberg55b97fe2016-01-28 05:22:45 -08002851 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002852}
2853
kwiberg55b97fe2016-01-28 05:22:45 -08002854uint32_t Channel::EncodeAndSend() {
2855 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2856 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002857
kwiberg55b97fe2016-01-28 05:22:45 -08002858 assert(_audioFrame.num_channels_ <= 2);
2859 if (_audioFrame.samples_per_channel_ == 0) {
2860 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2861 "Channel::EncodeAndSend() invalid audio frame");
2862 return 0xFFFFFFFF;
2863 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002864
kwiberg55b97fe2016-01-28 05:22:45 -08002865 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00002866
kwiberg55b97fe2016-01-28 05:22:45 -08002867 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002868
kwiberg55b97fe2016-01-28 05:22:45 -08002869 // The ACM resamples internally.
2870 _audioFrame.timestamp_ = _timeStamp;
2871 // This call will trigger AudioPacketizationCallback::SendData if encoding
2872 // is done and payload is ready for packetization and transmission.
2873 // Otherwise, it will return without invoking the callback.
2874 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
2875 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
2876 "Channel::EncodeAndSend() ACM encoding failed");
2877 return 0xFFFFFFFF;
2878 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002879
kwiberg55b97fe2016-01-28 05:22:45 -08002880 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
2881 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002882}
2883
solenberg7602aab2016-11-14 11:30:07 -08002884void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2885 RTC_DCHECK(!channel.channel() ||
2886 channel.channel()->ChannelId() != _channelId);
2887 rtc::CritScope lock(&assoc_send_channel_lock_);
2888 associate_send_channel_ = channel;
2889}
2890
Minyue2013aec2015-05-13 14:14:42 +02002891void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002892 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002893 Channel* channel = associate_send_channel_.channel();
2894 if (channel && channel->ChannelId() == channel_id) {
2895 // If this channel is associated with a send channel of the specified
2896 // Channel ID, disassociate with it.
2897 ChannelOwner ref(NULL);
2898 associate_send_channel_ = ref;
2899 }
2900}
2901
ivoc14d5dbe2016-07-04 07:06:55 -07002902void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2903 event_log_proxy_->SetEventLog(event_log);
2904}
2905
michaelt9332b7d2016-11-30 07:51:13 -08002906void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2907 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2908}
2909
nisse284542b2017-01-10 08:58:32 -08002910void Channel::UpdateOverheadForEncoder() {
2911 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2912 if (*encoder) {
2913 (*encoder)->OnReceivedOverhead(transport_overhead_per_packet_ +
2914 rtp_overhead_per_packet_);
2915 }
2916 });
2917}
2918
2919void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
2920 transport_overhead_per_packet_ = transport_overhead_per_packet;
2921 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08002922}
2923
michaeltbf65be52016-12-15 06:24:49 -08002924void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
nisse284542b2017-01-10 08:58:32 -08002925 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
2926 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08002927}
2928
kwiberg55b97fe2016-01-28 05:22:45 -08002929int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
2930 VoEMediaProcess& processObject) {
2931 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2932 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002933
kwiberg55b97fe2016-01-28 05:22:45 -08002934 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002935
kwiberg55b97fe2016-01-28 05:22:45 -08002936 if (kPlaybackPerChannel == type) {
2937 if (_outputExternalMediaCallbackPtr) {
2938 _engineStatisticsPtr->SetLastError(
2939 VE_INVALID_OPERATION, kTraceError,
2940 "Channel::RegisterExternalMediaProcessing() "
2941 "output external media already enabled");
2942 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002943 }
kwiberg55b97fe2016-01-28 05:22:45 -08002944 _outputExternalMediaCallbackPtr = &processObject;
2945 _outputExternalMedia = true;
2946 } else if (kRecordingPerChannel == type) {
2947 if (_inputExternalMediaCallbackPtr) {
2948 _engineStatisticsPtr->SetLastError(
2949 VE_INVALID_OPERATION, kTraceError,
2950 "Channel::RegisterExternalMediaProcessing() "
2951 "output external media already enabled");
2952 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002953 }
kwiberg55b97fe2016-01-28 05:22:45 -08002954 _inputExternalMediaCallbackPtr = &processObject;
2955 channel_state_.SetInputExternalMedia(true);
2956 }
2957 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002958}
2959
kwiberg55b97fe2016-01-28 05:22:45 -08002960int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
2961 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2962 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002963
kwiberg55b97fe2016-01-28 05:22:45 -08002964 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002965
kwiberg55b97fe2016-01-28 05:22:45 -08002966 if (kPlaybackPerChannel == type) {
2967 if (!_outputExternalMediaCallbackPtr) {
2968 _engineStatisticsPtr->SetLastError(
2969 VE_INVALID_OPERATION, kTraceWarning,
2970 "Channel::DeRegisterExternalMediaProcessing() "
2971 "output external media already disabled");
2972 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002973 }
kwiberg55b97fe2016-01-28 05:22:45 -08002974 _outputExternalMedia = false;
2975 _outputExternalMediaCallbackPtr = NULL;
2976 } else if (kRecordingPerChannel == type) {
2977 if (!_inputExternalMediaCallbackPtr) {
2978 _engineStatisticsPtr->SetLastError(
2979 VE_INVALID_OPERATION, kTraceWarning,
2980 "Channel::DeRegisterExternalMediaProcessing() "
2981 "input external media already disabled");
2982 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002983 }
kwiberg55b97fe2016-01-28 05:22:45 -08002984 channel_state_.SetInputExternalMedia(false);
2985 _inputExternalMediaCallbackPtr = NULL;
2986 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002987
kwiberg55b97fe2016-01-28 05:22:45 -08002988 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002989}
2990
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002991int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08002992 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2993 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002994
kwiberg55b97fe2016-01-28 05:22:45 -08002995 if (channel_state_.Get().playing) {
2996 _engineStatisticsPtr->SetLastError(
2997 VE_INVALID_OPERATION, kTraceError,
2998 "Channel::SetExternalMixing() "
2999 "external mixing cannot be changed while playing.");
3000 return -1;
3001 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003002
kwiberg55b97fe2016-01-28 05:22:45 -08003003 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003004
kwiberg55b97fe2016-01-28 05:22:45 -08003005 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00003006}
3007
kwiberg55b97fe2016-01-28 05:22:45 -08003008int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
3009 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00003010}
3011
wu@webrtc.org24301a62013-12-13 19:17:43 +00003012void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
3013 audio_coding_->GetDecodingCallStatistics(stats);
3014}
3015
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003016bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
3017 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08003018 rtc::CritScope lock(&video_sync_lock_);
henrik.lundinb3f1c5d2016-08-22 15:39:53 -07003019 *jitter_buffer_delay_ms = audio_coding_->FilteredCurrentDelayMs();
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003020 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003021 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00003022}
3023
solenberg358057b2015-11-27 10:46:42 -08003024uint32_t Channel::GetDelayEstimate() const {
3025 int jitter_buffer_delay_ms = 0;
3026 int playout_buffer_delay_ms = 0;
3027 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3028 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
3029}
3030
deadbeef74375882015-08-13 12:09:10 -07003031int Channel::LeastRequiredDelayMs() const {
3032 return audio_coding_->LeastRequiredDelayMs();
3033}
3034
kwiberg55b97fe2016-01-28 05:22:45 -08003035int Channel::SetMinimumPlayoutDelay(int delayMs) {
3036 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3037 "Channel::SetMinimumPlayoutDelay()");
3038 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
3039 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
3040 _engineStatisticsPtr->SetLastError(
3041 VE_INVALID_ARGUMENT, kTraceError,
3042 "SetMinimumPlayoutDelay() invalid min delay");
3043 return -1;
3044 }
3045 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3046 _engineStatisticsPtr->SetLastError(
3047 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3048 "SetMinimumPlayoutDelay() failed to set min playout delay");
3049 return -1;
3050 }
3051 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003052}
3053
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003054int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003055 uint32_t playout_timestamp_rtp = 0;
3056 {
tommi31fc21f2016-01-21 10:37:37 -08003057 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003058 playout_timestamp_rtp = playout_timestamp_rtp_;
3059 }
kwiberg55b97fe2016-01-28 05:22:45 -08003060 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003061 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07003062 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003063 "GetPlayoutTimestamp() failed to retrieve timestamp");
3064 return -1;
3065 }
deadbeef74375882015-08-13 12:09:10 -07003066 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003067 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003068}
3069
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003070int Channel::SetInitTimestamp(unsigned int timestamp) {
3071 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003072 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003073 if (channel_state_.Get().sending) {
3074 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3075 "SetInitTimestamp() already sending");
3076 return -1;
3077 }
3078 _rtpRtcpModule->SetStartTimestamp(timestamp);
3079 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003080}
3081
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003082int Channel::SetInitSequenceNumber(short sequenceNumber) {
3083 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3084 "Channel::SetInitSequenceNumber()");
3085 if (channel_state_.Get().sending) {
3086 _engineStatisticsPtr->SetLastError(
3087 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3088 return -1;
3089 }
3090 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3091 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003092}
3093
kwiberg55b97fe2016-01-28 05:22:45 -08003094int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3095 RtpReceiver** rtp_receiver) const {
3096 *rtpRtcpModule = _rtpRtcpModule.get();
3097 *rtp_receiver = rtp_receiver_.get();
3098 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003099}
3100
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003101// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3102// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003103int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003104 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003105 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003106
kwiberg55b97fe2016-01-28 05:22:45 -08003107 {
3108 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003109
kwiberg5a25d952016-08-17 07:31:12 -07003110 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003111 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3112 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3113 " doesnt exist");
3114 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003115 }
3116
kwiberg4ec01d92016-08-22 08:43:54 -07003117 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07003118 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003119 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3120 "Channel::MixOrReplaceAudioWithFile() file mixing "
3121 "failed");
3122 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003123 }
kwiberg55b97fe2016-01-28 05:22:45 -08003124 if (fileSamples == 0) {
3125 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3126 "Channel::MixOrReplaceAudioWithFile() file is ended");
3127 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003128 }
kwiberg55b97fe2016-01-28 05:22:45 -08003129 }
3130
3131 assert(_audioFrame.samples_per_channel_ == fileSamples);
3132
3133 if (_mixFileWithMicrophone) {
3134 // Currently file stream is always mono.
3135 // TODO(xians): Change the code when FilePlayer supports real stereo.
3136 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3137 1, fileSamples);
3138 } else {
3139 // Replace ACM audio with file.
3140 // Currently file stream is always mono.
3141 // TODO(xians): Change the code when FilePlayer supports real stereo.
3142 _audioFrame.UpdateFrame(
3143 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3144 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3145 }
3146 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003147}
3148
kwiberg55b97fe2016-01-28 05:22:45 -08003149int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3150 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003151
kwibergb7f89d62016-02-17 10:04:18 -08003152 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003153 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003154
kwiberg55b97fe2016-01-28 05:22:45 -08003155 {
3156 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003157
kwiberg5a25d952016-08-17 07:31:12 -07003158 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003159 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3160 "Channel::MixAudioWithFile() file mixing failed");
3161 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003162 }
3163
kwiberg55b97fe2016-01-28 05:22:45 -08003164 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07003165 if (output_file_player_->Get10msAudioFromFile(
3166 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003167 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3168 "Channel::MixAudioWithFile() file mixing failed");
3169 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003170 }
kwiberg55b97fe2016-01-28 05:22:45 -08003171 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003172
kwiberg55b97fe2016-01-28 05:22:45 -08003173 if (audioFrame.samples_per_channel_ == fileSamples) {
3174 // Currently file stream is always mono.
3175 // TODO(xians): Change the code when FilePlayer supports real stereo.
3176 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3177 fileSamples);
3178 } else {
3179 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3180 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3181 ") != "
3182 "fileSamples(%" PRIuS ")",
3183 audioFrame.samples_per_channel_, fileSamples);
3184 return -1;
3185 }
3186
3187 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003188}
3189
deadbeef74375882015-08-13 12:09:10 -07003190void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003191 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003192
henrik.lundin96bd5022016-04-06 04:13:56 -07003193 if (!jitter_buffer_playout_timestamp_) {
3194 // This can happen if this channel has not received any RTP packets. In
3195 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003196 return;
3197 }
3198
3199 uint16_t delay_ms = 0;
3200 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003201 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003202 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3203 " delay from the ADM");
3204 _engineStatisticsPtr->SetLastError(
3205 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3206 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3207 return;
3208 }
3209
henrik.lundin96bd5022016-04-06 04:13:56 -07003210 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3211 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003212
3213 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07003214 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003215
kwiberg55b97fe2016-01-28 05:22:45 -08003216 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003217 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003218 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003219
3220 {
tommi31fc21f2016-01-21 10:37:37 -08003221 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003222 if (rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003223 playout_timestamp_rtcp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003224 } else {
henrik.lundin96bd5022016-04-06 04:13:56 -07003225 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003226 }
3227 playout_delay_ms_ = delay_ms;
3228 }
3229}
3230
kwiberg55b97fe2016-01-28 05:22:45 -08003231void Channel::RegisterReceiveCodecsToRTPModule() {
3232 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3233 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003234
kwiberg55b97fe2016-01-28 05:22:45 -08003235 CodecInst codec;
3236 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003237
kwiberg55b97fe2016-01-28 05:22:45 -08003238 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3239 // Open up the RTP/RTCP receiver for all supported codecs
3240 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08003241 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08003242 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3243 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3244 " to register %s (%d/%d/%" PRIuS
3245 "/%d) to RTP/RTCP "
3246 "receiver",
3247 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3248 codec.rate);
3249 } else {
3250 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3251 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3252 "(%d/%d/%" PRIuS
3253 "/%d) has been added to the RTP/RTCP "
3254 "receiver",
3255 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3256 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003257 }
kwiberg55b97fe2016-01-28 05:22:45 -08003258 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003259}
3260
kwiberg55b97fe2016-01-28 05:22:45 -08003261int Channel::SetSendRtpHeaderExtension(bool enable,
3262 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003263 unsigned char id) {
3264 int error = 0;
3265 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3266 if (enable) {
3267 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3268 }
3269 return error;
3270}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003271
ossue280cde2016-10-12 11:04:10 -07003272int Channel::GetRtpTimestampRateHz() const {
3273 const auto format = audio_coding_->ReceiveFormat();
3274 // Default to the playout frequency if we've not gotten any packets yet.
3275 // TODO(ossu): Zero clockrate can only happen if we've added an external
3276 // decoder for a format we don't support internally. Remove once that way of
3277 // adding decoders is gone!
3278 return (format && format->clockrate_hz != 0)
3279 ? format->clockrate_hz
3280 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00003281}
3282
Minyue2013aec2015-05-13 14:14:42 +02003283int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003284 RtcpMode method = _rtpRtcpModule->RTCP();
3285 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003286 return 0;
3287 }
3288 std::vector<RTCPReportBlock> report_blocks;
3289 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003290
3291 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003292 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003293 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003294 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003295 Channel* channel = associate_send_channel_.channel();
3296 // Tries to get RTT from an associated channel. This is important for
3297 // receive-only channels.
3298 if (channel) {
3299 // To prevent infinite recursion and deadlock, calling GetRTT of
3300 // associate channel should always use "false" for argument:
3301 // |allow_associate_channel|.
3302 rtt = channel->GetRTT(false);
3303 }
3304 }
3305 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003306 }
3307
3308 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3309 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3310 for (; it != report_blocks.end(); ++it) {
3311 if (it->remoteSSRC == remoteSSRC)
3312 break;
3313 }
3314 if (it == report_blocks.end()) {
3315 // We have not received packets with SSRC matching the report blocks.
3316 // To calculate RTT we try with the SSRC of the first report block.
3317 // This is very important for send-only channels where we don't know
3318 // the SSRC of the other end.
3319 remoteSSRC = report_blocks[0].remoteSSRC;
3320 }
Minyue2013aec2015-05-13 14:14:42 +02003321
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003322 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003323 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003324 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003325 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3326 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003327 return 0;
3328 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003329 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003330}
3331
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003332} // namespace voe
3333} // namespace webrtc