blob: 31242f6db935626a25bf0a95089c71a7d7337079 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
henrika@webrtc.org2919e952012-01-31 08:45:03 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000011#include "webrtc/voice_engine/channel.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Henrik Lundin64dad832015-05-11 12:44:23 +020013#include <algorithm>
Tommif888bb52015-12-12 01:37:01 +010014#include <utility>
Henrik Lundin64dad832015-05-11 12:44:23 +020015
aleloi6321b492016-12-05 01:46:09 -080016#include "webrtc/audio/utility/audio_frame_operations.h"
henrik.lundin50499422016-11-29 04:26:24 -080017#include "webrtc/base/array_view.h"
Ivo Creusenae856f22015-09-17 16:30:16 +020018#include "webrtc/base/checks.h"
tommi31fc21f2016-01-21 10:37:37 -080019#include "webrtc/base/criticalsection.h"
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +000020#include "webrtc/base/format_macros.h"
tommidea489f2017-03-03 03:20:24 -080021#include "webrtc/base/location.h"
pbosad856222015-11-27 09:48:36 -080022#include "webrtc/base/logging.h"
Erik Språng737336d2016-07-29 12:59:36 +020023#include "webrtc/base/rate_limiter.h"
wu@webrtc.org94454b72014-06-05 20:34:08 +000024#include "webrtc/base/timeutils.h"
nisseb8f9a322017-03-27 05:36:15 -070025#include "webrtc/call/rtp_transport_controller_send.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020026#include "webrtc/config.h"
skvladcc91d282016-10-03 18:31:22 -070027#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kwibergda2bf4e2016-10-24 13:47:09 -070028#include "webrtc/modules/audio_coding/codecs/audio_format_conversion.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000029#include "webrtc/modules/audio_device/include/audio_device.h"
30#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010031#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010032#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010033#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
34#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
35#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
nisse657bab22017-02-21 06:28:10 -080036#include "webrtc/modules/rtp_rtcp/source/rtp_packet_received.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000037#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010038#include "webrtc/modules/utility/include/process_thread.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010039#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000040#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
41#include "webrtc/voice_engine/output_mixer.h"
42#include "webrtc/voice_engine/statistics.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000043#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 {
philipel32d00102017-02-27 02:18:46 -0800111 LogRtpHeader(direction, media_type, header, packet_length,
112 PacedPacketInfo::kNotAProbe);
113 }
114
115 void LogRtpHeader(webrtc::PacketDirection direction,
116 webrtc::MediaType media_type,
117 const uint8_t* header,
118 size_t packet_length,
119 int probe_cluster_id) override {
ivoc14d5dbe2016-07-04 07:06:55 -0700120 rtc::CritScope lock(&crit_);
121 if (event_log_) {
philipel32d00102017-02-27 02:18:46 -0800122 event_log_->LogRtpHeader(direction, media_type, header, packet_length,
123 probe_cluster_id);
ivoc14d5dbe2016-07-04 07:06:55 -0700124 }
125 }
126
127 void LogRtcpPacket(webrtc::PacketDirection direction,
128 webrtc::MediaType media_type,
129 const uint8_t* packet,
130 size_t length) override {
131 rtc::CritScope lock(&crit_);
132 if (event_log_) {
133 event_log_->LogRtcpPacket(direction, media_type, packet, length);
134 }
135 }
136
137 void LogAudioPlayout(uint32_t ssrc) override {
138 rtc::CritScope lock(&crit_);
139 if (event_log_) {
140 event_log_->LogAudioPlayout(ssrc);
141 }
142 }
143
terelius424e6cf2017-02-20 05:14:41 -0800144 void LogLossBasedBweUpdate(int32_t bitrate_bps,
ivoc14d5dbe2016-07-04 07:06:55 -0700145 uint8_t fraction_loss,
146 int32_t total_packets) override {
147 rtc::CritScope lock(&crit_);
148 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800149 event_log_->LogLossBasedBweUpdate(bitrate_bps, fraction_loss,
150 total_packets);
ivoc14d5dbe2016-07-04 07:06:55 -0700151 }
152 }
153
terelius424e6cf2017-02-20 05:14:41 -0800154 void LogDelayBasedBweUpdate(int32_t bitrate_bps,
terelius0baf55d2017-02-17 03:38:28 -0800155 BandwidthUsage detector_state) override {
156 rtc::CritScope lock(&crit_);
157 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800158 event_log_->LogDelayBasedBweUpdate(bitrate_bps, detector_state);
terelius0baf55d2017-02-17 03:38:28 -0800159 }
160 }
161
minyue4b7c9522017-01-24 04:54:59 -0800162 void LogAudioNetworkAdaptation(
163 const AudioNetworkAdaptor::EncoderRuntimeConfig& config) override {
164 rtc::CritScope lock(&crit_);
165 if (event_log_) {
166 event_log_->LogAudioNetworkAdaptation(config);
167 }
168 }
169
philipel32d00102017-02-27 02:18:46 -0800170 void LogProbeClusterCreated(int id,
171 int bitrate_bps,
172 int min_probes,
173 int min_bytes) override {
174 rtc::CritScope lock(&crit_);
175 if (event_log_) {
176 event_log_->LogProbeClusterCreated(id, bitrate_bps, min_probes,
177 min_bytes);
178 }
179 };
180
181 void LogProbeResultSuccess(int id, int bitrate_bps) override {
182 rtc::CritScope lock(&crit_);
183 if (event_log_) {
184 event_log_->LogProbeResultSuccess(id, bitrate_bps);
185 }
186 };
187
188 void LogProbeResultFailure(int id,
189 ProbeFailureReason failure_reason) override {
190 rtc::CritScope lock(&crit_);
191 if (event_log_) {
192 event_log_->LogProbeResultFailure(id, failure_reason);
193 }
194 };
195
ivoc14d5dbe2016-07-04 07:06:55 -0700196 void SetEventLog(RtcEventLog* event_log) {
197 rtc::CritScope lock(&crit_);
198 event_log_ = event_log;
199 }
200
201 private:
202 rtc::CriticalSection crit_;
203 RtcEventLog* event_log_ GUARDED_BY(crit_);
204 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
205};
206
michaelt9332b7d2016-11-30 07:51:13 -0800207class RtcpRttStatsProxy final : public RtcpRttStats {
208 public:
209 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
210
211 void OnRttUpdate(int64_t rtt) override {
212 rtc::CritScope lock(&crit_);
213 if (rtcp_rtt_stats_)
214 rtcp_rtt_stats_->OnRttUpdate(rtt);
215 }
216
217 int64_t LastProcessedRtt() const override {
218 rtc::CritScope lock(&crit_);
219 if (!rtcp_rtt_stats_)
220 return 0;
221 return rtcp_rtt_stats_->LastProcessedRtt();
222 }
223
224 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
225 rtc::CritScope lock(&crit_);
226 rtcp_rtt_stats_ = rtcp_rtt_stats;
227 }
228
229 private:
230 rtc::CriticalSection crit_;
231 RtcpRttStats* rtcp_rtt_stats_ GUARDED_BY(crit_);
232 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
233};
234
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100235class TransportFeedbackProxy : public TransportFeedbackObserver {
236 public:
237 TransportFeedbackProxy() : feedback_observer_(nullptr) {
238 pacer_thread_.DetachFromThread();
239 network_thread_.DetachFromThread();
240 }
241
242 void SetTransportFeedbackObserver(
243 TransportFeedbackObserver* feedback_observer) {
244 RTC_DCHECK(thread_checker_.CalledOnValidThread());
245 rtc::CritScope lock(&crit_);
246 feedback_observer_ = feedback_observer;
247 }
248
249 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700250 void AddPacket(uint32_t ssrc,
251 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100252 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800253 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100254 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
255 rtc::CritScope lock(&crit_);
256 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700257 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100258 }
philipel8aadd502017-02-23 02:56:13 -0800259
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100260 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
261 RTC_DCHECK(network_thread_.CalledOnValidThread());
262 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700263 if (feedback_observer_)
264 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200265 }
elad.alonf9490002017-03-06 05:32:21 -0800266 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200267 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800268 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100269 }
270
271 private:
272 rtc::CriticalSection crit_;
273 rtc::ThreadChecker thread_checker_;
274 rtc::ThreadChecker pacer_thread_;
275 rtc::ThreadChecker network_thread_;
276 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
277};
278
279class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
280 public:
281 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
282 pacer_thread_.DetachFromThread();
283 }
284
285 void SetSequenceNumberAllocator(
286 TransportSequenceNumberAllocator* seq_num_allocator) {
287 RTC_DCHECK(thread_checker_.CalledOnValidThread());
288 rtc::CritScope lock(&crit_);
289 seq_num_allocator_ = seq_num_allocator;
290 }
291
292 // Implements TransportSequenceNumberAllocator.
293 uint16_t AllocateSequenceNumber() override {
294 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
295 rtc::CritScope lock(&crit_);
296 if (!seq_num_allocator_)
297 return 0;
298 return seq_num_allocator_->AllocateSequenceNumber();
299 }
300
301 private:
302 rtc::CriticalSection crit_;
303 rtc::ThreadChecker thread_checker_;
304 rtc::ThreadChecker pacer_thread_;
305 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
306};
307
308class RtpPacketSenderProxy : public RtpPacketSender {
309 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800310 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100311
312 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
313 RTC_DCHECK(thread_checker_.CalledOnValidThread());
314 rtc::CritScope lock(&crit_);
315 rtp_packet_sender_ = rtp_packet_sender;
316 }
317
318 // Implements RtpPacketSender.
319 void InsertPacket(Priority priority,
320 uint32_t ssrc,
321 uint16_t sequence_number,
322 int64_t capture_time_ms,
323 size_t bytes,
324 bool retransmission) override {
325 rtc::CritScope lock(&crit_);
326 if (rtp_packet_sender_) {
327 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
328 capture_time_ms, bytes, retransmission);
329 }
330 }
331
332 private:
333 rtc::ThreadChecker thread_checker_;
334 rtc::CriticalSection crit_;
335 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
336};
337
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000338class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000339 public:
stefan7de8d642017-02-07 07:14:08 -0800340 explicit VoERtcpObserver(Channel* owner)
341 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000342 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000343
stefan7de8d642017-02-07 07:14:08 -0800344 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
345 rtc::CritScope lock(&crit_);
346 bandwidth_observer_ = bandwidth_observer;
347 }
348
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000349 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800350 rtc::CritScope lock(&crit_);
351 if (bandwidth_observer_) {
352 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
353 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000354 }
355
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000356 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
357 int64_t rtt,
358 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800359 {
360 rtc::CritScope lock(&crit_);
361 if (bandwidth_observer_) {
362 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
363 now_ms);
364 }
365 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000366 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
367 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
368 // report for VoiceEngine?
369 if (report_blocks.empty())
370 return;
371
372 int fraction_lost_aggregate = 0;
373 int total_number_of_packets = 0;
374
375 // If receiving multiple report blocks, calculate the weighted average based
376 // on the number of packets a report refers to.
377 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
378 block_it != report_blocks.end(); ++block_it) {
379 // Find the previous extended high sequence number for this remote SSRC,
380 // to calculate the number of RTP packets this report refers to. Ignore if
381 // we haven't seen this SSRC before.
382 std::map<uint32_t, uint32_t>::iterator seq_num_it =
383 extended_max_sequence_number_.find(block_it->sourceSSRC);
384 int number_of_packets = 0;
385 if (seq_num_it != extended_max_sequence_number_.end()) {
386 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
387 }
388 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
389 total_number_of_packets += number_of_packets;
390
391 extended_max_sequence_number_[block_it->sourceSSRC] =
392 block_it->extendedHighSeqNum;
393 }
394 int weighted_fraction_lost = 0;
395 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800396 weighted_fraction_lost =
397 (fraction_lost_aggregate + total_number_of_packets / 2) /
398 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000399 }
elad.alond12a8e12017-03-23 11:04:48 -0700400 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000401 }
402
403 private:
404 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000405 // Maps remote side ssrc to extended highest sequence number received.
406 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800407 rtc::CriticalSection crit_;
408 RtcpBandwidthObserver* bandwidth_observer_ GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000409};
410
kwiberg55b97fe2016-01-28 05:22:45 -0800411int32_t Channel::SendData(FrameType frameType,
412 uint8_t payloadType,
413 uint32_t timeStamp,
414 const uint8_t* payloadData,
415 size_t payloadSize,
416 const RTPFragmentationHeader* fragmentation) {
417 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
418 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
419 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
420 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000421
kwiberg55b97fe2016-01-28 05:22:45 -0800422 if (_includeAudioLevelIndication) {
423 // Store current audio level in the RTP/RTCP module.
424 // The level will be used in combination with voice-activity state
425 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800426 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800427 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000428
kwiberg55b97fe2016-01-28 05:22:45 -0800429 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
430 // packetization.
431 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700432 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800433 (FrameType&)frameType, payloadType, timeStamp,
434 // Leaving the time when this frame was
435 // received from the capture device as
436 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700437 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800438 _engineStatisticsPtr->SetLastError(
439 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
440 "Channel::SendData() failed to send data to RTP/RTCP module");
441 return -1;
442 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000443
kwiberg55b97fe2016-01-28 05:22:45 -0800444 _lastLocalTimeStamp = timeStamp;
445 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000446
kwiberg55b97fe2016-01-28 05:22:45 -0800447 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000448}
449
stefan1d8a5062015-10-02 03:39:33 -0700450bool Channel::SendRtp(const uint8_t* data,
451 size_t len,
452 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800453 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
454 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000455
kwiberg55b97fe2016-01-28 05:22:45 -0800456 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000457
kwiberg55b97fe2016-01-28 05:22:45 -0800458 if (_transportPtr == NULL) {
459 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
460 "Channel::SendPacket() failed to send RTP packet due to"
461 " invalid transport object");
462 return false;
463 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000464
kwiberg55b97fe2016-01-28 05:22:45 -0800465 uint8_t* bufferToSendPtr = (uint8_t*)data;
466 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000467
kwiberg55b97fe2016-01-28 05:22:45 -0800468 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
469 std::string transport_name =
470 _externalTransport ? "external transport" : "WebRtc sockets";
471 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
472 "Channel::SendPacket() RTP transmission using %s failed",
473 transport_name.c_str());
474 return false;
475 }
476 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000477}
478
kwiberg55b97fe2016-01-28 05:22:45 -0800479bool Channel::SendRtcp(const uint8_t* data, size_t len) {
480 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
481 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000482
kwiberg55b97fe2016-01-28 05:22:45 -0800483 rtc::CritScope cs(&_callbackCritSect);
484 if (_transportPtr == NULL) {
485 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
486 "Channel::SendRtcp() failed to send RTCP packet"
487 " due to invalid transport object");
488 return false;
489 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000490
kwiberg55b97fe2016-01-28 05:22:45 -0800491 uint8_t* bufferToSendPtr = (uint8_t*)data;
492 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000493
kwiberg55b97fe2016-01-28 05:22:45 -0800494 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
495 if (n < 0) {
496 std::string transport_name =
497 _externalTransport ? "external transport" : "WebRtc sockets";
498 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
499 "Channel::SendRtcp() transmission using %s failed",
500 transport_name.c_str());
501 return false;
502 }
503 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000504}
505
kwiberg55b97fe2016-01-28 05:22:45 -0800506void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
507 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
508 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000509
kwiberg55b97fe2016-01-28 05:22:45 -0800510 // Update ssrc so that NTP for AV sync can be updated.
511 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000512}
513
Peter Boströmac547a62015-09-17 23:03:57 +0200514void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
515 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
516 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
517 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000518}
519
Peter Boströmac547a62015-09-17 23:03:57 +0200520int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000521 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000522 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000523 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800524 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200525 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800526 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
527 "Channel::OnInitializeDecoder(payloadType=%d, "
528 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
529 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000530
kwiberg55b97fe2016-01-28 05:22:45 -0800531 CodecInst receiveCodec = {0};
532 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000533
kwiberg55b97fe2016-01-28 05:22:45 -0800534 receiveCodec.pltype = payloadType;
535 receiveCodec.plfreq = frequency;
536 receiveCodec.channels = channels;
537 receiveCodec.rate = rate;
538 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000539
kwiberg55b97fe2016-01-28 05:22:45 -0800540 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
541 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000542
kwiberg55b97fe2016-01-28 05:22:45 -0800543 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700544 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
545 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800546 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
547 "Channel::OnInitializeDecoder() invalid codec ("
548 "pt=%d, name=%s) received - 1",
549 payloadType, payloadName);
550 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
551 return -1;
552 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000553
kwiberg55b97fe2016-01-28 05:22:45 -0800554 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000555}
556
kwiberg55b97fe2016-01-28 05:22:45 -0800557int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
558 size_t payloadSize,
559 const WebRtcRTPHeader* rtpHeader) {
560 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
561 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
562 ","
563 " payloadType=%u, audioChannel=%" PRIuS ")",
564 payloadSize, rtpHeader->header.payloadType,
565 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000566
kwiberg55b97fe2016-01-28 05:22:45 -0800567 if (!channel_state_.Get().playing) {
568 // Avoid inserting into NetEQ when we are not playing. Count the
569 // packet as discarded.
570 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
571 "received packet is discarded since playing is not"
572 " activated");
niklase@google.com470e71d2011-07-07 08:21:25 +0000573 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800574 }
575
576 // Push the incoming payload (parsed and ready for decoding) into the ACM
577 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
578 0) {
579 _engineStatisticsPtr->SetLastError(
580 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
581 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
582 return -1;
583 }
584
kwiberg55b97fe2016-01-28 05:22:45 -0800585 int64_t round_trip_time = 0;
586 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
587 NULL);
588
589 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
590 if (!nack_list.empty()) {
591 // Can't use nack_list.data() since it's not supported by all
592 // compilers.
593 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
594 }
595 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000596}
597
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000598bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000599 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000600 RTPHeader header;
601 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
602 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
603 "IncomingPacket invalid RTP header");
604 return false;
605 }
606 header.payload_type_frequency =
607 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
608 if (header.payload_type_frequency < 0)
609 return false;
610 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
611}
612
henrik.lundin42dda502016-05-18 05:36:01 -0700613MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
614 int32_t id,
615 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700616 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800617 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700618 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800619 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700620 bool muted;
621 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
622 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800623 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
624 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
625 // In all likelihood, the audio in this frame is garbage. We return an
626 // error so that the audio mixer module doesn't add it to the mix. As
627 // a result, it won't be played out and the actions skipped here are
628 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700629 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800630 }
henrik.lundina89ab962016-05-18 08:52:45 -0700631
632 if (muted) {
633 // TODO(henrik.lundin): We should be able to do better than this. But we
634 // will have to go through all the cases below where the audio samples may
635 // be used, and handle the muted case in some way.
aleloi6321b492016-12-05 01:46:09 -0800636 AudioFrameOperations::Mute(audioFrame);
henrik.lundina89ab962016-05-18 08:52:45 -0700637 }
kwiberg55b97fe2016-01-28 05:22:45 -0800638
kwiberg55b97fe2016-01-28 05:22:45 -0800639 // Convert module ID to internal VoE channel ID
640 audioFrame->id_ = VoEChannelId(audioFrame->id_);
641 // Store speech type for dead-or-alive detection
642 _outputSpeechType = audioFrame->speech_type_;
643
644 ChannelState::State state = channel_state_.Get();
645
kwiberg55b97fe2016-01-28 05:22:45 -0800646 {
647 // Pass the audio buffers to an optional sink callback, before applying
648 // scaling/panning, as that applies to the mix operation.
649 // External recipients of the audio (e.g. via AudioTrack), will do their
650 // own mixing/dynamic processing.
651 rtc::CritScope cs(&_callbackCritSect);
652 if (audio_sink_) {
653 AudioSinkInterface::Data data(
654 &audioFrame->data_[0], audioFrame->samples_per_channel_,
655 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
656 audioFrame->timestamp_);
657 audio_sink_->OnData(data);
658 }
659 }
660
661 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800662 {
663 rtc::CritScope cs(&volume_settings_critsect_);
664 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800665 }
666
667 // Output volume scaling
668 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800669 // TODO(solenberg): Combine with mute state - this can cause clicks!
oprypin67fdb802017-03-09 06:25:06 -0800670 AudioFrameOperations::ScaleWithSat(output_gain, audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800671 }
672
kwiberg55b97fe2016-01-28 05:22:45 -0800673 // 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
kwiberg55b97fe2016-01-28 05:22:45 -0800679 // Record playout if enabled
680 {
681 rtc::CritScope cs(&_fileCritSect);
682
kwiberg5a25d952016-08-17 07:31:12 -0700683 if (_outputFileRecording && output_file_recorder_) {
684 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800685 }
686 }
687
688 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700689 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800690 _outputAudioLevel.ComputeLevel(*audioFrame);
691
692 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
693 // The first frame with a valid rtp timestamp.
694 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
695 }
696
697 if (capture_start_rtp_time_stamp_ >= 0) {
698 // audioFrame.timestamp_ should be valid from now on.
699
700 // Compute elapsed time.
701 int64_t unwrap_timestamp =
702 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
703 audioFrame->elapsed_time_ms_ =
704 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700705 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800706
niklase@google.com470e71d2011-07-07 08:21:25 +0000707 {
kwiberg55b97fe2016-01-28 05:22:45 -0800708 rtc::CritScope lock(&ts_stats_lock_);
709 // Compute ntp time.
710 audioFrame->ntp_time_ms_ =
711 ntp_estimator_.Estimate(audioFrame->timestamp_);
712 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
713 if (audioFrame->ntp_time_ms_ > 0) {
714 // Compute |capture_start_ntp_time_ms_| so that
715 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
716 capture_start_ntp_time_ms_ =
717 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000718 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000719 }
kwiberg55b97fe2016-01-28 05:22:45 -0800720 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000721
henrik.lundin42dda502016-05-18 05:36:01 -0700722 return muted ? MixerParticipant::AudioFrameInfo::kMuted
723 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000724}
725
aleloi6c278492016-10-20 14:24:39 -0700726AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
727 int sample_rate_hz,
728 AudioFrame* audio_frame) {
729 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700730
aleloi6c278492016-10-20 14:24:39 -0700731 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700732
733 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
734 FrameInfo new_audio_frame_info = FrameInfo::kError;
735 switch (frame_info) {
736 case MixerParticipant::AudioFrameInfo::kNormal:
737 new_audio_frame_info = FrameInfo::kNormal;
738 break;
739 case MixerParticipant::AudioFrameInfo::kMuted:
740 new_audio_frame_info = FrameInfo::kMuted;
741 break;
742 case MixerParticipant::AudioFrameInfo::kError:
743 new_audio_frame_info = FrameInfo::kError;
744 break;
745 }
aleloi6c278492016-10-20 14:24:39 -0700746 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700747}
748
kwiberg55b97fe2016-01-28 05:22:45 -0800749int32_t Channel::NeededFrequency(int32_t id) const {
750 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
751 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000752
kwiberg55b97fe2016-01-28 05:22:45 -0800753 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000754
kwiberg55b97fe2016-01-28 05:22:45 -0800755 // Determine highest needed receive frequency
756 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000757
kwiberg55b97fe2016-01-28 05:22:45 -0800758 // Return the bigger of playout and receive frequency in the ACM.
759 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
760 highestNeeded = audio_coding_->PlayoutFrequency();
761 } else {
762 highestNeeded = receiveFrequency;
763 }
764
765 // Special case, if we're playing a file on the playout side
766 // we take that frequency into consideration as well
767 // This is not needed on sending side, since the codec will
768 // limit the spectrum anyway.
769 if (channel_state_.Get().output_file_playing) {
770 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700771 if (output_file_player_) {
772 if (output_file_player_->Frequency() > highestNeeded) {
773 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800774 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000775 }
kwiberg55b97fe2016-01-28 05:22:45 -0800776 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000777
kwiberg55b97fe2016-01-28 05:22:45 -0800778 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000779}
780
ossu5f7cfa52016-05-30 08:11:28 -0700781int32_t Channel::CreateChannel(
782 Channel*& channel,
783 int32_t channelId,
784 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700785 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800786 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
787 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
788 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000789
solenberg88499ec2016-09-07 07:34:41 -0700790 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800791 if (channel == NULL) {
792 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
793 "Channel::CreateChannel() unable to allocate memory for"
794 " channel");
795 return -1;
796 }
797 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000798}
799
kwiberg55b97fe2016-01-28 05:22:45 -0800800void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
801 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
802 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
803 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000804
kwiberg55b97fe2016-01-28 05:22:45 -0800805 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000806}
807
kwiberg55b97fe2016-01-28 05:22:45 -0800808void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
809 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
810 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
811 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000812
kwiberg55b97fe2016-01-28 05:22:45 -0800813 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000814}
815
kwiberg55b97fe2016-01-28 05:22:45 -0800816void Channel::PlayFileEnded(int32_t id) {
817 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
818 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000819
kwiberg55b97fe2016-01-28 05:22:45 -0800820 if (id == _inputFilePlayerId) {
821 channel_state_.SetInputFilePlaying(false);
822 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
823 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000824 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800825 } else if (id == _outputFilePlayerId) {
826 channel_state_.SetOutputFilePlaying(false);
827 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
828 "Channel::PlayFileEnded() => output file player module is"
829 " shutdown");
830 }
831}
832
833void Channel::RecordFileEnded(int32_t id) {
834 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
835 "Channel::RecordFileEnded(id=%d)", id);
836
837 assert(id == _outputFileRecorderId);
838
839 rtc::CritScope cs(&_fileCritSect);
840
841 _outputFileRecording = false;
842 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
843 "Channel::RecordFileEnded() => output file recorder module is"
844 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000845}
846
pbos@webrtc.org92135212013-05-14 08:31:39 +0000847Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000848 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700849 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800850 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100851 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700852 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800853 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100854 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800855 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100856 rtp_receive_statistics_(
857 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
858 rtp_receiver_(
859 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100860 this,
861 this,
862 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700863 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100864 _outputAudioLevel(),
865 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100866 // Avoid conflict with other channels by adding 1024 - 1026,
867 // won't use as much as 1024 channels.
868 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
869 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
870 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
871 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100872 _timeStamp(0), // This is just an offset, RTP module will add it's own
873 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100874 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100875 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100876 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100877 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100878 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
879 capture_start_rtp_time_stamp_(-1),
880 capture_start_ntp_time_ms_(-1),
881 _engineStatisticsPtr(NULL),
882 _outputMixerPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100883 _moduleProcessThreadPtr(NULL),
884 _audioDeviceModulePtr(NULL),
885 _voiceEngineObserverPtr(NULL),
886 _callbackCritSectPtr(NULL),
887 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700888 input_mute_(false),
889 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100890 _outputGain(1.0f),
solenberg8d73f8c2017-03-08 01:52:20 -0800891 _mixFileWithMicrophone(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100892 _lastLocalTimeStamp(0),
893 _lastPayloadType(0),
894 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800895 transport_overhead_per_packet_(0),
896 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100897 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100898 restored_packet_in_use_(false),
899 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100900 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700901 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800902 feedback_observer_proxy_(new TransportFeedbackProxy()),
903 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700904 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200905 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
906 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700907 decoder_factory_(config.acm_config.decoder_factory),
908 // TODO(elad.alon): Subsequent CL experiments with PLR source.
909 use_twcc_plr_for_ana_(false) {
kwiberg55b97fe2016-01-28 05:22:45 -0800910 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
911 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700912 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800913 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700914 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800915 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200916
kwiberg55b97fe2016-01-28 05:22:45 -0800917 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000918
kwiberg55b97fe2016-01-28 05:22:45 -0800919 RtpRtcp::Configuration configuration;
920 configuration.audio = true;
921 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800922 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800923 configuration.receive_statistics = rtp_receive_statistics_.get();
924 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800925 if (pacing_enabled_) {
926 configuration.paced_sender = rtp_packet_sender_proxy_.get();
927 configuration.transport_sequence_number_allocator =
928 seq_num_allocator_proxy_.get();
929 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
930 }
ivoc14d5dbe2016-07-04 07:06:55 -0700931 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800932 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200933 configuration.retransmission_rate_limiter =
934 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000935
kwiberg55b97fe2016-01-28 05:22:45 -0800936 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100937 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000938}
939
kwiberg55b97fe2016-01-28 05:22:45 -0800940Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700941 RTC_DCHECK(!channel_state_.Get().sending);
942 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000943}
944
kwiberg55b97fe2016-01-28 05:22:45 -0800945int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700946 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800947 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
948 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000949
kwiberg55b97fe2016-01-28 05:22:45 -0800950 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000951
kwiberg55b97fe2016-01-28 05:22:45 -0800952 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000953
kwiberg55b97fe2016-01-28 05:22:45 -0800954 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
955 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
956 "Channel::Init() must call SetEngineInformation() first");
957 return -1;
958 }
959
960 // --- Add modules to process thread (for periodic schedulation)
961
tommidea489f2017-03-03 03:20:24 -0800962 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800963
964 // --- ACM initialization
965
966 if (audio_coding_->InitializeReceiver() == -1) {
967 _engineStatisticsPtr->SetLastError(
968 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
969 "Channel::Init() unable to initialize the ACM - 1");
970 return -1;
971 }
972
973 // --- RTP/RTCP module initialization
974
975 // Ensure that RTCP is enabled by default for the created channel.
976 // Note that, the module will keep generating RTCP until it is explicitly
977 // disabled by the user.
978 // After StopListen (when no sockets exists), RTCP packets will no longer
979 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700980 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800981 // RTCP is enabled by default.
982 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
983 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800984 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800985 _engineStatisticsPtr->SetLastError(
986 VE_CANNOT_INIT_CHANNEL, kTraceError,
987 "Channel::Init() callbacks not registered");
988 return -1;
989 }
990
kwiberg1c07c702017-03-27 07:15:49 -0700991 // Register a default set of send codecs.
992 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -0800993 for (int idx = 0; idx < nSupportedCodecs; idx++) {
kwiberg1c07c702017-03-27 07:15:49 -0700994 CodecInst codec;
995 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
996
997 // Ensure that PCMU is used as default send codec.
998 if (STR_CASE_CMP(codec.plname, "PCMU") == 0 && codec.channels == 1) {
999 SetSendCodec(codec);
1000 }
1001
1002 // Register default PT for 'telephone-event'
1003 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
1004 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1) {
1005 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1006 "Channel::Init() failed to register outband "
1007 "'telephone-event' (%d/%d) correctly",
1008 codec.pltype, codec.plfreq);
1009 }
1010 }
1011
1012 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
1013 if (!codec_manager_.RegisterEncoder(codec) ||
1014 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
1015 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
1016 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1017 "Channel::Init() failed to register CN (%d/%d) "
1018 "correctly - 1",
1019 codec.pltype, codec.plfreq);
1020 }
1021 }
1022 }
1023
1024 return 0;
1025}
1026
1027void Channel::RegisterLegacyReceiveCodecs() {
1028 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1029 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1030 CodecInst codec;
1031 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
1032
kwiberg55b97fe2016-01-28 05:22:45 -08001033 // Open up the RTP/RTCP receiver for all supported codecs
kwiberg1c07c702017-03-27 07:15:49 -07001034 if (rtp_receiver_->RegisterReceivePayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001035 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1036 "Channel::Init() unable to register %s "
1037 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1038 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1039 codec.rate);
1040 } else {
1041 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1042 "Channel::Init() %s (%d/%d/%" PRIuS
1043 "/%d) has been "
1044 "added to the RTP/RTCP receiver",
1045 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1046 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001047 }
1048
kwiberg1c07c702017-03-27 07:15:49 -07001049 // Register default PT for 'telephone-event'
1050 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
1051 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
kwibergda2bf4e2016-10-24 13:47:09 -07001052 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001053 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
kwiberg1c07c702017-03-27 07:15:49 -07001054 "Channel::Init() failed to register inband "
kwiberg55b97fe2016-01-28 05:22:45 -08001055 "'telephone-event' (%d/%d) correctly",
1056 codec.pltype, codec.plfreq);
1057 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001058 }
1059
kwiberg1c07c702017-03-27 07:15:49 -07001060 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
1061 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1062 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001063 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1064 "Channel::Init() failed to register CN (%d/%d) "
1065 "correctly - 1",
1066 codec.pltype, codec.plfreq);
1067 }
1068 }
kwiberg55b97fe2016-01-28 05:22:45 -08001069 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001070}
1071
tommi0a2391f2017-03-21 02:31:51 -07001072void Channel::Terminate() {
1073 RTC_DCHECK(construction_thread_.CalledOnValidThread());
1074 // Must be called on the same thread as Init().
1075 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
1076 "Channel::Terminate");
1077
1078 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
1079
1080 StopSend();
1081 StopPlayout();
1082
1083 {
1084 rtc::CritScope cs(&_fileCritSect);
1085 if (input_file_player_) {
1086 input_file_player_->RegisterModuleFileCallback(NULL);
1087 input_file_player_->StopPlayingFile();
1088 }
1089 if (output_file_player_) {
1090 output_file_player_->RegisterModuleFileCallback(NULL);
1091 output_file_player_->StopPlayingFile();
1092 }
1093 if (output_file_recorder_) {
1094 output_file_recorder_->RegisterModuleFileCallback(NULL);
1095 output_file_recorder_->StopRecording();
1096 }
1097 }
1098
1099 // The order to safely shutdown modules in a channel is:
1100 // 1. De-register callbacks in modules
1101 // 2. De-register modules in process thread
1102 // 3. Destroy modules
1103 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1104 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1105 "Terminate() failed to de-register transport callback"
1106 " (Audio coding module)");
1107 }
1108
1109 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1110 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1111 "Terminate() failed to de-register VAD callback"
1112 " (Audio coding module)");
1113 }
1114
1115 // De-register modules in process thread
1116 if (_moduleProcessThreadPtr)
1117 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
1118
1119 // End of modules shutdown
1120}
1121
kwiberg55b97fe2016-01-28 05:22:45 -08001122int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1123 OutputMixer& outputMixer,
kwiberg55b97fe2016-01-28 05:22:45 -08001124 ProcessThread& moduleProcessThread,
1125 AudioDeviceModule& audioDeviceModule,
1126 VoiceEngineObserver* voiceEngineObserver,
1127 rtc::CriticalSection* callbackCritSect) {
1128 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1129 "Channel::SetEngineInformation()");
1130 _engineStatisticsPtr = &engineStatistics;
1131 _outputMixerPtr = &outputMixer;
kwiberg55b97fe2016-01-28 05:22:45 -08001132 _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
solenberge374e012017-02-14 04:55:00 -08001161 // Add participant as candidates for mixing.
1162 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1163 _engineStatisticsPtr->SetLastError(
1164 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1165 "StartPlayout() failed to add participant to mixer");
1166 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001167 }
1168
1169 channel_state_.SetPlaying(true);
1170 if (RegisterFilePlayingToMixer() != 0)
1171 return -1;
1172
1173 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001174}
1175
kwiberg55b97fe2016-01-28 05:22:45 -08001176int32_t Channel::StopPlayout() {
1177 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1178 "Channel::StopPlayout()");
1179 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001180 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001181 }
1182
solenberge374e012017-02-14 04:55:00 -08001183 // Remove participant as candidates for mixing
1184 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1185 _engineStatisticsPtr->SetLastError(
1186 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1187 "StopPlayout() failed to remove participant from mixer");
1188 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001189 }
1190
1191 channel_state_.SetPlaying(false);
1192 _outputAudioLevel.Clear();
1193
1194 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001195}
1196
kwiberg55b97fe2016-01-28 05:22:45 -08001197int32_t Channel::StartSend() {
1198 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1199 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -08001200 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001201 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001202 }
1203 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001204
solenberg08b19df2017-02-15 00:42:31 -08001205 // Resume the previous sequence number which was reset by StopSend(). This
1206 // needs to be done before |sending| is set to true on the RTP/RTCP module.
1207 if (send_sequence_number_) {
1208 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
1209 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001210 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001211 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1212 _engineStatisticsPtr->SetLastError(
1213 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1214 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001215 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001216 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001217 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001218 return -1;
1219 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001220
kwiberg55b97fe2016-01-28 05:22:45 -08001221 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001222}
1223
kwiberg55b97fe2016-01-28 05:22:45 -08001224int32_t Channel::StopSend() {
1225 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1226 "Channel::StopSend()");
1227 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001228 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001229 }
1230 channel_state_.SetSending(false);
1231
1232 // Store the sequence number to be able to pick up the same sequence for
1233 // the next StartSend(). This is needed for restarting device, otherwise
1234 // it might cause libSRTP to complain about packets being replayed.
1235 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1236 // CL is landed. See issue
1237 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1238 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1239
1240 // Reset sending SSRC and sequence number and triggers direct transmission
1241 // of RTCP BYE
1242 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1243 _engineStatisticsPtr->SetLastError(
1244 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1245 "StartSend() RTP/RTCP failed to stop sending");
1246 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001247 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001248
1249 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001250}
1251
kwiberg55b97fe2016-01-28 05:22:45 -08001252int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1253 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1254 "Channel::RegisterVoiceEngineObserver()");
1255 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001256
kwiberg55b97fe2016-01-28 05:22:45 -08001257 if (_voiceEngineObserverPtr) {
1258 _engineStatisticsPtr->SetLastError(
1259 VE_INVALID_OPERATION, kTraceError,
1260 "RegisterVoiceEngineObserver() observer already enabled");
1261 return -1;
1262 }
1263 _voiceEngineObserverPtr = &observer;
1264 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001265}
1266
kwiberg55b97fe2016-01-28 05:22:45 -08001267int32_t Channel::DeRegisterVoiceEngineObserver() {
1268 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1269 "Channel::DeRegisterVoiceEngineObserver()");
1270 rtc::CritScope cs(&_callbackCritSect);
1271
1272 if (!_voiceEngineObserverPtr) {
1273 _engineStatisticsPtr->SetLastError(
1274 VE_INVALID_OPERATION, kTraceWarning,
1275 "DeRegisterVoiceEngineObserver() observer already disabled");
1276 return 0;
1277 }
1278 _voiceEngineObserverPtr = NULL;
1279 return 0;
1280}
1281
1282int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001283 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001284 if (send_codec) {
1285 codec = *send_codec;
1286 return 0;
1287 }
1288 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001289}
1290
kwiberg55b97fe2016-01-28 05:22:45 -08001291int32_t Channel::GetRecCodec(CodecInst& codec) {
1292 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001293}
1294
kwiberg55b97fe2016-01-28 05:22:45 -08001295int32_t Channel::SetSendCodec(const CodecInst& codec) {
1296 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1297 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001298
kwibergc8d071e2016-04-06 12:22:38 -07001299 if (!codec_manager_.RegisterEncoder(codec) ||
1300 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001301 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1302 "SetSendCodec() failed to register codec to ACM");
1303 return -1;
1304 }
1305
1306 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1307 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1308 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1309 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1310 "SetSendCodec() failed to register codec to"
1311 " RTP/RTCP module");
1312 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001313 }
kwiberg55b97fe2016-01-28 05:22:45 -08001314 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001315
kwiberg55b97fe2016-01-28 05:22:45 -08001316 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001317}
1318
minyue78b4d562016-11-30 04:47:39 -08001319void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001320 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1321 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001322 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001323 if (*encoder) {
1324 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001325 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001326 }
1327 });
michaelt566d8202017-01-12 10:17:38 -08001328 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001329}
1330
elad.alond12a8e12017-03-23 11:04:48 -07001331void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1332 if (!use_twcc_plr_for_ana_)
1333 return;
minyue7e304322016-10-12 05:00:55 -07001334 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001335 if (*encoder) {
1336 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1337 }
1338 });
1339}
1340
elad.alondadb4dc2017-03-23 15:29:50 -07001341void Channel::OnRecoverableUplinkPacketLossRate(
1342 float recoverable_packet_loss_rate) {
1343 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1344 if (*encoder) {
1345 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1346 recoverable_packet_loss_rate);
1347 }
1348 });
1349}
1350
elad.alond12a8e12017-03-23 11:04:48 -07001351void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1352 if (use_twcc_plr_for_ana_)
1353 return;
1354 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1355 if (*encoder) {
1356 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1357 }
minyue7e304322016-10-12 05:00:55 -07001358 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001359}
1360
kwiberg55b97fe2016-01-28 05:22:45 -08001361int32_t Channel::SetVADStatus(bool enableVAD,
1362 ACMVADMode mode,
1363 bool disableDTX) {
1364 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1365 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001366 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1367 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1368 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001369 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1370 kTraceError,
1371 "SetVADStatus() failed to set VAD");
1372 return -1;
1373 }
1374 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001375}
1376
kwiberg55b97fe2016-01-28 05:22:45 -08001377int32_t Channel::GetVADStatus(bool& enabledVAD,
1378 ACMVADMode& mode,
1379 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001380 const auto* params = codec_manager_.GetStackParams();
1381 enabledVAD = params->use_cng;
1382 mode = params->vad_mode;
1383 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001384 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001385}
1386
kwiberg1c07c702017-03-27 07:15:49 -07001387void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1388 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1389 audio_coding_->SetReceiveCodecs(codecs);
1390}
1391
kwiberg55b97fe2016-01-28 05:22:45 -08001392int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
kwibergd32bf752017-01-19 07:03:59 -08001393 return SetRecPayloadType(codec.pltype, CodecInstToSdp(codec));
1394}
1395
1396int32_t Channel::SetRecPayloadType(int payload_type,
1397 const SdpAudioFormat& format) {
kwiberg55b97fe2016-01-28 05:22:45 -08001398 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1399 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001400
kwiberg55b97fe2016-01-28 05:22:45 -08001401 if (channel_state_.Get().playing) {
1402 _engineStatisticsPtr->SetLastError(
1403 VE_ALREADY_PLAYING, kTraceError,
1404 "SetRecPayloadType() unable to set PT while playing");
1405 return -1;
1406 }
kwiberg55b97fe2016-01-28 05:22:45 -08001407
kwiberg09f090c2017-03-01 01:57:11 -08001408 const CodecInst codec = SdpToCodecInst(payload_type, format);
kwibergd32bf752017-01-19 07:03:59 -08001409
1410 if (payload_type == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001411 // De-register the selected codec (RTP/RTCP module and ACM)
1412
1413 int8_t pltype(-1);
1414 CodecInst rxCodec = codec;
1415
1416 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001417 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001418 rxCodec.pltype = pltype;
1419
1420 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1421 _engineStatisticsPtr->SetLastError(
1422 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1423 "SetRecPayloadType() RTP/RTCP-module deregistration "
1424 "failed");
1425 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001426 }
kwiberg55b97fe2016-01-28 05:22:45 -08001427 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1428 _engineStatisticsPtr->SetLastError(
1429 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1430 "SetRecPayloadType() ACM deregistration failed - 1");
1431 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001432 }
kwiberg55b97fe2016-01-28 05:22:45 -08001433 return 0;
1434 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001435
magjed56124bd2016-11-24 09:34:46 -08001436 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001437 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001438 // TODO(kwiberg): Retrying is probably not necessary, since
1439 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001440 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001441 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001442 _engineStatisticsPtr->SetLastError(
1443 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1444 "SetRecPayloadType() RTP/RTCP-module registration failed");
1445 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001446 }
kwiberg55b97fe2016-01-28 05:22:45 -08001447 }
kwibergd32bf752017-01-19 07:03:59 -08001448 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
1449 audio_coding_->UnregisterReceiveCodec(payload_type);
1450 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001451 _engineStatisticsPtr->SetLastError(
1452 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1453 "SetRecPayloadType() ACM registration failed - 1");
1454 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001455 }
kwiberg55b97fe2016-01-28 05:22:45 -08001456 }
1457 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001458}
1459
kwiberg55b97fe2016-01-28 05:22:45 -08001460int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1461 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001462 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001463 _engineStatisticsPtr->SetLastError(
1464 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1465 "GetRecPayloadType() failed to retrieve RX payload type");
1466 return -1;
1467 }
1468 codec.pltype = payloadType;
1469 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001470}
1471
kwiberg55b97fe2016-01-28 05:22:45 -08001472int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1473 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1474 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001475
kwiberg55b97fe2016-01-28 05:22:45 -08001476 CodecInst codec;
1477 int32_t samplingFreqHz(-1);
1478 const size_t kMono = 1;
1479 if (frequency == kFreq32000Hz)
1480 samplingFreqHz = 32000;
1481 else if (frequency == kFreq16000Hz)
1482 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001483
kwiberg55b97fe2016-01-28 05:22:45 -08001484 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1485 _engineStatisticsPtr->SetLastError(
1486 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1487 "SetSendCNPayloadType() failed to retrieve default CN codec "
1488 "settings");
1489 return -1;
1490 }
1491
1492 // Modify the payload type (must be set to dynamic range)
1493 codec.pltype = type;
1494
kwibergc8d071e2016-04-06 12:22:38 -07001495 if (!codec_manager_.RegisterEncoder(codec) ||
1496 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001497 _engineStatisticsPtr->SetLastError(
1498 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1499 "SetSendCNPayloadType() failed to register CN to ACM");
1500 return -1;
1501 }
1502
1503 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1504 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1505 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1506 _engineStatisticsPtr->SetLastError(
1507 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1508 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1509 "module");
1510 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001511 }
kwiberg55b97fe2016-01-28 05:22:45 -08001512 }
1513 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001514}
1515
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001516int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001517 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001518 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001519
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001520 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001521 _engineStatisticsPtr->SetLastError(
1522 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001523 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001524 return -1;
1525 }
1526 return 0;
1527}
1528
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001529int Channel::SetOpusDtx(bool enable_dtx) {
1530 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1531 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001532 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001533 : audio_coding_->DisableOpusDtx();
1534 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001535 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1536 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001537 return -1;
1538 }
1539 return 0;
1540}
1541
ivoc85228d62016-07-27 04:53:47 -07001542int Channel::GetOpusDtx(bool* enabled) {
1543 int success = -1;
1544 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1545 if (encoder) {
1546 *enabled = encoder->GetDtx();
1547 success = 0;
1548 }
1549 });
1550 return success;
1551}
1552
minyue7e304322016-10-12 05:00:55 -07001553bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1554 bool success = false;
1555 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1556 if (*encoder) {
1557 success = (*encoder)->EnableAudioNetworkAdaptor(
michaeltbf279fc2017-01-13 06:02:29 -08001558 config_string, event_log_proxy_.get(), Clock::GetRealTimeClock());
minyue7e304322016-10-12 05:00:55 -07001559 }
1560 });
1561 return success;
1562}
1563
1564void Channel::DisableAudioNetworkAdaptor() {
1565 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1566 if (*encoder)
1567 (*encoder)->DisableAudioNetworkAdaptor();
1568 });
1569}
1570
1571void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1572 int max_frame_length_ms) {
1573 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1574 if (*encoder) {
1575 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1576 max_frame_length_ms);
1577 }
1578 });
1579}
1580
mflodman3d7db262016-04-29 00:57:13 -07001581int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001582 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001583 "Channel::RegisterExternalTransport()");
1584
kwiberg55b97fe2016-01-28 05:22:45 -08001585 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001586 if (_externalTransport) {
1587 _engineStatisticsPtr->SetLastError(
1588 VE_INVALID_OPERATION, kTraceError,
1589 "RegisterExternalTransport() external transport already enabled");
1590 return -1;
1591 }
1592 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001593 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001594 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001595}
1596
kwiberg55b97fe2016-01-28 05:22:45 -08001597int32_t Channel::DeRegisterExternalTransport() {
1598 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1599 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001600
kwiberg55b97fe2016-01-28 05:22:45 -08001601 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001602 if (_transportPtr) {
1603 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1604 "DeRegisterExternalTransport() all transport is disabled");
1605 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001606 _engineStatisticsPtr->SetLastError(
1607 VE_INVALID_OPERATION, kTraceWarning,
1608 "DeRegisterExternalTransport() external transport already "
1609 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001610 }
1611 _externalTransport = false;
1612 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001613 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001614}
1615
nisse657bab22017-02-21 06:28:10 -08001616// TODO(nisse): Delete this method together with ReceivedRTPPacket.
1617// It's a temporary hack to support both ReceivedRTPPacket and
1618// OnRtpPacket interfaces without too much code duplication.
1619bool Channel::OnRtpPacketWithHeader(const uint8_t* received_packet,
1620 size_t length,
1621 RTPHeader *header) {
1622 // Store playout timestamp for the received RTP packet
1623 UpdatePlayoutTimestamp(false);
1624
1625 header->payload_type_frequency =
1626 rtp_payload_registry_->GetPayloadTypeFrequency(header->payloadType);
1627 if (header->payload_type_frequency < 0)
1628 return false;
1629 bool in_order = IsPacketInOrder(*header);
1630 rtp_receive_statistics_->IncomingPacket(
1631 *header, length, IsPacketRetransmitted(*header, in_order));
1632 rtp_payload_registry_->SetIncomingPayloadType(*header);
1633
1634 return ReceivePacket(received_packet, length, *header, in_order);
1635}
1636
mflodman3d7db262016-04-29 00:57:13 -07001637int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001638 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001639 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001640 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001641 "Channel::ReceivedRTPPacket()");
1642
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001643 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001644 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1645 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1646 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001647 return -1;
1648 }
nisse657bab22017-02-21 06:28:10 -08001649 return OnRtpPacketWithHeader(received_packet, length, &header) ? 0 : -1;
1650}
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001651
nisse657bab22017-02-21 06:28:10 -08001652void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1653 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
1654 "Channel::ReceivedRTPPacket()");
1655
1656 RTPHeader header;
1657 packet.GetHeader(&header);
1658 OnRtpPacketWithHeader(packet.data(), packet.size(), &header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001659}
1660
1661bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001662 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001663 const RTPHeader& header,
1664 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001665 if (rtp_payload_registry_->IsRtx(header)) {
1666 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001667 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001668 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001669 assert(packet_length >= header.headerLength);
1670 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001671 PayloadUnion payload_specific;
1672 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001673 &payload_specific)) {
1674 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001675 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001676 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1677 payload_specific, in_order);
1678}
1679
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001680bool Channel::HandleRtxPacket(const uint8_t* packet,
1681 size_t packet_length,
1682 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001683 if (!rtp_payload_registry_->IsRtx(header))
1684 return false;
1685
1686 // Remove the RTX header and parse the original RTP header.
1687 if (packet_length < header.headerLength)
1688 return false;
1689 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1690 return false;
1691 if (restored_packet_in_use_) {
1692 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1693 "Multiple RTX headers detected, dropping packet");
1694 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001695 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001696 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001697 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1698 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001699 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1700 "Incoming RTX packet: invalid RTP header");
1701 return false;
1702 }
1703 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001704 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001705 restored_packet_in_use_ = false;
1706 return ret;
1707}
1708
1709bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1710 StreamStatistician* statistician =
1711 rtp_receive_statistics_->GetStatistician(header.ssrc);
1712 if (!statistician)
1713 return false;
1714 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001715}
1716
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001717bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1718 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001719 // Retransmissions are handled separately if RTX is enabled.
1720 if (rtp_payload_registry_->RtxEnabled())
1721 return false;
1722 StreamStatistician* statistician =
1723 rtp_receive_statistics_->GetStatistician(header.ssrc);
1724 if (!statistician)
1725 return false;
1726 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001727 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001728 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001729 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001730}
1731
mflodman3d7db262016-04-29 00:57:13 -07001732int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001733 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001734 "Channel::ReceivedRTCPPacket()");
1735 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001736 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001737
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001738 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001739 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001740 _engineStatisticsPtr->SetLastError(
1741 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1742 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1743 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001744
Minyue2013aec2015-05-13 14:14:42 +02001745 int64_t rtt = GetRTT(true);
1746 if (rtt == 0) {
1747 // Waiting for valid RTT.
1748 return 0;
1749 }
Erik Språng737336d2016-07-29 12:59:36 +02001750
1751 int64_t nack_window_ms = rtt;
1752 if (nack_window_ms < kMinRetransmissionWindowMs) {
1753 nack_window_ms = kMinRetransmissionWindowMs;
1754 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1755 nack_window_ms = kMaxRetransmissionWindowMs;
1756 }
1757 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1758
minyue7e304322016-10-12 05:00:55 -07001759 // Invoke audio encoders OnReceivedRtt().
1760 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1761 if (*encoder)
1762 (*encoder)->OnReceivedRtt(rtt);
1763 });
1764
Minyue2013aec2015-05-13 14:14:42 +02001765 uint32_t ntp_secs = 0;
1766 uint32_t ntp_frac = 0;
1767 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001768 if (0 !=
1769 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1770 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001771 // Waiting for RTCP.
1772 return 0;
1773 }
1774
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001775 {
tommi31fc21f2016-01-21 10:37:37 -08001776 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001777 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001778 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001779 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001780}
1781
niklase@google.com470e71d2011-07-07 08:21:25 +00001782int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001783 bool loop,
1784 FileFormats format,
1785 int startPosition,
1786 float volumeScaling,
1787 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001788 const CodecInst* codecInst) {
1789 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1790 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1791 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1792 "stopPosition=%d)",
1793 fileName, loop, format, volumeScaling, startPosition,
1794 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001795
kwiberg55b97fe2016-01-28 05:22:45 -08001796 if (channel_state_.Get().output_file_playing) {
1797 _engineStatisticsPtr->SetLastError(
1798 VE_ALREADY_PLAYING, kTraceError,
1799 "StartPlayingFileLocally() is already playing");
1800 return -1;
1801 }
1802
1803 {
1804 rtc::CritScope cs(&_fileCritSect);
1805
kwiberg5a25d952016-08-17 07:31:12 -07001806 if (output_file_player_) {
1807 output_file_player_->RegisterModuleFileCallback(NULL);
1808 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001809 }
1810
kwiberg5b356f42016-09-08 04:32:33 -07001811 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001812 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001813
kwiberg5a25d952016-08-17 07:31:12 -07001814 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001815 _engineStatisticsPtr->SetLastError(
1816 VE_INVALID_ARGUMENT, kTraceError,
1817 "StartPlayingFileLocally() filePlayer format is not correct");
1818 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001819 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001820
kwiberg55b97fe2016-01-28 05:22:45 -08001821 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001822
kwiberg5a25d952016-08-17 07:31:12 -07001823 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001824 fileName, loop, startPosition, volumeScaling, notificationTime,
1825 stopPosition, (const CodecInst*)codecInst) != 0) {
1826 _engineStatisticsPtr->SetLastError(
1827 VE_BAD_FILE, kTraceError,
1828 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001829 output_file_player_->StopPlayingFile();
1830 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001831 return -1;
1832 }
kwiberg5a25d952016-08-17 07:31:12 -07001833 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001834 channel_state_.SetOutputFilePlaying(true);
1835 }
1836
1837 if (RegisterFilePlayingToMixer() != 0)
1838 return -1;
1839
1840 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001841}
1842
1843int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001844 FileFormats format,
1845 int startPosition,
1846 float volumeScaling,
1847 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001848 const CodecInst* codecInst) {
1849 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1850 "Channel::StartPlayingFileLocally(format=%d,"
1851 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1852 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001853
kwiberg55b97fe2016-01-28 05:22:45 -08001854 if (stream == NULL) {
1855 _engineStatisticsPtr->SetLastError(
1856 VE_BAD_FILE, kTraceError,
1857 "StartPlayingFileLocally() NULL as input stream");
1858 return -1;
1859 }
1860
1861 if (channel_state_.Get().output_file_playing) {
1862 _engineStatisticsPtr->SetLastError(
1863 VE_ALREADY_PLAYING, kTraceError,
1864 "StartPlayingFileLocally() is already playing");
1865 return -1;
1866 }
1867
1868 {
1869 rtc::CritScope cs(&_fileCritSect);
1870
1871 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001872 if (output_file_player_) {
1873 output_file_player_->RegisterModuleFileCallback(NULL);
1874 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001875 }
1876
kwiberg55b97fe2016-01-28 05:22:45 -08001877 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001878 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001879 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001880
kwiberg5a25d952016-08-17 07:31:12 -07001881 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001882 _engineStatisticsPtr->SetLastError(
1883 VE_INVALID_ARGUMENT, kTraceError,
1884 "StartPlayingFileLocally() filePlayer format isnot correct");
1885 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001886 }
1887
kwiberg55b97fe2016-01-28 05:22:45 -08001888 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001889
kwiberg4ec01d92016-08-22 08:43:54 -07001890 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001891 volumeScaling, notificationTime,
1892 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001893 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1894 "StartPlayingFile() failed to "
1895 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001896 output_file_player_->StopPlayingFile();
1897 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001898 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001899 }
kwiberg5a25d952016-08-17 07:31:12 -07001900 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001901 channel_state_.SetOutputFilePlaying(true);
1902 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001903
kwiberg55b97fe2016-01-28 05:22:45 -08001904 if (RegisterFilePlayingToMixer() != 0)
1905 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001906
kwiberg55b97fe2016-01-28 05:22:45 -08001907 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001908}
1909
kwiberg55b97fe2016-01-28 05:22:45 -08001910int Channel::StopPlayingFileLocally() {
1911 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1912 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001913
kwiberg55b97fe2016-01-28 05:22:45 -08001914 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001915 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001916 }
1917
1918 {
1919 rtc::CritScope cs(&_fileCritSect);
1920
kwiberg5a25d952016-08-17 07:31:12 -07001921 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001922 _engineStatisticsPtr->SetLastError(
1923 VE_STOP_RECORDING_FAILED, kTraceError,
1924 "StopPlayingFile() could not stop playing");
1925 return -1;
1926 }
kwiberg5a25d952016-08-17 07:31:12 -07001927 output_file_player_->RegisterModuleFileCallback(NULL);
1928 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001929 channel_state_.SetOutputFilePlaying(false);
1930 }
1931 // _fileCritSect cannot be taken while calling
1932 // SetAnonymousMixibilityStatus. Refer to comments in
1933 // StartPlayingFileLocally(const char* ...) for more details.
1934 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1935 _engineStatisticsPtr->SetLastError(
1936 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1937 "StopPlayingFile() failed to stop participant from playing as"
1938 "file in the mixer");
1939 return -1;
1940 }
1941
1942 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001943}
1944
kwiberg55b97fe2016-01-28 05:22:45 -08001945int Channel::IsPlayingFileLocally() const {
1946 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001947}
1948
kwiberg55b97fe2016-01-28 05:22:45 -08001949int Channel::RegisterFilePlayingToMixer() {
1950 // Return success for not registering for file playing to mixer if:
1951 // 1. playing file before playout is started on that channel.
1952 // 2. starting playout without file playing on that channel.
1953 if (!channel_state_.Get().playing ||
1954 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001955 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001956 }
1957
1958 // |_fileCritSect| cannot be taken while calling
1959 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1960 // frames can be pulled by the mixer. Since the frames are generated from
1961 // the file, _fileCritSect will be taken. This would result in a deadlock.
1962 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1963 channel_state_.SetOutputFilePlaying(false);
1964 rtc::CritScope cs(&_fileCritSect);
1965 _engineStatisticsPtr->SetLastError(
1966 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1967 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07001968 output_file_player_->StopPlayingFile();
1969 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001970 return -1;
1971 }
1972
1973 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001974}
1975
niklase@google.com470e71d2011-07-07 08:21:25 +00001976int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001977 bool loop,
1978 FileFormats format,
1979 int startPosition,
1980 float volumeScaling,
1981 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001982 const CodecInst* codecInst) {
1983 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1984 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1985 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1986 "stopPosition=%d)",
1987 fileName, loop, format, volumeScaling, startPosition,
1988 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001989
kwiberg55b97fe2016-01-28 05:22:45 -08001990 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001991
kwiberg55b97fe2016-01-28 05:22:45 -08001992 if (channel_state_.Get().input_file_playing) {
1993 _engineStatisticsPtr->SetLastError(
1994 VE_ALREADY_PLAYING, kTraceWarning,
1995 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001996 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001997 }
1998
1999 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002000 if (input_file_player_) {
2001 input_file_player_->RegisterModuleFileCallback(NULL);
2002 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002003 }
2004
2005 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002006 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002007 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002008
kwiberg5a25d952016-08-17 07:31:12 -07002009 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002010 _engineStatisticsPtr->SetLastError(
2011 VE_INVALID_ARGUMENT, kTraceError,
2012 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
2013 return -1;
2014 }
2015
2016 const uint32_t notificationTime(0);
2017
kwiberg5a25d952016-08-17 07:31:12 -07002018 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002019 fileName, loop, startPosition, volumeScaling, notificationTime,
2020 stopPosition, (const CodecInst*)codecInst) != 0) {
2021 _engineStatisticsPtr->SetLastError(
2022 VE_BAD_FILE, kTraceError,
2023 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002024 input_file_player_->StopPlayingFile();
2025 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002026 return -1;
2027 }
kwiberg5a25d952016-08-17 07:31:12 -07002028 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002029 channel_state_.SetInputFilePlaying(true);
2030
2031 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002032}
2033
2034int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002035 FileFormats format,
2036 int startPosition,
2037 float volumeScaling,
2038 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002039 const CodecInst* codecInst) {
2040 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2041 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2042 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2043 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002044
kwiberg55b97fe2016-01-28 05:22:45 -08002045 if (stream == NULL) {
2046 _engineStatisticsPtr->SetLastError(
2047 VE_BAD_FILE, kTraceError,
2048 "StartPlayingFileAsMicrophone NULL as input stream");
2049 return -1;
2050 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002051
kwiberg55b97fe2016-01-28 05:22:45 -08002052 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002053
kwiberg55b97fe2016-01-28 05:22:45 -08002054 if (channel_state_.Get().input_file_playing) {
2055 _engineStatisticsPtr->SetLastError(
2056 VE_ALREADY_PLAYING, kTraceWarning,
2057 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002058 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002059 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002060
kwiberg55b97fe2016-01-28 05:22:45 -08002061 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002062 if (input_file_player_) {
2063 input_file_player_->RegisterModuleFileCallback(NULL);
2064 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002065 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002066
kwiberg55b97fe2016-01-28 05:22:45 -08002067 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002068 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002069 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002070
kwiberg5a25d952016-08-17 07:31:12 -07002071 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002072 _engineStatisticsPtr->SetLastError(
2073 VE_INVALID_ARGUMENT, kTraceError,
2074 "StartPlayingInputFile() filePlayer format isnot correct");
2075 return -1;
2076 }
2077
2078 const uint32_t notificationTime(0);
2079
kwiberg4ec01d92016-08-22 08:43:54 -07002080 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2081 notificationTime, stopPosition,
2082 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002083 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2084 "StartPlayingFile() failed to start "
2085 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002086 input_file_player_->StopPlayingFile();
2087 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002088 return -1;
2089 }
2090
kwiberg5a25d952016-08-17 07:31:12 -07002091 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002092 channel_state_.SetInputFilePlaying(true);
2093
2094 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002095}
2096
kwiberg55b97fe2016-01-28 05:22:45 -08002097int Channel::StopPlayingFileAsMicrophone() {
2098 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2099 "Channel::StopPlayingFileAsMicrophone()");
2100
2101 rtc::CritScope cs(&_fileCritSect);
2102
2103 if (!channel_state_.Get().input_file_playing) {
2104 return 0;
2105 }
2106
kwiberg5a25d952016-08-17 07:31:12 -07002107 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002108 _engineStatisticsPtr->SetLastError(
2109 VE_STOP_RECORDING_FAILED, kTraceError,
2110 "StopPlayingFile() could not stop playing");
2111 return -1;
2112 }
kwiberg5a25d952016-08-17 07:31:12 -07002113 input_file_player_->RegisterModuleFileCallback(NULL);
2114 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002115 channel_state_.SetInputFilePlaying(false);
2116
2117 return 0;
2118}
2119
2120int Channel::IsPlayingFileAsMicrophone() const {
2121 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002122}
2123
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002124int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002125 const CodecInst* codecInst) {
2126 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2127 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002128
kwiberg55b97fe2016-01-28 05:22:45 -08002129 if (_outputFileRecording) {
2130 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2131 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002132 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002133 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002134
kwiberg55b97fe2016-01-28 05:22:45 -08002135 FileFormats format;
2136 const uint32_t notificationTime(0); // Not supported in VoE
2137 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002138
kwiberg55b97fe2016-01-28 05:22:45 -08002139 if ((codecInst != NULL) &&
2140 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2141 _engineStatisticsPtr->SetLastError(
2142 VE_BAD_ARGUMENT, kTraceError,
2143 "StartRecordingPlayout() invalid compression");
2144 return (-1);
2145 }
2146 if (codecInst == NULL) {
2147 format = kFileFormatPcm16kHzFile;
2148 codecInst = &dummyCodec;
2149 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2150 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2151 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2152 format = kFileFormatWavFile;
2153 } else {
2154 format = kFileFormatCompressedFile;
2155 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002156
kwiberg55b97fe2016-01-28 05:22:45 -08002157 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002158
kwiberg55b97fe2016-01-28 05:22:45 -08002159 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002160 if (output_file_recorder_) {
2161 output_file_recorder_->RegisterModuleFileCallback(NULL);
2162 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002163 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002164
kwiberg5a25d952016-08-17 07:31:12 -07002165 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002166 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002167 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002168 _engineStatisticsPtr->SetLastError(
2169 VE_INVALID_ARGUMENT, kTraceError,
2170 "StartRecordingPlayout() fileRecorder format isnot correct");
2171 return -1;
2172 }
2173
kwiberg5a25d952016-08-17 07:31:12 -07002174 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002175 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2176 _engineStatisticsPtr->SetLastError(
2177 VE_BAD_FILE, kTraceError,
2178 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002179 output_file_recorder_->StopRecording();
2180 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002181 return -1;
2182 }
kwiberg5a25d952016-08-17 07:31:12 -07002183 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002184 _outputFileRecording = true;
2185
2186 return 0;
2187}
2188
2189int Channel::StartRecordingPlayout(OutStream* stream,
2190 const CodecInst* codecInst) {
2191 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2192 "Channel::StartRecordingPlayout()");
2193
2194 if (_outputFileRecording) {
2195 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2196 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002197 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002198 }
2199
2200 FileFormats format;
2201 const uint32_t notificationTime(0); // Not supported in VoE
2202 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2203
2204 if (codecInst != NULL && codecInst->channels != 1) {
2205 _engineStatisticsPtr->SetLastError(
2206 VE_BAD_ARGUMENT, kTraceError,
2207 "StartRecordingPlayout() invalid compression");
2208 return (-1);
2209 }
2210 if (codecInst == NULL) {
2211 format = kFileFormatPcm16kHzFile;
2212 codecInst = &dummyCodec;
2213 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2214 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2215 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2216 format = kFileFormatWavFile;
2217 } else {
2218 format = kFileFormatCompressedFile;
2219 }
2220
2221 rtc::CritScope cs(&_fileCritSect);
2222
2223 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002224 if (output_file_recorder_) {
2225 output_file_recorder_->RegisterModuleFileCallback(NULL);
2226 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002227 }
2228
kwiberg5a25d952016-08-17 07:31:12 -07002229 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002230 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002231 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002232 _engineStatisticsPtr->SetLastError(
2233 VE_INVALID_ARGUMENT, kTraceError,
2234 "StartRecordingPlayout() fileRecorder format isnot correct");
2235 return -1;
2236 }
2237
kwiberg4ec01d92016-08-22 08:43:54 -07002238 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002239 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002240 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2241 "StartRecordingPlayout() failed to "
2242 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002243 output_file_recorder_->StopRecording();
2244 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002245 return -1;
2246 }
2247
kwiberg5a25d952016-08-17 07:31:12 -07002248 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002249 _outputFileRecording = true;
2250
2251 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002252}
2253
kwiberg55b97fe2016-01-28 05:22:45 -08002254int Channel::StopRecordingPlayout() {
2255 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2256 "Channel::StopRecordingPlayout()");
2257
2258 if (!_outputFileRecording) {
2259 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2260 "StopRecordingPlayout() isnot recording");
2261 return -1;
2262 }
2263
2264 rtc::CritScope cs(&_fileCritSect);
2265
kwiberg5a25d952016-08-17 07:31:12 -07002266 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002267 _engineStatisticsPtr->SetLastError(
2268 VE_STOP_RECORDING_FAILED, kTraceError,
2269 "StopRecording() could not stop recording");
2270 return (-1);
2271 }
kwiberg5a25d952016-08-17 07:31:12 -07002272 output_file_recorder_->RegisterModuleFileCallback(NULL);
2273 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002274 _outputFileRecording = false;
2275
2276 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002277}
2278
kwiberg55b97fe2016-01-28 05:22:45 -08002279void Channel::SetMixWithMicStatus(bool mix) {
2280 rtc::CritScope cs(&_fileCritSect);
2281 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002282}
2283
solenberg8d73f8c2017-03-08 01:52:20 -08002284int Channel::GetSpeechOutputLevel() const {
2285 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002286}
2287
solenberg8d73f8c2017-03-08 01:52:20 -08002288int Channel::GetSpeechOutputLevelFullRange() const {
2289 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08002290}
2291
solenberg8d73f8c2017-03-08 01:52:20 -08002292void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002293 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002294 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002295}
2296
solenberg1c2af8e2016-03-24 10:36:00 -07002297bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002298 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002299 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002300}
2301
solenberg8d73f8c2017-03-08 01:52:20 -08002302void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08002303 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08002304 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00002305}
2306
solenberg8842c3e2016-03-11 03:06:41 -08002307int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002308 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002309 "Channel::SendTelephoneEventOutband(...)");
2310 RTC_DCHECK_LE(0, event);
2311 RTC_DCHECK_GE(255, event);
2312 RTC_DCHECK_LE(0, duration_ms);
2313 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002314 if (!Sending()) {
2315 return -1;
2316 }
solenberg8842c3e2016-03-11 03:06:41 -08002317 if (_rtpRtcpModule->SendTelephoneEventOutband(
2318 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002319 _engineStatisticsPtr->SetLastError(
2320 VE_SEND_DTMF_FAILED, kTraceWarning,
2321 "SendTelephoneEventOutband() failed to send event");
2322 return -1;
2323 }
2324 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002325}
2326
solenbergffbbcac2016-11-17 05:25:37 -08002327int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2328 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002329 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002330 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002331 RTC_DCHECK_LE(0, payload_type);
2332 RTC_DCHECK_GE(127, payload_type);
2333 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002334 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002335 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002336 memcpy(codec.plname, "telephone-event", 16);
2337 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2338 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2339 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2340 _engineStatisticsPtr->SetLastError(
2341 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2342 "SetSendTelephoneEventPayloadType() failed to register send"
2343 "payload type");
2344 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002345 }
kwiberg55b97fe2016-01-28 05:22:45 -08002346 }
kwiberg55b97fe2016-01-28 05:22:45 -08002347 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002348}
2349
kwiberg55b97fe2016-01-28 05:22:45 -08002350int Channel::SetLocalSSRC(unsigned int ssrc) {
2351 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2352 "Channel::SetLocalSSRC()");
2353 if (channel_state_.Get().sending) {
2354 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2355 "SetLocalSSRC() already sending");
2356 return -1;
2357 }
2358 _rtpRtcpModule->SetSSRC(ssrc);
2359 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002360}
2361
kwiberg55b97fe2016-01-28 05:22:45 -08002362int Channel::GetLocalSSRC(unsigned int& ssrc) {
2363 ssrc = _rtpRtcpModule->SSRC();
2364 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002365}
2366
kwiberg55b97fe2016-01-28 05:22:45 -08002367int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2368 ssrc = rtp_receiver_->SSRC();
2369 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002370}
2371
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002372int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002373 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002374 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002375}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002376
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002377int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2378 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002379 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2380 if (enable &&
2381 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2382 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002383 return -1;
2384 }
2385 return 0;
2386}
2387
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002388void Channel::EnableSendTransportSequenceNumber(int id) {
2389 int ret =
2390 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2391 RTC_DCHECK_EQ(0, ret);
2392}
2393
stefan3313ec92016-01-21 06:32:43 -08002394void Channel::EnableReceiveTransportSequenceNumber(int id) {
2395 rtp_header_parser_->DeregisterRtpHeaderExtension(
2396 kRtpExtensionTransportSequenceNumber);
2397 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2398 kRtpExtensionTransportSequenceNumber, id);
2399 RTC_DCHECK(ret);
2400}
2401
stefanbba9dec2016-02-01 04:39:55 -08002402void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07002403 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08002404 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07002405 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
2406 TransportFeedbackObserver* transport_feedback_observer =
2407 transport->transport_feedback_observer();
2408 PacketRouter* packet_router = transport->packet_router();
2409
stefanbba9dec2016-02-01 04:39:55 -08002410 RTC_DCHECK(rtp_packet_sender);
2411 RTC_DCHECK(transport_feedback_observer);
2412 RTC_DCHECK(packet_router && !packet_router_);
stefan7de8d642017-02-07 07:14:08 -08002413 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08002414 feedback_observer_proxy_->SetTransportFeedbackObserver(
2415 transport_feedback_observer);
2416 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2417 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2418 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002419 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002420 packet_router_ = packet_router;
2421}
2422
stefanbba9dec2016-02-01 04:39:55 -08002423void Channel::RegisterReceiverCongestionControlObjects(
2424 PacketRouter* packet_router) {
2425 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002426 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002427 packet_router_ = packet_router;
2428}
2429
2430void Channel::ResetCongestionControlObjects() {
2431 RTC_DCHECK(packet_router_);
2432 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08002433 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08002434 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2435 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002436 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002437 packet_router_ = nullptr;
2438 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2439}
2440
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002441void Channel::SetRTCPStatus(bool enable) {
2442 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2443 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002444 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002445}
2446
kwiberg55b97fe2016-01-28 05:22:45 -08002447int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002448 RtcpMode method = _rtpRtcpModule->RTCP();
2449 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002450 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002451}
2452
kwiberg55b97fe2016-01-28 05:22:45 -08002453int Channel::SetRTCP_CNAME(const char cName[256]) {
2454 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2455 "Channel::SetRTCP_CNAME()");
2456 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2457 _engineStatisticsPtr->SetLastError(
2458 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2459 "SetRTCP_CNAME() failed to set RTCP CNAME");
2460 return -1;
2461 }
2462 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002463}
2464
kwiberg55b97fe2016-01-28 05:22:45 -08002465int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2466 if (cName == NULL) {
2467 _engineStatisticsPtr->SetLastError(
2468 VE_INVALID_ARGUMENT, kTraceError,
2469 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2470 return -1;
2471 }
2472 char cname[RTCP_CNAME_SIZE];
2473 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2474 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2475 _engineStatisticsPtr->SetLastError(
2476 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2477 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2478 return -1;
2479 }
2480 strcpy(cName, cname);
2481 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002482}
2483
kwiberg55b97fe2016-01-28 05:22:45 -08002484int Channel::SendApplicationDefinedRTCPPacket(
2485 unsigned char subType,
2486 unsigned int name,
2487 const char* data,
2488 unsigned short dataLengthInBytes) {
2489 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2490 "Channel::SendApplicationDefinedRTCPPacket()");
2491 if (!channel_state_.Get().sending) {
2492 _engineStatisticsPtr->SetLastError(
2493 VE_NOT_SENDING, kTraceError,
2494 "SendApplicationDefinedRTCPPacket() not sending");
2495 return -1;
2496 }
2497 if (NULL == data) {
2498 _engineStatisticsPtr->SetLastError(
2499 VE_INVALID_ARGUMENT, kTraceError,
2500 "SendApplicationDefinedRTCPPacket() invalid data value");
2501 return -1;
2502 }
2503 if (dataLengthInBytes % 4 != 0) {
2504 _engineStatisticsPtr->SetLastError(
2505 VE_INVALID_ARGUMENT, kTraceError,
2506 "SendApplicationDefinedRTCPPacket() invalid length value");
2507 return -1;
2508 }
2509 RtcpMode status = _rtpRtcpModule->RTCP();
2510 if (status == RtcpMode::kOff) {
2511 _engineStatisticsPtr->SetLastError(
2512 VE_RTCP_ERROR, kTraceError,
2513 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2514 return -1;
2515 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002516
kwiberg55b97fe2016-01-28 05:22:45 -08002517 // Create and schedule the RTCP APP packet for transmission
2518 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2519 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2520 _engineStatisticsPtr->SetLastError(
2521 VE_SEND_ERROR, kTraceError,
2522 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2523 return -1;
2524 }
2525 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002526}
2527
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002528int Channel::GetRemoteRTCPReportBlocks(
2529 std::vector<ReportBlock>* report_blocks) {
2530 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002531 _engineStatisticsPtr->SetLastError(
2532 VE_INVALID_ARGUMENT, kTraceError,
2533 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002534 return -1;
2535 }
2536
2537 // Get the report blocks from the latest received RTCP Sender or Receiver
2538 // Report. Each element in the vector contains the sender's SSRC and a
2539 // report block according to RFC 3550.
2540 std::vector<RTCPReportBlock> rtcp_report_blocks;
2541 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002542 return -1;
2543 }
2544
2545 if (rtcp_report_blocks.empty())
2546 return 0;
2547
2548 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2549 for (; it != rtcp_report_blocks.end(); ++it) {
2550 ReportBlock report_block;
2551 report_block.sender_SSRC = it->remoteSSRC;
2552 report_block.source_SSRC = it->sourceSSRC;
2553 report_block.fraction_lost = it->fractionLost;
2554 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2555 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2556 report_block.interarrival_jitter = it->jitter;
2557 report_block.last_SR_timestamp = it->lastSR;
2558 report_block.delay_since_last_SR = it->delaySinceLastSR;
2559 report_blocks->push_back(report_block);
2560 }
2561 return 0;
2562}
2563
kwiberg55b97fe2016-01-28 05:22:45 -08002564int Channel::GetRTPStatistics(CallStatistics& stats) {
2565 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002566
kwiberg55b97fe2016-01-28 05:22:45 -08002567 // The jitter statistics is updated for each received RTP packet and is
2568 // based on received packets.
2569 RtcpStatistics statistics;
2570 StreamStatistician* statistician =
2571 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002572 if (statistician) {
2573 statistician->GetStatistics(&statistics,
2574 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002575 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002576
kwiberg55b97fe2016-01-28 05:22:45 -08002577 stats.fractionLost = statistics.fraction_lost;
2578 stats.cumulativeLost = statistics.cumulative_lost;
2579 stats.extendedMax = statistics.extended_max_sequence_number;
2580 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002581
kwiberg55b97fe2016-01-28 05:22:45 -08002582 // --- RTT
2583 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002584
kwiberg55b97fe2016-01-28 05:22:45 -08002585 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002586
kwiberg55b97fe2016-01-28 05:22:45 -08002587 size_t bytesSent(0);
2588 uint32_t packetsSent(0);
2589 size_t bytesReceived(0);
2590 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002591
kwiberg55b97fe2016-01-28 05:22:45 -08002592 if (statistician) {
2593 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2594 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002595
kwiberg55b97fe2016-01-28 05:22:45 -08002596 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2597 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2598 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2599 " output will not be complete");
2600 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002601
kwiberg55b97fe2016-01-28 05:22:45 -08002602 stats.bytesSent = bytesSent;
2603 stats.packetsSent = packetsSent;
2604 stats.bytesReceived = bytesReceived;
2605 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002606
kwiberg55b97fe2016-01-28 05:22:45 -08002607 // --- Timestamps
2608 {
2609 rtc::CritScope lock(&ts_stats_lock_);
2610 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2611 }
2612 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002613}
2614
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002615int Channel::SetCodecFECStatus(bool enable) {
2616 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2617 "Channel::SetCodecFECStatus()");
2618
kwibergc8d071e2016-04-06 12:22:38 -07002619 if (!codec_manager_.SetCodecFEC(enable) ||
2620 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002621 _engineStatisticsPtr->SetLastError(
2622 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2623 "SetCodecFECStatus() failed to set FEC state");
2624 return -1;
2625 }
2626 return 0;
2627}
2628
2629bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002630 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002631}
2632
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002633void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2634 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002635 // If pacing is enabled we always store packets.
2636 if (!pacing_enabled_)
2637 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002638 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002639 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002640 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002641 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002642 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002643}
2644
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002645// Called when we are missing one or more packets.
2646int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002647 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2648}
2649
kwiberg55b97fe2016-01-28 05:22:45 -08002650uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2651 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2652 "Channel::Demultiplex()");
2653 _audioFrame.CopyFrom(audioFrame);
2654 _audioFrame.id_ = _channelId;
2655 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002656}
2657
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002658void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002659 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002660 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002661 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002662 CodecInst codec;
2663 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002664
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002665 // Never upsample or upmix the capture signal here. This should be done at the
2666 // end of the send chain.
2667 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2668 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2669 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2670 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002671}
2672
kwiberg55b97fe2016-01-28 05:22:45 -08002673uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2674 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2675 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002676
kwiberg55b97fe2016-01-28 05:22:45 -08002677 if (_audioFrame.samples_per_channel_ == 0) {
2678 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2679 "Channel::PrepareEncodeAndSend() invalid audio frame");
2680 return 0xFFFFFFFF;
2681 }
2682
2683 if (channel_state_.Get().input_file_playing) {
2684 MixOrReplaceAudioWithFile(mixingFrequency);
2685 }
2686
solenberg1c2af8e2016-03-24 10:36:00 -07002687 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2688 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002689
kwiberg55b97fe2016-01-28 05:22:45 -08002690 if (_includeAudioLevelIndication) {
2691 size_t length =
2692 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02002693 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002694 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002695 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002696 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002697 rms_level_.Analyze(
2698 rtc::ArrayView<const int16_t>(_audioFrame.data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002699 }
kwiberg55b97fe2016-01-28 05:22:45 -08002700 }
solenberg1c2af8e2016-03-24 10:36:00 -07002701 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002702
kwiberg55b97fe2016-01-28 05:22:45 -08002703 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002704}
2705
kwiberg55b97fe2016-01-28 05:22:45 -08002706uint32_t Channel::EncodeAndSend() {
2707 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2708 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002709
kwiberg55b97fe2016-01-28 05:22:45 -08002710 assert(_audioFrame.num_channels_ <= 2);
2711 if (_audioFrame.samples_per_channel_ == 0) {
2712 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2713 "Channel::EncodeAndSend() invalid audio frame");
2714 return 0xFFFFFFFF;
2715 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002716
kwiberg55b97fe2016-01-28 05:22:45 -08002717 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00002718
kwiberg55b97fe2016-01-28 05:22:45 -08002719 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002720
kwiberg55b97fe2016-01-28 05:22:45 -08002721 // The ACM resamples internally.
2722 _audioFrame.timestamp_ = _timeStamp;
2723 // This call will trigger AudioPacketizationCallback::SendData if encoding
2724 // is done and payload is ready for packetization and transmission.
2725 // Otherwise, it will return without invoking the callback.
2726 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
2727 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
2728 "Channel::EncodeAndSend() ACM encoding failed");
2729 return 0xFFFFFFFF;
2730 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002731
kwiberg55b97fe2016-01-28 05:22:45 -08002732 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
2733 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002734}
2735
solenberg7602aab2016-11-14 11:30:07 -08002736void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2737 RTC_DCHECK(!channel.channel() ||
2738 channel.channel()->ChannelId() != _channelId);
2739 rtc::CritScope lock(&assoc_send_channel_lock_);
2740 associate_send_channel_ = channel;
2741}
2742
Minyue2013aec2015-05-13 14:14:42 +02002743void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002744 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002745 Channel* channel = associate_send_channel_.channel();
2746 if (channel && channel->ChannelId() == channel_id) {
2747 // If this channel is associated with a send channel of the specified
2748 // Channel ID, disassociate with it.
2749 ChannelOwner ref(NULL);
2750 associate_send_channel_ = ref;
2751 }
2752}
2753
ivoc14d5dbe2016-07-04 07:06:55 -07002754void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2755 event_log_proxy_->SetEventLog(event_log);
2756}
2757
michaelt9332b7d2016-11-30 07:51:13 -08002758void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2759 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2760}
2761
nisse284542b2017-01-10 08:58:32 -08002762void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08002763 size_t overhead_per_packet =
2764 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08002765 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2766 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08002767 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08002768 }
2769 });
2770}
2771
2772void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002773 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002774 transport_overhead_per_packet_ = transport_overhead_per_packet;
2775 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08002776}
2777
hbos3fd31fe2017-02-28 05:43:16 -08002778// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08002779void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002780 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002781 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
2782 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08002783}
2784
kwiberg55b97fe2016-01-28 05:22:45 -08002785int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2786 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002787}
2788
wu@webrtc.org24301a62013-12-13 19:17:43 +00002789void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2790 audio_coding_->GetDecodingCallStatistics(stats);
2791}
2792
solenberg358057b2015-11-27 10:46:42 -08002793uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08002794 rtc::CritScope lock(&video_sync_lock_);
2795 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07002796}
2797
kwiberg55b97fe2016-01-28 05:22:45 -08002798int Channel::SetMinimumPlayoutDelay(int delayMs) {
2799 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2800 "Channel::SetMinimumPlayoutDelay()");
2801 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
2802 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
2803 _engineStatisticsPtr->SetLastError(
2804 VE_INVALID_ARGUMENT, kTraceError,
2805 "SetMinimumPlayoutDelay() invalid min delay");
2806 return -1;
2807 }
2808 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
2809 _engineStatisticsPtr->SetLastError(
2810 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2811 "SetMinimumPlayoutDelay() failed to set min playout delay");
2812 return -1;
2813 }
2814 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002815}
2816
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002817int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07002818 uint32_t playout_timestamp_rtp = 0;
2819 {
tommi31fc21f2016-01-21 10:37:37 -08002820 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07002821 playout_timestamp_rtp = playout_timestamp_rtp_;
2822 }
kwiberg55b97fe2016-01-28 05:22:45 -08002823 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002824 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07002825 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002826 "GetPlayoutTimestamp() failed to retrieve timestamp");
2827 return -1;
2828 }
deadbeef74375882015-08-13 12:09:10 -07002829 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002830 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002831}
2832
kwiberg55b97fe2016-01-28 05:22:45 -08002833int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
2834 RtpReceiver** rtp_receiver) const {
2835 *rtpRtcpModule = _rtpRtcpModule.get();
2836 *rtp_receiver = rtp_receiver_.get();
2837 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002838}
2839
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00002840// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
2841// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08002842int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08002843 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08002844 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002845
kwiberg55b97fe2016-01-28 05:22:45 -08002846 {
2847 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002848
kwiberg5a25d952016-08-17 07:31:12 -07002849 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002850 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2851 "Channel::MixOrReplaceAudioWithFile() fileplayer"
2852 " doesnt exist");
2853 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002854 }
2855
kwiberg4ec01d92016-08-22 08:43:54 -07002856 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07002857 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002858 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2859 "Channel::MixOrReplaceAudioWithFile() file mixing "
2860 "failed");
2861 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002862 }
kwiberg55b97fe2016-01-28 05:22:45 -08002863 if (fileSamples == 0) {
2864 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2865 "Channel::MixOrReplaceAudioWithFile() file is ended");
2866 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002867 }
kwiberg55b97fe2016-01-28 05:22:45 -08002868 }
2869
2870 assert(_audioFrame.samples_per_channel_ == fileSamples);
2871
2872 if (_mixFileWithMicrophone) {
2873 // Currently file stream is always mono.
2874 // TODO(xians): Change the code when FilePlayer supports real stereo.
2875 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
2876 1, fileSamples);
2877 } else {
2878 // Replace ACM audio with file.
2879 // Currently file stream is always mono.
2880 // TODO(xians): Change the code when FilePlayer supports real stereo.
2881 _audioFrame.UpdateFrame(
2882 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
2883 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
2884 }
2885 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002886}
2887
kwiberg55b97fe2016-01-28 05:22:45 -08002888int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
2889 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00002890
kwibergb7f89d62016-02-17 10:04:18 -08002891 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08002892 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002893
kwiberg55b97fe2016-01-28 05:22:45 -08002894 {
2895 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002896
kwiberg5a25d952016-08-17 07:31:12 -07002897 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002898 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2899 "Channel::MixAudioWithFile() file mixing failed");
2900 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002901 }
2902
kwiberg55b97fe2016-01-28 05:22:45 -08002903 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07002904 if (output_file_player_->Get10msAudioFromFile(
2905 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002906 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2907 "Channel::MixAudioWithFile() file mixing failed");
2908 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002909 }
kwiberg55b97fe2016-01-28 05:22:45 -08002910 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002911
kwiberg55b97fe2016-01-28 05:22:45 -08002912 if (audioFrame.samples_per_channel_ == fileSamples) {
2913 // Currently file stream is always mono.
2914 // TODO(xians): Change the code when FilePlayer supports real stereo.
2915 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
2916 fileSamples);
2917 } else {
2918 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2919 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
2920 ") != "
2921 "fileSamples(%" PRIuS ")",
2922 audioFrame.samples_per_channel_, fileSamples);
2923 return -1;
2924 }
2925
2926 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002927}
2928
deadbeef74375882015-08-13 12:09:10 -07002929void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002930 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07002931
henrik.lundin96bd5022016-04-06 04:13:56 -07002932 if (!jitter_buffer_playout_timestamp_) {
2933 // This can happen if this channel has not received any RTP packets. In
2934 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07002935 return;
2936 }
2937
2938 uint16_t delay_ms = 0;
2939 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002940 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002941 "Channel::UpdatePlayoutTimestamp() failed to read playout"
2942 " delay from the ADM");
2943 _engineStatisticsPtr->SetLastError(
2944 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
2945 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
2946 return;
2947 }
2948
henrik.lundin96bd5022016-04-06 04:13:56 -07002949 RTC_DCHECK(jitter_buffer_playout_timestamp_);
2950 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07002951
2952 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07002953 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07002954
kwiberg55b97fe2016-01-28 05:22:45 -08002955 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002956 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07002957 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07002958
2959 {
tommi31fc21f2016-01-21 10:37:37 -08002960 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08002961 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002962 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07002963 }
2964 playout_delay_ms_ = delay_ms;
2965 }
2966}
2967
kwiberg55b97fe2016-01-28 05:22:45 -08002968void Channel::RegisterReceiveCodecsToRTPModule() {
2969 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2970 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002971
kwiberg55b97fe2016-01-28 05:22:45 -08002972 CodecInst codec;
2973 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00002974
kwiberg55b97fe2016-01-28 05:22:45 -08002975 for (int idx = 0; idx < nSupportedCodecs; idx++) {
2976 // Open up the RTP/RTCP receiver for all supported codecs
2977 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08002978 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08002979 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2980 "Channel::RegisterReceiveCodecsToRTPModule() unable"
2981 " to register %s (%d/%d/%" PRIuS
2982 "/%d) to RTP/RTCP "
2983 "receiver",
2984 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2985 codec.rate);
2986 } else {
2987 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2988 "Channel::RegisterReceiveCodecsToRTPModule() %s "
2989 "(%d/%d/%" PRIuS
2990 "/%d) has been added to the RTP/RTCP "
2991 "receiver",
2992 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2993 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00002994 }
kwiberg55b97fe2016-01-28 05:22:45 -08002995 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002996}
2997
kwiberg55b97fe2016-01-28 05:22:45 -08002998int Channel::SetSendRtpHeaderExtension(bool enable,
2999 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003000 unsigned char id) {
3001 int error = 0;
3002 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3003 if (enable) {
3004 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3005 }
3006 return error;
3007}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003008
ossue280cde2016-10-12 11:04:10 -07003009int Channel::GetRtpTimestampRateHz() const {
3010 const auto format = audio_coding_->ReceiveFormat();
3011 // Default to the playout frequency if we've not gotten any packets yet.
3012 // TODO(ossu): Zero clockrate can only happen if we've added an external
3013 // decoder for a format we don't support internally. Remove once that way of
3014 // adding decoders is gone!
3015 return (format && format->clockrate_hz != 0)
3016 ? format->clockrate_hz
3017 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00003018}
3019
Minyue2013aec2015-05-13 14:14:42 +02003020int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003021 RtcpMode method = _rtpRtcpModule->RTCP();
3022 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003023 return 0;
3024 }
3025 std::vector<RTCPReportBlock> report_blocks;
3026 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003027
3028 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003029 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003030 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003031 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003032 Channel* channel = associate_send_channel_.channel();
3033 // Tries to get RTT from an associated channel. This is important for
3034 // receive-only channels.
3035 if (channel) {
3036 // To prevent infinite recursion and deadlock, calling GetRTT of
3037 // associate channel should always use "false" for argument:
3038 // |allow_associate_channel|.
3039 rtt = channel->GetRTT(false);
3040 }
3041 }
3042 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003043 }
3044
3045 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3046 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3047 for (; it != report_blocks.end(); ++it) {
3048 if (it->remoteSSRC == remoteSSRC)
3049 break;
3050 }
3051 if (it == report_blocks.end()) {
3052 // We have not received packets with SSRC matching the report blocks.
3053 // To calculate RTT we try with the SSRC of the first report block.
3054 // This is very important for send-only channels where we don't know
3055 // the SSRC of the other end.
3056 remoteSSRC = report_blocks[0].remoteSSRC;
3057 }
Minyue2013aec2015-05-13 14:14:42 +02003058
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003059 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003060 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003061 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003062 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3063 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003064 return 0;
3065 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003066 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003067}
3068
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003069} // namespace voe
3070} // namespace webrtc