blob: e9cbc77f41543b06c3adbc61149cb727b5b98c28 [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
kwiberg670a7f32017-03-24 05:56:21 -0700991 // --- Register all supported codecs to the receiving side of the
992 // RTP/RTCP module
kwiberg55b97fe2016-01-28 05:22:45 -0800993
994 CodecInst codec;
995 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
996
997 for (int idx = 0; idx < nSupportedCodecs; idx++) {
998 // Open up the RTP/RTCP receiver for all supported codecs
999 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08001000 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001001 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1002 "Channel::Init() unable to register %s "
1003 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1004 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1005 codec.rate);
1006 } else {
1007 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1008 "Channel::Init() %s (%d/%d/%" PRIuS
1009 "/%d) has been "
1010 "added to the RTP/RTCP receiver",
1011 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1012 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001013 }
1014
kwiberg55b97fe2016-01-28 05:22:45 -08001015 // Ensure that PCMU is used as default codec on the sending side
1016 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
1017 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +00001018 }
1019
kwiberg55b97fe2016-01-28 05:22:45 -08001020 // Register default PT for outband 'telephone-event'
1021 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -07001022 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
kwibergda2bf4e2016-10-24 13:47:09 -07001023 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1024 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001025 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1026 "Channel::Init() failed to register outband "
1027 "'telephone-event' (%d/%d) correctly",
1028 codec.pltype, codec.plfreq);
1029 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001030 }
1031
kwiberg55b97fe2016-01-28 05:22:45 -08001032 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -07001033 if (!codec_manager_.RegisterEncoder(codec) ||
1034 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
kwibergda2bf4e2016-10-24 13:47:09 -07001035 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1036 CodecInstToSdp(codec)) ||
kwibergc8d071e2016-04-06 12:22:38 -07001037 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001038 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1039 "Channel::Init() failed to register CN (%d/%d) "
1040 "correctly - 1",
1041 codec.pltype, codec.plfreq);
1042 }
1043 }
kwiberg55b97fe2016-01-28 05:22:45 -08001044 }
kwiberg670a7f32017-03-24 05:56:21 -07001045
1046 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001047}
1048
tommi0a2391f2017-03-21 02:31:51 -07001049void Channel::Terminate() {
1050 RTC_DCHECK(construction_thread_.CalledOnValidThread());
1051 // Must be called on the same thread as Init().
1052 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
1053 "Channel::Terminate");
1054
1055 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
1056
1057 StopSend();
1058 StopPlayout();
1059
1060 {
1061 rtc::CritScope cs(&_fileCritSect);
1062 if (input_file_player_) {
1063 input_file_player_->RegisterModuleFileCallback(NULL);
1064 input_file_player_->StopPlayingFile();
1065 }
1066 if (output_file_player_) {
1067 output_file_player_->RegisterModuleFileCallback(NULL);
1068 output_file_player_->StopPlayingFile();
1069 }
1070 if (output_file_recorder_) {
1071 output_file_recorder_->RegisterModuleFileCallback(NULL);
1072 output_file_recorder_->StopRecording();
1073 }
1074 }
1075
1076 // The order to safely shutdown modules in a channel is:
1077 // 1. De-register callbacks in modules
1078 // 2. De-register modules in process thread
1079 // 3. Destroy modules
1080 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1081 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1082 "Terminate() failed to de-register transport callback"
1083 " (Audio coding module)");
1084 }
1085
1086 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1087 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1088 "Terminate() failed to de-register VAD callback"
1089 " (Audio coding module)");
1090 }
1091
1092 // De-register modules in process thread
1093 if (_moduleProcessThreadPtr)
1094 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
1095
1096 // End of modules shutdown
1097}
1098
kwiberg55b97fe2016-01-28 05:22:45 -08001099int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1100 OutputMixer& outputMixer,
kwiberg55b97fe2016-01-28 05:22:45 -08001101 ProcessThread& moduleProcessThread,
1102 AudioDeviceModule& audioDeviceModule,
1103 VoiceEngineObserver* voiceEngineObserver,
1104 rtc::CriticalSection* callbackCritSect) {
1105 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1106 "Channel::SetEngineInformation()");
1107 _engineStatisticsPtr = &engineStatistics;
1108 _outputMixerPtr = &outputMixer;
kwiberg55b97fe2016-01-28 05:22:45 -08001109 _moduleProcessThreadPtr = &moduleProcessThread;
1110 _audioDeviceModulePtr = &audioDeviceModule;
1111 _voiceEngineObserverPtr = voiceEngineObserver;
1112 _callbackCritSectPtr = callbackCritSect;
1113 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001114}
1115
kwiberg55b97fe2016-01-28 05:22:45 -08001116int32_t Channel::UpdateLocalTimeStamp() {
1117 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1118 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001119}
1120
kwibergb7f89d62016-02-17 10:04:18 -08001121void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001122 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001123 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001124}
1125
ossu29b1a8d2016-06-13 07:34:51 -07001126const rtc::scoped_refptr<AudioDecoderFactory>&
1127Channel::GetAudioDecoderFactory() const {
1128 return decoder_factory_;
1129}
1130
kwiberg55b97fe2016-01-28 05:22:45 -08001131int32_t Channel::StartPlayout() {
1132 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1133 "Channel::StartPlayout()");
1134 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001135 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001136 }
1137
solenberge374e012017-02-14 04:55:00 -08001138 // Add participant as candidates for mixing.
1139 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1140 _engineStatisticsPtr->SetLastError(
1141 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1142 "StartPlayout() failed to add participant to mixer");
1143 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001144 }
1145
1146 channel_state_.SetPlaying(true);
1147 if (RegisterFilePlayingToMixer() != 0)
1148 return -1;
1149
1150 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001151}
1152
kwiberg55b97fe2016-01-28 05:22:45 -08001153int32_t Channel::StopPlayout() {
1154 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1155 "Channel::StopPlayout()");
1156 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001157 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001158 }
1159
solenberge374e012017-02-14 04:55:00 -08001160 // Remove participant as candidates for mixing
1161 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1162 _engineStatisticsPtr->SetLastError(
1163 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1164 "StopPlayout() failed to remove participant from mixer");
1165 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001166 }
1167
1168 channel_state_.SetPlaying(false);
1169 _outputAudioLevel.Clear();
1170
1171 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001172}
1173
kwiberg55b97fe2016-01-28 05:22:45 -08001174int32_t Channel::StartSend() {
1175 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1176 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -08001177 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001178 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001179 }
1180 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001181
solenberg08b19df2017-02-15 00:42:31 -08001182 // Resume the previous sequence number which was reset by StopSend(). This
1183 // needs to be done before |sending| is set to true on the RTP/RTCP module.
1184 if (send_sequence_number_) {
1185 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
1186 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001187 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001188 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1189 _engineStatisticsPtr->SetLastError(
1190 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1191 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001192 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001193 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001194 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001195 return -1;
1196 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001197
kwiberg55b97fe2016-01-28 05:22:45 -08001198 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001199}
1200
kwiberg55b97fe2016-01-28 05:22:45 -08001201int32_t Channel::StopSend() {
1202 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1203 "Channel::StopSend()");
1204 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001205 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001206 }
1207 channel_state_.SetSending(false);
1208
1209 // Store the sequence number to be able to pick up the same sequence for
1210 // the next StartSend(). This is needed for restarting device, otherwise
1211 // it might cause libSRTP to complain about packets being replayed.
1212 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1213 // CL is landed. See issue
1214 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1215 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1216
1217 // Reset sending SSRC and sequence number and triggers direct transmission
1218 // of RTCP BYE
1219 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1220 _engineStatisticsPtr->SetLastError(
1221 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1222 "StartSend() RTP/RTCP failed to stop sending");
1223 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001224 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001225
1226 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001227}
1228
kwiberg55b97fe2016-01-28 05:22:45 -08001229int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1230 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1231 "Channel::RegisterVoiceEngineObserver()");
1232 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001233
kwiberg55b97fe2016-01-28 05:22:45 -08001234 if (_voiceEngineObserverPtr) {
1235 _engineStatisticsPtr->SetLastError(
1236 VE_INVALID_OPERATION, kTraceError,
1237 "RegisterVoiceEngineObserver() observer already enabled");
1238 return -1;
1239 }
1240 _voiceEngineObserverPtr = &observer;
1241 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001242}
1243
kwiberg55b97fe2016-01-28 05:22:45 -08001244int32_t Channel::DeRegisterVoiceEngineObserver() {
1245 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1246 "Channel::DeRegisterVoiceEngineObserver()");
1247 rtc::CritScope cs(&_callbackCritSect);
1248
1249 if (!_voiceEngineObserverPtr) {
1250 _engineStatisticsPtr->SetLastError(
1251 VE_INVALID_OPERATION, kTraceWarning,
1252 "DeRegisterVoiceEngineObserver() observer already disabled");
1253 return 0;
1254 }
1255 _voiceEngineObserverPtr = NULL;
1256 return 0;
1257}
1258
1259int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001260 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001261 if (send_codec) {
1262 codec = *send_codec;
1263 return 0;
1264 }
1265 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001266}
1267
kwiberg55b97fe2016-01-28 05:22:45 -08001268int32_t Channel::GetRecCodec(CodecInst& codec) {
1269 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001270}
1271
kwiberg55b97fe2016-01-28 05:22:45 -08001272int32_t Channel::SetSendCodec(const CodecInst& codec) {
1273 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1274 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001275
kwibergc8d071e2016-04-06 12:22:38 -07001276 if (!codec_manager_.RegisterEncoder(codec) ||
1277 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001278 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1279 "SetSendCodec() failed to register codec to ACM");
1280 return -1;
1281 }
1282
1283 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1284 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1285 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1286 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1287 "SetSendCodec() failed to register codec to"
1288 " RTP/RTCP module");
1289 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001290 }
kwiberg55b97fe2016-01-28 05:22:45 -08001291 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001292
kwiberg55b97fe2016-01-28 05:22:45 -08001293 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001294}
1295
minyue78b4d562016-11-30 04:47:39 -08001296void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001297 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1298 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001299 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001300 if (*encoder) {
1301 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001302 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001303 }
1304 });
michaelt566d8202017-01-12 10:17:38 -08001305 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001306}
1307
elad.alond12a8e12017-03-23 11:04:48 -07001308void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1309 if (!use_twcc_plr_for_ana_)
1310 return;
minyue7e304322016-10-12 05:00:55 -07001311 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001312 if (*encoder) {
1313 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1314 }
1315 });
1316}
1317
elad.alondadb4dc2017-03-23 15:29:50 -07001318void Channel::OnRecoverableUplinkPacketLossRate(
1319 float recoverable_packet_loss_rate) {
1320 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1321 if (*encoder) {
1322 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1323 recoverable_packet_loss_rate);
1324 }
1325 });
1326}
1327
elad.alond12a8e12017-03-23 11:04:48 -07001328void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1329 if (use_twcc_plr_for_ana_)
1330 return;
1331 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1332 if (*encoder) {
1333 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1334 }
minyue7e304322016-10-12 05:00:55 -07001335 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001336}
1337
kwiberg55b97fe2016-01-28 05:22:45 -08001338int32_t Channel::SetVADStatus(bool enableVAD,
1339 ACMVADMode mode,
1340 bool disableDTX) {
1341 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1342 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001343 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1344 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1345 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001346 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1347 kTraceError,
1348 "SetVADStatus() failed to set VAD");
1349 return -1;
1350 }
1351 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001352}
1353
kwiberg55b97fe2016-01-28 05:22:45 -08001354int32_t Channel::GetVADStatus(bool& enabledVAD,
1355 ACMVADMode& mode,
1356 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001357 const auto* params = codec_manager_.GetStackParams();
1358 enabledVAD = params->use_cng;
1359 mode = params->vad_mode;
1360 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001361 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001362}
1363
kwiberg55b97fe2016-01-28 05:22:45 -08001364int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
kwibergd32bf752017-01-19 07:03:59 -08001365 return SetRecPayloadType(codec.pltype, CodecInstToSdp(codec));
1366}
1367
1368int32_t Channel::SetRecPayloadType(int payload_type,
1369 const SdpAudioFormat& format) {
kwiberg55b97fe2016-01-28 05:22:45 -08001370 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1371 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001372
kwiberg55b97fe2016-01-28 05:22:45 -08001373 if (channel_state_.Get().playing) {
1374 _engineStatisticsPtr->SetLastError(
1375 VE_ALREADY_PLAYING, kTraceError,
1376 "SetRecPayloadType() unable to set PT while playing");
1377 return -1;
1378 }
kwiberg55b97fe2016-01-28 05:22:45 -08001379
kwiberg09f090c2017-03-01 01:57:11 -08001380 const CodecInst codec = SdpToCodecInst(payload_type, format);
kwibergd32bf752017-01-19 07:03:59 -08001381
1382 if (payload_type == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001383 // De-register the selected codec (RTP/RTCP module and ACM)
1384
1385 int8_t pltype(-1);
1386 CodecInst rxCodec = codec;
1387
1388 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001389 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001390 rxCodec.pltype = pltype;
1391
1392 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1393 _engineStatisticsPtr->SetLastError(
1394 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1395 "SetRecPayloadType() RTP/RTCP-module deregistration "
1396 "failed");
1397 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001398 }
kwiberg55b97fe2016-01-28 05:22:45 -08001399 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1400 _engineStatisticsPtr->SetLastError(
1401 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1402 "SetRecPayloadType() ACM deregistration failed - 1");
1403 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001404 }
kwiberg55b97fe2016-01-28 05:22:45 -08001405 return 0;
1406 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001407
magjed56124bd2016-11-24 09:34:46 -08001408 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001409 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001410 // TODO(kwiberg): Retrying is probably not necessary, since
1411 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001412 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001413 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001414 _engineStatisticsPtr->SetLastError(
1415 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1416 "SetRecPayloadType() RTP/RTCP-module registration failed");
1417 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001418 }
kwiberg55b97fe2016-01-28 05:22:45 -08001419 }
kwibergd32bf752017-01-19 07:03:59 -08001420 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
1421 audio_coding_->UnregisterReceiveCodec(payload_type);
1422 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001423 _engineStatisticsPtr->SetLastError(
1424 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1425 "SetRecPayloadType() ACM registration failed - 1");
1426 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001427 }
kwiberg55b97fe2016-01-28 05:22:45 -08001428 }
1429 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001430}
1431
kwiberg55b97fe2016-01-28 05:22:45 -08001432int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1433 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001434 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001435 _engineStatisticsPtr->SetLastError(
1436 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1437 "GetRecPayloadType() failed to retrieve RX payload type");
1438 return -1;
1439 }
1440 codec.pltype = payloadType;
1441 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001442}
1443
kwiberg55b97fe2016-01-28 05:22:45 -08001444int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1445 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1446 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001447
kwiberg55b97fe2016-01-28 05:22:45 -08001448 CodecInst codec;
1449 int32_t samplingFreqHz(-1);
1450 const size_t kMono = 1;
1451 if (frequency == kFreq32000Hz)
1452 samplingFreqHz = 32000;
1453 else if (frequency == kFreq16000Hz)
1454 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001455
kwiberg55b97fe2016-01-28 05:22:45 -08001456 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1457 _engineStatisticsPtr->SetLastError(
1458 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1459 "SetSendCNPayloadType() failed to retrieve default CN codec "
1460 "settings");
1461 return -1;
1462 }
1463
1464 // Modify the payload type (must be set to dynamic range)
1465 codec.pltype = type;
1466
kwibergc8d071e2016-04-06 12:22:38 -07001467 if (!codec_manager_.RegisterEncoder(codec) ||
1468 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001469 _engineStatisticsPtr->SetLastError(
1470 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1471 "SetSendCNPayloadType() failed to register CN to ACM");
1472 return -1;
1473 }
1474
1475 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1476 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1477 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1478 _engineStatisticsPtr->SetLastError(
1479 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1480 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1481 "module");
1482 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001483 }
kwiberg55b97fe2016-01-28 05:22:45 -08001484 }
1485 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001486}
1487
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001488int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001489 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001490 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001491
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001492 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001493 _engineStatisticsPtr->SetLastError(
1494 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001495 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001496 return -1;
1497 }
1498 return 0;
1499}
1500
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001501int Channel::SetOpusDtx(bool enable_dtx) {
1502 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1503 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001504 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001505 : audio_coding_->DisableOpusDtx();
1506 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001507 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1508 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001509 return -1;
1510 }
1511 return 0;
1512}
1513
ivoc85228d62016-07-27 04:53:47 -07001514int Channel::GetOpusDtx(bool* enabled) {
1515 int success = -1;
1516 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1517 if (encoder) {
1518 *enabled = encoder->GetDtx();
1519 success = 0;
1520 }
1521 });
1522 return success;
1523}
1524
minyue7e304322016-10-12 05:00:55 -07001525bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1526 bool success = false;
1527 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1528 if (*encoder) {
1529 success = (*encoder)->EnableAudioNetworkAdaptor(
michaeltbf279fc2017-01-13 06:02:29 -08001530 config_string, event_log_proxy_.get(), Clock::GetRealTimeClock());
minyue7e304322016-10-12 05:00:55 -07001531 }
1532 });
1533 return success;
1534}
1535
1536void Channel::DisableAudioNetworkAdaptor() {
1537 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1538 if (*encoder)
1539 (*encoder)->DisableAudioNetworkAdaptor();
1540 });
1541}
1542
1543void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1544 int max_frame_length_ms) {
1545 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1546 if (*encoder) {
1547 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1548 max_frame_length_ms);
1549 }
1550 });
1551}
1552
mflodman3d7db262016-04-29 00:57:13 -07001553int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001554 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001555 "Channel::RegisterExternalTransport()");
1556
kwiberg55b97fe2016-01-28 05:22:45 -08001557 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001558 if (_externalTransport) {
1559 _engineStatisticsPtr->SetLastError(
1560 VE_INVALID_OPERATION, kTraceError,
1561 "RegisterExternalTransport() external transport already enabled");
1562 return -1;
1563 }
1564 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001565 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001566 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001567}
1568
kwiberg55b97fe2016-01-28 05:22:45 -08001569int32_t Channel::DeRegisterExternalTransport() {
1570 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1571 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001572
kwiberg55b97fe2016-01-28 05:22:45 -08001573 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001574 if (_transportPtr) {
1575 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1576 "DeRegisterExternalTransport() all transport is disabled");
1577 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001578 _engineStatisticsPtr->SetLastError(
1579 VE_INVALID_OPERATION, kTraceWarning,
1580 "DeRegisterExternalTransport() external transport already "
1581 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001582 }
1583 _externalTransport = false;
1584 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001585 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001586}
1587
nisse657bab22017-02-21 06:28:10 -08001588// TODO(nisse): Delete this method together with ReceivedRTPPacket.
1589// It's a temporary hack to support both ReceivedRTPPacket and
1590// OnRtpPacket interfaces without too much code duplication.
1591bool Channel::OnRtpPacketWithHeader(const uint8_t* received_packet,
1592 size_t length,
1593 RTPHeader *header) {
1594 // Store playout timestamp for the received RTP packet
1595 UpdatePlayoutTimestamp(false);
1596
1597 header->payload_type_frequency =
1598 rtp_payload_registry_->GetPayloadTypeFrequency(header->payloadType);
1599 if (header->payload_type_frequency < 0)
1600 return false;
1601 bool in_order = IsPacketInOrder(*header);
1602 rtp_receive_statistics_->IncomingPacket(
1603 *header, length, IsPacketRetransmitted(*header, in_order));
1604 rtp_payload_registry_->SetIncomingPayloadType(*header);
1605
1606 return ReceivePacket(received_packet, length, *header, in_order);
1607}
1608
mflodman3d7db262016-04-29 00:57:13 -07001609int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001610 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001611 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001612 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001613 "Channel::ReceivedRTPPacket()");
1614
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001615 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001616 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1617 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1618 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001619 return -1;
1620 }
nisse657bab22017-02-21 06:28:10 -08001621 return OnRtpPacketWithHeader(received_packet, length, &header) ? 0 : -1;
1622}
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001623
nisse657bab22017-02-21 06:28:10 -08001624void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1625 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
1626 "Channel::ReceivedRTPPacket()");
1627
1628 RTPHeader header;
1629 packet.GetHeader(&header);
1630 OnRtpPacketWithHeader(packet.data(), packet.size(), &header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001631}
1632
1633bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001634 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001635 const RTPHeader& header,
1636 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001637 if (rtp_payload_registry_->IsRtx(header)) {
1638 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001639 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001640 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001641 assert(packet_length >= header.headerLength);
1642 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001643 PayloadUnion payload_specific;
1644 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001645 &payload_specific)) {
1646 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001647 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001648 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1649 payload_specific, in_order);
1650}
1651
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001652bool Channel::HandleRtxPacket(const uint8_t* packet,
1653 size_t packet_length,
1654 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001655 if (!rtp_payload_registry_->IsRtx(header))
1656 return false;
1657
1658 // Remove the RTX header and parse the original RTP header.
1659 if (packet_length < header.headerLength)
1660 return false;
1661 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1662 return false;
1663 if (restored_packet_in_use_) {
1664 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1665 "Multiple RTX headers detected, dropping packet");
1666 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001667 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001668 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001669 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1670 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001671 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1672 "Incoming RTX packet: invalid RTP header");
1673 return false;
1674 }
1675 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001676 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001677 restored_packet_in_use_ = false;
1678 return ret;
1679}
1680
1681bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1682 StreamStatistician* statistician =
1683 rtp_receive_statistics_->GetStatistician(header.ssrc);
1684 if (!statistician)
1685 return false;
1686 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001687}
1688
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001689bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1690 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001691 // Retransmissions are handled separately if RTX is enabled.
1692 if (rtp_payload_registry_->RtxEnabled())
1693 return false;
1694 StreamStatistician* statistician =
1695 rtp_receive_statistics_->GetStatistician(header.ssrc);
1696 if (!statistician)
1697 return false;
1698 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001699 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001700 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001701 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001702}
1703
mflodman3d7db262016-04-29 00:57:13 -07001704int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001705 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001706 "Channel::ReceivedRTCPPacket()");
1707 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001708 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001709
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001710 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001711 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001712 _engineStatisticsPtr->SetLastError(
1713 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1714 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1715 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001716
Minyue2013aec2015-05-13 14:14:42 +02001717 int64_t rtt = GetRTT(true);
1718 if (rtt == 0) {
1719 // Waiting for valid RTT.
1720 return 0;
1721 }
Erik Språng737336d2016-07-29 12:59:36 +02001722
1723 int64_t nack_window_ms = rtt;
1724 if (nack_window_ms < kMinRetransmissionWindowMs) {
1725 nack_window_ms = kMinRetransmissionWindowMs;
1726 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1727 nack_window_ms = kMaxRetransmissionWindowMs;
1728 }
1729 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1730
minyue7e304322016-10-12 05:00:55 -07001731 // Invoke audio encoders OnReceivedRtt().
1732 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1733 if (*encoder)
1734 (*encoder)->OnReceivedRtt(rtt);
1735 });
1736
Minyue2013aec2015-05-13 14:14:42 +02001737 uint32_t ntp_secs = 0;
1738 uint32_t ntp_frac = 0;
1739 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001740 if (0 !=
1741 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1742 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001743 // Waiting for RTCP.
1744 return 0;
1745 }
1746
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001747 {
tommi31fc21f2016-01-21 10:37:37 -08001748 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001749 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001750 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001751 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001752}
1753
niklase@google.com470e71d2011-07-07 08:21:25 +00001754int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001755 bool loop,
1756 FileFormats format,
1757 int startPosition,
1758 float volumeScaling,
1759 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001760 const CodecInst* codecInst) {
1761 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1762 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1763 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1764 "stopPosition=%d)",
1765 fileName, loop, format, volumeScaling, startPosition,
1766 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001767
kwiberg55b97fe2016-01-28 05:22:45 -08001768 if (channel_state_.Get().output_file_playing) {
1769 _engineStatisticsPtr->SetLastError(
1770 VE_ALREADY_PLAYING, kTraceError,
1771 "StartPlayingFileLocally() is already playing");
1772 return -1;
1773 }
1774
1775 {
1776 rtc::CritScope cs(&_fileCritSect);
1777
kwiberg5a25d952016-08-17 07:31:12 -07001778 if (output_file_player_) {
1779 output_file_player_->RegisterModuleFileCallback(NULL);
1780 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001781 }
1782
kwiberg5b356f42016-09-08 04:32:33 -07001783 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001784 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001785
kwiberg5a25d952016-08-17 07:31:12 -07001786 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001787 _engineStatisticsPtr->SetLastError(
1788 VE_INVALID_ARGUMENT, kTraceError,
1789 "StartPlayingFileLocally() filePlayer format is not correct");
1790 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001791 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001792
kwiberg55b97fe2016-01-28 05:22:45 -08001793 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001794
kwiberg5a25d952016-08-17 07:31:12 -07001795 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001796 fileName, loop, startPosition, volumeScaling, notificationTime,
1797 stopPosition, (const CodecInst*)codecInst) != 0) {
1798 _engineStatisticsPtr->SetLastError(
1799 VE_BAD_FILE, kTraceError,
1800 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001801 output_file_player_->StopPlayingFile();
1802 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001803 return -1;
1804 }
kwiberg5a25d952016-08-17 07:31:12 -07001805 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001806 channel_state_.SetOutputFilePlaying(true);
1807 }
1808
1809 if (RegisterFilePlayingToMixer() != 0)
1810 return -1;
1811
1812 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001813}
1814
1815int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001816 FileFormats format,
1817 int startPosition,
1818 float volumeScaling,
1819 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001820 const CodecInst* codecInst) {
1821 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1822 "Channel::StartPlayingFileLocally(format=%d,"
1823 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1824 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001825
kwiberg55b97fe2016-01-28 05:22:45 -08001826 if (stream == NULL) {
1827 _engineStatisticsPtr->SetLastError(
1828 VE_BAD_FILE, kTraceError,
1829 "StartPlayingFileLocally() NULL as input stream");
1830 return -1;
1831 }
1832
1833 if (channel_state_.Get().output_file_playing) {
1834 _engineStatisticsPtr->SetLastError(
1835 VE_ALREADY_PLAYING, kTraceError,
1836 "StartPlayingFileLocally() is already playing");
1837 return -1;
1838 }
1839
1840 {
1841 rtc::CritScope cs(&_fileCritSect);
1842
1843 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001844 if (output_file_player_) {
1845 output_file_player_->RegisterModuleFileCallback(NULL);
1846 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001847 }
1848
kwiberg55b97fe2016-01-28 05:22:45 -08001849 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001850 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001851 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001852
kwiberg5a25d952016-08-17 07:31:12 -07001853 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001854 _engineStatisticsPtr->SetLastError(
1855 VE_INVALID_ARGUMENT, kTraceError,
1856 "StartPlayingFileLocally() filePlayer format isnot correct");
1857 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001858 }
1859
kwiberg55b97fe2016-01-28 05:22:45 -08001860 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001861
kwiberg4ec01d92016-08-22 08:43:54 -07001862 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001863 volumeScaling, notificationTime,
1864 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001865 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1866 "StartPlayingFile() failed to "
1867 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001868 output_file_player_->StopPlayingFile();
1869 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001870 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001871 }
kwiberg5a25d952016-08-17 07:31:12 -07001872 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001873 channel_state_.SetOutputFilePlaying(true);
1874 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001875
kwiberg55b97fe2016-01-28 05:22:45 -08001876 if (RegisterFilePlayingToMixer() != 0)
1877 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001878
kwiberg55b97fe2016-01-28 05:22:45 -08001879 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001880}
1881
kwiberg55b97fe2016-01-28 05:22:45 -08001882int Channel::StopPlayingFileLocally() {
1883 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1884 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001885
kwiberg55b97fe2016-01-28 05:22:45 -08001886 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001887 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001888 }
1889
1890 {
1891 rtc::CritScope cs(&_fileCritSect);
1892
kwiberg5a25d952016-08-17 07:31:12 -07001893 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001894 _engineStatisticsPtr->SetLastError(
1895 VE_STOP_RECORDING_FAILED, kTraceError,
1896 "StopPlayingFile() could not stop playing");
1897 return -1;
1898 }
kwiberg5a25d952016-08-17 07:31:12 -07001899 output_file_player_->RegisterModuleFileCallback(NULL);
1900 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001901 channel_state_.SetOutputFilePlaying(false);
1902 }
1903 // _fileCritSect cannot be taken while calling
1904 // SetAnonymousMixibilityStatus. Refer to comments in
1905 // StartPlayingFileLocally(const char* ...) for more details.
1906 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1907 _engineStatisticsPtr->SetLastError(
1908 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1909 "StopPlayingFile() failed to stop participant from playing as"
1910 "file in the mixer");
1911 return -1;
1912 }
1913
1914 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001915}
1916
kwiberg55b97fe2016-01-28 05:22:45 -08001917int Channel::IsPlayingFileLocally() const {
1918 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001919}
1920
kwiberg55b97fe2016-01-28 05:22:45 -08001921int Channel::RegisterFilePlayingToMixer() {
1922 // Return success for not registering for file playing to mixer if:
1923 // 1. playing file before playout is started on that channel.
1924 // 2. starting playout without file playing on that channel.
1925 if (!channel_state_.Get().playing ||
1926 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001927 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001928 }
1929
1930 // |_fileCritSect| cannot be taken while calling
1931 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1932 // frames can be pulled by the mixer. Since the frames are generated from
1933 // the file, _fileCritSect will be taken. This would result in a deadlock.
1934 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1935 channel_state_.SetOutputFilePlaying(false);
1936 rtc::CritScope cs(&_fileCritSect);
1937 _engineStatisticsPtr->SetLastError(
1938 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1939 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07001940 output_file_player_->StopPlayingFile();
1941 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001942 return -1;
1943 }
1944
1945 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001946}
1947
niklase@google.com470e71d2011-07-07 08:21:25 +00001948int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001949 bool loop,
1950 FileFormats format,
1951 int startPosition,
1952 float volumeScaling,
1953 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001954 const CodecInst* codecInst) {
1955 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1956 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1957 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1958 "stopPosition=%d)",
1959 fileName, loop, format, volumeScaling, startPosition,
1960 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001961
kwiberg55b97fe2016-01-28 05:22:45 -08001962 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001963
kwiberg55b97fe2016-01-28 05:22:45 -08001964 if (channel_state_.Get().input_file_playing) {
1965 _engineStatisticsPtr->SetLastError(
1966 VE_ALREADY_PLAYING, kTraceWarning,
1967 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001968 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001969 }
1970
1971 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001972 if (input_file_player_) {
1973 input_file_player_->RegisterModuleFileCallback(NULL);
1974 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001975 }
1976
1977 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001978 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07001979 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08001980
kwiberg5a25d952016-08-17 07:31:12 -07001981 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001982 _engineStatisticsPtr->SetLastError(
1983 VE_INVALID_ARGUMENT, kTraceError,
1984 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1985 return -1;
1986 }
1987
1988 const uint32_t notificationTime(0);
1989
kwiberg5a25d952016-08-17 07:31:12 -07001990 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001991 fileName, loop, startPosition, volumeScaling, notificationTime,
1992 stopPosition, (const CodecInst*)codecInst) != 0) {
1993 _engineStatisticsPtr->SetLastError(
1994 VE_BAD_FILE, kTraceError,
1995 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001996 input_file_player_->StopPlayingFile();
1997 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001998 return -1;
1999 }
kwiberg5a25d952016-08-17 07:31:12 -07002000 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002001 channel_state_.SetInputFilePlaying(true);
2002
2003 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002004}
2005
2006int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002007 FileFormats format,
2008 int startPosition,
2009 float volumeScaling,
2010 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002011 const CodecInst* codecInst) {
2012 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2013 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2014 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2015 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002016
kwiberg55b97fe2016-01-28 05:22:45 -08002017 if (stream == NULL) {
2018 _engineStatisticsPtr->SetLastError(
2019 VE_BAD_FILE, kTraceError,
2020 "StartPlayingFileAsMicrophone NULL as input stream");
2021 return -1;
2022 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002023
kwiberg55b97fe2016-01-28 05:22:45 -08002024 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002025
kwiberg55b97fe2016-01-28 05:22:45 -08002026 if (channel_state_.Get().input_file_playing) {
2027 _engineStatisticsPtr->SetLastError(
2028 VE_ALREADY_PLAYING, kTraceWarning,
2029 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002030 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002031 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002032
kwiberg55b97fe2016-01-28 05:22:45 -08002033 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002034 if (input_file_player_) {
2035 input_file_player_->RegisterModuleFileCallback(NULL);
2036 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002037 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002038
kwiberg55b97fe2016-01-28 05:22:45 -08002039 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002040 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002041 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002042
kwiberg5a25d952016-08-17 07:31:12 -07002043 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002044 _engineStatisticsPtr->SetLastError(
2045 VE_INVALID_ARGUMENT, kTraceError,
2046 "StartPlayingInputFile() filePlayer format isnot correct");
2047 return -1;
2048 }
2049
2050 const uint32_t notificationTime(0);
2051
kwiberg4ec01d92016-08-22 08:43:54 -07002052 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2053 notificationTime, stopPosition,
2054 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002055 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2056 "StartPlayingFile() failed to start "
2057 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002058 input_file_player_->StopPlayingFile();
2059 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002060 return -1;
2061 }
2062
kwiberg5a25d952016-08-17 07:31:12 -07002063 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002064 channel_state_.SetInputFilePlaying(true);
2065
2066 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002067}
2068
kwiberg55b97fe2016-01-28 05:22:45 -08002069int Channel::StopPlayingFileAsMicrophone() {
2070 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2071 "Channel::StopPlayingFileAsMicrophone()");
2072
2073 rtc::CritScope cs(&_fileCritSect);
2074
2075 if (!channel_state_.Get().input_file_playing) {
2076 return 0;
2077 }
2078
kwiberg5a25d952016-08-17 07:31:12 -07002079 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002080 _engineStatisticsPtr->SetLastError(
2081 VE_STOP_RECORDING_FAILED, kTraceError,
2082 "StopPlayingFile() could not stop playing");
2083 return -1;
2084 }
kwiberg5a25d952016-08-17 07:31:12 -07002085 input_file_player_->RegisterModuleFileCallback(NULL);
2086 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002087 channel_state_.SetInputFilePlaying(false);
2088
2089 return 0;
2090}
2091
2092int Channel::IsPlayingFileAsMicrophone() const {
2093 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002094}
2095
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002096int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002097 const CodecInst* codecInst) {
2098 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2099 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002100
kwiberg55b97fe2016-01-28 05:22:45 -08002101 if (_outputFileRecording) {
2102 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2103 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002104 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002105 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002106
kwiberg55b97fe2016-01-28 05:22:45 -08002107 FileFormats format;
2108 const uint32_t notificationTime(0); // Not supported in VoE
2109 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002110
kwiberg55b97fe2016-01-28 05:22:45 -08002111 if ((codecInst != NULL) &&
2112 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2113 _engineStatisticsPtr->SetLastError(
2114 VE_BAD_ARGUMENT, kTraceError,
2115 "StartRecordingPlayout() invalid compression");
2116 return (-1);
2117 }
2118 if (codecInst == NULL) {
2119 format = kFileFormatPcm16kHzFile;
2120 codecInst = &dummyCodec;
2121 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2122 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2123 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2124 format = kFileFormatWavFile;
2125 } else {
2126 format = kFileFormatCompressedFile;
2127 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002128
kwiberg55b97fe2016-01-28 05:22:45 -08002129 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002130
kwiberg55b97fe2016-01-28 05:22:45 -08002131 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002132 if (output_file_recorder_) {
2133 output_file_recorder_->RegisterModuleFileCallback(NULL);
2134 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002135 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002136
kwiberg5a25d952016-08-17 07:31:12 -07002137 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002138 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002139 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002140 _engineStatisticsPtr->SetLastError(
2141 VE_INVALID_ARGUMENT, kTraceError,
2142 "StartRecordingPlayout() fileRecorder format isnot correct");
2143 return -1;
2144 }
2145
kwiberg5a25d952016-08-17 07:31:12 -07002146 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002147 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2148 _engineStatisticsPtr->SetLastError(
2149 VE_BAD_FILE, kTraceError,
2150 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002151 output_file_recorder_->StopRecording();
2152 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002153 return -1;
2154 }
kwiberg5a25d952016-08-17 07:31:12 -07002155 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002156 _outputFileRecording = true;
2157
2158 return 0;
2159}
2160
2161int Channel::StartRecordingPlayout(OutStream* stream,
2162 const CodecInst* codecInst) {
2163 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2164 "Channel::StartRecordingPlayout()");
2165
2166 if (_outputFileRecording) {
2167 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2168 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002169 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002170 }
2171
2172 FileFormats format;
2173 const uint32_t notificationTime(0); // Not supported in VoE
2174 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2175
2176 if (codecInst != NULL && codecInst->channels != 1) {
2177 _engineStatisticsPtr->SetLastError(
2178 VE_BAD_ARGUMENT, kTraceError,
2179 "StartRecordingPlayout() invalid compression");
2180 return (-1);
2181 }
2182 if (codecInst == NULL) {
2183 format = kFileFormatPcm16kHzFile;
2184 codecInst = &dummyCodec;
2185 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2186 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2187 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2188 format = kFileFormatWavFile;
2189 } else {
2190 format = kFileFormatCompressedFile;
2191 }
2192
2193 rtc::CritScope cs(&_fileCritSect);
2194
2195 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002196 if (output_file_recorder_) {
2197 output_file_recorder_->RegisterModuleFileCallback(NULL);
2198 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002199 }
2200
kwiberg5a25d952016-08-17 07:31:12 -07002201 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002202 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002203 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002204 _engineStatisticsPtr->SetLastError(
2205 VE_INVALID_ARGUMENT, kTraceError,
2206 "StartRecordingPlayout() fileRecorder format isnot correct");
2207 return -1;
2208 }
2209
kwiberg4ec01d92016-08-22 08:43:54 -07002210 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002211 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002212 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2213 "StartRecordingPlayout() failed to "
2214 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002215 output_file_recorder_->StopRecording();
2216 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002217 return -1;
2218 }
2219
kwiberg5a25d952016-08-17 07:31:12 -07002220 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002221 _outputFileRecording = true;
2222
2223 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002224}
2225
kwiberg55b97fe2016-01-28 05:22:45 -08002226int Channel::StopRecordingPlayout() {
2227 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2228 "Channel::StopRecordingPlayout()");
2229
2230 if (!_outputFileRecording) {
2231 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2232 "StopRecordingPlayout() isnot recording");
2233 return -1;
2234 }
2235
2236 rtc::CritScope cs(&_fileCritSect);
2237
kwiberg5a25d952016-08-17 07:31:12 -07002238 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002239 _engineStatisticsPtr->SetLastError(
2240 VE_STOP_RECORDING_FAILED, kTraceError,
2241 "StopRecording() could not stop recording");
2242 return (-1);
2243 }
kwiberg5a25d952016-08-17 07:31:12 -07002244 output_file_recorder_->RegisterModuleFileCallback(NULL);
2245 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002246 _outputFileRecording = false;
2247
2248 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002249}
2250
kwiberg55b97fe2016-01-28 05:22:45 -08002251void Channel::SetMixWithMicStatus(bool mix) {
2252 rtc::CritScope cs(&_fileCritSect);
2253 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002254}
2255
solenberg8d73f8c2017-03-08 01:52:20 -08002256int Channel::GetSpeechOutputLevel() const {
2257 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002258}
2259
solenberg8d73f8c2017-03-08 01:52:20 -08002260int Channel::GetSpeechOutputLevelFullRange() const {
2261 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08002262}
2263
solenberg8d73f8c2017-03-08 01:52:20 -08002264void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002265 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002266 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002267}
2268
solenberg1c2af8e2016-03-24 10:36:00 -07002269bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002270 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002271 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002272}
2273
solenberg8d73f8c2017-03-08 01:52:20 -08002274void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08002275 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08002276 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00002277}
2278
solenberg8842c3e2016-03-11 03:06:41 -08002279int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002280 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002281 "Channel::SendTelephoneEventOutband(...)");
2282 RTC_DCHECK_LE(0, event);
2283 RTC_DCHECK_GE(255, event);
2284 RTC_DCHECK_LE(0, duration_ms);
2285 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002286 if (!Sending()) {
2287 return -1;
2288 }
solenberg8842c3e2016-03-11 03:06:41 -08002289 if (_rtpRtcpModule->SendTelephoneEventOutband(
2290 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002291 _engineStatisticsPtr->SetLastError(
2292 VE_SEND_DTMF_FAILED, kTraceWarning,
2293 "SendTelephoneEventOutband() failed to send event");
2294 return -1;
2295 }
2296 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002297}
2298
solenbergffbbcac2016-11-17 05:25:37 -08002299int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2300 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002301 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002302 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002303 RTC_DCHECK_LE(0, payload_type);
2304 RTC_DCHECK_GE(127, payload_type);
2305 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002306 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002307 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002308 memcpy(codec.plname, "telephone-event", 16);
2309 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2310 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2311 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2312 _engineStatisticsPtr->SetLastError(
2313 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2314 "SetSendTelephoneEventPayloadType() failed to register send"
2315 "payload type");
2316 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002317 }
kwiberg55b97fe2016-01-28 05:22:45 -08002318 }
kwiberg55b97fe2016-01-28 05:22:45 -08002319 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002320}
2321
kwiberg55b97fe2016-01-28 05:22:45 -08002322int Channel::SetLocalSSRC(unsigned int ssrc) {
2323 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2324 "Channel::SetLocalSSRC()");
2325 if (channel_state_.Get().sending) {
2326 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2327 "SetLocalSSRC() already sending");
2328 return -1;
2329 }
2330 _rtpRtcpModule->SetSSRC(ssrc);
2331 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002332}
2333
kwiberg55b97fe2016-01-28 05:22:45 -08002334int Channel::GetLocalSSRC(unsigned int& ssrc) {
2335 ssrc = _rtpRtcpModule->SSRC();
2336 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002337}
2338
kwiberg55b97fe2016-01-28 05:22:45 -08002339int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2340 ssrc = rtp_receiver_->SSRC();
2341 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002342}
2343
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002344int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002345 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002346 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002347}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002348
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002349int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2350 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002351 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2352 if (enable &&
2353 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2354 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002355 return -1;
2356 }
2357 return 0;
2358}
2359
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002360void Channel::EnableSendTransportSequenceNumber(int id) {
2361 int ret =
2362 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2363 RTC_DCHECK_EQ(0, ret);
2364}
2365
stefan3313ec92016-01-21 06:32:43 -08002366void Channel::EnableReceiveTransportSequenceNumber(int id) {
2367 rtp_header_parser_->DeregisterRtpHeaderExtension(
2368 kRtpExtensionTransportSequenceNumber);
2369 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2370 kRtpExtensionTransportSequenceNumber, id);
2371 RTC_DCHECK(ret);
2372}
2373
stefanbba9dec2016-02-01 04:39:55 -08002374void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07002375 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08002376 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07002377 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
2378 TransportFeedbackObserver* transport_feedback_observer =
2379 transport->transport_feedback_observer();
2380 PacketRouter* packet_router = transport->packet_router();
2381
stefanbba9dec2016-02-01 04:39:55 -08002382 RTC_DCHECK(rtp_packet_sender);
2383 RTC_DCHECK(transport_feedback_observer);
2384 RTC_DCHECK(packet_router && !packet_router_);
stefan7de8d642017-02-07 07:14:08 -08002385 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08002386 feedback_observer_proxy_->SetTransportFeedbackObserver(
2387 transport_feedback_observer);
2388 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2389 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2390 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002391 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002392 packet_router_ = packet_router;
2393}
2394
stefanbba9dec2016-02-01 04:39:55 -08002395void Channel::RegisterReceiverCongestionControlObjects(
2396 PacketRouter* packet_router) {
2397 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002398 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002399 packet_router_ = packet_router;
2400}
2401
2402void Channel::ResetCongestionControlObjects() {
2403 RTC_DCHECK(packet_router_);
2404 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08002405 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08002406 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2407 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002408 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002409 packet_router_ = nullptr;
2410 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2411}
2412
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002413void Channel::SetRTCPStatus(bool enable) {
2414 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2415 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002416 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002417}
2418
kwiberg55b97fe2016-01-28 05:22:45 -08002419int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002420 RtcpMode method = _rtpRtcpModule->RTCP();
2421 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002422 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002423}
2424
kwiberg55b97fe2016-01-28 05:22:45 -08002425int Channel::SetRTCP_CNAME(const char cName[256]) {
2426 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2427 "Channel::SetRTCP_CNAME()");
2428 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2429 _engineStatisticsPtr->SetLastError(
2430 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2431 "SetRTCP_CNAME() failed to set RTCP CNAME");
2432 return -1;
2433 }
2434 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002435}
2436
kwiberg55b97fe2016-01-28 05:22:45 -08002437int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2438 if (cName == NULL) {
2439 _engineStatisticsPtr->SetLastError(
2440 VE_INVALID_ARGUMENT, kTraceError,
2441 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2442 return -1;
2443 }
2444 char cname[RTCP_CNAME_SIZE];
2445 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2446 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2447 _engineStatisticsPtr->SetLastError(
2448 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2449 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2450 return -1;
2451 }
2452 strcpy(cName, cname);
2453 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002454}
2455
kwiberg55b97fe2016-01-28 05:22:45 -08002456int Channel::SendApplicationDefinedRTCPPacket(
2457 unsigned char subType,
2458 unsigned int name,
2459 const char* data,
2460 unsigned short dataLengthInBytes) {
2461 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2462 "Channel::SendApplicationDefinedRTCPPacket()");
2463 if (!channel_state_.Get().sending) {
2464 _engineStatisticsPtr->SetLastError(
2465 VE_NOT_SENDING, kTraceError,
2466 "SendApplicationDefinedRTCPPacket() not sending");
2467 return -1;
2468 }
2469 if (NULL == data) {
2470 _engineStatisticsPtr->SetLastError(
2471 VE_INVALID_ARGUMENT, kTraceError,
2472 "SendApplicationDefinedRTCPPacket() invalid data value");
2473 return -1;
2474 }
2475 if (dataLengthInBytes % 4 != 0) {
2476 _engineStatisticsPtr->SetLastError(
2477 VE_INVALID_ARGUMENT, kTraceError,
2478 "SendApplicationDefinedRTCPPacket() invalid length value");
2479 return -1;
2480 }
2481 RtcpMode status = _rtpRtcpModule->RTCP();
2482 if (status == RtcpMode::kOff) {
2483 _engineStatisticsPtr->SetLastError(
2484 VE_RTCP_ERROR, kTraceError,
2485 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2486 return -1;
2487 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002488
kwiberg55b97fe2016-01-28 05:22:45 -08002489 // Create and schedule the RTCP APP packet for transmission
2490 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2491 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2492 _engineStatisticsPtr->SetLastError(
2493 VE_SEND_ERROR, kTraceError,
2494 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2495 return -1;
2496 }
2497 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002498}
2499
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002500int Channel::GetRemoteRTCPReportBlocks(
2501 std::vector<ReportBlock>* report_blocks) {
2502 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002503 _engineStatisticsPtr->SetLastError(
2504 VE_INVALID_ARGUMENT, kTraceError,
2505 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002506 return -1;
2507 }
2508
2509 // Get the report blocks from the latest received RTCP Sender or Receiver
2510 // Report. Each element in the vector contains the sender's SSRC and a
2511 // report block according to RFC 3550.
2512 std::vector<RTCPReportBlock> rtcp_report_blocks;
2513 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002514 return -1;
2515 }
2516
2517 if (rtcp_report_blocks.empty())
2518 return 0;
2519
2520 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2521 for (; it != rtcp_report_blocks.end(); ++it) {
2522 ReportBlock report_block;
2523 report_block.sender_SSRC = it->remoteSSRC;
2524 report_block.source_SSRC = it->sourceSSRC;
2525 report_block.fraction_lost = it->fractionLost;
2526 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2527 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2528 report_block.interarrival_jitter = it->jitter;
2529 report_block.last_SR_timestamp = it->lastSR;
2530 report_block.delay_since_last_SR = it->delaySinceLastSR;
2531 report_blocks->push_back(report_block);
2532 }
2533 return 0;
2534}
2535
kwiberg55b97fe2016-01-28 05:22:45 -08002536int Channel::GetRTPStatistics(CallStatistics& stats) {
2537 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002538
kwiberg55b97fe2016-01-28 05:22:45 -08002539 // The jitter statistics is updated for each received RTP packet and is
2540 // based on received packets.
2541 RtcpStatistics statistics;
2542 StreamStatistician* statistician =
2543 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002544 if (statistician) {
2545 statistician->GetStatistics(&statistics,
2546 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002547 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002548
kwiberg55b97fe2016-01-28 05:22:45 -08002549 stats.fractionLost = statistics.fraction_lost;
2550 stats.cumulativeLost = statistics.cumulative_lost;
2551 stats.extendedMax = statistics.extended_max_sequence_number;
2552 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002553
kwiberg55b97fe2016-01-28 05:22:45 -08002554 // --- RTT
2555 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002556
kwiberg55b97fe2016-01-28 05:22:45 -08002557 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002558
kwiberg55b97fe2016-01-28 05:22:45 -08002559 size_t bytesSent(0);
2560 uint32_t packetsSent(0);
2561 size_t bytesReceived(0);
2562 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002563
kwiberg55b97fe2016-01-28 05:22:45 -08002564 if (statistician) {
2565 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2566 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002567
kwiberg55b97fe2016-01-28 05:22:45 -08002568 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2569 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2570 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2571 " output will not be complete");
2572 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002573
kwiberg55b97fe2016-01-28 05:22:45 -08002574 stats.bytesSent = bytesSent;
2575 stats.packetsSent = packetsSent;
2576 stats.bytesReceived = bytesReceived;
2577 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002578
kwiberg55b97fe2016-01-28 05:22:45 -08002579 // --- Timestamps
2580 {
2581 rtc::CritScope lock(&ts_stats_lock_);
2582 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2583 }
2584 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002585}
2586
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002587int Channel::SetCodecFECStatus(bool enable) {
2588 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2589 "Channel::SetCodecFECStatus()");
2590
kwibergc8d071e2016-04-06 12:22:38 -07002591 if (!codec_manager_.SetCodecFEC(enable) ||
2592 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002593 _engineStatisticsPtr->SetLastError(
2594 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2595 "SetCodecFECStatus() failed to set FEC state");
2596 return -1;
2597 }
2598 return 0;
2599}
2600
2601bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002602 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002603}
2604
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002605void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2606 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002607 // If pacing is enabled we always store packets.
2608 if (!pacing_enabled_)
2609 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002610 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002611 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002612 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002613 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002614 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002615}
2616
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002617// Called when we are missing one or more packets.
2618int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002619 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2620}
2621
kwiberg55b97fe2016-01-28 05:22:45 -08002622uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2623 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2624 "Channel::Demultiplex()");
2625 _audioFrame.CopyFrom(audioFrame);
2626 _audioFrame.id_ = _channelId;
2627 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002628}
2629
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002630void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002631 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002632 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002633 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002634 CodecInst codec;
2635 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002636
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002637 // Never upsample or upmix the capture signal here. This should be done at the
2638 // end of the send chain.
2639 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2640 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2641 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2642 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002643}
2644
kwiberg55b97fe2016-01-28 05:22:45 -08002645uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2646 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2647 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002648
kwiberg55b97fe2016-01-28 05:22:45 -08002649 if (_audioFrame.samples_per_channel_ == 0) {
2650 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2651 "Channel::PrepareEncodeAndSend() invalid audio frame");
2652 return 0xFFFFFFFF;
2653 }
2654
2655 if (channel_state_.Get().input_file_playing) {
2656 MixOrReplaceAudioWithFile(mixingFrequency);
2657 }
2658
solenberg1c2af8e2016-03-24 10:36:00 -07002659 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2660 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002661
kwiberg55b97fe2016-01-28 05:22:45 -08002662 if (_includeAudioLevelIndication) {
2663 size_t length =
2664 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02002665 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002666 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002667 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002668 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002669 rms_level_.Analyze(
2670 rtc::ArrayView<const int16_t>(_audioFrame.data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002671 }
kwiberg55b97fe2016-01-28 05:22:45 -08002672 }
solenberg1c2af8e2016-03-24 10:36:00 -07002673 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002674
kwiberg55b97fe2016-01-28 05:22:45 -08002675 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002676}
2677
kwiberg55b97fe2016-01-28 05:22:45 -08002678uint32_t Channel::EncodeAndSend() {
2679 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2680 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002681
kwiberg55b97fe2016-01-28 05:22:45 -08002682 assert(_audioFrame.num_channels_ <= 2);
2683 if (_audioFrame.samples_per_channel_ == 0) {
2684 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2685 "Channel::EncodeAndSend() invalid audio frame");
2686 return 0xFFFFFFFF;
2687 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002688
kwiberg55b97fe2016-01-28 05:22:45 -08002689 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00002690
kwiberg55b97fe2016-01-28 05:22:45 -08002691 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002692
kwiberg55b97fe2016-01-28 05:22:45 -08002693 // The ACM resamples internally.
2694 _audioFrame.timestamp_ = _timeStamp;
2695 // This call will trigger AudioPacketizationCallback::SendData if encoding
2696 // is done and payload is ready for packetization and transmission.
2697 // Otherwise, it will return without invoking the callback.
2698 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
2699 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
2700 "Channel::EncodeAndSend() ACM encoding failed");
2701 return 0xFFFFFFFF;
2702 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002703
kwiberg55b97fe2016-01-28 05:22:45 -08002704 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
2705 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002706}
2707
solenberg7602aab2016-11-14 11:30:07 -08002708void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2709 RTC_DCHECK(!channel.channel() ||
2710 channel.channel()->ChannelId() != _channelId);
2711 rtc::CritScope lock(&assoc_send_channel_lock_);
2712 associate_send_channel_ = channel;
2713}
2714
Minyue2013aec2015-05-13 14:14:42 +02002715void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002716 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002717 Channel* channel = associate_send_channel_.channel();
2718 if (channel && channel->ChannelId() == channel_id) {
2719 // If this channel is associated with a send channel of the specified
2720 // Channel ID, disassociate with it.
2721 ChannelOwner ref(NULL);
2722 associate_send_channel_ = ref;
2723 }
2724}
2725
ivoc14d5dbe2016-07-04 07:06:55 -07002726void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2727 event_log_proxy_->SetEventLog(event_log);
2728}
2729
michaelt9332b7d2016-11-30 07:51:13 -08002730void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2731 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2732}
2733
nisse284542b2017-01-10 08:58:32 -08002734void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08002735 size_t overhead_per_packet =
2736 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08002737 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2738 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08002739 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08002740 }
2741 });
2742}
2743
2744void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002745 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002746 transport_overhead_per_packet_ = transport_overhead_per_packet;
2747 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08002748}
2749
hbos3fd31fe2017-02-28 05:43:16 -08002750// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08002751void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002752 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002753 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
2754 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08002755}
2756
kwiberg55b97fe2016-01-28 05:22:45 -08002757int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2758 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002759}
2760
wu@webrtc.org24301a62013-12-13 19:17:43 +00002761void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2762 audio_coding_->GetDecodingCallStatistics(stats);
2763}
2764
solenberg358057b2015-11-27 10:46:42 -08002765uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08002766 rtc::CritScope lock(&video_sync_lock_);
2767 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07002768}
2769
kwiberg55b97fe2016-01-28 05:22:45 -08002770int Channel::SetMinimumPlayoutDelay(int delayMs) {
2771 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2772 "Channel::SetMinimumPlayoutDelay()");
2773 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
2774 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
2775 _engineStatisticsPtr->SetLastError(
2776 VE_INVALID_ARGUMENT, kTraceError,
2777 "SetMinimumPlayoutDelay() invalid min delay");
2778 return -1;
2779 }
2780 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
2781 _engineStatisticsPtr->SetLastError(
2782 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2783 "SetMinimumPlayoutDelay() failed to set min playout delay");
2784 return -1;
2785 }
2786 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002787}
2788
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002789int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07002790 uint32_t playout_timestamp_rtp = 0;
2791 {
tommi31fc21f2016-01-21 10:37:37 -08002792 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07002793 playout_timestamp_rtp = playout_timestamp_rtp_;
2794 }
kwiberg55b97fe2016-01-28 05:22:45 -08002795 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002796 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07002797 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002798 "GetPlayoutTimestamp() failed to retrieve timestamp");
2799 return -1;
2800 }
deadbeef74375882015-08-13 12:09:10 -07002801 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002802 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002803}
2804
kwiberg55b97fe2016-01-28 05:22:45 -08002805int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
2806 RtpReceiver** rtp_receiver) const {
2807 *rtpRtcpModule = _rtpRtcpModule.get();
2808 *rtp_receiver = rtp_receiver_.get();
2809 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002810}
2811
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00002812// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
2813// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08002814int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08002815 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08002816 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002817
kwiberg55b97fe2016-01-28 05:22:45 -08002818 {
2819 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002820
kwiberg5a25d952016-08-17 07:31:12 -07002821 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002822 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2823 "Channel::MixOrReplaceAudioWithFile() fileplayer"
2824 " doesnt exist");
2825 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002826 }
2827
kwiberg4ec01d92016-08-22 08:43:54 -07002828 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07002829 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002830 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2831 "Channel::MixOrReplaceAudioWithFile() file mixing "
2832 "failed");
2833 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002834 }
kwiberg55b97fe2016-01-28 05:22:45 -08002835 if (fileSamples == 0) {
2836 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2837 "Channel::MixOrReplaceAudioWithFile() file is ended");
2838 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002839 }
kwiberg55b97fe2016-01-28 05:22:45 -08002840 }
2841
2842 assert(_audioFrame.samples_per_channel_ == fileSamples);
2843
2844 if (_mixFileWithMicrophone) {
2845 // Currently file stream is always mono.
2846 // TODO(xians): Change the code when FilePlayer supports real stereo.
2847 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
2848 1, fileSamples);
2849 } else {
2850 // Replace ACM audio with file.
2851 // Currently file stream is always mono.
2852 // TODO(xians): Change the code when FilePlayer supports real stereo.
2853 _audioFrame.UpdateFrame(
2854 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
2855 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
2856 }
2857 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002858}
2859
kwiberg55b97fe2016-01-28 05:22:45 -08002860int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
2861 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00002862
kwibergb7f89d62016-02-17 10:04:18 -08002863 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08002864 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002865
kwiberg55b97fe2016-01-28 05:22:45 -08002866 {
2867 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002868
kwiberg5a25d952016-08-17 07:31:12 -07002869 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002870 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2871 "Channel::MixAudioWithFile() file mixing failed");
2872 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002873 }
2874
kwiberg55b97fe2016-01-28 05:22:45 -08002875 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07002876 if (output_file_player_->Get10msAudioFromFile(
2877 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002878 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2879 "Channel::MixAudioWithFile() file mixing failed");
2880 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002881 }
kwiberg55b97fe2016-01-28 05:22:45 -08002882 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002883
kwiberg55b97fe2016-01-28 05:22:45 -08002884 if (audioFrame.samples_per_channel_ == fileSamples) {
2885 // Currently file stream is always mono.
2886 // TODO(xians): Change the code when FilePlayer supports real stereo.
2887 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
2888 fileSamples);
2889 } else {
2890 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2891 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
2892 ") != "
2893 "fileSamples(%" PRIuS ")",
2894 audioFrame.samples_per_channel_, fileSamples);
2895 return -1;
2896 }
2897
2898 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002899}
2900
deadbeef74375882015-08-13 12:09:10 -07002901void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002902 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07002903
henrik.lundin96bd5022016-04-06 04:13:56 -07002904 if (!jitter_buffer_playout_timestamp_) {
2905 // This can happen if this channel has not received any RTP packets. In
2906 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07002907 return;
2908 }
2909
2910 uint16_t delay_ms = 0;
2911 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002912 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002913 "Channel::UpdatePlayoutTimestamp() failed to read playout"
2914 " delay from the ADM");
2915 _engineStatisticsPtr->SetLastError(
2916 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
2917 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
2918 return;
2919 }
2920
henrik.lundin96bd5022016-04-06 04:13:56 -07002921 RTC_DCHECK(jitter_buffer_playout_timestamp_);
2922 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07002923
2924 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07002925 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07002926
kwiberg55b97fe2016-01-28 05:22:45 -08002927 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002928 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07002929 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07002930
2931 {
tommi31fc21f2016-01-21 10:37:37 -08002932 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08002933 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002934 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07002935 }
2936 playout_delay_ms_ = delay_ms;
2937 }
2938}
2939
kwiberg55b97fe2016-01-28 05:22:45 -08002940void Channel::RegisterReceiveCodecsToRTPModule() {
2941 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2942 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002943
kwiberg55b97fe2016-01-28 05:22:45 -08002944 CodecInst codec;
2945 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00002946
kwiberg55b97fe2016-01-28 05:22:45 -08002947 for (int idx = 0; idx < nSupportedCodecs; idx++) {
2948 // Open up the RTP/RTCP receiver for all supported codecs
2949 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08002950 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08002951 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2952 "Channel::RegisterReceiveCodecsToRTPModule() unable"
2953 " to register %s (%d/%d/%" PRIuS
2954 "/%d) to RTP/RTCP "
2955 "receiver",
2956 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2957 codec.rate);
2958 } else {
2959 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2960 "Channel::RegisterReceiveCodecsToRTPModule() %s "
2961 "(%d/%d/%" PRIuS
2962 "/%d) has been added to the RTP/RTCP "
2963 "receiver",
2964 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2965 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00002966 }
kwiberg55b97fe2016-01-28 05:22:45 -08002967 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002968}
2969
kwiberg55b97fe2016-01-28 05:22:45 -08002970int Channel::SetSendRtpHeaderExtension(bool enable,
2971 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002972 unsigned char id) {
2973 int error = 0;
2974 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
2975 if (enable) {
2976 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
2977 }
2978 return error;
2979}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002980
ossue280cde2016-10-12 11:04:10 -07002981int Channel::GetRtpTimestampRateHz() const {
2982 const auto format = audio_coding_->ReceiveFormat();
2983 // Default to the playout frequency if we've not gotten any packets yet.
2984 // TODO(ossu): Zero clockrate can only happen if we've added an external
2985 // decoder for a format we don't support internally. Remove once that way of
2986 // adding decoders is gone!
2987 return (format && format->clockrate_hz != 0)
2988 ? format->clockrate_hz
2989 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00002990}
2991
Minyue2013aec2015-05-13 14:14:42 +02002992int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07002993 RtcpMode method = _rtpRtcpModule->RTCP();
2994 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002995 return 0;
2996 }
2997 std::vector<RTCPReportBlock> report_blocks;
2998 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02002999
3000 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003001 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003002 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003003 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003004 Channel* channel = associate_send_channel_.channel();
3005 // Tries to get RTT from an associated channel. This is important for
3006 // receive-only channels.
3007 if (channel) {
3008 // To prevent infinite recursion and deadlock, calling GetRTT of
3009 // associate channel should always use "false" for argument:
3010 // |allow_associate_channel|.
3011 rtt = channel->GetRTT(false);
3012 }
3013 }
3014 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003015 }
3016
3017 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3018 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3019 for (; it != report_blocks.end(); ++it) {
3020 if (it->remoteSSRC == remoteSSRC)
3021 break;
3022 }
3023 if (it == report_blocks.end()) {
3024 // We have not received packets with SSRC matching the report blocks.
3025 // To calculate RTT we try with the SSRC of the first report block.
3026 // This is very important for send-only channels where we don't know
3027 // the SSRC of the other end.
3028 remoteSSRC = report_blocks[0].remoteSSRC;
3029 }
Minyue2013aec2015-05-13 14:14:42 +02003030
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003031 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003032 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003033 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003034 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3035 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003036 return 0;
3037 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003038 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003039}
3040
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003041} // namespace voe
3042} // namespace webrtc