blob: 8d95c7bfbbcbc3b25a0811c372ef3a524bb56e5b [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
henrik.lundin50499422016-11-29 04:26:24 -080016#include "webrtc/base/array_view.h"
Ivo Creusenae856f22015-09-17 16:30:16 +020017#include "webrtc/base/checks.h"
tommi31fc21f2016-01-21 10:37:37 -080018#include "webrtc/base/criticalsection.h"
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +000019#include "webrtc/base/format_macros.h"
pbosad856222015-11-27 09:48:36 -080020#include "webrtc/base/logging.h"
Erik Språng737336d2016-07-29 12:59:36 +020021#include "webrtc/base/rate_limiter.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010022#include "webrtc/base/thread_checker.h"
wu@webrtc.org94454b72014-06-05 20:34:08 +000023#include "webrtc/base/timeutils.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020024#include "webrtc/config.h"
skvladcc91d282016-10-03 18:31:22 -070025#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kwibergda2bf4e2016-10-24 13:47:09 -070026#include "webrtc/modules/audio_coding/codecs/audio_format_conversion.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000027#include "webrtc/modules/audio_device/include/audio_device.h"
28#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010029#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010030#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010031#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
32#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
33#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000034#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010035#include "webrtc/modules/utility/include/audio_frame_operations.h"
36#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
143 void SetEventLog(RtcEventLog* event_log) {
144 rtc::CritScope lock(&crit_);
145 event_log_ = event_log;
146 }
147
148 private:
149 rtc::CriticalSection crit_;
150 RtcEventLog* event_log_ GUARDED_BY(crit_);
151 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
152};
153
michaelt9332b7d2016-11-30 07:51:13 -0800154class RtcpRttStatsProxy final : public RtcpRttStats {
155 public:
156 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
157
158 void OnRttUpdate(int64_t rtt) override {
159 rtc::CritScope lock(&crit_);
160 if (rtcp_rtt_stats_)
161 rtcp_rtt_stats_->OnRttUpdate(rtt);
162 }
163
164 int64_t LastProcessedRtt() const override {
165 rtc::CritScope lock(&crit_);
166 if (!rtcp_rtt_stats_)
167 return 0;
168 return rtcp_rtt_stats_->LastProcessedRtt();
169 }
170
171 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
172 rtc::CritScope lock(&crit_);
173 rtcp_rtt_stats_ = rtcp_rtt_stats;
174 }
175
176 private:
177 rtc::CriticalSection crit_;
178 RtcpRttStats* rtcp_rtt_stats_ GUARDED_BY(crit_);
179 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
180};
181
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100182class TransportFeedbackProxy : public TransportFeedbackObserver {
183 public:
184 TransportFeedbackProxy() : feedback_observer_(nullptr) {
185 pacer_thread_.DetachFromThread();
186 network_thread_.DetachFromThread();
187 }
188
189 void SetTransportFeedbackObserver(
190 TransportFeedbackObserver* feedback_observer) {
191 RTC_DCHECK(thread_checker_.CalledOnValidThread());
192 rtc::CritScope lock(&crit_);
193 feedback_observer_ = feedback_observer;
194 }
195
196 // Implements TransportFeedbackObserver.
197 void AddPacket(uint16_t sequence_number,
198 size_t length,
philipela1ed0b32016-06-01 06:31:17 -0700199 int probe_cluster_id) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100200 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
201 rtc::CritScope lock(&crit_);
202 if (feedback_observer_)
pbos2169d8b2016-06-20 11:53:02 -0700203 feedback_observer_->AddPacket(sequence_number, length, probe_cluster_id);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100204 }
205 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
206 RTC_DCHECK(network_thread_.CalledOnValidThread());
207 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700208 if (feedback_observer_)
209 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200210 }
211 std::vector<PacketInfo> GetTransportFeedbackVector() const override {
212 RTC_NOTREACHED();
213 return std::vector<PacketInfo>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100214 }
215
216 private:
217 rtc::CriticalSection crit_;
218 rtc::ThreadChecker thread_checker_;
219 rtc::ThreadChecker pacer_thread_;
220 rtc::ThreadChecker network_thread_;
221 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
222};
223
224class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
225 public:
226 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
227 pacer_thread_.DetachFromThread();
228 }
229
230 void SetSequenceNumberAllocator(
231 TransportSequenceNumberAllocator* seq_num_allocator) {
232 RTC_DCHECK(thread_checker_.CalledOnValidThread());
233 rtc::CritScope lock(&crit_);
234 seq_num_allocator_ = seq_num_allocator;
235 }
236
237 // Implements TransportSequenceNumberAllocator.
238 uint16_t AllocateSequenceNumber() override {
239 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
240 rtc::CritScope lock(&crit_);
241 if (!seq_num_allocator_)
242 return 0;
243 return seq_num_allocator_->AllocateSequenceNumber();
244 }
245
246 private:
247 rtc::CriticalSection crit_;
248 rtc::ThreadChecker thread_checker_;
249 rtc::ThreadChecker pacer_thread_;
250 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
251};
252
253class RtpPacketSenderProxy : public RtpPacketSender {
254 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800255 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100256
257 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
258 RTC_DCHECK(thread_checker_.CalledOnValidThread());
259 rtc::CritScope lock(&crit_);
260 rtp_packet_sender_ = rtp_packet_sender;
261 }
262
263 // Implements RtpPacketSender.
264 void InsertPacket(Priority priority,
265 uint32_t ssrc,
266 uint16_t sequence_number,
267 int64_t capture_time_ms,
268 size_t bytes,
269 bool retransmission) override {
270 rtc::CritScope lock(&crit_);
271 if (rtp_packet_sender_) {
272 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
273 capture_time_ms, bytes, retransmission);
274 }
275 }
276
277 private:
278 rtc::ThreadChecker thread_checker_;
279 rtc::CriticalSection crit_;
280 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
281};
282
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000283// Extend the default RTCP statistics struct with max_jitter, defined as the
284// maximum jitter value seen in an RTCP report block.
285struct ChannelStatistics : public RtcpStatistics {
286 ChannelStatistics() : rtcp(), max_jitter(0) {}
287
288 RtcpStatistics rtcp;
289 uint32_t max_jitter;
290};
291
292// Statistics callback, called at each generation of a new RTCP report block.
293class StatisticsProxy : public RtcpStatisticsCallback {
294 public:
tommi31fc21f2016-01-21 10:37:37 -0800295 StatisticsProxy(uint32_t ssrc) : ssrc_(ssrc) {}
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000296 virtual ~StatisticsProxy() {}
297
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000298 void StatisticsUpdated(const RtcpStatistics& statistics,
299 uint32_t ssrc) override {
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000300 if (ssrc != ssrc_)
301 return;
302
tommi31fc21f2016-01-21 10:37:37 -0800303 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000304 stats_.rtcp = statistics;
305 if (statistics.jitter > stats_.max_jitter) {
306 stats_.max_jitter = statistics.jitter;
307 }
308 }
309
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000310 void CNameChanged(const char* cname, uint32_t ssrc) override {}
pbos@webrtc.orgce4e9a32014-12-18 13:50:16 +0000311
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000312 ChannelStatistics GetStats() {
tommi31fc21f2016-01-21 10:37:37 -0800313 rtc::CritScope cs(&stats_lock_);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000314 return stats_;
315 }
316
317 private:
318 // StatisticsUpdated calls are triggered from threads in the RTP module,
319 // while GetStats calls can be triggered from the public voice engine API,
320 // hence synchronization is needed.
tommi31fc21f2016-01-21 10:37:37 -0800321 rtc::CriticalSection stats_lock_;
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000322 const uint32_t ssrc_;
323 ChannelStatistics stats_;
324};
325
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000326class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000327 public:
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000328 explicit VoERtcpObserver(Channel* owner) : owner_(owner) {}
329 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000330
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000331 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
332 // Not used for Voice Engine.
333 }
334
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000335 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
336 int64_t rtt,
337 int64_t now_ms) override {
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000338 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
339 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
340 // report for VoiceEngine?
341 if (report_blocks.empty())
342 return;
343
344 int fraction_lost_aggregate = 0;
345 int total_number_of_packets = 0;
346
347 // If receiving multiple report blocks, calculate the weighted average based
348 // on the number of packets a report refers to.
349 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
350 block_it != report_blocks.end(); ++block_it) {
351 // Find the previous extended high sequence number for this remote SSRC,
352 // to calculate the number of RTP packets this report refers to. Ignore if
353 // we haven't seen this SSRC before.
354 std::map<uint32_t, uint32_t>::iterator seq_num_it =
355 extended_max_sequence_number_.find(block_it->sourceSSRC);
356 int number_of_packets = 0;
357 if (seq_num_it != extended_max_sequence_number_.end()) {
358 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
359 }
360 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
361 total_number_of_packets += number_of_packets;
362
363 extended_max_sequence_number_[block_it->sourceSSRC] =
364 block_it->extendedHighSeqNum;
365 }
366 int weighted_fraction_lost = 0;
367 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800368 weighted_fraction_lost =
369 (fraction_lost_aggregate + total_number_of_packets / 2) /
370 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000371 }
372 owner_->OnIncomingFractionLoss(weighted_fraction_lost);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000373 }
374
375 private:
376 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000377 // Maps remote side ssrc to extended highest sequence number received.
378 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000379};
380
kwiberg55b97fe2016-01-28 05:22:45 -0800381int32_t Channel::SendData(FrameType frameType,
382 uint8_t payloadType,
383 uint32_t timeStamp,
384 const uint8_t* payloadData,
385 size_t payloadSize,
386 const RTPFragmentationHeader* fragmentation) {
387 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
388 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
389 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
390 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000391
kwiberg55b97fe2016-01-28 05:22:45 -0800392 if (_includeAudioLevelIndication) {
393 // Store current audio level in the RTP/RTCP module.
394 // The level will be used in combination with voice-activity state
395 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800396 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800397 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000398
kwiberg55b97fe2016-01-28 05:22:45 -0800399 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
400 // packetization.
401 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700402 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800403 (FrameType&)frameType, payloadType, timeStamp,
404 // Leaving the time when this frame was
405 // received from the capture device as
406 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700407 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800408 _engineStatisticsPtr->SetLastError(
409 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
410 "Channel::SendData() failed to send data to RTP/RTCP module");
411 return -1;
412 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000413
kwiberg55b97fe2016-01-28 05:22:45 -0800414 _lastLocalTimeStamp = timeStamp;
415 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000416
kwiberg55b97fe2016-01-28 05:22:45 -0800417 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000418}
419
kwiberg55b97fe2016-01-28 05:22:45 -0800420int32_t Channel::InFrameType(FrameType frame_type) {
421 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
422 "Channel::InFrameType(frame_type=%d)", frame_type);
niklase@google.com470e71d2011-07-07 08:21:25 +0000423
kwiberg55b97fe2016-01-28 05:22:45 -0800424 rtc::CritScope cs(&_callbackCritSect);
425 _sendFrameType = (frame_type == kAudioFrameSpeech);
426 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000427}
428
stefan1d8a5062015-10-02 03:39:33 -0700429bool Channel::SendRtp(const uint8_t* data,
430 size_t len,
431 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800432 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
433 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000434
kwiberg55b97fe2016-01-28 05:22:45 -0800435 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000436
kwiberg55b97fe2016-01-28 05:22:45 -0800437 if (_transportPtr == NULL) {
438 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
439 "Channel::SendPacket() failed to send RTP packet due to"
440 " invalid transport object");
441 return false;
442 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000443
kwiberg55b97fe2016-01-28 05:22:45 -0800444 uint8_t* bufferToSendPtr = (uint8_t*)data;
445 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000446
kwiberg55b97fe2016-01-28 05:22:45 -0800447 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
448 std::string transport_name =
449 _externalTransport ? "external transport" : "WebRtc sockets";
450 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
451 "Channel::SendPacket() RTP transmission using %s failed",
452 transport_name.c_str());
453 return false;
454 }
455 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000456}
457
kwiberg55b97fe2016-01-28 05:22:45 -0800458bool Channel::SendRtcp(const uint8_t* data, size_t len) {
459 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
460 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000461
kwiberg55b97fe2016-01-28 05:22:45 -0800462 rtc::CritScope cs(&_callbackCritSect);
463 if (_transportPtr == NULL) {
464 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
465 "Channel::SendRtcp() failed to send RTCP packet"
466 " due to 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 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
474 if (n < 0) {
475 std::string transport_name =
476 _externalTransport ? "external transport" : "WebRtc sockets";
477 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
478 "Channel::SendRtcp() transmission using %s failed",
479 transport_name.c_str());
480 return false;
481 }
482 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000483}
484
kwiberg55b97fe2016-01-28 05:22:45 -0800485void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
486 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
487 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000488
kwiberg55b97fe2016-01-28 05:22:45 -0800489 // Update ssrc so that NTP for AV sync can be updated.
490 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000491}
492
Peter Boströmac547a62015-09-17 23:03:57 +0200493void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
494 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
495 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
496 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000497}
498
Peter Boströmac547a62015-09-17 23:03:57 +0200499int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000500 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000501 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000502 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800503 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200504 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800505 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
506 "Channel::OnInitializeDecoder(payloadType=%d, "
507 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
508 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000509
kwiberg55b97fe2016-01-28 05:22:45 -0800510 CodecInst receiveCodec = {0};
511 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000512
kwiberg55b97fe2016-01-28 05:22:45 -0800513 receiveCodec.pltype = payloadType;
514 receiveCodec.plfreq = frequency;
515 receiveCodec.channels = channels;
516 receiveCodec.rate = rate;
517 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000518
kwiberg55b97fe2016-01-28 05:22:45 -0800519 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
520 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000521
kwiberg55b97fe2016-01-28 05:22:45 -0800522 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700523 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
524 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800525 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
526 "Channel::OnInitializeDecoder() invalid codec ("
527 "pt=%d, name=%s) received - 1",
528 payloadType, payloadName);
529 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
530 return -1;
531 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000532
kwiberg55b97fe2016-01-28 05:22:45 -0800533 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000534}
535
kwiberg55b97fe2016-01-28 05:22:45 -0800536int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
537 size_t payloadSize,
538 const WebRtcRTPHeader* rtpHeader) {
539 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
540 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
541 ","
542 " payloadType=%u, audioChannel=%" PRIuS ")",
543 payloadSize, rtpHeader->header.payloadType,
544 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000545
kwiberg55b97fe2016-01-28 05:22:45 -0800546 if (!channel_state_.Get().playing) {
547 // Avoid inserting into NetEQ when we are not playing. Count the
548 // packet as discarded.
549 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
550 "received packet is discarded since playing is not"
551 " activated");
552 _numberOfDiscardedPackets++;
niklase@google.com470e71d2011-07-07 08:21:25 +0000553 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800554 }
555
556 // Push the incoming payload (parsed and ready for decoding) into the ACM
557 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
558 0) {
559 _engineStatisticsPtr->SetLastError(
560 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
561 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
562 return -1;
563 }
564
kwiberg55b97fe2016-01-28 05:22:45 -0800565 int64_t round_trip_time = 0;
566 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
567 NULL);
568
569 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
570 if (!nack_list.empty()) {
571 // Can't use nack_list.data() since it's not supported by all
572 // compilers.
573 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
574 }
575 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000576}
577
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000578bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000579 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000580 RTPHeader header;
581 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
582 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
583 "IncomingPacket invalid RTP header");
584 return false;
585 }
586 header.payload_type_frequency =
587 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
588 if (header.payload_type_frequency < 0)
589 return false;
590 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
591}
592
henrik.lundin42dda502016-05-18 05:36:01 -0700593MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
594 int32_t id,
595 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700596 unsigned int ssrc;
597 RTC_CHECK_EQ(GetLocalSSRC(ssrc), 0);
598 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800599 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700600 bool muted;
601 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
602 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800603 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
604 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
605 // In all likelihood, the audio in this frame is garbage. We return an
606 // error so that the audio mixer module doesn't add it to the mix. As
607 // a result, it won't be played out and the actions skipped here are
608 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700609 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800610 }
henrik.lundina89ab962016-05-18 08:52:45 -0700611
612 if (muted) {
613 // TODO(henrik.lundin): We should be able to do better than this. But we
614 // will have to go through all the cases below where the audio samples may
615 // be used, and handle the muted case in some way.
616 audioFrame->Mute();
617 }
kwiberg55b97fe2016-01-28 05:22:45 -0800618
kwiberg55b97fe2016-01-28 05:22:45 -0800619 // Convert module ID to internal VoE channel ID
620 audioFrame->id_ = VoEChannelId(audioFrame->id_);
621 // Store speech type for dead-or-alive detection
622 _outputSpeechType = audioFrame->speech_type_;
623
624 ChannelState::State state = channel_state_.Get();
625
kwiberg55b97fe2016-01-28 05:22:45 -0800626 {
627 // Pass the audio buffers to an optional sink callback, before applying
628 // scaling/panning, as that applies to the mix operation.
629 // External recipients of the audio (e.g. via AudioTrack), will do their
630 // own mixing/dynamic processing.
631 rtc::CritScope cs(&_callbackCritSect);
632 if (audio_sink_) {
633 AudioSinkInterface::Data data(
634 &audioFrame->data_[0], audioFrame->samples_per_channel_,
635 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
636 audioFrame->timestamp_);
637 audio_sink_->OnData(data);
638 }
639 }
640
641 float output_gain = 1.0f;
642 float left_pan = 1.0f;
643 float right_pan = 1.0f;
644 {
645 rtc::CritScope cs(&volume_settings_critsect_);
646 output_gain = _outputGain;
647 left_pan = _panLeft;
648 right_pan = _panRight;
649 }
650
651 // Output volume scaling
652 if (output_gain < 0.99f || output_gain > 1.01f) {
653 AudioFrameOperations::ScaleWithSat(output_gain, *audioFrame);
654 }
655
656 // Scale left and/or right channel(s) if stereo and master balance is
657 // active
658
659 if (left_pan != 1.0f || right_pan != 1.0f) {
660 if (audioFrame->num_channels_ == 1) {
661 // Emulate stereo mode since panning is active.
662 // The mono signal is copied to both left and right channels here.
663 AudioFrameOperations::MonoToStereo(audioFrame);
664 }
665 // For true stereo mode (when we are receiving a stereo signal), no
666 // action is needed.
667
668 // Do the panning operation (the audio frame contains stereo at this
669 // stage)
670 AudioFrameOperations::Scale(left_pan, right_pan, *audioFrame);
671 }
672
673 // Mix decoded PCM output with file if file mixing is enabled
674 if (state.output_file_playing) {
675 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700676 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800677 }
678
679 // External media
680 if (_outputExternalMedia) {
681 rtc::CritScope cs(&_callbackCritSect);
682 const bool isStereo = (audioFrame->num_channels_ == 2);
683 if (_outputExternalMediaCallbackPtr) {
684 _outputExternalMediaCallbackPtr->Process(
685 _channelId, kPlaybackPerChannel, (int16_t*)audioFrame->data_,
686 audioFrame->samples_per_channel_, audioFrame->sample_rate_hz_,
687 isStereo);
688 }
689 }
690
691 // Record playout if enabled
692 {
693 rtc::CritScope cs(&_fileCritSect);
694
kwiberg5a25d952016-08-17 07:31:12 -0700695 if (_outputFileRecording && output_file_recorder_) {
696 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800697 }
698 }
699
700 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700701 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800702 _outputAudioLevel.ComputeLevel(*audioFrame);
703
704 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
705 // The first frame with a valid rtp timestamp.
706 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
707 }
708
709 if (capture_start_rtp_time_stamp_ >= 0) {
710 // audioFrame.timestamp_ should be valid from now on.
711
712 // Compute elapsed time.
713 int64_t unwrap_timestamp =
714 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
715 audioFrame->elapsed_time_ms_ =
716 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700717 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800718
niklase@google.com470e71d2011-07-07 08:21:25 +0000719 {
kwiberg55b97fe2016-01-28 05:22:45 -0800720 rtc::CritScope lock(&ts_stats_lock_);
721 // Compute ntp time.
722 audioFrame->ntp_time_ms_ =
723 ntp_estimator_.Estimate(audioFrame->timestamp_);
724 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
725 if (audioFrame->ntp_time_ms_ > 0) {
726 // Compute |capture_start_ntp_time_ms_| so that
727 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
728 capture_start_ntp_time_ms_ =
729 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000730 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000731 }
kwiberg55b97fe2016-01-28 05:22:45 -0800732 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000733
henrik.lundin42dda502016-05-18 05:36:01 -0700734 return muted ? MixerParticipant::AudioFrameInfo::kMuted
735 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000736}
737
aleloi6c278492016-10-20 14:24:39 -0700738AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
739 int sample_rate_hz,
740 AudioFrame* audio_frame) {
741 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700742
aleloi6c278492016-10-20 14:24:39 -0700743 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700744
745 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
746 FrameInfo new_audio_frame_info = FrameInfo::kError;
747 switch (frame_info) {
748 case MixerParticipant::AudioFrameInfo::kNormal:
749 new_audio_frame_info = FrameInfo::kNormal;
750 break;
751 case MixerParticipant::AudioFrameInfo::kMuted:
752 new_audio_frame_info = FrameInfo::kMuted;
753 break;
754 case MixerParticipant::AudioFrameInfo::kError:
755 new_audio_frame_info = FrameInfo::kError;
756 break;
757 }
aleloi6c278492016-10-20 14:24:39 -0700758 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700759}
760
kwiberg55b97fe2016-01-28 05:22:45 -0800761int32_t Channel::NeededFrequency(int32_t id) const {
762 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
763 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000764
kwiberg55b97fe2016-01-28 05:22:45 -0800765 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000766
kwiberg55b97fe2016-01-28 05:22:45 -0800767 // Determine highest needed receive frequency
768 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000769
kwiberg55b97fe2016-01-28 05:22:45 -0800770 // Return the bigger of playout and receive frequency in the ACM.
771 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
772 highestNeeded = audio_coding_->PlayoutFrequency();
773 } else {
774 highestNeeded = receiveFrequency;
775 }
776
777 // Special case, if we're playing a file on the playout side
778 // we take that frequency into consideration as well
779 // This is not needed on sending side, since the codec will
780 // limit the spectrum anyway.
781 if (channel_state_.Get().output_file_playing) {
782 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700783 if (output_file_player_) {
784 if (output_file_player_->Frequency() > highestNeeded) {
785 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800786 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000787 }
kwiberg55b97fe2016-01-28 05:22:45 -0800788 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000789
kwiberg55b97fe2016-01-28 05:22:45 -0800790 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000791}
792
ossu5f7cfa52016-05-30 08:11:28 -0700793int32_t Channel::CreateChannel(
794 Channel*& channel,
795 int32_t channelId,
796 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700797 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800798 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
799 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
800 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000801
solenberg88499ec2016-09-07 07:34:41 -0700802 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800803 if (channel == NULL) {
804 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
805 "Channel::CreateChannel() unable to allocate memory for"
806 " channel");
807 return -1;
808 }
809 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000810}
811
kwiberg55b97fe2016-01-28 05:22:45 -0800812void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
813 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
814 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
815 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000816
kwiberg55b97fe2016-01-28 05:22:45 -0800817 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000818}
819
kwiberg55b97fe2016-01-28 05:22:45 -0800820void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
821 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
822 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
823 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000824
kwiberg55b97fe2016-01-28 05:22:45 -0800825 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000826}
827
kwiberg55b97fe2016-01-28 05:22:45 -0800828void Channel::PlayFileEnded(int32_t id) {
829 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
830 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000831
kwiberg55b97fe2016-01-28 05:22:45 -0800832 if (id == _inputFilePlayerId) {
833 channel_state_.SetInputFilePlaying(false);
834 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
835 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000836 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800837 } else if (id == _outputFilePlayerId) {
838 channel_state_.SetOutputFilePlaying(false);
839 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
840 "Channel::PlayFileEnded() => output file player module is"
841 " shutdown");
842 }
843}
844
845void Channel::RecordFileEnded(int32_t id) {
846 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
847 "Channel::RecordFileEnded(id=%d)", id);
848
849 assert(id == _outputFileRecorderId);
850
851 rtc::CritScope cs(&_fileCritSect);
852
853 _outputFileRecording = false;
854 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
855 "Channel::RecordFileEnded() => output file recorder module is"
856 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000857}
858
pbos@webrtc.org92135212013-05-14 08:31:39 +0000859Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000860 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700861 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800862 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100863 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700864 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800865 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100866 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800867 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100868 rtp_receive_statistics_(
869 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
870 rtp_receiver_(
871 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100872 this,
873 this,
874 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700875 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100876 _outputAudioLevel(),
877 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100878 // Avoid conflict with other channels by adding 1024 - 1026,
879 // won't use as much as 1024 channels.
880 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
881 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
882 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
883 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100884 _outputExternalMedia(false),
885 _inputExternalMediaCallbackPtr(NULL),
886 _outputExternalMediaCallbackPtr(NULL),
887 _timeStamp(0), // This is just an offset, RTP module will add it's own
888 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100889 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100890 playout_timestamp_rtp_(0),
891 playout_timestamp_rtcp_(0),
892 playout_delay_ms_(0),
893 _numberOfDiscardedPackets(0),
894 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100895 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
896 capture_start_rtp_time_stamp_(-1),
897 capture_start_ntp_time_ms_(-1),
898 _engineStatisticsPtr(NULL),
899 _outputMixerPtr(NULL),
900 _transmitMixerPtr(NULL),
901 _moduleProcessThreadPtr(NULL),
902 _audioDeviceModulePtr(NULL),
903 _voiceEngineObserverPtr(NULL),
904 _callbackCritSectPtr(NULL),
905 _transportPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100906 _sendFrameType(0),
907 _externalMixing(false),
908 _mixFileWithMicrophone(false),
solenberg1c2af8e2016-03-24 10:36:00 -0700909 input_mute_(false),
910 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100911 _panLeft(1.0f),
912 _panRight(1.0f),
913 _outputGain(1.0f),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100914 _lastLocalTimeStamp(0),
915 _lastPayloadType(0),
916 _includeAudioLevelIndication(false),
917 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100918 restored_packet_in_use_(false),
919 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100920 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700921 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800922 feedback_observer_proxy_(new TransportFeedbackProxy()),
923 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700924 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200925 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
926 kMaxRetransmissionWindowMs)),
michaelt2fedf9c2016-11-28 02:34:18 -0800927 decoder_factory_(config.acm_config.decoder_factory),
928 // Bitrate smoother can be initialized with arbitrary time constant
929 // (0 used here). The actual time constant will be set in SetBitRate.
930 bitrate_smoother_(0, Clock::GetRealTimeClock()) {
kwiberg55b97fe2016-01-28 05:22:45 -0800931 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
932 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700933 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800934 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700935 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800936 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200937
kwiberg55b97fe2016-01-28 05:22:45 -0800938 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000939
kwiberg55b97fe2016-01-28 05:22:45 -0800940 RtpRtcp::Configuration configuration;
941 configuration.audio = true;
942 configuration.outgoing_transport = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800943 configuration.receive_statistics = rtp_receive_statistics_.get();
944 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800945 if (pacing_enabled_) {
946 configuration.paced_sender = rtp_packet_sender_proxy_.get();
947 configuration.transport_sequence_number_allocator =
948 seq_num_allocator_proxy_.get();
949 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
950 }
ivoc14d5dbe2016-07-04 07:06:55 -0700951 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800952 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200953 configuration.retransmission_rate_limiter =
954 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000955
kwiberg55b97fe2016-01-28 05:22:45 -0800956 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100957 _rtpRtcpModule->SetSendingMediaStatus(false);
sprang@webrtc.org54ae4ff2013-12-19 13:26:02 +0000958
kwiberg55b97fe2016-01-28 05:22:45 -0800959 statistics_proxy_.reset(new StatisticsProxy(_rtpRtcpModule->SSRC()));
960 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(
961 statistics_proxy_.get());
niklase@google.com470e71d2011-07-07 08:21:25 +0000962}
963
kwiberg55b97fe2016-01-28 05:22:45 -0800964Channel::~Channel() {
965 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
966 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
967 "Channel::~Channel() - dtor");
niklase@google.com470e71d2011-07-07 08:21:25 +0000968
kwiberg55b97fe2016-01-28 05:22:45 -0800969 if (_outputExternalMedia) {
970 DeRegisterExternalMediaProcessing(kPlaybackPerChannel);
971 }
972 if (channel_state_.Get().input_external_media) {
973 DeRegisterExternalMediaProcessing(kRecordingPerChannel);
974 }
975 StopSend();
976 StopPlayout();
niklase@google.com470e71d2011-07-07 08:21:25 +0000977
kwiberg55b97fe2016-01-28 05:22:45 -0800978 {
979 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700980 if (input_file_player_) {
981 input_file_player_->RegisterModuleFileCallback(NULL);
982 input_file_player_->StopPlayingFile();
niklase@google.com470e71d2011-07-07 08:21:25 +0000983 }
kwiberg5a25d952016-08-17 07:31:12 -0700984 if (output_file_player_) {
985 output_file_player_->RegisterModuleFileCallback(NULL);
986 output_file_player_->StopPlayingFile();
kwiberg55b97fe2016-01-28 05:22:45 -0800987 }
kwiberg5a25d952016-08-17 07:31:12 -0700988 if (output_file_recorder_) {
989 output_file_recorder_->RegisterModuleFileCallback(NULL);
990 output_file_recorder_->StopRecording();
kwiberg55b97fe2016-01-28 05:22:45 -0800991 }
992 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000993
kwiberg55b97fe2016-01-28 05:22:45 -0800994 // The order to safely shutdown modules in a channel is:
995 // 1. De-register callbacks in modules
996 // 2. De-register modules in process thread
997 // 3. Destroy modules
998 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
999 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1000 "~Channel() failed to de-register transport callback"
1001 " (Audio coding module)");
1002 }
1003 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1004 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1005 "~Channel() failed to de-register VAD callback"
1006 " (Audio coding module)");
1007 }
1008 // De-register modules in process thread
1009 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
tommi@webrtc.org3985f012015-02-27 13:36:34 +00001010
kwiberg55b97fe2016-01-28 05:22:45 -08001011 // End of modules shutdown
niklase@google.com470e71d2011-07-07 08:21:25 +00001012}
1013
kwiberg55b97fe2016-01-28 05:22:45 -08001014int32_t Channel::Init() {
1015 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1016 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001017
kwiberg55b97fe2016-01-28 05:22:45 -08001018 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001019
kwiberg55b97fe2016-01-28 05:22:45 -08001020 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +00001021
kwiberg55b97fe2016-01-28 05:22:45 -08001022 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
1023 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1024 "Channel::Init() must call SetEngineInformation() first");
1025 return -1;
1026 }
1027
1028 // --- Add modules to process thread (for periodic schedulation)
1029
1030 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get());
1031
1032 // --- ACM initialization
1033
1034 if (audio_coding_->InitializeReceiver() == -1) {
1035 _engineStatisticsPtr->SetLastError(
1036 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1037 "Channel::Init() unable to initialize the ACM - 1");
1038 return -1;
1039 }
1040
1041 // --- RTP/RTCP module initialization
1042
1043 // Ensure that RTCP is enabled by default for the created channel.
1044 // Note that, the module will keep generating RTCP until it is explicitly
1045 // disabled by the user.
1046 // After StopListen (when no sockets exists), RTCP packets will no longer
1047 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -07001048 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001049 // RTCP is enabled by default.
1050 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
1051 // --- Register all permanent callbacks
1052 const bool fail = (audio_coding_->RegisterTransportCallback(this) == -1) ||
1053 (audio_coding_->RegisterVADCallback(this) == -1);
1054
1055 if (fail) {
1056 _engineStatisticsPtr->SetLastError(
1057 VE_CANNOT_INIT_CHANNEL, kTraceError,
1058 "Channel::Init() callbacks not registered");
1059 return -1;
1060 }
1061
1062 // --- Register all supported codecs to the receiving side of the
1063 // RTP/RTCP module
1064
1065 CodecInst codec;
1066 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1067
1068 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1069 // Open up the RTP/RTCP receiver for all supported codecs
1070 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001071 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001072 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1073 "Channel::Init() unable to register %s "
1074 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1075 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1076 codec.rate);
1077 } else {
1078 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1079 "Channel::Init() %s (%d/%d/%" PRIuS
1080 "/%d) has been "
1081 "added to the RTP/RTCP receiver",
1082 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1083 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001084 }
1085
kwiberg55b97fe2016-01-28 05:22:45 -08001086 // Ensure that PCMU is used as default codec on the sending side
1087 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
1088 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +00001089 }
1090
kwiberg55b97fe2016-01-28 05:22:45 -08001091 // Register default PT for outband 'telephone-event'
1092 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -07001093 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
kwibergda2bf4e2016-10-24 13:47:09 -07001094 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1095 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001096 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1097 "Channel::Init() failed to register outband "
1098 "'telephone-event' (%d/%d) correctly",
1099 codec.pltype, codec.plfreq);
1100 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001101 }
1102
kwiberg55b97fe2016-01-28 05:22:45 -08001103 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -07001104 if (!codec_manager_.RegisterEncoder(codec) ||
1105 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
kwibergda2bf4e2016-10-24 13:47:09 -07001106 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1107 CodecInstToSdp(codec)) ||
kwibergc8d071e2016-04-06 12:22:38 -07001108 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001109 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1110 "Channel::Init() failed to register CN (%d/%d) "
1111 "correctly - 1",
1112 codec.pltype, codec.plfreq);
1113 }
1114 }
kwiberg55b97fe2016-01-28 05:22:45 -08001115 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001116
kwiberg55b97fe2016-01-28 05:22:45 -08001117 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001118}
1119
kwiberg55b97fe2016-01-28 05:22:45 -08001120int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1121 OutputMixer& outputMixer,
1122 voe::TransmitMixer& transmitMixer,
1123 ProcessThread& moduleProcessThread,
1124 AudioDeviceModule& audioDeviceModule,
1125 VoiceEngineObserver* voiceEngineObserver,
1126 rtc::CriticalSection* callbackCritSect) {
1127 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1128 "Channel::SetEngineInformation()");
1129 _engineStatisticsPtr = &engineStatistics;
1130 _outputMixerPtr = &outputMixer;
1131 _transmitMixerPtr = &transmitMixer,
1132 _moduleProcessThreadPtr = &moduleProcessThread;
1133 _audioDeviceModulePtr = &audioDeviceModule;
1134 _voiceEngineObserverPtr = voiceEngineObserver;
1135 _callbackCritSectPtr = callbackCritSect;
1136 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001137}
1138
kwiberg55b97fe2016-01-28 05:22:45 -08001139int32_t Channel::UpdateLocalTimeStamp() {
1140 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1141 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001142}
1143
kwibergb7f89d62016-02-17 10:04:18 -08001144void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001145 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001146 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001147}
1148
ossu29b1a8d2016-06-13 07:34:51 -07001149const rtc::scoped_refptr<AudioDecoderFactory>&
1150Channel::GetAudioDecoderFactory() const {
1151 return decoder_factory_;
1152}
1153
kwiberg55b97fe2016-01-28 05:22:45 -08001154int32_t Channel::StartPlayout() {
1155 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1156 "Channel::StartPlayout()");
1157 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001158 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001159 }
1160
1161 if (!_externalMixing) {
1162 // Add participant as candidates for mixing.
1163 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1164 _engineStatisticsPtr->SetLastError(
1165 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1166 "StartPlayout() failed to add participant to mixer");
1167 return -1;
1168 }
1169 }
1170
1171 channel_state_.SetPlaying(true);
1172 if (RegisterFilePlayingToMixer() != 0)
1173 return -1;
1174
1175 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001176}
1177
kwiberg55b97fe2016-01-28 05:22:45 -08001178int32_t Channel::StopPlayout() {
1179 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1180 "Channel::StopPlayout()");
1181 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001182 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001183 }
1184
1185 if (!_externalMixing) {
1186 // Remove participant as candidates for mixing
1187 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1188 _engineStatisticsPtr->SetLastError(
1189 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1190 "StopPlayout() failed to remove participant from mixer");
1191 return -1;
1192 }
1193 }
1194
1195 channel_state_.SetPlaying(false);
1196 _outputAudioLevel.Clear();
1197
1198 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001199}
1200
kwiberg55b97fe2016-01-28 05:22:45 -08001201int32_t Channel::StartSend() {
1202 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1203 "Channel::StartSend()");
1204 // Resume the previous sequence number which was reset by StopSend().
1205 // This needs to be done before |sending| is set to true.
1206 if (send_sequence_number_)
1207 SetInitSequenceNumber(send_sequence_number_);
xians@webrtc.org09e8c472013-07-31 16:30:19 +00001208
kwiberg55b97fe2016-01-28 05:22:45 -08001209 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001210 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001211 }
1212 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001213
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001214 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001215 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1216 _engineStatisticsPtr->SetLastError(
1217 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1218 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001219 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001220 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001221 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001222 return -1;
1223 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001224
kwiberg55b97fe2016-01-28 05:22:45 -08001225 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001226}
1227
kwiberg55b97fe2016-01-28 05:22:45 -08001228int32_t Channel::StopSend() {
1229 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1230 "Channel::StopSend()");
1231 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001232 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001233 }
1234 channel_state_.SetSending(false);
1235
1236 // Store the sequence number to be able to pick up the same sequence for
1237 // the next StartSend(). This is needed for restarting device, otherwise
1238 // it might cause libSRTP to complain about packets being replayed.
1239 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1240 // CL is landed. See issue
1241 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1242 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1243
1244 // Reset sending SSRC and sequence number and triggers direct transmission
1245 // of RTCP BYE
1246 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1247 _engineStatisticsPtr->SetLastError(
1248 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1249 "StartSend() RTP/RTCP failed to stop sending");
1250 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001251 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001252
1253 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001254}
1255
solenberge566ac72016-10-31 12:52:33 -07001256void Channel::ResetDiscardedPacketCount() {
kwiberg55b97fe2016-01-28 05:22:45 -08001257 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberge566ac72016-10-31 12:52:33 -07001258 "Channel::ResetDiscardedPacketCount()");
kwiberg55b97fe2016-01-28 05:22:45 -08001259 _numberOfDiscardedPackets = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001260}
1261
kwiberg55b97fe2016-01-28 05:22:45 -08001262int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1263 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1264 "Channel::RegisterVoiceEngineObserver()");
1265 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001266
kwiberg55b97fe2016-01-28 05:22:45 -08001267 if (_voiceEngineObserverPtr) {
1268 _engineStatisticsPtr->SetLastError(
1269 VE_INVALID_OPERATION, kTraceError,
1270 "RegisterVoiceEngineObserver() observer already enabled");
1271 return -1;
1272 }
1273 _voiceEngineObserverPtr = &observer;
1274 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001275}
1276
kwiberg55b97fe2016-01-28 05:22:45 -08001277int32_t Channel::DeRegisterVoiceEngineObserver() {
1278 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1279 "Channel::DeRegisterVoiceEngineObserver()");
1280 rtc::CritScope cs(&_callbackCritSect);
1281
1282 if (!_voiceEngineObserverPtr) {
1283 _engineStatisticsPtr->SetLastError(
1284 VE_INVALID_OPERATION, kTraceWarning,
1285 "DeRegisterVoiceEngineObserver() observer already disabled");
1286 return 0;
1287 }
1288 _voiceEngineObserverPtr = NULL;
1289 return 0;
1290}
1291
1292int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001293 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001294 if (send_codec) {
1295 codec = *send_codec;
1296 return 0;
1297 }
1298 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001299}
1300
kwiberg55b97fe2016-01-28 05:22:45 -08001301int32_t Channel::GetRecCodec(CodecInst& codec) {
1302 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001303}
1304
kwiberg55b97fe2016-01-28 05:22:45 -08001305int32_t Channel::SetSendCodec(const CodecInst& codec) {
1306 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1307 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001308
kwibergc8d071e2016-04-06 12:22:38 -07001309 if (!codec_manager_.RegisterEncoder(codec) ||
1310 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001311 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1312 "SetSendCodec() failed to register codec to ACM");
1313 return -1;
1314 }
1315
1316 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1317 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1318 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1319 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1320 "SetSendCodec() failed to register codec to"
1321 " RTP/RTCP module");
1322 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001323 }
kwiberg55b97fe2016-01-28 05:22:45 -08001324 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001325
kwiberg55b97fe2016-01-28 05:22:45 -08001326 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001327}
1328
minyue78b4d562016-11-30 04:47:39 -08001329void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001330 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1331 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001332 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1333 if (*encoder)
1334 (*encoder)->OnReceivedTargetAudioBitrate(bitrate_bps);
1335 });
Erik Språng737336d2016-07-29 12:59:36 +02001336 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
michaelt2fedf9c2016-11-28 02:34:18 -08001337
1338 // We give smoothed bitrate allocation to audio network adaptor as
1339 // the uplink bandwidth.
minyue78b4d562016-11-30 04:47:39 -08001340 // The probing spikes should not affect the bitrate smoother more than 25%.
1341 // To simplify the calculations we use a step response as input signal.
1342 // The step response of an exponential filter is
1343 // u(t) = 1 - e^(-t / time_constant).
1344 // In order to limit the affect of a BWE spike within 25% of its value before
1345 // the next probing, we would choose a time constant that fulfills
1346 // 1 - e^(-probing_interval_ms / time_constant) < 0.25
1347 // Then 4 * probing_interval_ms is a good choice.
1348 bitrate_smoother_.SetTimeConstantMs(probing_interval_ms * 4);
michaelt2fedf9c2016-11-28 02:34:18 -08001349 bitrate_smoother_.AddSample(bitrate_bps);
1350 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1351 if (*encoder) {
1352 (*encoder)->OnReceivedUplinkBandwidth(
1353 static_cast<int>(*bitrate_smoother_.GetAverage()));
1354 }
1355 });
Ivo Creusenadf89b72015-04-29 16:03:33 +02001356}
1357
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +00001358void Channel::OnIncomingFractionLoss(int fraction_lost) {
minyue7e304322016-10-12 05:00:55 -07001359 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1360 if (*encoder)
1361 (*encoder)->OnReceivedUplinkPacketLossFraction(fraction_lost / 255.0f);
1362 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001363}
1364
kwiberg55b97fe2016-01-28 05:22:45 -08001365int32_t Channel::SetVADStatus(bool enableVAD,
1366 ACMVADMode mode,
1367 bool disableDTX) {
1368 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1369 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001370 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1371 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1372 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001373 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1374 kTraceError,
1375 "SetVADStatus() failed to set VAD");
1376 return -1;
1377 }
1378 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001379}
1380
kwiberg55b97fe2016-01-28 05:22:45 -08001381int32_t Channel::GetVADStatus(bool& enabledVAD,
1382 ACMVADMode& mode,
1383 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001384 const auto* params = codec_manager_.GetStackParams();
1385 enabledVAD = params->use_cng;
1386 mode = params->vad_mode;
1387 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001388 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001389}
1390
kwiberg55b97fe2016-01-28 05:22:45 -08001391int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
1392 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1393 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001394
kwiberg55b97fe2016-01-28 05:22:45 -08001395 if (channel_state_.Get().playing) {
1396 _engineStatisticsPtr->SetLastError(
1397 VE_ALREADY_PLAYING, kTraceError,
1398 "SetRecPayloadType() unable to set PT while playing");
1399 return -1;
1400 }
kwiberg55b97fe2016-01-28 05:22:45 -08001401
1402 if (codec.pltype == -1) {
1403 // De-register the selected codec (RTP/RTCP module and ACM)
1404
1405 int8_t pltype(-1);
1406 CodecInst rxCodec = codec;
1407
1408 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001409 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001410 rxCodec.pltype = pltype;
1411
1412 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1413 _engineStatisticsPtr->SetLastError(
1414 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1415 "SetRecPayloadType() RTP/RTCP-module deregistration "
1416 "failed");
1417 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001418 }
kwiberg55b97fe2016-01-28 05:22:45 -08001419 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1420 _engineStatisticsPtr->SetLastError(
1421 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1422 "SetRecPayloadType() ACM deregistration failed - 1");
1423 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001424 }
kwiberg55b97fe2016-01-28 05:22:45 -08001425 return 0;
1426 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001427
magjed56124bd2016-11-24 09:34:46 -08001428 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001429 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001430 // TODO(kwiberg): Retrying is probably not necessary, since
1431 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001432 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001433 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001434 _engineStatisticsPtr->SetLastError(
1435 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1436 "SetRecPayloadType() RTP/RTCP-module registration failed");
1437 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001438 }
kwiberg55b97fe2016-01-28 05:22:45 -08001439 }
kwibergda2bf4e2016-10-24 13:47:09 -07001440 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1441 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001442 audio_coding_->UnregisterReceiveCodec(codec.pltype);
kwibergda2bf4e2016-10-24 13:47:09 -07001443 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1444 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001445 _engineStatisticsPtr->SetLastError(
1446 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1447 "SetRecPayloadType() ACM registration failed - 1");
1448 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001449 }
kwiberg55b97fe2016-01-28 05:22:45 -08001450 }
1451 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001452}
1453
kwiberg55b97fe2016-01-28 05:22:45 -08001454int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1455 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001456 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001457 _engineStatisticsPtr->SetLastError(
1458 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1459 "GetRecPayloadType() failed to retrieve RX payload type");
1460 return -1;
1461 }
1462 codec.pltype = payloadType;
1463 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001464}
1465
kwiberg55b97fe2016-01-28 05:22:45 -08001466int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1467 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1468 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001469
kwiberg55b97fe2016-01-28 05:22:45 -08001470 CodecInst codec;
1471 int32_t samplingFreqHz(-1);
1472 const size_t kMono = 1;
1473 if (frequency == kFreq32000Hz)
1474 samplingFreqHz = 32000;
1475 else if (frequency == kFreq16000Hz)
1476 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001477
kwiberg55b97fe2016-01-28 05:22:45 -08001478 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1479 _engineStatisticsPtr->SetLastError(
1480 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1481 "SetSendCNPayloadType() failed to retrieve default CN codec "
1482 "settings");
1483 return -1;
1484 }
1485
1486 // Modify the payload type (must be set to dynamic range)
1487 codec.pltype = type;
1488
kwibergc8d071e2016-04-06 12:22:38 -07001489 if (!codec_manager_.RegisterEncoder(codec) ||
1490 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001491 _engineStatisticsPtr->SetLastError(
1492 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1493 "SetSendCNPayloadType() failed to register CN to ACM");
1494 return -1;
1495 }
1496
1497 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1498 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1499 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1500 _engineStatisticsPtr->SetLastError(
1501 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1502 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1503 "module");
1504 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001505 }
kwiberg55b97fe2016-01-28 05:22:45 -08001506 }
1507 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001508}
1509
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001510int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001511 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001512 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001513
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001514 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001515 _engineStatisticsPtr->SetLastError(
1516 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001517 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001518 return -1;
1519 }
1520 return 0;
1521}
1522
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001523int Channel::SetOpusDtx(bool enable_dtx) {
1524 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1525 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001526 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001527 : audio_coding_->DisableOpusDtx();
1528 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001529 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1530 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001531 return -1;
1532 }
1533 return 0;
1534}
1535
ivoc85228d62016-07-27 04:53:47 -07001536int Channel::GetOpusDtx(bool* enabled) {
1537 int success = -1;
1538 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1539 if (encoder) {
1540 *enabled = encoder->GetDtx();
1541 success = 0;
1542 }
1543 });
1544 return success;
1545}
1546
minyue7e304322016-10-12 05:00:55 -07001547bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1548 bool success = false;
1549 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1550 if (*encoder) {
1551 success = (*encoder)->EnableAudioNetworkAdaptor(
1552 config_string, Clock::GetRealTimeClock());
1553 }
1554 });
1555 return success;
1556}
1557
1558void Channel::DisableAudioNetworkAdaptor() {
1559 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1560 if (*encoder)
1561 (*encoder)->DisableAudioNetworkAdaptor();
1562 });
1563}
1564
1565void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1566 int max_frame_length_ms) {
1567 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1568 if (*encoder) {
1569 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1570 max_frame_length_ms);
1571 }
1572 });
1573}
1574
mflodman3d7db262016-04-29 00:57:13 -07001575int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001576 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001577 "Channel::RegisterExternalTransport()");
1578
kwiberg55b97fe2016-01-28 05:22:45 -08001579 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001580 if (_externalTransport) {
1581 _engineStatisticsPtr->SetLastError(
1582 VE_INVALID_OPERATION, kTraceError,
1583 "RegisterExternalTransport() external transport already enabled");
1584 return -1;
1585 }
1586 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001587 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001588 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001589}
1590
kwiberg55b97fe2016-01-28 05:22:45 -08001591int32_t Channel::DeRegisterExternalTransport() {
1592 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1593 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001594
kwiberg55b97fe2016-01-28 05:22:45 -08001595 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001596 if (_transportPtr) {
1597 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1598 "DeRegisterExternalTransport() all transport is disabled");
1599 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001600 _engineStatisticsPtr->SetLastError(
1601 VE_INVALID_OPERATION, kTraceWarning,
1602 "DeRegisterExternalTransport() external transport already "
1603 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001604 }
1605 _externalTransport = false;
1606 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001607 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001608}
1609
mflodman3d7db262016-04-29 00:57:13 -07001610int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001611 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001612 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001613 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001614 "Channel::ReceivedRTPPacket()");
1615
1616 // Store playout timestamp for the received RTP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001617 UpdatePlayoutTimestamp(false);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001618
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001619 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001620 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1621 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1622 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001623 return -1;
1624 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001625 header.payload_type_frequency =
1626 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001627 if (header.payload_type_frequency < 0)
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001628 return -1;
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001629 bool in_order = IsPacketInOrder(header);
kwiberg55b97fe2016-01-28 05:22:45 -08001630 rtp_receive_statistics_->IncomingPacket(
1631 header, length, IsPacketRetransmitted(header, in_order));
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001632 rtp_payload_registry_->SetIncomingPayloadType(header);
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001633
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001634 return ReceivePacket(received_packet, length, header, in_order) ? 0 : -1;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001635}
1636
1637bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001638 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001639 const RTPHeader& header,
1640 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001641 if (rtp_payload_registry_->IsRtx(header)) {
1642 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001643 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001644 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001645 assert(packet_length >= header.headerLength);
1646 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001647 PayloadUnion payload_specific;
1648 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001649 &payload_specific)) {
1650 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001651 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001652 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1653 payload_specific, in_order);
1654}
1655
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001656bool Channel::HandleRtxPacket(const uint8_t* packet,
1657 size_t packet_length,
1658 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001659 if (!rtp_payload_registry_->IsRtx(header))
1660 return false;
1661
1662 // Remove the RTX header and parse the original RTP header.
1663 if (packet_length < header.headerLength)
1664 return false;
1665 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1666 return false;
1667 if (restored_packet_in_use_) {
1668 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1669 "Multiple RTX headers detected, dropping packet");
1670 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001671 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001672 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001673 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1674 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001675 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1676 "Incoming RTX packet: invalid RTP header");
1677 return false;
1678 }
1679 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001680 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001681 restored_packet_in_use_ = false;
1682 return ret;
1683}
1684
1685bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1686 StreamStatistician* statistician =
1687 rtp_receive_statistics_->GetStatistician(header.ssrc);
1688 if (!statistician)
1689 return false;
1690 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001691}
1692
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001693bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1694 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001695 // Retransmissions are handled separately if RTX is enabled.
1696 if (rtp_payload_registry_->RtxEnabled())
1697 return false;
1698 StreamStatistician* statistician =
1699 rtp_receive_statistics_->GetStatistician(header.ssrc);
1700 if (!statistician)
1701 return false;
1702 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001703 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001704 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001705 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001706}
1707
mflodman3d7db262016-04-29 00:57:13 -07001708int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001709 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001710 "Channel::ReceivedRTCPPacket()");
1711 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001712 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001713
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001714 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001715 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001716 _engineStatisticsPtr->SetLastError(
1717 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1718 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1719 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001720
Minyue2013aec2015-05-13 14:14:42 +02001721 int64_t rtt = GetRTT(true);
1722 if (rtt == 0) {
1723 // Waiting for valid RTT.
1724 return 0;
1725 }
Erik Språng737336d2016-07-29 12:59:36 +02001726
1727 int64_t nack_window_ms = rtt;
1728 if (nack_window_ms < kMinRetransmissionWindowMs) {
1729 nack_window_ms = kMinRetransmissionWindowMs;
1730 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1731 nack_window_ms = kMaxRetransmissionWindowMs;
1732 }
1733 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1734
minyue7e304322016-10-12 05:00:55 -07001735 // Invoke audio encoders OnReceivedRtt().
1736 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1737 if (*encoder)
1738 (*encoder)->OnReceivedRtt(rtt);
1739 });
1740
Minyue2013aec2015-05-13 14:14:42 +02001741 uint32_t ntp_secs = 0;
1742 uint32_t ntp_frac = 0;
1743 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001744 if (0 !=
1745 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1746 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001747 // Waiting for RTCP.
1748 return 0;
1749 }
1750
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001751 {
tommi31fc21f2016-01-21 10:37:37 -08001752 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001753 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001754 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001755 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001756}
1757
niklase@google.com470e71d2011-07-07 08:21:25 +00001758int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001759 bool loop,
1760 FileFormats format,
1761 int startPosition,
1762 float volumeScaling,
1763 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001764 const CodecInst* codecInst) {
1765 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1766 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1767 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1768 "stopPosition=%d)",
1769 fileName, loop, format, volumeScaling, startPosition,
1770 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001771
kwiberg55b97fe2016-01-28 05:22:45 -08001772 if (channel_state_.Get().output_file_playing) {
1773 _engineStatisticsPtr->SetLastError(
1774 VE_ALREADY_PLAYING, kTraceError,
1775 "StartPlayingFileLocally() is already playing");
1776 return -1;
1777 }
1778
1779 {
1780 rtc::CritScope cs(&_fileCritSect);
1781
kwiberg5a25d952016-08-17 07:31:12 -07001782 if (output_file_player_) {
1783 output_file_player_->RegisterModuleFileCallback(NULL);
1784 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001785 }
1786
kwiberg5b356f42016-09-08 04:32:33 -07001787 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001788 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001789
kwiberg5a25d952016-08-17 07:31:12 -07001790 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001791 _engineStatisticsPtr->SetLastError(
1792 VE_INVALID_ARGUMENT, kTraceError,
1793 "StartPlayingFileLocally() filePlayer format is not correct");
1794 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001795 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001796
kwiberg55b97fe2016-01-28 05:22:45 -08001797 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001798
kwiberg5a25d952016-08-17 07:31:12 -07001799 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001800 fileName, loop, startPosition, volumeScaling, notificationTime,
1801 stopPosition, (const CodecInst*)codecInst) != 0) {
1802 _engineStatisticsPtr->SetLastError(
1803 VE_BAD_FILE, kTraceError,
1804 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001805 output_file_player_->StopPlayingFile();
1806 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001807 return -1;
1808 }
kwiberg5a25d952016-08-17 07:31:12 -07001809 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001810 channel_state_.SetOutputFilePlaying(true);
1811 }
1812
1813 if (RegisterFilePlayingToMixer() != 0)
1814 return -1;
1815
1816 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001817}
1818
1819int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001820 FileFormats format,
1821 int startPosition,
1822 float volumeScaling,
1823 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001824 const CodecInst* codecInst) {
1825 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1826 "Channel::StartPlayingFileLocally(format=%d,"
1827 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1828 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001829
kwiberg55b97fe2016-01-28 05:22:45 -08001830 if (stream == NULL) {
1831 _engineStatisticsPtr->SetLastError(
1832 VE_BAD_FILE, kTraceError,
1833 "StartPlayingFileLocally() NULL as input stream");
1834 return -1;
1835 }
1836
1837 if (channel_state_.Get().output_file_playing) {
1838 _engineStatisticsPtr->SetLastError(
1839 VE_ALREADY_PLAYING, kTraceError,
1840 "StartPlayingFileLocally() is already playing");
1841 return -1;
1842 }
1843
1844 {
1845 rtc::CritScope cs(&_fileCritSect);
1846
1847 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001848 if (output_file_player_) {
1849 output_file_player_->RegisterModuleFileCallback(NULL);
1850 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001851 }
1852
kwiberg55b97fe2016-01-28 05:22:45 -08001853 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001854 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001855 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001856
kwiberg5a25d952016-08-17 07:31:12 -07001857 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001858 _engineStatisticsPtr->SetLastError(
1859 VE_INVALID_ARGUMENT, kTraceError,
1860 "StartPlayingFileLocally() filePlayer format isnot correct");
1861 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001862 }
1863
kwiberg55b97fe2016-01-28 05:22:45 -08001864 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001865
kwiberg4ec01d92016-08-22 08:43:54 -07001866 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001867 volumeScaling, notificationTime,
1868 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001869 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1870 "StartPlayingFile() failed to "
1871 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001872 output_file_player_->StopPlayingFile();
1873 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001874 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001875 }
kwiberg5a25d952016-08-17 07:31:12 -07001876 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001877 channel_state_.SetOutputFilePlaying(true);
1878 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001879
kwiberg55b97fe2016-01-28 05:22:45 -08001880 if (RegisterFilePlayingToMixer() != 0)
1881 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001882
kwiberg55b97fe2016-01-28 05:22:45 -08001883 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001884}
1885
kwiberg55b97fe2016-01-28 05:22:45 -08001886int Channel::StopPlayingFileLocally() {
1887 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1888 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001889
kwiberg55b97fe2016-01-28 05:22:45 -08001890 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001891 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001892 }
1893
1894 {
1895 rtc::CritScope cs(&_fileCritSect);
1896
kwiberg5a25d952016-08-17 07:31:12 -07001897 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001898 _engineStatisticsPtr->SetLastError(
1899 VE_STOP_RECORDING_FAILED, kTraceError,
1900 "StopPlayingFile() could not stop playing");
1901 return -1;
1902 }
kwiberg5a25d952016-08-17 07:31:12 -07001903 output_file_player_->RegisterModuleFileCallback(NULL);
1904 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001905 channel_state_.SetOutputFilePlaying(false);
1906 }
1907 // _fileCritSect cannot be taken while calling
1908 // SetAnonymousMixibilityStatus. Refer to comments in
1909 // StartPlayingFileLocally(const char* ...) for more details.
1910 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1911 _engineStatisticsPtr->SetLastError(
1912 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1913 "StopPlayingFile() failed to stop participant from playing as"
1914 "file in the mixer");
1915 return -1;
1916 }
1917
1918 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001919}
1920
kwiberg55b97fe2016-01-28 05:22:45 -08001921int Channel::IsPlayingFileLocally() const {
1922 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001923}
1924
kwiberg55b97fe2016-01-28 05:22:45 -08001925int Channel::RegisterFilePlayingToMixer() {
1926 // Return success for not registering for file playing to mixer if:
1927 // 1. playing file before playout is started on that channel.
1928 // 2. starting playout without file playing on that channel.
1929 if (!channel_state_.Get().playing ||
1930 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001931 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001932 }
1933
1934 // |_fileCritSect| cannot be taken while calling
1935 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1936 // frames can be pulled by the mixer. Since the frames are generated from
1937 // the file, _fileCritSect will be taken. This would result in a deadlock.
1938 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1939 channel_state_.SetOutputFilePlaying(false);
1940 rtc::CritScope cs(&_fileCritSect);
1941 _engineStatisticsPtr->SetLastError(
1942 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1943 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07001944 output_file_player_->StopPlayingFile();
1945 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001946 return -1;
1947 }
1948
1949 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001950}
1951
niklase@google.com470e71d2011-07-07 08:21:25 +00001952int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001953 bool loop,
1954 FileFormats format,
1955 int startPosition,
1956 float volumeScaling,
1957 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001958 const CodecInst* codecInst) {
1959 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1960 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1961 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1962 "stopPosition=%d)",
1963 fileName, loop, format, volumeScaling, startPosition,
1964 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001965
kwiberg55b97fe2016-01-28 05:22:45 -08001966 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001967
kwiberg55b97fe2016-01-28 05:22:45 -08001968 if (channel_state_.Get().input_file_playing) {
1969 _engineStatisticsPtr->SetLastError(
1970 VE_ALREADY_PLAYING, kTraceWarning,
1971 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001972 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001973 }
1974
1975 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001976 if (input_file_player_) {
1977 input_file_player_->RegisterModuleFileCallback(NULL);
1978 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001979 }
1980
1981 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001982 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07001983 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08001984
kwiberg5a25d952016-08-17 07:31:12 -07001985 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001986 _engineStatisticsPtr->SetLastError(
1987 VE_INVALID_ARGUMENT, kTraceError,
1988 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1989 return -1;
1990 }
1991
1992 const uint32_t notificationTime(0);
1993
kwiberg5a25d952016-08-17 07:31:12 -07001994 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001995 fileName, loop, startPosition, volumeScaling, notificationTime,
1996 stopPosition, (const CodecInst*)codecInst) != 0) {
1997 _engineStatisticsPtr->SetLastError(
1998 VE_BAD_FILE, kTraceError,
1999 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002000 input_file_player_->StopPlayingFile();
2001 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002002 return -1;
2003 }
kwiberg5a25d952016-08-17 07:31:12 -07002004 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002005 channel_state_.SetInputFilePlaying(true);
2006
2007 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002008}
2009
2010int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002011 FileFormats format,
2012 int startPosition,
2013 float volumeScaling,
2014 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002015 const CodecInst* codecInst) {
2016 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2017 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2018 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2019 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002020
kwiberg55b97fe2016-01-28 05:22:45 -08002021 if (stream == NULL) {
2022 _engineStatisticsPtr->SetLastError(
2023 VE_BAD_FILE, kTraceError,
2024 "StartPlayingFileAsMicrophone NULL as input stream");
2025 return -1;
2026 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002027
kwiberg55b97fe2016-01-28 05:22:45 -08002028 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002029
kwiberg55b97fe2016-01-28 05:22:45 -08002030 if (channel_state_.Get().input_file_playing) {
2031 _engineStatisticsPtr->SetLastError(
2032 VE_ALREADY_PLAYING, kTraceWarning,
2033 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002034 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002035 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002036
kwiberg55b97fe2016-01-28 05:22:45 -08002037 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002038 if (input_file_player_) {
2039 input_file_player_->RegisterModuleFileCallback(NULL);
2040 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002041 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002042
kwiberg55b97fe2016-01-28 05:22:45 -08002043 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002044 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002045 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002046
kwiberg5a25d952016-08-17 07:31:12 -07002047 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002048 _engineStatisticsPtr->SetLastError(
2049 VE_INVALID_ARGUMENT, kTraceError,
2050 "StartPlayingInputFile() filePlayer format isnot correct");
2051 return -1;
2052 }
2053
2054 const uint32_t notificationTime(0);
2055
kwiberg4ec01d92016-08-22 08:43:54 -07002056 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2057 notificationTime, stopPosition,
2058 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002059 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2060 "StartPlayingFile() failed to start "
2061 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002062 input_file_player_->StopPlayingFile();
2063 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002064 return -1;
2065 }
2066
kwiberg5a25d952016-08-17 07:31:12 -07002067 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002068 channel_state_.SetInputFilePlaying(true);
2069
2070 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002071}
2072
kwiberg55b97fe2016-01-28 05:22:45 -08002073int Channel::StopPlayingFileAsMicrophone() {
2074 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2075 "Channel::StopPlayingFileAsMicrophone()");
2076
2077 rtc::CritScope cs(&_fileCritSect);
2078
2079 if (!channel_state_.Get().input_file_playing) {
2080 return 0;
2081 }
2082
kwiberg5a25d952016-08-17 07:31:12 -07002083 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002084 _engineStatisticsPtr->SetLastError(
2085 VE_STOP_RECORDING_FAILED, kTraceError,
2086 "StopPlayingFile() could not stop playing");
2087 return -1;
2088 }
kwiberg5a25d952016-08-17 07:31:12 -07002089 input_file_player_->RegisterModuleFileCallback(NULL);
2090 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002091 channel_state_.SetInputFilePlaying(false);
2092
2093 return 0;
2094}
2095
2096int Channel::IsPlayingFileAsMicrophone() const {
2097 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002098}
2099
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002100int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002101 const CodecInst* codecInst) {
2102 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2103 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002104
kwiberg55b97fe2016-01-28 05:22:45 -08002105 if (_outputFileRecording) {
2106 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2107 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002108 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002109 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002110
kwiberg55b97fe2016-01-28 05:22:45 -08002111 FileFormats format;
2112 const uint32_t notificationTime(0); // Not supported in VoE
2113 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002114
kwiberg55b97fe2016-01-28 05:22:45 -08002115 if ((codecInst != NULL) &&
2116 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2117 _engineStatisticsPtr->SetLastError(
2118 VE_BAD_ARGUMENT, kTraceError,
2119 "StartRecordingPlayout() invalid compression");
2120 return (-1);
2121 }
2122 if (codecInst == NULL) {
2123 format = kFileFormatPcm16kHzFile;
2124 codecInst = &dummyCodec;
2125 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2126 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2127 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2128 format = kFileFormatWavFile;
2129 } else {
2130 format = kFileFormatCompressedFile;
2131 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002132
kwiberg55b97fe2016-01-28 05:22:45 -08002133 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002134
kwiberg55b97fe2016-01-28 05:22:45 -08002135 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002136 if (output_file_recorder_) {
2137 output_file_recorder_->RegisterModuleFileCallback(NULL);
2138 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002139 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002140
kwiberg5a25d952016-08-17 07:31:12 -07002141 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002142 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002143 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002144 _engineStatisticsPtr->SetLastError(
2145 VE_INVALID_ARGUMENT, kTraceError,
2146 "StartRecordingPlayout() fileRecorder format isnot correct");
2147 return -1;
2148 }
2149
kwiberg5a25d952016-08-17 07:31:12 -07002150 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002151 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2152 _engineStatisticsPtr->SetLastError(
2153 VE_BAD_FILE, kTraceError,
2154 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002155 output_file_recorder_->StopRecording();
2156 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002157 return -1;
2158 }
kwiberg5a25d952016-08-17 07:31:12 -07002159 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002160 _outputFileRecording = true;
2161
2162 return 0;
2163}
2164
2165int Channel::StartRecordingPlayout(OutStream* stream,
2166 const CodecInst* codecInst) {
2167 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2168 "Channel::StartRecordingPlayout()");
2169
2170 if (_outputFileRecording) {
2171 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2172 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002173 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002174 }
2175
2176 FileFormats format;
2177 const uint32_t notificationTime(0); // Not supported in VoE
2178 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2179
2180 if (codecInst != NULL && codecInst->channels != 1) {
2181 _engineStatisticsPtr->SetLastError(
2182 VE_BAD_ARGUMENT, kTraceError,
2183 "StartRecordingPlayout() invalid compression");
2184 return (-1);
2185 }
2186 if (codecInst == NULL) {
2187 format = kFileFormatPcm16kHzFile;
2188 codecInst = &dummyCodec;
2189 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2190 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2191 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2192 format = kFileFormatWavFile;
2193 } else {
2194 format = kFileFormatCompressedFile;
2195 }
2196
2197 rtc::CritScope cs(&_fileCritSect);
2198
2199 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002200 if (output_file_recorder_) {
2201 output_file_recorder_->RegisterModuleFileCallback(NULL);
2202 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002203 }
2204
kwiberg5a25d952016-08-17 07:31:12 -07002205 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002206 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002207 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002208 _engineStatisticsPtr->SetLastError(
2209 VE_INVALID_ARGUMENT, kTraceError,
2210 "StartRecordingPlayout() fileRecorder format isnot correct");
2211 return -1;
2212 }
2213
kwiberg4ec01d92016-08-22 08:43:54 -07002214 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002215 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002216 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2217 "StartRecordingPlayout() failed to "
2218 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002219 output_file_recorder_->StopRecording();
2220 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002221 return -1;
2222 }
2223
kwiberg5a25d952016-08-17 07:31:12 -07002224 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002225 _outputFileRecording = true;
2226
2227 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002228}
2229
kwiberg55b97fe2016-01-28 05:22:45 -08002230int Channel::StopRecordingPlayout() {
2231 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2232 "Channel::StopRecordingPlayout()");
2233
2234 if (!_outputFileRecording) {
2235 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2236 "StopRecordingPlayout() isnot recording");
2237 return -1;
2238 }
2239
2240 rtc::CritScope cs(&_fileCritSect);
2241
kwiberg5a25d952016-08-17 07:31:12 -07002242 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002243 _engineStatisticsPtr->SetLastError(
2244 VE_STOP_RECORDING_FAILED, kTraceError,
2245 "StopRecording() could not stop recording");
2246 return (-1);
2247 }
kwiberg5a25d952016-08-17 07:31:12 -07002248 output_file_recorder_->RegisterModuleFileCallback(NULL);
2249 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002250 _outputFileRecording = false;
2251
2252 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002253}
2254
kwiberg55b97fe2016-01-28 05:22:45 -08002255void Channel::SetMixWithMicStatus(bool mix) {
2256 rtc::CritScope cs(&_fileCritSect);
2257 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002258}
2259
kwiberg55b97fe2016-01-28 05:22:45 -08002260int Channel::GetSpeechOutputLevel(uint32_t& level) const {
2261 int8_t currentLevel = _outputAudioLevel.Level();
2262 level = static_cast<int32_t>(currentLevel);
2263 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002264}
2265
kwiberg55b97fe2016-01-28 05:22:45 -08002266int Channel::GetSpeechOutputLevelFullRange(uint32_t& level) const {
2267 int16_t currentLevel = _outputAudioLevel.LevelFullRange();
2268 level = static_cast<int32_t>(currentLevel);
2269 return 0;
2270}
2271
solenberg1c2af8e2016-03-24 10:36:00 -07002272int Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002273 rtc::CritScope cs(&volume_settings_critsect_);
2274 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002275 "Channel::SetMute(enable=%d)", enable);
solenberg1c2af8e2016-03-24 10:36:00 -07002276 input_mute_ = enable;
kwiberg55b97fe2016-01-28 05:22:45 -08002277 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002278}
2279
solenberg1c2af8e2016-03-24 10:36:00 -07002280bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002281 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002282 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002283}
2284
kwiberg55b97fe2016-01-28 05:22:45 -08002285int Channel::SetOutputVolumePan(float left, float right) {
2286 rtc::CritScope cs(&volume_settings_critsect_);
2287 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002288 "Channel::SetOutputVolumePan()");
kwiberg55b97fe2016-01-28 05:22:45 -08002289 _panLeft = left;
2290 _panRight = right;
2291 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002292}
2293
kwiberg55b97fe2016-01-28 05:22:45 -08002294int Channel::GetOutputVolumePan(float& left, float& right) const {
2295 rtc::CritScope cs(&volume_settings_critsect_);
2296 left = _panLeft;
2297 right = _panRight;
2298 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002299}
2300
kwiberg55b97fe2016-01-28 05:22:45 -08002301int Channel::SetChannelOutputVolumeScaling(float scaling) {
2302 rtc::CritScope cs(&volume_settings_critsect_);
2303 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002304 "Channel::SetChannelOutputVolumeScaling()");
kwiberg55b97fe2016-01-28 05:22:45 -08002305 _outputGain = scaling;
2306 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002307}
2308
kwiberg55b97fe2016-01-28 05:22:45 -08002309int Channel::GetChannelOutputVolumeScaling(float& scaling) const {
2310 rtc::CritScope cs(&volume_settings_critsect_);
2311 scaling = _outputGain;
2312 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002313}
2314
solenberg8842c3e2016-03-11 03:06:41 -08002315int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002316 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002317 "Channel::SendTelephoneEventOutband(...)");
2318 RTC_DCHECK_LE(0, event);
2319 RTC_DCHECK_GE(255, event);
2320 RTC_DCHECK_LE(0, duration_ms);
2321 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002322 if (!Sending()) {
2323 return -1;
2324 }
solenberg8842c3e2016-03-11 03:06:41 -08002325 if (_rtpRtcpModule->SendTelephoneEventOutband(
2326 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002327 _engineStatisticsPtr->SetLastError(
2328 VE_SEND_DTMF_FAILED, kTraceWarning,
2329 "SendTelephoneEventOutband() failed to send event");
2330 return -1;
2331 }
2332 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002333}
2334
solenbergffbbcac2016-11-17 05:25:37 -08002335int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2336 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002337 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002338 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002339 RTC_DCHECK_LE(0, payload_type);
2340 RTC_DCHECK_GE(127, payload_type);
2341 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002342 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002343 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002344 memcpy(codec.plname, "telephone-event", 16);
2345 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2346 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2347 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2348 _engineStatisticsPtr->SetLastError(
2349 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2350 "SetSendTelephoneEventPayloadType() failed to register send"
2351 "payload type");
2352 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002353 }
kwiberg55b97fe2016-01-28 05:22:45 -08002354 }
kwiberg55b97fe2016-01-28 05:22:45 -08002355 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002356}
2357
kwiberg55b97fe2016-01-28 05:22:45 -08002358int Channel::VoiceActivityIndicator(int& activity) {
2359 activity = _sendFrameType;
2360 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002361}
2362
kwiberg55b97fe2016-01-28 05:22:45 -08002363int Channel::SetLocalSSRC(unsigned int ssrc) {
2364 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2365 "Channel::SetLocalSSRC()");
2366 if (channel_state_.Get().sending) {
2367 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2368 "SetLocalSSRC() already sending");
2369 return -1;
2370 }
2371 _rtpRtcpModule->SetSSRC(ssrc);
2372 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002373}
2374
kwiberg55b97fe2016-01-28 05:22:45 -08002375int Channel::GetLocalSSRC(unsigned int& ssrc) {
2376 ssrc = _rtpRtcpModule->SSRC();
2377 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002378}
2379
kwiberg55b97fe2016-01-28 05:22:45 -08002380int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2381 ssrc = rtp_receiver_->SSRC();
2382 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002383}
2384
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002385int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002386 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002387 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002388}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002389
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002390int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2391 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002392 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2393 if (enable &&
2394 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2395 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002396 return -1;
2397 }
2398 return 0;
2399}
2400
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002401void Channel::EnableSendTransportSequenceNumber(int id) {
2402 int ret =
2403 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2404 RTC_DCHECK_EQ(0, ret);
2405}
2406
stefan3313ec92016-01-21 06:32:43 -08002407void Channel::EnableReceiveTransportSequenceNumber(int id) {
2408 rtp_header_parser_->DeregisterRtpHeaderExtension(
2409 kRtpExtensionTransportSequenceNumber);
2410 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2411 kRtpExtensionTransportSequenceNumber, id);
2412 RTC_DCHECK(ret);
2413}
2414
stefanbba9dec2016-02-01 04:39:55 -08002415void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002416 RtpPacketSender* rtp_packet_sender,
2417 TransportFeedbackObserver* transport_feedback_observer,
2418 PacketRouter* packet_router) {
stefanbba9dec2016-02-01 04:39:55 -08002419 RTC_DCHECK(rtp_packet_sender);
2420 RTC_DCHECK(transport_feedback_observer);
2421 RTC_DCHECK(packet_router && !packet_router_);
2422 feedback_observer_proxy_->SetTransportFeedbackObserver(
2423 transport_feedback_observer);
2424 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2425 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2426 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002427 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002428 packet_router_ = packet_router;
2429}
2430
stefanbba9dec2016-02-01 04:39:55 -08002431void Channel::RegisterReceiverCongestionControlObjects(
2432 PacketRouter* packet_router) {
2433 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002434 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002435 packet_router_ = packet_router;
2436}
2437
2438void Channel::ResetCongestionControlObjects() {
2439 RTC_DCHECK(packet_router_);
2440 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
2441 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2442 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002443 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002444 packet_router_ = nullptr;
2445 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2446}
2447
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002448void Channel::SetRTCPStatus(bool enable) {
2449 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2450 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002451 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002452}
2453
kwiberg55b97fe2016-01-28 05:22:45 -08002454int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002455 RtcpMode method = _rtpRtcpModule->RTCP();
2456 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002457 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002458}
2459
kwiberg55b97fe2016-01-28 05:22:45 -08002460int Channel::SetRTCP_CNAME(const char cName[256]) {
2461 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2462 "Channel::SetRTCP_CNAME()");
2463 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2464 _engineStatisticsPtr->SetLastError(
2465 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2466 "SetRTCP_CNAME() failed to set RTCP CNAME");
2467 return -1;
2468 }
2469 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002470}
2471
kwiberg55b97fe2016-01-28 05:22:45 -08002472int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2473 if (cName == NULL) {
2474 _engineStatisticsPtr->SetLastError(
2475 VE_INVALID_ARGUMENT, kTraceError,
2476 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2477 return -1;
2478 }
2479 char cname[RTCP_CNAME_SIZE];
2480 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2481 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2482 _engineStatisticsPtr->SetLastError(
2483 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2484 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2485 return -1;
2486 }
2487 strcpy(cName, cname);
2488 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002489}
2490
kwiberg55b97fe2016-01-28 05:22:45 -08002491int Channel::GetRemoteRTCPData(unsigned int& NTPHigh,
2492 unsigned int& NTPLow,
2493 unsigned int& timestamp,
2494 unsigned int& playoutTimestamp,
2495 unsigned int* jitter,
2496 unsigned short* fractionLost) {
2497 // --- Information from sender info in received Sender Reports
niklase@google.com470e71d2011-07-07 08:21:25 +00002498
kwiberg55b97fe2016-01-28 05:22:45 -08002499 RTCPSenderInfo senderInfo;
2500 if (_rtpRtcpModule->RemoteRTCPStat(&senderInfo) != 0) {
2501 _engineStatisticsPtr->SetLastError(
2502 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2503 "GetRemoteRTCPData() failed to retrieve sender info for remote "
2504 "side");
2505 return -1;
2506 }
2507
2508 // We only utilize 12 out of 20 bytes in the sender info (ignores packet
2509 // and octet count)
2510 NTPHigh = senderInfo.NTPseconds;
2511 NTPLow = senderInfo.NTPfraction;
2512 timestamp = senderInfo.RTPtimeStamp;
2513
2514 // --- Locally derived information
2515
2516 // This value is updated on each incoming RTCP packet (0 when no packet
2517 // has been received)
2518 playoutTimestamp = playout_timestamp_rtcp_;
2519
2520 if (NULL != jitter || NULL != fractionLost) {
2521 // Get all RTCP receiver report blocks that have been received on this
2522 // channel. If we receive RTP packets from a remote source we know the
2523 // remote SSRC and use the report block from him.
2524 // Otherwise use the first report block.
2525 std::vector<RTCPReportBlock> remote_stats;
2526 if (_rtpRtcpModule->RemoteRTCPStat(&remote_stats) != 0 ||
2527 remote_stats.empty()) {
2528 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2529 "GetRemoteRTCPData() failed to measure statistics due"
2530 " to lack of received RTP and/or RTCP packets");
2531 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002532 }
2533
kwiberg55b97fe2016-01-28 05:22:45 -08002534 uint32_t remoteSSRC = rtp_receiver_->SSRC();
2535 std::vector<RTCPReportBlock>::const_iterator it = remote_stats.begin();
2536 for (; it != remote_stats.end(); ++it) {
2537 if (it->remoteSSRC == remoteSSRC)
2538 break;
niklase@google.com470e71d2011-07-07 08:21:25 +00002539 }
kwiberg55b97fe2016-01-28 05:22:45 -08002540
2541 if (it == remote_stats.end()) {
2542 // If we have not received any RTCP packets from this SSRC it probably
2543 // means that we have not received any RTP packets.
2544 // Use the first received report block instead.
2545 it = remote_stats.begin();
2546 remoteSSRC = it->remoteSSRC;
2547 }
2548
2549 if (jitter) {
2550 *jitter = it->jitter;
2551 }
2552
2553 if (fractionLost) {
2554 *fractionLost = it->fractionLost;
2555 }
2556 }
2557 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002558}
2559
kwiberg55b97fe2016-01-28 05:22:45 -08002560int Channel::SendApplicationDefinedRTCPPacket(
2561 unsigned char subType,
2562 unsigned int name,
2563 const char* data,
2564 unsigned short dataLengthInBytes) {
2565 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2566 "Channel::SendApplicationDefinedRTCPPacket()");
2567 if (!channel_state_.Get().sending) {
2568 _engineStatisticsPtr->SetLastError(
2569 VE_NOT_SENDING, kTraceError,
2570 "SendApplicationDefinedRTCPPacket() not sending");
2571 return -1;
2572 }
2573 if (NULL == data) {
2574 _engineStatisticsPtr->SetLastError(
2575 VE_INVALID_ARGUMENT, kTraceError,
2576 "SendApplicationDefinedRTCPPacket() invalid data value");
2577 return -1;
2578 }
2579 if (dataLengthInBytes % 4 != 0) {
2580 _engineStatisticsPtr->SetLastError(
2581 VE_INVALID_ARGUMENT, kTraceError,
2582 "SendApplicationDefinedRTCPPacket() invalid length value");
2583 return -1;
2584 }
2585 RtcpMode status = _rtpRtcpModule->RTCP();
2586 if (status == RtcpMode::kOff) {
2587 _engineStatisticsPtr->SetLastError(
2588 VE_RTCP_ERROR, kTraceError,
2589 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2590 return -1;
2591 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002592
kwiberg55b97fe2016-01-28 05:22:45 -08002593 // Create and schedule the RTCP APP packet for transmission
2594 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2595 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2596 _engineStatisticsPtr->SetLastError(
2597 VE_SEND_ERROR, kTraceError,
2598 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2599 return -1;
2600 }
2601 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002602}
2603
kwiberg55b97fe2016-01-28 05:22:45 -08002604int Channel::GetRTPStatistics(unsigned int& averageJitterMs,
2605 unsigned int& maxJitterMs,
2606 unsigned int& discardedPackets) {
2607 // The jitter statistics is updated for each received RTP packet and is
2608 // based on received packets.
2609 if (_rtpRtcpModule->RTCP() == RtcpMode::kOff) {
2610 // If RTCP is off, there is no timed thread in the RTCP module regularly
2611 // generating new stats, trigger the update manually here instead.
2612 StreamStatistician* statistician =
2613 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
2614 if (statistician) {
2615 // Don't use returned statistics, use data from proxy instead so that
2616 // max jitter can be fetched atomically.
2617 RtcpStatistics s;
2618 statistician->GetStatistics(&s, true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002619 }
kwiberg55b97fe2016-01-28 05:22:45 -08002620 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002621
kwiberg55b97fe2016-01-28 05:22:45 -08002622 ChannelStatistics stats = statistics_proxy_->GetStats();
2623 const int32_t playoutFrequency = audio_coding_->PlayoutFrequency();
2624 if (playoutFrequency > 0) {
2625 // Scale RTP statistics given the current playout frequency
2626 maxJitterMs = stats.max_jitter / (playoutFrequency / 1000);
2627 averageJitterMs = stats.rtcp.jitter / (playoutFrequency / 1000);
2628 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002629
kwiberg55b97fe2016-01-28 05:22:45 -08002630 discardedPackets = _numberOfDiscardedPackets;
niklase@google.com470e71d2011-07-07 08:21:25 +00002631
kwiberg55b97fe2016-01-28 05:22:45 -08002632 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002633}
2634
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002635int Channel::GetRemoteRTCPReportBlocks(
2636 std::vector<ReportBlock>* report_blocks) {
2637 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002638 _engineStatisticsPtr->SetLastError(
2639 VE_INVALID_ARGUMENT, kTraceError,
2640 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002641 return -1;
2642 }
2643
2644 // Get the report blocks from the latest received RTCP Sender or Receiver
2645 // Report. Each element in the vector contains the sender's SSRC and a
2646 // report block according to RFC 3550.
2647 std::vector<RTCPReportBlock> rtcp_report_blocks;
2648 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002649 return -1;
2650 }
2651
2652 if (rtcp_report_blocks.empty())
2653 return 0;
2654
2655 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2656 for (; it != rtcp_report_blocks.end(); ++it) {
2657 ReportBlock report_block;
2658 report_block.sender_SSRC = it->remoteSSRC;
2659 report_block.source_SSRC = it->sourceSSRC;
2660 report_block.fraction_lost = it->fractionLost;
2661 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2662 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2663 report_block.interarrival_jitter = it->jitter;
2664 report_block.last_SR_timestamp = it->lastSR;
2665 report_block.delay_since_last_SR = it->delaySinceLastSR;
2666 report_blocks->push_back(report_block);
2667 }
2668 return 0;
2669}
2670
kwiberg55b97fe2016-01-28 05:22:45 -08002671int Channel::GetRTPStatistics(CallStatistics& stats) {
2672 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002673
kwiberg55b97fe2016-01-28 05:22:45 -08002674 // The jitter statistics is updated for each received RTP packet and is
2675 // based on received packets.
2676 RtcpStatistics statistics;
2677 StreamStatistician* statistician =
2678 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002679 if (statistician) {
2680 statistician->GetStatistics(&statistics,
2681 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002682 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002683
kwiberg55b97fe2016-01-28 05:22:45 -08002684 stats.fractionLost = statistics.fraction_lost;
2685 stats.cumulativeLost = statistics.cumulative_lost;
2686 stats.extendedMax = statistics.extended_max_sequence_number;
2687 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002688
kwiberg55b97fe2016-01-28 05:22:45 -08002689 // --- RTT
2690 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002691
kwiberg55b97fe2016-01-28 05:22:45 -08002692 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002693
kwiberg55b97fe2016-01-28 05:22:45 -08002694 size_t bytesSent(0);
2695 uint32_t packetsSent(0);
2696 size_t bytesReceived(0);
2697 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002698
kwiberg55b97fe2016-01-28 05:22:45 -08002699 if (statistician) {
2700 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2701 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002702
kwiberg55b97fe2016-01-28 05:22:45 -08002703 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2704 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2705 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2706 " output will not be complete");
2707 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002708
kwiberg55b97fe2016-01-28 05:22:45 -08002709 stats.bytesSent = bytesSent;
2710 stats.packetsSent = packetsSent;
2711 stats.bytesReceived = bytesReceived;
2712 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002713
kwiberg55b97fe2016-01-28 05:22:45 -08002714 // --- Timestamps
2715 {
2716 rtc::CritScope lock(&ts_stats_lock_);
2717 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2718 }
2719 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002720}
2721
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002722int Channel::SetCodecFECStatus(bool enable) {
2723 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2724 "Channel::SetCodecFECStatus()");
2725
kwibergc8d071e2016-04-06 12:22:38 -07002726 if (!codec_manager_.SetCodecFEC(enable) ||
2727 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002728 _engineStatisticsPtr->SetLastError(
2729 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2730 "SetCodecFECStatus() failed to set FEC state");
2731 return -1;
2732 }
2733 return 0;
2734}
2735
2736bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002737 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002738}
2739
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002740void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2741 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002742 // If pacing is enabled we always store packets.
2743 if (!pacing_enabled_)
2744 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002745 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002746 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002747 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002748 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002749 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002750}
2751
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002752// Called when we are missing one or more packets.
2753int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002754 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2755}
2756
kwiberg55b97fe2016-01-28 05:22:45 -08002757uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2758 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2759 "Channel::Demultiplex()");
2760 _audioFrame.CopyFrom(audioFrame);
2761 _audioFrame.id_ = _channelId;
2762 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002763}
2764
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002765void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002766 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002767 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002768 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002769 CodecInst codec;
2770 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002771
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002772 // Never upsample or upmix the capture signal here. This should be done at the
2773 // end of the send chain.
2774 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2775 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2776 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2777 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002778}
2779
kwiberg55b97fe2016-01-28 05:22:45 -08002780uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2781 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2782 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002783
kwiberg55b97fe2016-01-28 05:22:45 -08002784 if (_audioFrame.samples_per_channel_ == 0) {
2785 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2786 "Channel::PrepareEncodeAndSend() invalid audio frame");
2787 return 0xFFFFFFFF;
2788 }
2789
2790 if (channel_state_.Get().input_file_playing) {
2791 MixOrReplaceAudioWithFile(mixingFrequency);
2792 }
2793
solenberg1c2af8e2016-03-24 10:36:00 -07002794 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2795 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002796
2797 if (channel_state_.Get().input_external_media) {
2798 rtc::CritScope cs(&_callbackCritSect);
2799 const bool isStereo = (_audioFrame.num_channels_ == 2);
2800 if (_inputExternalMediaCallbackPtr) {
2801 _inputExternalMediaCallbackPtr->Process(
2802 _channelId, kRecordingPerChannel, (int16_t*)_audioFrame.data_,
2803 _audioFrame.samples_per_channel_, _audioFrame.sample_rate_hz_,
2804 isStereo);
niklase@google.com470e71d2011-07-07 08:21:25 +00002805 }
kwiberg55b97fe2016-01-28 05:22:45 -08002806 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002807
kwiberg55b97fe2016-01-28 05:22:45 -08002808 if (_includeAudioLevelIndication) {
2809 size_t length =
2810 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02002811 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002812 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002813 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002814 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002815 rms_level_.Analyze(
2816 rtc::ArrayView<const int16_t>(_audioFrame.data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002817 }
kwiberg55b97fe2016-01-28 05:22:45 -08002818 }
solenberg1c2af8e2016-03-24 10:36:00 -07002819 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002820
kwiberg55b97fe2016-01-28 05:22:45 -08002821 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002822}
2823
kwiberg55b97fe2016-01-28 05:22:45 -08002824uint32_t Channel::EncodeAndSend() {
2825 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2826 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002827
kwiberg55b97fe2016-01-28 05:22:45 -08002828 assert(_audioFrame.num_channels_ <= 2);
2829 if (_audioFrame.samples_per_channel_ == 0) {
2830 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2831 "Channel::EncodeAndSend() invalid audio frame");
2832 return 0xFFFFFFFF;
2833 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002834
kwiberg55b97fe2016-01-28 05:22:45 -08002835 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00002836
kwiberg55b97fe2016-01-28 05:22:45 -08002837 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002838
kwiberg55b97fe2016-01-28 05:22:45 -08002839 // The ACM resamples internally.
2840 _audioFrame.timestamp_ = _timeStamp;
2841 // This call will trigger AudioPacketizationCallback::SendData if encoding
2842 // is done and payload is ready for packetization and transmission.
2843 // Otherwise, it will return without invoking the callback.
2844 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
2845 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
2846 "Channel::EncodeAndSend() ACM encoding failed");
2847 return 0xFFFFFFFF;
2848 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002849
kwiberg55b97fe2016-01-28 05:22:45 -08002850 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
2851 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002852}
2853
solenberg7602aab2016-11-14 11:30:07 -08002854void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2855 RTC_DCHECK(!channel.channel() ||
2856 channel.channel()->ChannelId() != _channelId);
2857 rtc::CritScope lock(&assoc_send_channel_lock_);
2858 associate_send_channel_ = channel;
2859}
2860
Minyue2013aec2015-05-13 14:14:42 +02002861void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002862 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002863 Channel* channel = associate_send_channel_.channel();
2864 if (channel && channel->ChannelId() == channel_id) {
2865 // If this channel is associated with a send channel of the specified
2866 // Channel ID, disassociate with it.
2867 ChannelOwner ref(NULL);
2868 associate_send_channel_ = ref;
2869 }
2870}
2871
ivoc14d5dbe2016-07-04 07:06:55 -07002872void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2873 event_log_proxy_->SetEventLog(event_log);
2874}
2875
michaelt9332b7d2016-11-30 07:51:13 -08002876void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2877 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2878}
2879
michaelt79e05882016-11-08 02:50:09 -08002880void Channel::SetTransportOverhead(int transport_overhead_per_packet) {
2881 _rtpRtcpModule->SetTransportOverhead(transport_overhead_per_packet);
2882}
2883
kwiberg55b97fe2016-01-28 05:22:45 -08002884int Channel::RegisterExternalMediaProcessing(ProcessingTypes type,
2885 VoEMediaProcess& processObject) {
2886 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2887 "Channel::RegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002888
kwiberg55b97fe2016-01-28 05:22:45 -08002889 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002890
kwiberg55b97fe2016-01-28 05:22:45 -08002891 if (kPlaybackPerChannel == type) {
2892 if (_outputExternalMediaCallbackPtr) {
2893 _engineStatisticsPtr->SetLastError(
2894 VE_INVALID_OPERATION, kTraceError,
2895 "Channel::RegisterExternalMediaProcessing() "
2896 "output external media already enabled");
2897 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002898 }
kwiberg55b97fe2016-01-28 05:22:45 -08002899 _outputExternalMediaCallbackPtr = &processObject;
2900 _outputExternalMedia = true;
2901 } else if (kRecordingPerChannel == type) {
2902 if (_inputExternalMediaCallbackPtr) {
2903 _engineStatisticsPtr->SetLastError(
2904 VE_INVALID_OPERATION, kTraceError,
2905 "Channel::RegisterExternalMediaProcessing() "
2906 "output external media already enabled");
2907 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002908 }
kwiberg55b97fe2016-01-28 05:22:45 -08002909 _inputExternalMediaCallbackPtr = &processObject;
2910 channel_state_.SetInputExternalMedia(true);
2911 }
2912 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002913}
2914
kwiberg55b97fe2016-01-28 05:22:45 -08002915int Channel::DeRegisterExternalMediaProcessing(ProcessingTypes type) {
2916 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2917 "Channel::DeRegisterExternalMediaProcessing()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002918
kwiberg55b97fe2016-01-28 05:22:45 -08002919 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002920
kwiberg55b97fe2016-01-28 05:22:45 -08002921 if (kPlaybackPerChannel == type) {
2922 if (!_outputExternalMediaCallbackPtr) {
2923 _engineStatisticsPtr->SetLastError(
2924 VE_INVALID_OPERATION, kTraceWarning,
2925 "Channel::DeRegisterExternalMediaProcessing() "
2926 "output external media already disabled");
2927 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002928 }
kwiberg55b97fe2016-01-28 05:22:45 -08002929 _outputExternalMedia = false;
2930 _outputExternalMediaCallbackPtr = NULL;
2931 } else if (kRecordingPerChannel == type) {
2932 if (!_inputExternalMediaCallbackPtr) {
2933 _engineStatisticsPtr->SetLastError(
2934 VE_INVALID_OPERATION, kTraceWarning,
2935 "Channel::DeRegisterExternalMediaProcessing() "
2936 "input external media already disabled");
2937 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002938 }
kwiberg55b97fe2016-01-28 05:22:45 -08002939 channel_state_.SetInputExternalMedia(false);
2940 _inputExternalMediaCallbackPtr = NULL;
2941 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002942
kwiberg55b97fe2016-01-28 05:22:45 -08002943 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002944}
2945
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002946int Channel::SetExternalMixing(bool enabled) {
kwiberg55b97fe2016-01-28 05:22:45 -08002947 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2948 "Channel::SetExternalMixing(enabled=%d)", enabled);
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002949
kwiberg55b97fe2016-01-28 05:22:45 -08002950 if (channel_state_.Get().playing) {
2951 _engineStatisticsPtr->SetLastError(
2952 VE_INVALID_OPERATION, kTraceError,
2953 "Channel::SetExternalMixing() "
2954 "external mixing cannot be changed while playing.");
2955 return -1;
2956 }
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002957
kwiberg55b97fe2016-01-28 05:22:45 -08002958 _externalMixing = enabled;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002959
kwiberg55b97fe2016-01-28 05:22:45 -08002960 return 0;
roosa@google.com1b60ceb2012-12-12 23:00:29 +00002961}
2962
kwiberg55b97fe2016-01-28 05:22:45 -08002963int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2964 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002965}
2966
wu@webrtc.org24301a62013-12-13 19:17:43 +00002967void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2968 audio_coding_->GetDecodingCallStatistics(stats);
2969}
2970
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002971bool Channel::GetDelayEstimate(int* jitter_buffer_delay_ms,
2972 int* playout_buffer_delay_ms) const {
tommi31fc21f2016-01-21 10:37:37 -08002973 rtc::CritScope lock(&video_sync_lock_);
henrik.lundinb3f1c5d2016-08-22 15:39:53 -07002974 *jitter_buffer_delay_ms = audio_coding_->FilteredCurrentDelayMs();
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002975 *playout_buffer_delay_ms = playout_delay_ms_;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002976 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +00002977}
2978
solenberg358057b2015-11-27 10:46:42 -08002979uint32_t Channel::GetDelayEstimate() const {
2980 int jitter_buffer_delay_ms = 0;
2981 int playout_buffer_delay_ms = 0;
2982 GetDelayEstimate(&jitter_buffer_delay_ms, &playout_buffer_delay_ms);
2983 return jitter_buffer_delay_ms + playout_buffer_delay_ms;
2984}
2985
deadbeef74375882015-08-13 12:09:10 -07002986int Channel::LeastRequiredDelayMs() const {
2987 return audio_coding_->LeastRequiredDelayMs();
2988}
2989
kwiberg55b97fe2016-01-28 05:22:45 -08002990int Channel::SetMinimumPlayoutDelay(int delayMs) {
2991 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2992 "Channel::SetMinimumPlayoutDelay()");
2993 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
2994 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
2995 _engineStatisticsPtr->SetLastError(
2996 VE_INVALID_ARGUMENT, kTraceError,
2997 "SetMinimumPlayoutDelay() invalid min delay");
2998 return -1;
2999 }
3000 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
3001 _engineStatisticsPtr->SetLastError(
3002 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
3003 "SetMinimumPlayoutDelay() failed to set min playout delay");
3004 return -1;
3005 }
3006 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003007}
3008
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003009int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07003010 uint32_t playout_timestamp_rtp = 0;
3011 {
tommi31fc21f2016-01-21 10:37:37 -08003012 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003013 playout_timestamp_rtp = playout_timestamp_rtp_;
3014 }
kwiberg55b97fe2016-01-28 05:22:45 -08003015 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003016 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07003017 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003018 "GetPlayoutTimestamp() failed to retrieve timestamp");
3019 return -1;
3020 }
deadbeef74375882015-08-13 12:09:10 -07003021 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00003022 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003023}
3024
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003025int Channel::SetInitTimestamp(unsigned int timestamp) {
3026 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00003027 "Channel::SetInitTimestamp()");
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003028 if (channel_state_.Get().sending) {
3029 _engineStatisticsPtr->SetLastError(VE_SENDING, kTraceError,
3030 "SetInitTimestamp() already sending");
3031 return -1;
3032 }
3033 _rtpRtcpModule->SetStartTimestamp(timestamp);
3034 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003035}
3036
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00003037int Channel::SetInitSequenceNumber(short sequenceNumber) {
3038 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3039 "Channel::SetInitSequenceNumber()");
3040 if (channel_state_.Get().sending) {
3041 _engineStatisticsPtr->SetLastError(
3042 VE_SENDING, kTraceError, "SetInitSequenceNumber() already sending");
3043 return -1;
3044 }
3045 _rtpRtcpModule->SetSequenceNumber(sequenceNumber);
3046 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003047}
3048
kwiberg55b97fe2016-01-28 05:22:45 -08003049int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
3050 RtpReceiver** rtp_receiver) const {
3051 *rtpRtcpModule = _rtpRtcpModule.get();
3052 *rtp_receiver = rtp_receiver_.get();
3053 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003054}
3055
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00003056// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
3057// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08003058int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08003059 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08003060 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003061
kwiberg55b97fe2016-01-28 05:22:45 -08003062 {
3063 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003064
kwiberg5a25d952016-08-17 07:31:12 -07003065 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003066 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3067 "Channel::MixOrReplaceAudioWithFile() fileplayer"
3068 " doesnt exist");
3069 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003070 }
3071
kwiberg4ec01d92016-08-22 08:43:54 -07003072 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07003073 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003074 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3075 "Channel::MixOrReplaceAudioWithFile() file mixing "
3076 "failed");
3077 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003078 }
kwiberg55b97fe2016-01-28 05:22:45 -08003079 if (fileSamples == 0) {
3080 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3081 "Channel::MixOrReplaceAudioWithFile() file is ended");
3082 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003083 }
kwiberg55b97fe2016-01-28 05:22:45 -08003084 }
3085
3086 assert(_audioFrame.samples_per_channel_ == fileSamples);
3087
3088 if (_mixFileWithMicrophone) {
3089 // Currently file stream is always mono.
3090 // TODO(xians): Change the code when FilePlayer supports real stereo.
3091 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
3092 1, fileSamples);
3093 } else {
3094 // Replace ACM audio with file.
3095 // Currently file stream is always mono.
3096 // TODO(xians): Change the code when FilePlayer supports real stereo.
3097 _audioFrame.UpdateFrame(
3098 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
3099 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
3100 }
3101 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003102}
3103
kwiberg55b97fe2016-01-28 05:22:45 -08003104int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
3105 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00003106
kwibergb7f89d62016-02-17 10:04:18 -08003107 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003108 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003109
kwiberg55b97fe2016-01-28 05:22:45 -08003110 {
3111 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003112
kwiberg5a25d952016-08-17 07:31:12 -07003113 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003114 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3115 "Channel::MixAudioWithFile() file mixing failed");
3116 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003117 }
3118
kwiberg55b97fe2016-01-28 05:22:45 -08003119 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07003120 if (output_file_player_->Get10msAudioFromFile(
3121 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003122 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3123 "Channel::MixAudioWithFile() file mixing failed");
3124 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003125 }
kwiberg55b97fe2016-01-28 05:22:45 -08003126 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003127
kwiberg55b97fe2016-01-28 05:22:45 -08003128 if (audioFrame.samples_per_channel_ == fileSamples) {
3129 // Currently file stream is always mono.
3130 // TODO(xians): Change the code when FilePlayer supports real stereo.
3131 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
3132 fileSamples);
3133 } else {
3134 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3135 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3136 ") != "
3137 "fileSamples(%" PRIuS ")",
3138 audioFrame.samples_per_channel_, fileSamples);
3139 return -1;
3140 }
3141
3142 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003143}
3144
deadbeef74375882015-08-13 12:09:10 -07003145void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003146 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003147
henrik.lundin96bd5022016-04-06 04:13:56 -07003148 if (!jitter_buffer_playout_timestamp_) {
3149 // This can happen if this channel has not received any RTP packets. In
3150 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003151 return;
3152 }
3153
3154 uint16_t delay_ms = 0;
3155 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003156 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003157 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3158 " delay from the ADM");
3159 _engineStatisticsPtr->SetLastError(
3160 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3161 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3162 return;
3163 }
3164
henrik.lundin96bd5022016-04-06 04:13:56 -07003165 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3166 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003167
3168 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07003169 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003170
kwiberg55b97fe2016-01-28 05:22:45 -08003171 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003172 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003173 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003174
3175 {
tommi31fc21f2016-01-21 10:37:37 -08003176 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07003177 if (rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003178 playout_timestamp_rtcp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003179 } else {
henrik.lundin96bd5022016-04-06 04:13:56 -07003180 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003181 }
3182 playout_delay_ms_ = delay_ms;
3183 }
3184}
3185
kwiberg55b97fe2016-01-28 05:22:45 -08003186void Channel::RegisterReceiveCodecsToRTPModule() {
3187 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3188 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003189
kwiberg55b97fe2016-01-28 05:22:45 -08003190 CodecInst codec;
3191 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003192
kwiberg55b97fe2016-01-28 05:22:45 -08003193 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3194 // Open up the RTP/RTCP receiver for all supported codecs
3195 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08003196 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08003197 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3198 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3199 " to register %s (%d/%d/%" PRIuS
3200 "/%d) to RTP/RTCP "
3201 "receiver",
3202 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3203 codec.rate);
3204 } else {
3205 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3206 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3207 "(%d/%d/%" PRIuS
3208 "/%d) has been added to the RTP/RTCP "
3209 "receiver",
3210 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3211 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003212 }
kwiberg55b97fe2016-01-28 05:22:45 -08003213 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003214}
3215
kwiberg55b97fe2016-01-28 05:22:45 -08003216int Channel::SetSendRtpHeaderExtension(bool enable,
3217 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003218 unsigned char id) {
3219 int error = 0;
3220 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3221 if (enable) {
3222 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3223 }
3224 return error;
3225}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003226
ossue280cde2016-10-12 11:04:10 -07003227int Channel::GetRtpTimestampRateHz() const {
3228 const auto format = audio_coding_->ReceiveFormat();
3229 // Default to the playout frequency if we've not gotten any packets yet.
3230 // TODO(ossu): Zero clockrate can only happen if we've added an external
3231 // decoder for a format we don't support internally. Remove once that way of
3232 // adding decoders is gone!
3233 return (format && format->clockrate_hz != 0)
3234 ? format->clockrate_hz
3235 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00003236}
3237
Minyue2013aec2015-05-13 14:14:42 +02003238int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003239 RtcpMode method = _rtpRtcpModule->RTCP();
3240 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003241 return 0;
3242 }
3243 std::vector<RTCPReportBlock> report_blocks;
3244 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003245
3246 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003247 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003248 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003249 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003250 Channel* channel = associate_send_channel_.channel();
3251 // Tries to get RTT from an associated channel. This is important for
3252 // receive-only channels.
3253 if (channel) {
3254 // To prevent infinite recursion and deadlock, calling GetRTT of
3255 // associate channel should always use "false" for argument:
3256 // |allow_associate_channel|.
3257 rtt = channel->GetRTT(false);
3258 }
3259 }
3260 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003261 }
3262
3263 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3264 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3265 for (; it != report_blocks.end(); ++it) {
3266 if (it->remoteSSRC == remoteSSRC)
3267 break;
3268 }
3269 if (it == report_blocks.end()) {
3270 // We have not received packets with SSRC matching the report blocks.
3271 // To calculate RTT we try with the SSRC of the first report block.
3272 // This is very important for send-only channels where we don't know
3273 // the SSRC of the other end.
3274 remoteSSRC = report_blocks[0].remoteSSRC;
3275 }
Minyue2013aec2015-05-13 14:14:42 +02003276
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003277 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003278 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003279 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003280 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3281 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003282 return 0;
3283 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003284 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003285}
3286
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003287} // namespace voe
3288} // namespace webrtc