blob: d2b30ca8f7d41c07b7ea406e6f26a84d59699ca5 [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"
Henrik Lundin64dad832015-05-11 12:44:23 +020025#include "webrtc/config.h"
skvladcc91d282016-10-03 18:31:22 -070026#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kwibergda2bf4e2016-10-24 13:47:09 -070027#include "webrtc/modules/audio_coding/codecs/audio_format_conversion.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000028#include "webrtc/modules/audio_device/include/audio_device.h"
29#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010030#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010031#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010032#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
33#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
34#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
nisse657bab22017-02-21 06:28:10 -080035#include "webrtc/modules/rtp_rtcp/source/rtp_packet_received.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000036#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010037#include "webrtc/modules/utility/include/process_thread.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010038#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000039#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
40#include "webrtc/voice_engine/output_mixer.h"
41#include "webrtc/voice_engine/statistics.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000042#include "webrtc/voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000043
andrew@webrtc.org50419b02012-11-14 19:07:54 +000044namespace webrtc {
45namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000046
kwibergc8d071e2016-04-06 12:22:38 -070047namespace {
48
Erik Språng737336d2016-07-29 12:59:36 +020049constexpr int64_t kMaxRetransmissionWindowMs = 1000;
50constexpr int64_t kMinRetransmissionWindowMs = 30;
51
kwibergc8d071e2016-04-06 12:22:38 -070052} // namespace
53
solenberg8842c3e2016-03-11 03:06:41 -080054const int kTelephoneEventAttenuationdB = 10;
55
ivoc14d5dbe2016-07-04 07:06:55 -070056class RtcEventLogProxy final : public webrtc::RtcEventLog {
57 public:
58 RtcEventLogProxy() : event_log_(nullptr) {}
59
60 bool StartLogging(const std::string& file_name,
61 int64_t max_size_bytes) override {
62 RTC_NOTREACHED();
63 return false;
64 }
65
66 bool StartLogging(rtc::PlatformFile log_file,
67 int64_t max_size_bytes) override {
68 RTC_NOTREACHED();
69 return false;
70 }
71
72 void StopLogging() override { RTC_NOTREACHED(); }
73
74 void LogVideoReceiveStreamConfig(
75 const webrtc::VideoReceiveStream::Config& config) override {
76 rtc::CritScope lock(&crit_);
77 if (event_log_) {
78 event_log_->LogVideoReceiveStreamConfig(config);
79 }
80 }
81
82 void LogVideoSendStreamConfig(
83 const webrtc::VideoSendStream::Config& config) override {
84 rtc::CritScope lock(&crit_);
85 if (event_log_) {
86 event_log_->LogVideoSendStreamConfig(config);
87 }
88 }
89
ivoce0928d82016-10-10 05:12:51 -070090 void LogAudioReceiveStreamConfig(
91 const webrtc::AudioReceiveStream::Config& config) override {
92 rtc::CritScope lock(&crit_);
93 if (event_log_) {
94 event_log_->LogAudioReceiveStreamConfig(config);
95 }
96 }
97
98 void LogAudioSendStreamConfig(
99 const webrtc::AudioSendStream::Config& config) override {
100 rtc::CritScope lock(&crit_);
101 if (event_log_) {
102 event_log_->LogAudioSendStreamConfig(config);
103 }
104 }
105
ivoc14d5dbe2016-07-04 07:06:55 -0700106 void LogRtpHeader(webrtc::PacketDirection direction,
107 webrtc::MediaType media_type,
108 const uint8_t* header,
109 size_t packet_length) override {
philipel32d00102017-02-27 02:18:46 -0800110 LogRtpHeader(direction, media_type, header, packet_length,
111 PacedPacketInfo::kNotAProbe);
112 }
113
114 void LogRtpHeader(webrtc::PacketDirection direction,
115 webrtc::MediaType media_type,
116 const uint8_t* header,
117 size_t packet_length,
118 int probe_cluster_id) override {
ivoc14d5dbe2016-07-04 07:06:55 -0700119 rtc::CritScope lock(&crit_);
120 if (event_log_) {
philipel32d00102017-02-27 02:18:46 -0800121 event_log_->LogRtpHeader(direction, media_type, header, packet_length,
122 probe_cluster_id);
ivoc14d5dbe2016-07-04 07:06:55 -0700123 }
124 }
125
126 void LogRtcpPacket(webrtc::PacketDirection direction,
127 webrtc::MediaType media_type,
128 const uint8_t* packet,
129 size_t length) override {
130 rtc::CritScope lock(&crit_);
131 if (event_log_) {
132 event_log_->LogRtcpPacket(direction, media_type, packet, length);
133 }
134 }
135
136 void LogAudioPlayout(uint32_t ssrc) override {
137 rtc::CritScope lock(&crit_);
138 if (event_log_) {
139 event_log_->LogAudioPlayout(ssrc);
140 }
141 }
142
terelius424e6cf2017-02-20 05:14:41 -0800143 void LogLossBasedBweUpdate(int32_t bitrate_bps,
ivoc14d5dbe2016-07-04 07:06:55 -0700144 uint8_t fraction_loss,
145 int32_t total_packets) override {
146 rtc::CritScope lock(&crit_);
147 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800148 event_log_->LogLossBasedBweUpdate(bitrate_bps, fraction_loss,
149 total_packets);
ivoc14d5dbe2016-07-04 07:06:55 -0700150 }
151 }
152
terelius424e6cf2017-02-20 05:14:41 -0800153 void LogDelayBasedBweUpdate(int32_t bitrate_bps,
terelius0baf55d2017-02-17 03:38:28 -0800154 BandwidthUsage detector_state) override {
155 rtc::CritScope lock(&crit_);
156 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800157 event_log_->LogDelayBasedBweUpdate(bitrate_bps, detector_state);
terelius0baf55d2017-02-17 03:38:28 -0800158 }
159 }
160
minyue4b7c9522017-01-24 04:54:59 -0800161 void LogAudioNetworkAdaptation(
162 const AudioNetworkAdaptor::EncoderRuntimeConfig& config) override {
163 rtc::CritScope lock(&crit_);
164 if (event_log_) {
165 event_log_->LogAudioNetworkAdaptation(config);
166 }
167 }
168
philipel32d00102017-02-27 02:18:46 -0800169 void LogProbeClusterCreated(int id,
170 int bitrate_bps,
171 int min_probes,
172 int min_bytes) override {
173 rtc::CritScope lock(&crit_);
174 if (event_log_) {
175 event_log_->LogProbeClusterCreated(id, bitrate_bps, min_probes,
176 min_bytes);
177 }
178 };
179
180 void LogProbeResultSuccess(int id, int bitrate_bps) override {
181 rtc::CritScope lock(&crit_);
182 if (event_log_) {
183 event_log_->LogProbeResultSuccess(id, bitrate_bps);
184 }
185 };
186
187 void LogProbeResultFailure(int id,
188 ProbeFailureReason failure_reason) override {
189 rtc::CritScope lock(&crit_);
190 if (event_log_) {
191 event_log_->LogProbeResultFailure(id, failure_reason);
192 }
193 };
194
ivoc14d5dbe2016-07-04 07:06:55 -0700195 void SetEventLog(RtcEventLog* event_log) {
196 rtc::CritScope lock(&crit_);
197 event_log_ = event_log;
198 }
199
200 private:
201 rtc::CriticalSection crit_;
202 RtcEventLog* event_log_ GUARDED_BY(crit_);
203 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
204};
205
michaelt9332b7d2016-11-30 07:51:13 -0800206class RtcpRttStatsProxy final : public RtcpRttStats {
207 public:
208 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
209
210 void OnRttUpdate(int64_t rtt) override {
211 rtc::CritScope lock(&crit_);
212 if (rtcp_rtt_stats_)
213 rtcp_rtt_stats_->OnRttUpdate(rtt);
214 }
215
216 int64_t LastProcessedRtt() const override {
217 rtc::CritScope lock(&crit_);
218 if (!rtcp_rtt_stats_)
219 return 0;
220 return rtcp_rtt_stats_->LastProcessedRtt();
221 }
222
223 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
224 rtc::CritScope lock(&crit_);
225 rtcp_rtt_stats_ = rtcp_rtt_stats;
226 }
227
228 private:
229 rtc::CriticalSection crit_;
230 RtcpRttStats* rtcp_rtt_stats_ GUARDED_BY(crit_);
231 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
232};
233
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100234class TransportFeedbackProxy : public TransportFeedbackObserver {
235 public:
236 TransportFeedbackProxy() : feedback_observer_(nullptr) {
237 pacer_thread_.DetachFromThread();
238 network_thread_.DetachFromThread();
239 }
240
241 void SetTransportFeedbackObserver(
242 TransportFeedbackObserver* feedback_observer) {
243 RTC_DCHECK(thread_checker_.CalledOnValidThread());
244 rtc::CritScope lock(&crit_);
245 feedback_observer_ = feedback_observer;
246 }
247
248 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700249 void AddPacket(uint32_t ssrc,
250 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100251 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800252 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100253 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
254 rtc::CritScope lock(&crit_);
255 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700256 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100257 }
philipel8aadd502017-02-23 02:56:13 -0800258
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100259 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
260 RTC_DCHECK(network_thread_.CalledOnValidThread());
261 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700262 if (feedback_observer_)
263 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200264 }
elad.alonf9490002017-03-06 05:32:21 -0800265 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200266 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800267 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100268 }
269
270 private:
271 rtc::CriticalSection crit_;
272 rtc::ThreadChecker thread_checker_;
273 rtc::ThreadChecker pacer_thread_;
274 rtc::ThreadChecker network_thread_;
275 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
276};
277
278class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
279 public:
280 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
281 pacer_thread_.DetachFromThread();
282 }
283
284 void SetSequenceNumberAllocator(
285 TransportSequenceNumberAllocator* seq_num_allocator) {
286 RTC_DCHECK(thread_checker_.CalledOnValidThread());
287 rtc::CritScope lock(&crit_);
288 seq_num_allocator_ = seq_num_allocator;
289 }
290
291 // Implements TransportSequenceNumberAllocator.
292 uint16_t AllocateSequenceNumber() override {
293 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
294 rtc::CritScope lock(&crit_);
295 if (!seq_num_allocator_)
296 return 0;
297 return seq_num_allocator_->AllocateSequenceNumber();
298 }
299
300 private:
301 rtc::CriticalSection crit_;
302 rtc::ThreadChecker thread_checker_;
303 rtc::ThreadChecker pacer_thread_;
304 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
305};
306
307class RtpPacketSenderProxy : public RtpPacketSender {
308 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800309 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100310
311 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
312 RTC_DCHECK(thread_checker_.CalledOnValidThread());
313 rtc::CritScope lock(&crit_);
314 rtp_packet_sender_ = rtp_packet_sender;
315 }
316
317 // Implements RtpPacketSender.
318 void InsertPacket(Priority priority,
319 uint32_t ssrc,
320 uint16_t sequence_number,
321 int64_t capture_time_ms,
322 size_t bytes,
323 bool retransmission) override {
324 rtc::CritScope lock(&crit_);
325 if (rtp_packet_sender_) {
326 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
327 capture_time_ms, bytes, retransmission);
328 }
329 }
330
331 private:
332 rtc::ThreadChecker thread_checker_;
333 rtc::CriticalSection crit_;
334 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
335};
336
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000337class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000338 public:
stefan7de8d642017-02-07 07:14:08 -0800339 explicit VoERtcpObserver(Channel* owner)
340 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000341 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000342
stefan7de8d642017-02-07 07:14:08 -0800343 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
344 rtc::CritScope lock(&crit_);
345 bandwidth_observer_ = bandwidth_observer;
346 }
347
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000348 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800349 rtc::CritScope lock(&crit_);
350 if (bandwidth_observer_) {
351 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
352 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000353 }
354
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000355 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
356 int64_t rtt,
357 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800358 {
359 rtc::CritScope lock(&crit_);
360 if (bandwidth_observer_) {
361 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
362 now_ms);
363 }
364 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000365 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
366 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
367 // report for VoiceEngine?
368 if (report_blocks.empty())
369 return;
370
371 int fraction_lost_aggregate = 0;
372 int total_number_of_packets = 0;
373
374 // If receiving multiple report blocks, calculate the weighted average based
375 // on the number of packets a report refers to.
376 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
377 block_it != report_blocks.end(); ++block_it) {
378 // Find the previous extended high sequence number for this remote SSRC,
379 // to calculate the number of RTP packets this report refers to. Ignore if
380 // we haven't seen this SSRC before.
381 std::map<uint32_t, uint32_t>::iterator seq_num_it =
382 extended_max_sequence_number_.find(block_it->sourceSSRC);
383 int number_of_packets = 0;
384 if (seq_num_it != extended_max_sequence_number_.end()) {
385 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
386 }
387 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
388 total_number_of_packets += number_of_packets;
389
390 extended_max_sequence_number_[block_it->sourceSSRC] =
391 block_it->extendedHighSeqNum;
392 }
393 int weighted_fraction_lost = 0;
394 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800395 weighted_fraction_lost =
396 (fraction_lost_aggregate + total_number_of_packets / 2) /
397 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000398 }
elad.alond12a8e12017-03-23 11:04:48 -0700399 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000400 }
401
402 private:
403 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000404 // Maps remote side ssrc to extended highest sequence number received.
405 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800406 rtc::CriticalSection crit_;
407 RtcpBandwidthObserver* bandwidth_observer_ GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000408};
409
kwiberg55b97fe2016-01-28 05:22:45 -0800410int32_t Channel::SendData(FrameType frameType,
411 uint8_t payloadType,
412 uint32_t timeStamp,
413 const uint8_t* payloadData,
414 size_t payloadSize,
415 const RTPFragmentationHeader* fragmentation) {
416 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
417 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
418 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
419 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000420
kwiberg55b97fe2016-01-28 05:22:45 -0800421 if (_includeAudioLevelIndication) {
422 // Store current audio level in the RTP/RTCP module.
423 // The level will be used in combination with voice-activity state
424 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800425 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800426 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000427
kwiberg55b97fe2016-01-28 05:22:45 -0800428 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
429 // packetization.
430 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700431 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800432 (FrameType&)frameType, payloadType, timeStamp,
433 // Leaving the time when this frame was
434 // received from the capture device as
435 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700436 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800437 _engineStatisticsPtr->SetLastError(
438 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
439 "Channel::SendData() failed to send data to RTP/RTCP module");
440 return -1;
441 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000442
kwiberg55b97fe2016-01-28 05:22:45 -0800443 _lastLocalTimeStamp = timeStamp;
444 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000445
kwiberg55b97fe2016-01-28 05:22:45 -0800446 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000447}
448
stefan1d8a5062015-10-02 03:39:33 -0700449bool Channel::SendRtp(const uint8_t* data,
450 size_t len,
451 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800452 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
453 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000454
kwiberg55b97fe2016-01-28 05:22:45 -0800455 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000456
kwiberg55b97fe2016-01-28 05:22:45 -0800457 if (_transportPtr == NULL) {
458 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
459 "Channel::SendPacket() failed to send RTP packet due to"
460 " invalid transport object");
461 return false;
462 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000463
kwiberg55b97fe2016-01-28 05:22:45 -0800464 uint8_t* bufferToSendPtr = (uint8_t*)data;
465 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000466
kwiberg55b97fe2016-01-28 05:22:45 -0800467 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
468 std::string transport_name =
469 _externalTransport ? "external transport" : "WebRtc sockets";
470 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
471 "Channel::SendPacket() RTP transmission using %s failed",
472 transport_name.c_str());
473 return false;
474 }
475 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000476}
477
kwiberg55b97fe2016-01-28 05:22:45 -0800478bool Channel::SendRtcp(const uint8_t* data, size_t len) {
479 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
480 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000481
kwiberg55b97fe2016-01-28 05:22:45 -0800482 rtc::CritScope cs(&_callbackCritSect);
483 if (_transportPtr == NULL) {
484 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
485 "Channel::SendRtcp() failed to send RTCP packet"
486 " due to invalid transport object");
487 return false;
488 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000489
kwiberg55b97fe2016-01-28 05:22:45 -0800490 uint8_t* bufferToSendPtr = (uint8_t*)data;
491 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000492
kwiberg55b97fe2016-01-28 05:22:45 -0800493 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
494 if (n < 0) {
495 std::string transport_name =
496 _externalTransport ? "external transport" : "WebRtc sockets";
497 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
498 "Channel::SendRtcp() transmission using %s failed",
499 transport_name.c_str());
500 return false;
501 }
502 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000503}
504
kwiberg55b97fe2016-01-28 05:22:45 -0800505void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
506 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
507 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000508
kwiberg55b97fe2016-01-28 05:22:45 -0800509 // Update ssrc so that NTP for AV sync can be updated.
510 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000511}
512
Peter Boströmac547a62015-09-17 23:03:57 +0200513void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
514 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
515 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
516 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000517}
518
Peter Boströmac547a62015-09-17 23:03:57 +0200519int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000520 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000521 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000522 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800523 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200524 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800525 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
526 "Channel::OnInitializeDecoder(payloadType=%d, "
527 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
528 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000529
kwiberg55b97fe2016-01-28 05:22:45 -0800530 CodecInst receiveCodec = {0};
531 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000532
kwiberg55b97fe2016-01-28 05:22:45 -0800533 receiveCodec.pltype = payloadType;
534 receiveCodec.plfreq = frequency;
535 receiveCodec.channels = channels;
536 receiveCodec.rate = rate;
537 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000538
kwiberg55b97fe2016-01-28 05:22:45 -0800539 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
540 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000541
kwiberg55b97fe2016-01-28 05:22:45 -0800542 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700543 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
544 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800545 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
546 "Channel::OnInitializeDecoder() invalid codec ("
547 "pt=%d, name=%s) received - 1",
548 payloadType, payloadName);
549 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
550 return -1;
551 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000552
kwiberg55b97fe2016-01-28 05:22:45 -0800553 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000554}
555
kwiberg55b97fe2016-01-28 05:22:45 -0800556int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
557 size_t payloadSize,
558 const WebRtcRTPHeader* rtpHeader) {
559 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
560 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
561 ","
562 " payloadType=%u, audioChannel=%" PRIuS ")",
563 payloadSize, rtpHeader->header.payloadType,
564 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000565
kwiberg55b97fe2016-01-28 05:22:45 -0800566 if (!channel_state_.Get().playing) {
567 // Avoid inserting into NetEQ when we are not playing. Count the
568 // packet as discarded.
569 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
570 "received packet is discarded since playing is not"
571 " activated");
niklase@google.com470e71d2011-07-07 08:21:25 +0000572 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800573 }
574
575 // Push the incoming payload (parsed and ready for decoding) into the ACM
576 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
577 0) {
578 _engineStatisticsPtr->SetLastError(
579 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
580 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
581 return -1;
582 }
583
kwiberg55b97fe2016-01-28 05:22:45 -0800584 int64_t round_trip_time = 0;
585 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
586 NULL);
587
588 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
589 if (!nack_list.empty()) {
590 // Can't use nack_list.data() since it's not supported by all
591 // compilers.
592 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
593 }
594 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000595}
596
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000597bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000598 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000599 RTPHeader header;
600 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
601 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
602 "IncomingPacket invalid RTP header");
603 return false;
604 }
605 header.payload_type_frequency =
606 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
607 if (header.payload_type_frequency < 0)
608 return false;
609 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
610}
611
henrik.lundin42dda502016-05-18 05:36:01 -0700612MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
613 int32_t id,
614 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700615 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800616 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700617 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800618 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700619 bool muted;
620 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
621 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800622 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
623 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
624 // In all likelihood, the audio in this frame is garbage. We return an
625 // error so that the audio mixer module doesn't add it to the mix. As
626 // a result, it won't be played out and the actions skipped here are
627 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700628 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800629 }
henrik.lundina89ab962016-05-18 08:52:45 -0700630
631 if (muted) {
632 // TODO(henrik.lundin): We should be able to do better than this. But we
633 // will have to go through all the cases below where the audio samples may
634 // be used, and handle the muted case in some way.
aleloi6321b492016-12-05 01:46:09 -0800635 AudioFrameOperations::Mute(audioFrame);
henrik.lundina89ab962016-05-18 08:52:45 -0700636 }
kwiberg55b97fe2016-01-28 05:22:45 -0800637
kwiberg55b97fe2016-01-28 05:22:45 -0800638 // Convert module ID to internal VoE channel ID
639 audioFrame->id_ = VoEChannelId(audioFrame->id_);
640 // Store speech type for dead-or-alive detection
641 _outputSpeechType = audioFrame->speech_type_;
642
643 ChannelState::State state = channel_state_.Get();
644
kwiberg55b97fe2016-01-28 05:22:45 -0800645 {
646 // Pass the audio buffers to an optional sink callback, before applying
647 // scaling/panning, as that applies to the mix operation.
648 // External recipients of the audio (e.g. via AudioTrack), will do their
649 // own mixing/dynamic processing.
650 rtc::CritScope cs(&_callbackCritSect);
651 if (audio_sink_) {
652 AudioSinkInterface::Data data(
653 &audioFrame->data_[0], audioFrame->samples_per_channel_,
654 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
655 audioFrame->timestamp_);
656 audio_sink_->OnData(data);
657 }
658 }
659
660 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800661 {
662 rtc::CritScope cs(&volume_settings_critsect_);
663 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800664 }
665
666 // Output volume scaling
667 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800668 // TODO(solenberg): Combine with mute state - this can cause clicks!
oprypin67fdb802017-03-09 06:25:06 -0800669 AudioFrameOperations::ScaleWithSat(output_gain, audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800670 }
671
kwiberg55b97fe2016-01-28 05:22:45 -0800672 // Mix decoded PCM output with file if file mixing is enabled
673 if (state.output_file_playing) {
674 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700675 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800676 }
677
kwiberg55b97fe2016-01-28 05:22:45 -0800678 // Record playout if enabled
679 {
680 rtc::CritScope cs(&_fileCritSect);
681
kwiberg5a25d952016-08-17 07:31:12 -0700682 if (_outputFileRecording && output_file_recorder_) {
683 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800684 }
685 }
686
687 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700688 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800689 _outputAudioLevel.ComputeLevel(*audioFrame);
690
691 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
692 // The first frame with a valid rtp timestamp.
693 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
694 }
695
696 if (capture_start_rtp_time_stamp_ >= 0) {
697 // audioFrame.timestamp_ should be valid from now on.
698
699 // Compute elapsed time.
700 int64_t unwrap_timestamp =
701 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
702 audioFrame->elapsed_time_ms_ =
703 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700704 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800705
niklase@google.com470e71d2011-07-07 08:21:25 +0000706 {
kwiberg55b97fe2016-01-28 05:22:45 -0800707 rtc::CritScope lock(&ts_stats_lock_);
708 // Compute ntp time.
709 audioFrame->ntp_time_ms_ =
710 ntp_estimator_.Estimate(audioFrame->timestamp_);
711 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
712 if (audioFrame->ntp_time_ms_ > 0) {
713 // Compute |capture_start_ntp_time_ms_| so that
714 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
715 capture_start_ntp_time_ms_ =
716 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000717 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000718 }
kwiberg55b97fe2016-01-28 05:22:45 -0800719 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000720
henrik.lundin42dda502016-05-18 05:36:01 -0700721 return muted ? MixerParticipant::AudioFrameInfo::kMuted
722 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000723}
724
aleloi6c278492016-10-20 14:24:39 -0700725AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
726 int sample_rate_hz,
727 AudioFrame* audio_frame) {
728 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700729
aleloi6c278492016-10-20 14:24:39 -0700730 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700731
732 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
733 FrameInfo new_audio_frame_info = FrameInfo::kError;
734 switch (frame_info) {
735 case MixerParticipant::AudioFrameInfo::kNormal:
736 new_audio_frame_info = FrameInfo::kNormal;
737 break;
738 case MixerParticipant::AudioFrameInfo::kMuted:
739 new_audio_frame_info = FrameInfo::kMuted;
740 break;
741 case MixerParticipant::AudioFrameInfo::kError:
742 new_audio_frame_info = FrameInfo::kError;
743 break;
744 }
aleloi6c278492016-10-20 14:24:39 -0700745 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700746}
747
kwiberg55b97fe2016-01-28 05:22:45 -0800748int32_t Channel::NeededFrequency(int32_t id) const {
749 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
750 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000751
kwiberg55b97fe2016-01-28 05:22:45 -0800752 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000753
kwiberg55b97fe2016-01-28 05:22:45 -0800754 // Determine highest needed receive frequency
755 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000756
kwiberg55b97fe2016-01-28 05:22:45 -0800757 // Return the bigger of playout and receive frequency in the ACM.
758 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
759 highestNeeded = audio_coding_->PlayoutFrequency();
760 } else {
761 highestNeeded = receiveFrequency;
762 }
763
764 // Special case, if we're playing a file on the playout side
765 // we take that frequency into consideration as well
766 // This is not needed on sending side, since the codec will
767 // limit the spectrum anyway.
768 if (channel_state_.Get().output_file_playing) {
769 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700770 if (output_file_player_) {
771 if (output_file_player_->Frequency() > highestNeeded) {
772 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800773 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000774 }
kwiberg55b97fe2016-01-28 05:22:45 -0800775 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000776
kwiberg55b97fe2016-01-28 05:22:45 -0800777 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000778}
779
ossu5f7cfa52016-05-30 08:11:28 -0700780int32_t Channel::CreateChannel(
781 Channel*& channel,
782 int32_t channelId,
783 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700784 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800785 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
786 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
787 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000788
solenberg88499ec2016-09-07 07:34:41 -0700789 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800790 if (channel == NULL) {
791 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
792 "Channel::CreateChannel() unable to allocate memory for"
793 " channel");
794 return -1;
795 }
796 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000797}
798
kwiberg55b97fe2016-01-28 05:22:45 -0800799void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
800 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
801 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
802 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000803
kwiberg55b97fe2016-01-28 05:22:45 -0800804 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000805}
806
kwiberg55b97fe2016-01-28 05:22:45 -0800807void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
808 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
809 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
810 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000811
kwiberg55b97fe2016-01-28 05:22:45 -0800812 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000813}
814
kwiberg55b97fe2016-01-28 05:22:45 -0800815void Channel::PlayFileEnded(int32_t id) {
816 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
817 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000818
kwiberg55b97fe2016-01-28 05:22:45 -0800819 if (id == _inputFilePlayerId) {
820 channel_state_.SetInputFilePlaying(false);
821 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
822 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000823 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800824 } else if (id == _outputFilePlayerId) {
825 channel_state_.SetOutputFilePlaying(false);
826 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
827 "Channel::PlayFileEnded() => output file player module is"
828 " shutdown");
829 }
830}
831
832void Channel::RecordFileEnded(int32_t id) {
833 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
834 "Channel::RecordFileEnded(id=%d)", id);
835
836 assert(id == _outputFileRecorderId);
837
838 rtc::CritScope cs(&_fileCritSect);
839
840 _outputFileRecording = false;
841 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
842 "Channel::RecordFileEnded() => output file recorder module is"
843 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000844}
845
pbos@webrtc.org92135212013-05-14 08:31:39 +0000846Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000847 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700848 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800849 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100850 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700851 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800852 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100853 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800854 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100855 rtp_receive_statistics_(
856 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
857 rtp_receiver_(
858 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100859 this,
860 this,
861 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700862 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100863 _outputAudioLevel(),
864 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100865 // Avoid conflict with other channels by adding 1024 - 1026,
866 // won't use as much as 1024 channels.
867 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
868 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
869 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
870 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100871 _timeStamp(0), // This is just an offset, RTP module will add it's own
872 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100873 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100874 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100875 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100876 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100877 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
878 capture_start_rtp_time_stamp_(-1),
879 capture_start_ntp_time_ms_(-1),
880 _engineStatisticsPtr(NULL),
881 _outputMixerPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100882 _moduleProcessThreadPtr(NULL),
883 _audioDeviceModulePtr(NULL),
884 _voiceEngineObserverPtr(NULL),
885 _callbackCritSectPtr(NULL),
886 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700887 input_mute_(false),
888 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100889 _outputGain(1.0f),
solenberg8d73f8c2017-03-08 01:52:20 -0800890 _mixFileWithMicrophone(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100891 _lastLocalTimeStamp(0),
892 _lastPayloadType(0),
893 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800894 transport_overhead_per_packet_(0),
895 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100896 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100897 restored_packet_in_use_(false),
898 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100899 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700900 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800901 feedback_observer_proxy_(new TransportFeedbackProxy()),
902 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700903 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200904 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
905 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700906 decoder_factory_(config.acm_config.decoder_factory),
907 // TODO(elad.alon): Subsequent CL experiments with PLR source.
908 use_twcc_plr_for_ana_(false) {
kwiberg55b97fe2016-01-28 05:22:45 -0800909 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
910 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700911 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800912 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700913 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800914 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200915
kwiberg55b97fe2016-01-28 05:22:45 -0800916 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000917
kwiberg55b97fe2016-01-28 05:22:45 -0800918 RtpRtcp::Configuration configuration;
919 configuration.audio = true;
920 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800921 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800922 configuration.receive_statistics = rtp_receive_statistics_.get();
923 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800924 if (pacing_enabled_) {
925 configuration.paced_sender = rtp_packet_sender_proxy_.get();
926 configuration.transport_sequence_number_allocator =
927 seq_num_allocator_proxy_.get();
928 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
929 }
ivoc14d5dbe2016-07-04 07:06:55 -0700930 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800931 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200932 configuration.retransmission_rate_limiter =
933 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000934
kwiberg55b97fe2016-01-28 05:22:45 -0800935 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100936 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000937}
938
kwiberg55b97fe2016-01-28 05:22:45 -0800939Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700940 RTC_DCHECK(!channel_state_.Get().sending);
941 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000942}
943
kwiberg55b97fe2016-01-28 05:22:45 -0800944int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700945 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800946 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
947 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000948
kwiberg55b97fe2016-01-28 05:22:45 -0800949 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000950
kwiberg55b97fe2016-01-28 05:22:45 -0800951 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000952
kwiberg55b97fe2016-01-28 05:22:45 -0800953 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
954 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
955 "Channel::Init() must call SetEngineInformation() first");
956 return -1;
957 }
958
959 // --- Add modules to process thread (for periodic schedulation)
960
tommidea489f2017-03-03 03:20:24 -0800961 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800962
963 // --- ACM initialization
964
965 if (audio_coding_->InitializeReceiver() == -1) {
966 _engineStatisticsPtr->SetLastError(
967 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
968 "Channel::Init() unable to initialize the ACM - 1");
969 return -1;
970 }
971
972 // --- RTP/RTCP module initialization
973
974 // Ensure that RTCP is enabled by default for the created channel.
975 // Note that, the module will keep generating RTCP until it is explicitly
976 // disabled by the user.
977 // After StopListen (when no sockets exists), RTCP packets will no longer
978 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700979 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800980 // RTCP is enabled by default.
981 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
982 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800983 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800984 _engineStatisticsPtr->SetLastError(
985 VE_CANNOT_INIT_CHANNEL, kTraceError,
986 "Channel::Init() callbacks not registered");
987 return -1;
988 }
989
990 // --- Register all supported codecs to the receiving side of the
991 // RTP/RTCP module
992
993 CodecInst codec;
994 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
995
996 for (int idx = 0; idx < nSupportedCodecs; idx++) {
997 // Open up the RTP/RTCP receiver for all supported codecs
998 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -0800999 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001000 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1001 "Channel::Init() unable to register %s "
1002 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1003 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1004 codec.rate);
1005 } else {
1006 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1007 "Channel::Init() %s (%d/%d/%" PRIuS
1008 "/%d) has been "
1009 "added to the RTP/RTCP receiver",
1010 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1011 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001012 }
1013
kwiberg55b97fe2016-01-28 05:22:45 -08001014 // Ensure that PCMU is used as default codec on the sending side
1015 if (!STR_CASE_CMP(codec.plname, "PCMU") && (codec.channels == 1)) {
1016 SetSendCodec(codec);
niklase@google.com470e71d2011-07-07 08:21:25 +00001017 }
1018
kwiberg55b97fe2016-01-28 05:22:45 -08001019 // Register default PT for outband 'telephone-event'
1020 if (!STR_CASE_CMP(codec.plname, "telephone-event")) {
kwibergc8d071e2016-04-06 12:22:38 -07001021 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1 ||
kwibergda2bf4e2016-10-24 13:47:09 -07001022 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1023 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001024 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1025 "Channel::Init() failed to register outband "
1026 "'telephone-event' (%d/%d) correctly",
1027 codec.pltype, codec.plfreq);
1028 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001029 }
1030
kwiberg55b97fe2016-01-28 05:22:45 -08001031 if (!STR_CASE_CMP(codec.plname, "CN")) {
kwibergc8d071e2016-04-06 12:22:38 -07001032 if (!codec_manager_.RegisterEncoder(codec) ||
1033 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
kwibergda2bf4e2016-10-24 13:47:09 -07001034 !audio_coding_->RegisterReceiveCodec(codec.pltype,
1035 CodecInstToSdp(codec)) ||
kwibergc8d071e2016-04-06 12:22:38 -07001036 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001037 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1038 "Channel::Init() failed to register CN (%d/%d) "
1039 "correctly - 1",
1040 codec.pltype, codec.plfreq);
1041 }
1042 }
kwiberg55b97fe2016-01-28 05:22:45 -08001043 }
pwestin@webrtc.org684f0572013-03-13 23:20:57 +00001044
kwiberg55b97fe2016-01-28 05:22:45 -08001045 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001046}
1047
tommi0a2391f2017-03-21 02:31:51 -07001048void Channel::Terminate() {
1049 RTC_DCHECK(construction_thread_.CalledOnValidThread());
1050 // Must be called on the same thread as Init().
1051 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
1052 "Channel::Terminate");
1053
1054 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
1055
1056 StopSend();
1057 StopPlayout();
1058
1059 {
1060 rtc::CritScope cs(&_fileCritSect);
1061 if (input_file_player_) {
1062 input_file_player_->RegisterModuleFileCallback(NULL);
1063 input_file_player_->StopPlayingFile();
1064 }
1065 if (output_file_player_) {
1066 output_file_player_->RegisterModuleFileCallback(NULL);
1067 output_file_player_->StopPlayingFile();
1068 }
1069 if (output_file_recorder_) {
1070 output_file_recorder_->RegisterModuleFileCallback(NULL);
1071 output_file_recorder_->StopRecording();
1072 }
1073 }
1074
1075 // The order to safely shutdown modules in a channel is:
1076 // 1. De-register callbacks in modules
1077 // 2. De-register modules in process thread
1078 // 3. Destroy modules
1079 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1080 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1081 "Terminate() failed to de-register transport callback"
1082 " (Audio coding module)");
1083 }
1084
1085 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1086 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1087 "Terminate() failed to de-register VAD callback"
1088 " (Audio coding module)");
1089 }
1090
1091 // De-register modules in process thread
1092 if (_moduleProcessThreadPtr)
1093 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
1094
1095 // End of modules shutdown
1096}
1097
kwiberg55b97fe2016-01-28 05:22:45 -08001098int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1099 OutputMixer& outputMixer,
kwiberg55b97fe2016-01-28 05:22:45 -08001100 ProcessThread& moduleProcessThread,
1101 AudioDeviceModule& audioDeviceModule,
1102 VoiceEngineObserver* voiceEngineObserver,
1103 rtc::CriticalSection* callbackCritSect) {
1104 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1105 "Channel::SetEngineInformation()");
1106 _engineStatisticsPtr = &engineStatistics;
1107 _outputMixerPtr = &outputMixer;
kwiberg55b97fe2016-01-28 05:22:45 -08001108 _moduleProcessThreadPtr = &moduleProcessThread;
1109 _audioDeviceModulePtr = &audioDeviceModule;
1110 _voiceEngineObserverPtr = voiceEngineObserver;
1111 _callbackCritSectPtr = callbackCritSect;
1112 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001113}
1114
kwiberg55b97fe2016-01-28 05:22:45 -08001115int32_t Channel::UpdateLocalTimeStamp() {
1116 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1117 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001118}
1119
kwibergb7f89d62016-02-17 10:04:18 -08001120void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001121 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001122 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001123}
1124
ossu29b1a8d2016-06-13 07:34:51 -07001125const rtc::scoped_refptr<AudioDecoderFactory>&
1126Channel::GetAudioDecoderFactory() const {
1127 return decoder_factory_;
1128}
1129
kwiberg55b97fe2016-01-28 05:22:45 -08001130int32_t Channel::StartPlayout() {
1131 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1132 "Channel::StartPlayout()");
1133 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001134 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001135 }
1136
solenberge374e012017-02-14 04:55:00 -08001137 // Add participant as candidates for mixing.
1138 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1139 _engineStatisticsPtr->SetLastError(
1140 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1141 "StartPlayout() failed to add participant to mixer");
1142 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001143 }
1144
1145 channel_state_.SetPlaying(true);
1146 if (RegisterFilePlayingToMixer() != 0)
1147 return -1;
1148
1149 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001150}
1151
kwiberg55b97fe2016-01-28 05:22:45 -08001152int32_t Channel::StopPlayout() {
1153 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1154 "Channel::StopPlayout()");
1155 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001156 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001157 }
1158
solenberge374e012017-02-14 04:55:00 -08001159 // Remove participant as candidates for mixing
1160 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1161 _engineStatisticsPtr->SetLastError(
1162 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1163 "StopPlayout() failed to remove participant from mixer");
1164 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001165 }
1166
1167 channel_state_.SetPlaying(false);
1168 _outputAudioLevel.Clear();
1169
1170 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001171}
1172
kwiberg55b97fe2016-01-28 05:22:45 -08001173int32_t Channel::StartSend() {
1174 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1175 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -08001176 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001177 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001178 }
1179 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001180
solenberg08b19df2017-02-15 00:42:31 -08001181 // Resume the previous sequence number which was reset by StopSend(). This
1182 // needs to be done before |sending| is set to true on the RTP/RTCP module.
1183 if (send_sequence_number_) {
1184 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
1185 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001186 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001187 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1188 _engineStatisticsPtr->SetLastError(
1189 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1190 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001191 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001192 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001193 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001194 return -1;
1195 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001196
kwiberg55b97fe2016-01-28 05:22:45 -08001197 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001198}
1199
kwiberg55b97fe2016-01-28 05:22:45 -08001200int32_t Channel::StopSend() {
1201 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1202 "Channel::StopSend()");
1203 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001204 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001205 }
1206 channel_state_.SetSending(false);
1207
1208 // Store the sequence number to be able to pick up the same sequence for
1209 // the next StartSend(). This is needed for restarting device, otherwise
1210 // it might cause libSRTP to complain about packets being replayed.
1211 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1212 // CL is landed. See issue
1213 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1214 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1215
1216 // Reset sending SSRC and sequence number and triggers direct transmission
1217 // of RTCP BYE
1218 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1219 _engineStatisticsPtr->SetLastError(
1220 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1221 "StartSend() RTP/RTCP failed to stop sending");
1222 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001223 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001224
1225 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001226}
1227
kwiberg55b97fe2016-01-28 05:22:45 -08001228int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1229 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1230 "Channel::RegisterVoiceEngineObserver()");
1231 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001232
kwiberg55b97fe2016-01-28 05:22:45 -08001233 if (_voiceEngineObserverPtr) {
1234 _engineStatisticsPtr->SetLastError(
1235 VE_INVALID_OPERATION, kTraceError,
1236 "RegisterVoiceEngineObserver() observer already enabled");
1237 return -1;
1238 }
1239 _voiceEngineObserverPtr = &observer;
1240 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001241}
1242
kwiberg55b97fe2016-01-28 05:22:45 -08001243int32_t Channel::DeRegisterVoiceEngineObserver() {
1244 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1245 "Channel::DeRegisterVoiceEngineObserver()");
1246 rtc::CritScope cs(&_callbackCritSect);
1247
1248 if (!_voiceEngineObserverPtr) {
1249 _engineStatisticsPtr->SetLastError(
1250 VE_INVALID_OPERATION, kTraceWarning,
1251 "DeRegisterVoiceEngineObserver() observer already disabled");
1252 return 0;
1253 }
1254 _voiceEngineObserverPtr = NULL;
1255 return 0;
1256}
1257
1258int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001259 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001260 if (send_codec) {
1261 codec = *send_codec;
1262 return 0;
1263 }
1264 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001265}
1266
kwiberg55b97fe2016-01-28 05:22:45 -08001267int32_t Channel::GetRecCodec(CodecInst& codec) {
1268 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001269}
1270
kwiberg55b97fe2016-01-28 05:22:45 -08001271int32_t Channel::SetSendCodec(const CodecInst& codec) {
1272 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1273 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001274
kwibergc8d071e2016-04-06 12:22:38 -07001275 if (!codec_manager_.RegisterEncoder(codec) ||
1276 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001277 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1278 "SetSendCodec() failed to register codec to ACM");
1279 return -1;
1280 }
1281
1282 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1283 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1284 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1285 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1286 "SetSendCodec() failed to register codec to"
1287 " RTP/RTCP module");
1288 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001289 }
kwiberg55b97fe2016-01-28 05:22:45 -08001290 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001291
kwiberg55b97fe2016-01-28 05:22:45 -08001292 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001293}
1294
minyue78b4d562016-11-30 04:47:39 -08001295void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001296 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1297 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001298 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001299 if (*encoder) {
1300 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001301 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001302 }
1303 });
michaelt566d8202017-01-12 10:17:38 -08001304 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001305}
1306
elad.alond12a8e12017-03-23 11:04:48 -07001307void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1308 if (!use_twcc_plr_for_ana_)
1309 return;
minyue7e304322016-10-12 05:00:55 -07001310 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001311 if (*encoder) {
1312 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1313 }
1314 });
1315}
1316
elad.alondadb4dc2017-03-23 15:29:50 -07001317void Channel::OnRecoverableUplinkPacketLossRate(
1318 float recoverable_packet_loss_rate) {
1319 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1320 if (*encoder) {
1321 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1322 recoverable_packet_loss_rate);
1323 }
1324 });
1325}
1326
elad.alond12a8e12017-03-23 11:04:48 -07001327void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1328 if (use_twcc_plr_for_ana_)
1329 return;
1330 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1331 if (*encoder) {
1332 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1333 }
minyue7e304322016-10-12 05:00:55 -07001334 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001335}
1336
kwiberg55b97fe2016-01-28 05:22:45 -08001337int32_t Channel::SetVADStatus(bool enableVAD,
1338 ACMVADMode mode,
1339 bool disableDTX) {
1340 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1341 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001342 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1343 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1344 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001345 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1346 kTraceError,
1347 "SetVADStatus() failed to set VAD");
1348 return -1;
1349 }
1350 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001351}
1352
kwiberg55b97fe2016-01-28 05:22:45 -08001353int32_t Channel::GetVADStatus(bool& enabledVAD,
1354 ACMVADMode& mode,
1355 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001356 const auto* params = codec_manager_.GetStackParams();
1357 enabledVAD = params->use_cng;
1358 mode = params->vad_mode;
1359 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001360 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001361}
1362
kwiberg55b97fe2016-01-28 05:22:45 -08001363int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
kwibergd32bf752017-01-19 07:03:59 -08001364 return SetRecPayloadType(codec.pltype, CodecInstToSdp(codec));
1365}
1366
1367int32_t Channel::SetRecPayloadType(int payload_type,
1368 const SdpAudioFormat& format) {
kwiberg55b97fe2016-01-28 05:22:45 -08001369 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1370 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001371
kwiberg55b97fe2016-01-28 05:22:45 -08001372 if (channel_state_.Get().playing) {
1373 _engineStatisticsPtr->SetLastError(
1374 VE_ALREADY_PLAYING, kTraceError,
1375 "SetRecPayloadType() unable to set PT while playing");
1376 return -1;
1377 }
kwiberg55b97fe2016-01-28 05:22:45 -08001378
kwiberg09f090c2017-03-01 01:57:11 -08001379 const CodecInst codec = SdpToCodecInst(payload_type, format);
kwibergd32bf752017-01-19 07:03:59 -08001380
1381 if (payload_type == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001382 // De-register the selected codec (RTP/RTCP module and ACM)
1383
1384 int8_t pltype(-1);
1385 CodecInst rxCodec = codec;
1386
1387 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001388 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001389 rxCodec.pltype = pltype;
1390
1391 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1392 _engineStatisticsPtr->SetLastError(
1393 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1394 "SetRecPayloadType() RTP/RTCP-module deregistration "
1395 "failed");
1396 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001397 }
kwiberg55b97fe2016-01-28 05:22:45 -08001398 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1399 _engineStatisticsPtr->SetLastError(
1400 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1401 "SetRecPayloadType() ACM deregistration failed - 1");
1402 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001403 }
kwiberg55b97fe2016-01-28 05:22:45 -08001404 return 0;
1405 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001406
magjed56124bd2016-11-24 09:34:46 -08001407 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001408 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001409 // TODO(kwiberg): Retrying is probably not necessary, since
1410 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001411 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001412 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001413 _engineStatisticsPtr->SetLastError(
1414 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1415 "SetRecPayloadType() RTP/RTCP-module registration failed");
1416 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001417 }
kwiberg55b97fe2016-01-28 05:22:45 -08001418 }
kwibergd32bf752017-01-19 07:03:59 -08001419 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
1420 audio_coding_->UnregisterReceiveCodec(payload_type);
1421 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001422 _engineStatisticsPtr->SetLastError(
1423 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1424 "SetRecPayloadType() ACM registration failed - 1");
1425 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001426 }
kwiberg55b97fe2016-01-28 05:22:45 -08001427 }
1428 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001429}
1430
kwiberg55b97fe2016-01-28 05:22:45 -08001431int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1432 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001433 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001434 _engineStatisticsPtr->SetLastError(
1435 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1436 "GetRecPayloadType() failed to retrieve RX payload type");
1437 return -1;
1438 }
1439 codec.pltype = payloadType;
1440 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001441}
1442
kwiberg55b97fe2016-01-28 05:22:45 -08001443int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1444 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1445 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001446
kwiberg55b97fe2016-01-28 05:22:45 -08001447 CodecInst codec;
1448 int32_t samplingFreqHz(-1);
1449 const size_t kMono = 1;
1450 if (frequency == kFreq32000Hz)
1451 samplingFreqHz = 32000;
1452 else if (frequency == kFreq16000Hz)
1453 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001454
kwiberg55b97fe2016-01-28 05:22:45 -08001455 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1456 _engineStatisticsPtr->SetLastError(
1457 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1458 "SetSendCNPayloadType() failed to retrieve default CN codec "
1459 "settings");
1460 return -1;
1461 }
1462
1463 // Modify the payload type (must be set to dynamic range)
1464 codec.pltype = type;
1465
kwibergc8d071e2016-04-06 12:22:38 -07001466 if (!codec_manager_.RegisterEncoder(codec) ||
1467 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001468 _engineStatisticsPtr->SetLastError(
1469 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1470 "SetSendCNPayloadType() failed to register CN to ACM");
1471 return -1;
1472 }
1473
1474 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1475 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1476 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1477 _engineStatisticsPtr->SetLastError(
1478 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1479 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1480 "module");
1481 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001482 }
kwiberg55b97fe2016-01-28 05:22:45 -08001483 }
1484 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001485}
1486
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001487int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001488 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001489 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001490
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001491 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001492 _engineStatisticsPtr->SetLastError(
1493 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001494 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001495 return -1;
1496 }
1497 return 0;
1498}
1499
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001500int Channel::SetOpusDtx(bool enable_dtx) {
1501 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1502 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001503 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001504 : audio_coding_->DisableOpusDtx();
1505 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001506 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1507 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001508 return -1;
1509 }
1510 return 0;
1511}
1512
ivoc85228d62016-07-27 04:53:47 -07001513int Channel::GetOpusDtx(bool* enabled) {
1514 int success = -1;
1515 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1516 if (encoder) {
1517 *enabled = encoder->GetDtx();
1518 success = 0;
1519 }
1520 });
1521 return success;
1522}
1523
minyue7e304322016-10-12 05:00:55 -07001524bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1525 bool success = false;
1526 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1527 if (*encoder) {
1528 success = (*encoder)->EnableAudioNetworkAdaptor(
michaeltbf279fc2017-01-13 06:02:29 -08001529 config_string, event_log_proxy_.get(), Clock::GetRealTimeClock());
minyue7e304322016-10-12 05:00:55 -07001530 }
1531 });
1532 return success;
1533}
1534
1535void Channel::DisableAudioNetworkAdaptor() {
1536 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1537 if (*encoder)
1538 (*encoder)->DisableAudioNetworkAdaptor();
1539 });
1540}
1541
1542void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1543 int max_frame_length_ms) {
1544 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1545 if (*encoder) {
1546 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1547 max_frame_length_ms);
1548 }
1549 });
1550}
1551
mflodman3d7db262016-04-29 00:57:13 -07001552int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001553 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001554 "Channel::RegisterExternalTransport()");
1555
kwiberg55b97fe2016-01-28 05:22:45 -08001556 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001557 if (_externalTransport) {
1558 _engineStatisticsPtr->SetLastError(
1559 VE_INVALID_OPERATION, kTraceError,
1560 "RegisterExternalTransport() external transport already enabled");
1561 return -1;
1562 }
1563 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001564 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001565 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001566}
1567
kwiberg55b97fe2016-01-28 05:22:45 -08001568int32_t Channel::DeRegisterExternalTransport() {
1569 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1570 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001571
kwiberg55b97fe2016-01-28 05:22:45 -08001572 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001573 if (_transportPtr) {
1574 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1575 "DeRegisterExternalTransport() all transport is disabled");
1576 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001577 _engineStatisticsPtr->SetLastError(
1578 VE_INVALID_OPERATION, kTraceWarning,
1579 "DeRegisterExternalTransport() external transport already "
1580 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001581 }
1582 _externalTransport = false;
1583 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001584 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001585}
1586
nisse657bab22017-02-21 06:28:10 -08001587// TODO(nisse): Delete this method together with ReceivedRTPPacket.
1588// It's a temporary hack to support both ReceivedRTPPacket and
1589// OnRtpPacket interfaces without too much code duplication.
1590bool Channel::OnRtpPacketWithHeader(const uint8_t* received_packet,
1591 size_t length,
1592 RTPHeader *header) {
1593 // Store playout timestamp for the received RTP packet
1594 UpdatePlayoutTimestamp(false);
1595
1596 header->payload_type_frequency =
1597 rtp_payload_registry_->GetPayloadTypeFrequency(header->payloadType);
1598 if (header->payload_type_frequency < 0)
1599 return false;
1600 bool in_order = IsPacketInOrder(*header);
1601 rtp_receive_statistics_->IncomingPacket(
1602 *header, length, IsPacketRetransmitted(*header, in_order));
1603 rtp_payload_registry_->SetIncomingPayloadType(*header);
1604
1605 return ReceivePacket(received_packet, length, *header, in_order);
1606}
1607
mflodman3d7db262016-04-29 00:57:13 -07001608int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001609 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001610 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001611 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001612 "Channel::ReceivedRTPPacket()");
1613
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001614 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001615 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1616 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1617 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001618 return -1;
1619 }
nisse657bab22017-02-21 06:28:10 -08001620 return OnRtpPacketWithHeader(received_packet, length, &header) ? 0 : -1;
1621}
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001622
nisse657bab22017-02-21 06:28:10 -08001623void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1624 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
1625 "Channel::ReceivedRTPPacket()");
1626
1627 RTPHeader header;
1628 packet.GetHeader(&header);
1629 OnRtpPacketWithHeader(packet.data(), packet.size(), &header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001630}
1631
1632bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001633 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001634 const RTPHeader& header,
1635 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001636 if (rtp_payload_registry_->IsRtx(header)) {
1637 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001638 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001639 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001640 assert(packet_length >= header.headerLength);
1641 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001642 PayloadUnion payload_specific;
1643 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001644 &payload_specific)) {
1645 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001646 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001647 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1648 payload_specific, in_order);
1649}
1650
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001651bool Channel::HandleRtxPacket(const uint8_t* packet,
1652 size_t packet_length,
1653 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001654 if (!rtp_payload_registry_->IsRtx(header))
1655 return false;
1656
1657 // Remove the RTX header and parse the original RTP header.
1658 if (packet_length < header.headerLength)
1659 return false;
1660 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1661 return false;
1662 if (restored_packet_in_use_) {
1663 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1664 "Multiple RTX headers detected, dropping packet");
1665 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001666 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001667 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001668 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1669 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001670 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1671 "Incoming RTX packet: invalid RTP header");
1672 return false;
1673 }
1674 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001675 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001676 restored_packet_in_use_ = false;
1677 return ret;
1678}
1679
1680bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1681 StreamStatistician* statistician =
1682 rtp_receive_statistics_->GetStatistician(header.ssrc);
1683 if (!statistician)
1684 return false;
1685 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001686}
1687
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001688bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1689 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001690 // Retransmissions are handled separately if RTX is enabled.
1691 if (rtp_payload_registry_->RtxEnabled())
1692 return false;
1693 StreamStatistician* statistician =
1694 rtp_receive_statistics_->GetStatistician(header.ssrc);
1695 if (!statistician)
1696 return false;
1697 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001698 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001699 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001700 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001701}
1702
mflodman3d7db262016-04-29 00:57:13 -07001703int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001704 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001705 "Channel::ReceivedRTCPPacket()");
1706 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001707 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001708
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001709 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001710 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001711 _engineStatisticsPtr->SetLastError(
1712 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1713 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1714 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001715
Minyue2013aec2015-05-13 14:14:42 +02001716 int64_t rtt = GetRTT(true);
1717 if (rtt == 0) {
1718 // Waiting for valid RTT.
1719 return 0;
1720 }
Erik Språng737336d2016-07-29 12:59:36 +02001721
1722 int64_t nack_window_ms = rtt;
1723 if (nack_window_ms < kMinRetransmissionWindowMs) {
1724 nack_window_ms = kMinRetransmissionWindowMs;
1725 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1726 nack_window_ms = kMaxRetransmissionWindowMs;
1727 }
1728 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1729
minyue7e304322016-10-12 05:00:55 -07001730 // Invoke audio encoders OnReceivedRtt().
1731 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1732 if (*encoder)
1733 (*encoder)->OnReceivedRtt(rtt);
1734 });
1735
Minyue2013aec2015-05-13 14:14:42 +02001736 uint32_t ntp_secs = 0;
1737 uint32_t ntp_frac = 0;
1738 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001739 if (0 !=
1740 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1741 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001742 // Waiting for RTCP.
1743 return 0;
1744 }
1745
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001746 {
tommi31fc21f2016-01-21 10:37:37 -08001747 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001748 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001749 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001750 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001751}
1752
niklase@google.com470e71d2011-07-07 08:21:25 +00001753int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001754 bool loop,
1755 FileFormats format,
1756 int startPosition,
1757 float volumeScaling,
1758 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001759 const CodecInst* codecInst) {
1760 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1761 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1762 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1763 "stopPosition=%d)",
1764 fileName, loop, format, volumeScaling, startPosition,
1765 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001766
kwiberg55b97fe2016-01-28 05:22:45 -08001767 if (channel_state_.Get().output_file_playing) {
1768 _engineStatisticsPtr->SetLastError(
1769 VE_ALREADY_PLAYING, kTraceError,
1770 "StartPlayingFileLocally() is already playing");
1771 return -1;
1772 }
1773
1774 {
1775 rtc::CritScope cs(&_fileCritSect);
1776
kwiberg5a25d952016-08-17 07:31:12 -07001777 if (output_file_player_) {
1778 output_file_player_->RegisterModuleFileCallback(NULL);
1779 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001780 }
1781
kwiberg5b356f42016-09-08 04:32:33 -07001782 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001783 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001784
kwiberg5a25d952016-08-17 07:31:12 -07001785 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001786 _engineStatisticsPtr->SetLastError(
1787 VE_INVALID_ARGUMENT, kTraceError,
1788 "StartPlayingFileLocally() filePlayer format is not correct");
1789 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001790 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001791
kwiberg55b97fe2016-01-28 05:22:45 -08001792 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001793
kwiberg5a25d952016-08-17 07:31:12 -07001794 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001795 fileName, loop, startPosition, volumeScaling, notificationTime,
1796 stopPosition, (const CodecInst*)codecInst) != 0) {
1797 _engineStatisticsPtr->SetLastError(
1798 VE_BAD_FILE, kTraceError,
1799 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001800 output_file_player_->StopPlayingFile();
1801 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001802 return -1;
1803 }
kwiberg5a25d952016-08-17 07:31:12 -07001804 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001805 channel_state_.SetOutputFilePlaying(true);
1806 }
1807
1808 if (RegisterFilePlayingToMixer() != 0)
1809 return -1;
1810
1811 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001812}
1813
1814int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001815 FileFormats format,
1816 int startPosition,
1817 float volumeScaling,
1818 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001819 const CodecInst* codecInst) {
1820 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1821 "Channel::StartPlayingFileLocally(format=%d,"
1822 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1823 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001824
kwiberg55b97fe2016-01-28 05:22:45 -08001825 if (stream == NULL) {
1826 _engineStatisticsPtr->SetLastError(
1827 VE_BAD_FILE, kTraceError,
1828 "StartPlayingFileLocally() NULL as input stream");
1829 return -1;
1830 }
1831
1832 if (channel_state_.Get().output_file_playing) {
1833 _engineStatisticsPtr->SetLastError(
1834 VE_ALREADY_PLAYING, kTraceError,
1835 "StartPlayingFileLocally() is already playing");
1836 return -1;
1837 }
1838
1839 {
1840 rtc::CritScope cs(&_fileCritSect);
1841
1842 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001843 if (output_file_player_) {
1844 output_file_player_->RegisterModuleFileCallback(NULL);
1845 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001846 }
1847
kwiberg55b97fe2016-01-28 05:22:45 -08001848 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001849 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001850 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001851
kwiberg5a25d952016-08-17 07:31:12 -07001852 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001853 _engineStatisticsPtr->SetLastError(
1854 VE_INVALID_ARGUMENT, kTraceError,
1855 "StartPlayingFileLocally() filePlayer format isnot correct");
1856 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001857 }
1858
kwiberg55b97fe2016-01-28 05:22:45 -08001859 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001860
kwiberg4ec01d92016-08-22 08:43:54 -07001861 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001862 volumeScaling, notificationTime,
1863 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001864 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1865 "StartPlayingFile() failed to "
1866 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001867 output_file_player_->StopPlayingFile();
1868 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001869 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001870 }
kwiberg5a25d952016-08-17 07:31:12 -07001871 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001872 channel_state_.SetOutputFilePlaying(true);
1873 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001874
kwiberg55b97fe2016-01-28 05:22:45 -08001875 if (RegisterFilePlayingToMixer() != 0)
1876 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001877
kwiberg55b97fe2016-01-28 05:22:45 -08001878 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001879}
1880
kwiberg55b97fe2016-01-28 05:22:45 -08001881int Channel::StopPlayingFileLocally() {
1882 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1883 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001884
kwiberg55b97fe2016-01-28 05:22:45 -08001885 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001886 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001887 }
1888
1889 {
1890 rtc::CritScope cs(&_fileCritSect);
1891
kwiberg5a25d952016-08-17 07:31:12 -07001892 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001893 _engineStatisticsPtr->SetLastError(
1894 VE_STOP_RECORDING_FAILED, kTraceError,
1895 "StopPlayingFile() could not stop playing");
1896 return -1;
1897 }
kwiberg5a25d952016-08-17 07:31:12 -07001898 output_file_player_->RegisterModuleFileCallback(NULL);
1899 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001900 channel_state_.SetOutputFilePlaying(false);
1901 }
1902 // _fileCritSect cannot be taken while calling
1903 // SetAnonymousMixibilityStatus. Refer to comments in
1904 // StartPlayingFileLocally(const char* ...) for more details.
1905 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1906 _engineStatisticsPtr->SetLastError(
1907 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1908 "StopPlayingFile() failed to stop participant from playing as"
1909 "file in the mixer");
1910 return -1;
1911 }
1912
1913 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001914}
1915
kwiberg55b97fe2016-01-28 05:22:45 -08001916int Channel::IsPlayingFileLocally() const {
1917 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001918}
1919
kwiberg55b97fe2016-01-28 05:22:45 -08001920int Channel::RegisterFilePlayingToMixer() {
1921 // Return success for not registering for file playing to mixer if:
1922 // 1. playing file before playout is started on that channel.
1923 // 2. starting playout without file playing on that channel.
1924 if (!channel_state_.Get().playing ||
1925 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001926 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001927 }
1928
1929 // |_fileCritSect| cannot be taken while calling
1930 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1931 // frames can be pulled by the mixer. Since the frames are generated from
1932 // the file, _fileCritSect will be taken. This would result in a deadlock.
1933 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1934 channel_state_.SetOutputFilePlaying(false);
1935 rtc::CritScope cs(&_fileCritSect);
1936 _engineStatisticsPtr->SetLastError(
1937 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1938 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07001939 output_file_player_->StopPlayingFile();
1940 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001941 return -1;
1942 }
1943
1944 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001945}
1946
niklase@google.com470e71d2011-07-07 08:21:25 +00001947int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001948 bool loop,
1949 FileFormats format,
1950 int startPosition,
1951 float volumeScaling,
1952 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001953 const CodecInst* codecInst) {
1954 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1955 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1956 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1957 "stopPosition=%d)",
1958 fileName, loop, format, volumeScaling, startPosition,
1959 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001960
kwiberg55b97fe2016-01-28 05:22:45 -08001961 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001962
kwiberg55b97fe2016-01-28 05:22:45 -08001963 if (channel_state_.Get().input_file_playing) {
1964 _engineStatisticsPtr->SetLastError(
1965 VE_ALREADY_PLAYING, kTraceWarning,
1966 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001967 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001968 }
1969
1970 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001971 if (input_file_player_) {
1972 input_file_player_->RegisterModuleFileCallback(NULL);
1973 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001974 }
1975
1976 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001977 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07001978 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08001979
kwiberg5a25d952016-08-17 07:31:12 -07001980 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001981 _engineStatisticsPtr->SetLastError(
1982 VE_INVALID_ARGUMENT, kTraceError,
1983 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
1984 return -1;
1985 }
1986
1987 const uint32_t notificationTime(0);
1988
kwiberg5a25d952016-08-17 07:31:12 -07001989 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001990 fileName, loop, startPosition, volumeScaling, notificationTime,
1991 stopPosition, (const CodecInst*)codecInst) != 0) {
1992 _engineStatisticsPtr->SetLastError(
1993 VE_BAD_FILE, kTraceError,
1994 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001995 input_file_player_->StopPlayingFile();
1996 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001997 return -1;
1998 }
kwiberg5a25d952016-08-17 07:31:12 -07001999 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002000 channel_state_.SetInputFilePlaying(true);
2001
2002 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002003}
2004
2005int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002006 FileFormats format,
2007 int startPosition,
2008 float volumeScaling,
2009 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002010 const CodecInst* codecInst) {
2011 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2012 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2013 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2014 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002015
kwiberg55b97fe2016-01-28 05:22:45 -08002016 if (stream == NULL) {
2017 _engineStatisticsPtr->SetLastError(
2018 VE_BAD_FILE, kTraceError,
2019 "StartPlayingFileAsMicrophone NULL as input stream");
2020 return -1;
2021 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002022
kwiberg55b97fe2016-01-28 05:22:45 -08002023 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002024
kwiberg55b97fe2016-01-28 05:22:45 -08002025 if (channel_state_.Get().input_file_playing) {
2026 _engineStatisticsPtr->SetLastError(
2027 VE_ALREADY_PLAYING, kTraceWarning,
2028 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002029 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002030 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002031
kwiberg55b97fe2016-01-28 05:22:45 -08002032 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002033 if (input_file_player_) {
2034 input_file_player_->RegisterModuleFileCallback(NULL);
2035 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002036 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002037
kwiberg55b97fe2016-01-28 05:22:45 -08002038 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002039 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002040 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002041
kwiberg5a25d952016-08-17 07:31:12 -07002042 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002043 _engineStatisticsPtr->SetLastError(
2044 VE_INVALID_ARGUMENT, kTraceError,
2045 "StartPlayingInputFile() filePlayer format isnot correct");
2046 return -1;
2047 }
2048
2049 const uint32_t notificationTime(0);
2050
kwiberg4ec01d92016-08-22 08:43:54 -07002051 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2052 notificationTime, stopPosition,
2053 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002054 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2055 "StartPlayingFile() failed to start "
2056 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002057 input_file_player_->StopPlayingFile();
2058 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002059 return -1;
2060 }
2061
kwiberg5a25d952016-08-17 07:31:12 -07002062 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002063 channel_state_.SetInputFilePlaying(true);
2064
2065 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002066}
2067
kwiberg55b97fe2016-01-28 05:22:45 -08002068int Channel::StopPlayingFileAsMicrophone() {
2069 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2070 "Channel::StopPlayingFileAsMicrophone()");
2071
2072 rtc::CritScope cs(&_fileCritSect);
2073
2074 if (!channel_state_.Get().input_file_playing) {
2075 return 0;
2076 }
2077
kwiberg5a25d952016-08-17 07:31:12 -07002078 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002079 _engineStatisticsPtr->SetLastError(
2080 VE_STOP_RECORDING_FAILED, kTraceError,
2081 "StopPlayingFile() could not stop playing");
2082 return -1;
2083 }
kwiberg5a25d952016-08-17 07:31:12 -07002084 input_file_player_->RegisterModuleFileCallback(NULL);
2085 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002086 channel_state_.SetInputFilePlaying(false);
2087
2088 return 0;
2089}
2090
2091int Channel::IsPlayingFileAsMicrophone() const {
2092 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002093}
2094
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002095int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002096 const CodecInst* codecInst) {
2097 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2098 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002099
kwiberg55b97fe2016-01-28 05:22:45 -08002100 if (_outputFileRecording) {
2101 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2102 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002103 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002104 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002105
kwiberg55b97fe2016-01-28 05:22:45 -08002106 FileFormats format;
2107 const uint32_t notificationTime(0); // Not supported in VoE
2108 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002109
kwiberg55b97fe2016-01-28 05:22:45 -08002110 if ((codecInst != NULL) &&
2111 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2112 _engineStatisticsPtr->SetLastError(
2113 VE_BAD_ARGUMENT, kTraceError,
2114 "StartRecordingPlayout() invalid compression");
2115 return (-1);
2116 }
2117 if (codecInst == NULL) {
2118 format = kFileFormatPcm16kHzFile;
2119 codecInst = &dummyCodec;
2120 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2121 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2122 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2123 format = kFileFormatWavFile;
2124 } else {
2125 format = kFileFormatCompressedFile;
2126 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002127
kwiberg55b97fe2016-01-28 05:22:45 -08002128 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002129
kwiberg55b97fe2016-01-28 05:22:45 -08002130 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002131 if (output_file_recorder_) {
2132 output_file_recorder_->RegisterModuleFileCallback(NULL);
2133 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002134 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002135
kwiberg5a25d952016-08-17 07:31:12 -07002136 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002137 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002138 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002139 _engineStatisticsPtr->SetLastError(
2140 VE_INVALID_ARGUMENT, kTraceError,
2141 "StartRecordingPlayout() fileRecorder format isnot correct");
2142 return -1;
2143 }
2144
kwiberg5a25d952016-08-17 07:31:12 -07002145 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002146 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2147 _engineStatisticsPtr->SetLastError(
2148 VE_BAD_FILE, kTraceError,
2149 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002150 output_file_recorder_->StopRecording();
2151 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002152 return -1;
2153 }
kwiberg5a25d952016-08-17 07:31:12 -07002154 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002155 _outputFileRecording = true;
2156
2157 return 0;
2158}
2159
2160int Channel::StartRecordingPlayout(OutStream* stream,
2161 const CodecInst* codecInst) {
2162 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2163 "Channel::StartRecordingPlayout()");
2164
2165 if (_outputFileRecording) {
2166 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2167 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002168 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002169 }
2170
2171 FileFormats format;
2172 const uint32_t notificationTime(0); // Not supported in VoE
2173 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2174
2175 if (codecInst != NULL && codecInst->channels != 1) {
2176 _engineStatisticsPtr->SetLastError(
2177 VE_BAD_ARGUMENT, kTraceError,
2178 "StartRecordingPlayout() invalid compression");
2179 return (-1);
2180 }
2181 if (codecInst == NULL) {
2182 format = kFileFormatPcm16kHzFile;
2183 codecInst = &dummyCodec;
2184 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2185 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2186 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2187 format = kFileFormatWavFile;
2188 } else {
2189 format = kFileFormatCompressedFile;
2190 }
2191
2192 rtc::CritScope cs(&_fileCritSect);
2193
2194 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002195 if (output_file_recorder_) {
2196 output_file_recorder_->RegisterModuleFileCallback(NULL);
2197 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002198 }
2199
kwiberg5a25d952016-08-17 07:31:12 -07002200 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002201 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002202 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002203 _engineStatisticsPtr->SetLastError(
2204 VE_INVALID_ARGUMENT, kTraceError,
2205 "StartRecordingPlayout() fileRecorder format isnot correct");
2206 return -1;
2207 }
2208
kwiberg4ec01d92016-08-22 08:43:54 -07002209 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002210 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002211 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2212 "StartRecordingPlayout() failed to "
2213 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002214 output_file_recorder_->StopRecording();
2215 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002216 return -1;
2217 }
2218
kwiberg5a25d952016-08-17 07:31:12 -07002219 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002220 _outputFileRecording = true;
2221
2222 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002223}
2224
kwiberg55b97fe2016-01-28 05:22:45 -08002225int Channel::StopRecordingPlayout() {
2226 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2227 "Channel::StopRecordingPlayout()");
2228
2229 if (!_outputFileRecording) {
2230 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2231 "StopRecordingPlayout() isnot recording");
2232 return -1;
2233 }
2234
2235 rtc::CritScope cs(&_fileCritSect);
2236
kwiberg5a25d952016-08-17 07:31:12 -07002237 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002238 _engineStatisticsPtr->SetLastError(
2239 VE_STOP_RECORDING_FAILED, kTraceError,
2240 "StopRecording() could not stop recording");
2241 return (-1);
2242 }
kwiberg5a25d952016-08-17 07:31:12 -07002243 output_file_recorder_->RegisterModuleFileCallback(NULL);
2244 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002245 _outputFileRecording = false;
2246
2247 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002248}
2249
kwiberg55b97fe2016-01-28 05:22:45 -08002250void Channel::SetMixWithMicStatus(bool mix) {
2251 rtc::CritScope cs(&_fileCritSect);
2252 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002253}
2254
solenberg8d73f8c2017-03-08 01:52:20 -08002255int Channel::GetSpeechOutputLevel() const {
2256 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002257}
2258
solenberg8d73f8c2017-03-08 01:52:20 -08002259int Channel::GetSpeechOutputLevelFullRange() const {
2260 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08002261}
2262
solenberg8d73f8c2017-03-08 01:52:20 -08002263void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002264 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002265 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002266}
2267
solenberg1c2af8e2016-03-24 10:36:00 -07002268bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002269 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002270 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002271}
2272
solenberg8d73f8c2017-03-08 01:52:20 -08002273void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08002274 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08002275 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00002276}
2277
solenberg8842c3e2016-03-11 03:06:41 -08002278int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002279 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002280 "Channel::SendTelephoneEventOutband(...)");
2281 RTC_DCHECK_LE(0, event);
2282 RTC_DCHECK_GE(255, event);
2283 RTC_DCHECK_LE(0, duration_ms);
2284 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002285 if (!Sending()) {
2286 return -1;
2287 }
solenberg8842c3e2016-03-11 03:06:41 -08002288 if (_rtpRtcpModule->SendTelephoneEventOutband(
2289 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002290 _engineStatisticsPtr->SetLastError(
2291 VE_SEND_DTMF_FAILED, kTraceWarning,
2292 "SendTelephoneEventOutband() failed to send event");
2293 return -1;
2294 }
2295 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002296}
2297
solenbergffbbcac2016-11-17 05:25:37 -08002298int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2299 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002300 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002301 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002302 RTC_DCHECK_LE(0, payload_type);
2303 RTC_DCHECK_GE(127, payload_type);
2304 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002305 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002306 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002307 memcpy(codec.plname, "telephone-event", 16);
2308 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2309 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2310 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2311 _engineStatisticsPtr->SetLastError(
2312 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2313 "SetSendTelephoneEventPayloadType() failed to register send"
2314 "payload type");
2315 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002316 }
kwiberg55b97fe2016-01-28 05:22:45 -08002317 }
kwiberg55b97fe2016-01-28 05:22:45 -08002318 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002319}
2320
kwiberg55b97fe2016-01-28 05:22:45 -08002321int Channel::SetLocalSSRC(unsigned int ssrc) {
2322 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2323 "Channel::SetLocalSSRC()");
2324 if (channel_state_.Get().sending) {
2325 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2326 "SetLocalSSRC() already sending");
2327 return -1;
2328 }
2329 _rtpRtcpModule->SetSSRC(ssrc);
2330 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002331}
2332
kwiberg55b97fe2016-01-28 05:22:45 -08002333int Channel::GetLocalSSRC(unsigned int& ssrc) {
2334 ssrc = _rtpRtcpModule->SSRC();
2335 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002336}
2337
kwiberg55b97fe2016-01-28 05:22:45 -08002338int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2339 ssrc = rtp_receiver_->SSRC();
2340 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002341}
2342
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002343int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002344 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002345 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002346}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002347
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002348int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2349 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002350 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2351 if (enable &&
2352 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2353 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002354 return -1;
2355 }
2356 return 0;
2357}
2358
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002359void Channel::EnableSendTransportSequenceNumber(int id) {
2360 int ret =
2361 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2362 RTC_DCHECK_EQ(0, ret);
2363}
2364
stefan3313ec92016-01-21 06:32:43 -08002365void Channel::EnableReceiveTransportSequenceNumber(int id) {
2366 rtp_header_parser_->DeregisterRtpHeaderExtension(
2367 kRtpExtensionTransportSequenceNumber);
2368 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2369 kRtpExtensionTransportSequenceNumber, id);
2370 RTC_DCHECK(ret);
2371}
2372
stefanbba9dec2016-02-01 04:39:55 -08002373void Channel::RegisterSenderCongestionControlObjects(
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002374 RtpPacketSender* rtp_packet_sender,
2375 TransportFeedbackObserver* transport_feedback_observer,
stefan7de8d642017-02-07 07:14:08 -08002376 PacketRouter* packet_router,
2377 RtcpBandwidthObserver* bandwidth_observer) {
stefanbba9dec2016-02-01 04:39:55 -08002378 RTC_DCHECK(rtp_packet_sender);
2379 RTC_DCHECK(transport_feedback_observer);
2380 RTC_DCHECK(packet_router && !packet_router_);
stefan7de8d642017-02-07 07:14:08 -08002381 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08002382 feedback_observer_proxy_->SetTransportFeedbackObserver(
2383 transport_feedback_observer);
2384 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2385 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2386 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002387 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002388 packet_router_ = packet_router;
2389}
2390
stefanbba9dec2016-02-01 04:39:55 -08002391void Channel::RegisterReceiverCongestionControlObjects(
2392 PacketRouter* packet_router) {
2393 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002394 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002395 packet_router_ = packet_router;
2396}
2397
2398void Channel::ResetCongestionControlObjects() {
2399 RTC_DCHECK(packet_router_);
2400 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08002401 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08002402 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2403 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002404 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002405 packet_router_ = nullptr;
2406 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2407}
2408
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002409void Channel::SetRTCPStatus(bool enable) {
2410 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2411 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002412 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002413}
2414
kwiberg55b97fe2016-01-28 05:22:45 -08002415int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002416 RtcpMode method = _rtpRtcpModule->RTCP();
2417 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002418 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002419}
2420
kwiberg55b97fe2016-01-28 05:22:45 -08002421int Channel::SetRTCP_CNAME(const char cName[256]) {
2422 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2423 "Channel::SetRTCP_CNAME()");
2424 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2425 _engineStatisticsPtr->SetLastError(
2426 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2427 "SetRTCP_CNAME() failed to set RTCP CNAME");
2428 return -1;
2429 }
2430 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002431}
2432
kwiberg55b97fe2016-01-28 05:22:45 -08002433int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2434 if (cName == NULL) {
2435 _engineStatisticsPtr->SetLastError(
2436 VE_INVALID_ARGUMENT, kTraceError,
2437 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2438 return -1;
2439 }
2440 char cname[RTCP_CNAME_SIZE];
2441 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2442 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2443 _engineStatisticsPtr->SetLastError(
2444 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2445 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2446 return -1;
2447 }
2448 strcpy(cName, cname);
2449 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002450}
2451
kwiberg55b97fe2016-01-28 05:22:45 -08002452int Channel::SendApplicationDefinedRTCPPacket(
2453 unsigned char subType,
2454 unsigned int name,
2455 const char* data,
2456 unsigned short dataLengthInBytes) {
2457 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2458 "Channel::SendApplicationDefinedRTCPPacket()");
2459 if (!channel_state_.Get().sending) {
2460 _engineStatisticsPtr->SetLastError(
2461 VE_NOT_SENDING, kTraceError,
2462 "SendApplicationDefinedRTCPPacket() not sending");
2463 return -1;
2464 }
2465 if (NULL == data) {
2466 _engineStatisticsPtr->SetLastError(
2467 VE_INVALID_ARGUMENT, kTraceError,
2468 "SendApplicationDefinedRTCPPacket() invalid data value");
2469 return -1;
2470 }
2471 if (dataLengthInBytes % 4 != 0) {
2472 _engineStatisticsPtr->SetLastError(
2473 VE_INVALID_ARGUMENT, kTraceError,
2474 "SendApplicationDefinedRTCPPacket() invalid length value");
2475 return -1;
2476 }
2477 RtcpMode status = _rtpRtcpModule->RTCP();
2478 if (status == RtcpMode::kOff) {
2479 _engineStatisticsPtr->SetLastError(
2480 VE_RTCP_ERROR, kTraceError,
2481 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2482 return -1;
2483 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002484
kwiberg55b97fe2016-01-28 05:22:45 -08002485 // Create and schedule the RTCP APP packet for transmission
2486 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2487 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2488 _engineStatisticsPtr->SetLastError(
2489 VE_SEND_ERROR, kTraceError,
2490 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2491 return -1;
2492 }
2493 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002494}
2495
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002496int Channel::GetRemoteRTCPReportBlocks(
2497 std::vector<ReportBlock>* report_blocks) {
2498 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002499 _engineStatisticsPtr->SetLastError(
2500 VE_INVALID_ARGUMENT, kTraceError,
2501 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002502 return -1;
2503 }
2504
2505 // Get the report blocks from the latest received RTCP Sender or Receiver
2506 // Report. Each element in the vector contains the sender's SSRC and a
2507 // report block according to RFC 3550.
2508 std::vector<RTCPReportBlock> rtcp_report_blocks;
2509 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002510 return -1;
2511 }
2512
2513 if (rtcp_report_blocks.empty())
2514 return 0;
2515
2516 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2517 for (; it != rtcp_report_blocks.end(); ++it) {
2518 ReportBlock report_block;
2519 report_block.sender_SSRC = it->remoteSSRC;
2520 report_block.source_SSRC = it->sourceSSRC;
2521 report_block.fraction_lost = it->fractionLost;
2522 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2523 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2524 report_block.interarrival_jitter = it->jitter;
2525 report_block.last_SR_timestamp = it->lastSR;
2526 report_block.delay_since_last_SR = it->delaySinceLastSR;
2527 report_blocks->push_back(report_block);
2528 }
2529 return 0;
2530}
2531
kwiberg55b97fe2016-01-28 05:22:45 -08002532int Channel::GetRTPStatistics(CallStatistics& stats) {
2533 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002534
kwiberg55b97fe2016-01-28 05:22:45 -08002535 // The jitter statistics is updated for each received RTP packet and is
2536 // based on received packets.
2537 RtcpStatistics statistics;
2538 StreamStatistician* statistician =
2539 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002540 if (statistician) {
2541 statistician->GetStatistics(&statistics,
2542 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002543 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002544
kwiberg55b97fe2016-01-28 05:22:45 -08002545 stats.fractionLost = statistics.fraction_lost;
2546 stats.cumulativeLost = statistics.cumulative_lost;
2547 stats.extendedMax = statistics.extended_max_sequence_number;
2548 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002549
kwiberg55b97fe2016-01-28 05:22:45 -08002550 // --- RTT
2551 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002552
kwiberg55b97fe2016-01-28 05:22:45 -08002553 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002554
kwiberg55b97fe2016-01-28 05:22:45 -08002555 size_t bytesSent(0);
2556 uint32_t packetsSent(0);
2557 size_t bytesReceived(0);
2558 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002559
kwiberg55b97fe2016-01-28 05:22:45 -08002560 if (statistician) {
2561 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2562 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002563
kwiberg55b97fe2016-01-28 05:22:45 -08002564 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2565 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2566 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2567 " output will not be complete");
2568 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002569
kwiberg55b97fe2016-01-28 05:22:45 -08002570 stats.bytesSent = bytesSent;
2571 stats.packetsSent = packetsSent;
2572 stats.bytesReceived = bytesReceived;
2573 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002574
kwiberg55b97fe2016-01-28 05:22:45 -08002575 // --- Timestamps
2576 {
2577 rtc::CritScope lock(&ts_stats_lock_);
2578 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2579 }
2580 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002581}
2582
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002583int Channel::SetCodecFECStatus(bool enable) {
2584 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2585 "Channel::SetCodecFECStatus()");
2586
kwibergc8d071e2016-04-06 12:22:38 -07002587 if (!codec_manager_.SetCodecFEC(enable) ||
2588 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002589 _engineStatisticsPtr->SetLastError(
2590 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2591 "SetCodecFECStatus() failed to set FEC state");
2592 return -1;
2593 }
2594 return 0;
2595}
2596
2597bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002598 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002599}
2600
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002601void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2602 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002603 // If pacing is enabled we always store packets.
2604 if (!pacing_enabled_)
2605 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002606 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002607 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002608 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002609 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002610 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002611}
2612
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002613// Called when we are missing one or more packets.
2614int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002615 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2616}
2617
kwiberg55b97fe2016-01-28 05:22:45 -08002618uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2619 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2620 "Channel::Demultiplex()");
2621 _audioFrame.CopyFrom(audioFrame);
2622 _audioFrame.id_ = _channelId;
2623 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002624}
2625
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002626void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002627 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002628 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002629 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002630 CodecInst codec;
2631 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002632
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002633 // Never upsample or upmix the capture signal here. This should be done at the
2634 // end of the send chain.
2635 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2636 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2637 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2638 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002639}
2640
kwiberg55b97fe2016-01-28 05:22:45 -08002641uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2642 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2643 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002644
kwiberg55b97fe2016-01-28 05:22:45 -08002645 if (_audioFrame.samples_per_channel_ == 0) {
2646 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2647 "Channel::PrepareEncodeAndSend() invalid audio frame");
2648 return 0xFFFFFFFF;
2649 }
2650
2651 if (channel_state_.Get().input_file_playing) {
2652 MixOrReplaceAudioWithFile(mixingFrequency);
2653 }
2654
solenberg1c2af8e2016-03-24 10:36:00 -07002655 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2656 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002657
kwiberg55b97fe2016-01-28 05:22:45 -08002658 if (_includeAudioLevelIndication) {
2659 size_t length =
2660 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02002661 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002662 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002663 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002664 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002665 rms_level_.Analyze(
2666 rtc::ArrayView<const int16_t>(_audioFrame.data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002667 }
kwiberg55b97fe2016-01-28 05:22:45 -08002668 }
solenberg1c2af8e2016-03-24 10:36:00 -07002669 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002670
kwiberg55b97fe2016-01-28 05:22:45 -08002671 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002672}
2673
kwiberg55b97fe2016-01-28 05:22:45 -08002674uint32_t Channel::EncodeAndSend() {
2675 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2676 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002677
kwiberg55b97fe2016-01-28 05:22:45 -08002678 assert(_audioFrame.num_channels_ <= 2);
2679 if (_audioFrame.samples_per_channel_ == 0) {
2680 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2681 "Channel::EncodeAndSend() invalid audio frame");
2682 return 0xFFFFFFFF;
2683 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002684
kwiberg55b97fe2016-01-28 05:22:45 -08002685 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00002686
kwiberg55b97fe2016-01-28 05:22:45 -08002687 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002688
kwiberg55b97fe2016-01-28 05:22:45 -08002689 // The ACM resamples internally.
2690 _audioFrame.timestamp_ = _timeStamp;
2691 // This call will trigger AudioPacketizationCallback::SendData if encoding
2692 // is done and payload is ready for packetization and transmission.
2693 // Otherwise, it will return without invoking the callback.
2694 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
2695 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
2696 "Channel::EncodeAndSend() ACM encoding failed");
2697 return 0xFFFFFFFF;
2698 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002699
kwiberg55b97fe2016-01-28 05:22:45 -08002700 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
2701 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002702}
2703
solenberg7602aab2016-11-14 11:30:07 -08002704void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2705 RTC_DCHECK(!channel.channel() ||
2706 channel.channel()->ChannelId() != _channelId);
2707 rtc::CritScope lock(&assoc_send_channel_lock_);
2708 associate_send_channel_ = channel;
2709}
2710
Minyue2013aec2015-05-13 14:14:42 +02002711void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002712 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002713 Channel* channel = associate_send_channel_.channel();
2714 if (channel && channel->ChannelId() == channel_id) {
2715 // If this channel is associated with a send channel of the specified
2716 // Channel ID, disassociate with it.
2717 ChannelOwner ref(NULL);
2718 associate_send_channel_ = ref;
2719 }
2720}
2721
ivoc14d5dbe2016-07-04 07:06:55 -07002722void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2723 event_log_proxy_->SetEventLog(event_log);
2724}
2725
michaelt9332b7d2016-11-30 07:51:13 -08002726void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2727 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2728}
2729
nisse284542b2017-01-10 08:58:32 -08002730void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08002731 size_t overhead_per_packet =
2732 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08002733 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2734 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08002735 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08002736 }
2737 });
2738}
2739
2740void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002741 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002742 transport_overhead_per_packet_ = transport_overhead_per_packet;
2743 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08002744}
2745
hbos3fd31fe2017-02-28 05:43:16 -08002746// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08002747void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002748 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002749 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
2750 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08002751}
2752
kwiberg55b97fe2016-01-28 05:22:45 -08002753int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2754 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002755}
2756
wu@webrtc.org24301a62013-12-13 19:17:43 +00002757void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2758 audio_coding_->GetDecodingCallStatistics(stats);
2759}
2760
solenberg358057b2015-11-27 10:46:42 -08002761uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08002762 rtc::CritScope lock(&video_sync_lock_);
2763 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07002764}
2765
kwiberg55b97fe2016-01-28 05:22:45 -08002766int Channel::SetMinimumPlayoutDelay(int delayMs) {
2767 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2768 "Channel::SetMinimumPlayoutDelay()");
2769 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
2770 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
2771 _engineStatisticsPtr->SetLastError(
2772 VE_INVALID_ARGUMENT, kTraceError,
2773 "SetMinimumPlayoutDelay() invalid min delay");
2774 return -1;
2775 }
2776 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
2777 _engineStatisticsPtr->SetLastError(
2778 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2779 "SetMinimumPlayoutDelay() failed to set min playout delay");
2780 return -1;
2781 }
2782 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002783}
2784
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002785int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07002786 uint32_t playout_timestamp_rtp = 0;
2787 {
tommi31fc21f2016-01-21 10:37:37 -08002788 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07002789 playout_timestamp_rtp = playout_timestamp_rtp_;
2790 }
kwiberg55b97fe2016-01-28 05:22:45 -08002791 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002792 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07002793 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002794 "GetPlayoutTimestamp() failed to retrieve timestamp");
2795 return -1;
2796 }
deadbeef74375882015-08-13 12:09:10 -07002797 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002798 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002799}
2800
kwiberg55b97fe2016-01-28 05:22:45 -08002801int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
2802 RtpReceiver** rtp_receiver) const {
2803 *rtpRtcpModule = _rtpRtcpModule.get();
2804 *rtp_receiver = rtp_receiver_.get();
2805 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002806}
2807
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00002808// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
2809// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08002810int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08002811 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08002812 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002813
kwiberg55b97fe2016-01-28 05:22:45 -08002814 {
2815 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002816
kwiberg5a25d952016-08-17 07:31:12 -07002817 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002818 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2819 "Channel::MixOrReplaceAudioWithFile() fileplayer"
2820 " doesnt exist");
2821 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002822 }
2823
kwiberg4ec01d92016-08-22 08:43:54 -07002824 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07002825 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002826 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2827 "Channel::MixOrReplaceAudioWithFile() file mixing "
2828 "failed");
2829 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002830 }
kwiberg55b97fe2016-01-28 05:22:45 -08002831 if (fileSamples == 0) {
2832 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2833 "Channel::MixOrReplaceAudioWithFile() file is ended");
2834 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002835 }
kwiberg55b97fe2016-01-28 05:22:45 -08002836 }
2837
2838 assert(_audioFrame.samples_per_channel_ == fileSamples);
2839
2840 if (_mixFileWithMicrophone) {
2841 // Currently file stream is always mono.
2842 // TODO(xians): Change the code when FilePlayer supports real stereo.
2843 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
2844 1, fileSamples);
2845 } else {
2846 // Replace ACM audio with file.
2847 // Currently file stream is always mono.
2848 // TODO(xians): Change the code when FilePlayer supports real stereo.
2849 _audioFrame.UpdateFrame(
2850 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
2851 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
2852 }
2853 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002854}
2855
kwiberg55b97fe2016-01-28 05:22:45 -08002856int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
2857 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00002858
kwibergb7f89d62016-02-17 10:04:18 -08002859 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08002860 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002861
kwiberg55b97fe2016-01-28 05:22:45 -08002862 {
2863 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002864
kwiberg5a25d952016-08-17 07:31:12 -07002865 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002866 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2867 "Channel::MixAudioWithFile() file mixing failed");
2868 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002869 }
2870
kwiberg55b97fe2016-01-28 05:22:45 -08002871 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07002872 if (output_file_player_->Get10msAudioFromFile(
2873 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002874 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2875 "Channel::MixAudioWithFile() file mixing failed");
2876 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002877 }
kwiberg55b97fe2016-01-28 05:22:45 -08002878 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002879
kwiberg55b97fe2016-01-28 05:22:45 -08002880 if (audioFrame.samples_per_channel_ == fileSamples) {
2881 // Currently file stream is always mono.
2882 // TODO(xians): Change the code when FilePlayer supports real stereo.
2883 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
2884 fileSamples);
2885 } else {
2886 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2887 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
2888 ") != "
2889 "fileSamples(%" PRIuS ")",
2890 audioFrame.samples_per_channel_, fileSamples);
2891 return -1;
2892 }
2893
2894 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002895}
2896
deadbeef74375882015-08-13 12:09:10 -07002897void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002898 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07002899
henrik.lundin96bd5022016-04-06 04:13:56 -07002900 if (!jitter_buffer_playout_timestamp_) {
2901 // This can happen if this channel has not received any RTP packets. In
2902 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07002903 return;
2904 }
2905
2906 uint16_t delay_ms = 0;
2907 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002908 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002909 "Channel::UpdatePlayoutTimestamp() failed to read playout"
2910 " delay from the ADM");
2911 _engineStatisticsPtr->SetLastError(
2912 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
2913 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
2914 return;
2915 }
2916
henrik.lundin96bd5022016-04-06 04:13:56 -07002917 RTC_DCHECK(jitter_buffer_playout_timestamp_);
2918 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07002919
2920 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07002921 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07002922
kwiberg55b97fe2016-01-28 05:22:45 -08002923 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002924 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07002925 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07002926
2927 {
tommi31fc21f2016-01-21 10:37:37 -08002928 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08002929 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002930 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07002931 }
2932 playout_delay_ms_ = delay_ms;
2933 }
2934}
2935
kwiberg55b97fe2016-01-28 05:22:45 -08002936void Channel::RegisterReceiveCodecsToRTPModule() {
2937 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2938 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002939
kwiberg55b97fe2016-01-28 05:22:45 -08002940 CodecInst codec;
2941 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00002942
kwiberg55b97fe2016-01-28 05:22:45 -08002943 for (int idx = 0; idx < nSupportedCodecs; idx++) {
2944 // Open up the RTP/RTCP receiver for all supported codecs
2945 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08002946 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08002947 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2948 "Channel::RegisterReceiveCodecsToRTPModule() unable"
2949 " to register %s (%d/%d/%" PRIuS
2950 "/%d) to RTP/RTCP "
2951 "receiver",
2952 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2953 codec.rate);
2954 } else {
2955 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2956 "Channel::RegisterReceiveCodecsToRTPModule() %s "
2957 "(%d/%d/%" PRIuS
2958 "/%d) has been added to the RTP/RTCP "
2959 "receiver",
2960 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2961 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00002962 }
kwiberg55b97fe2016-01-28 05:22:45 -08002963 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002964}
2965
kwiberg55b97fe2016-01-28 05:22:45 -08002966int Channel::SetSendRtpHeaderExtension(bool enable,
2967 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002968 unsigned char id) {
2969 int error = 0;
2970 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
2971 if (enable) {
2972 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
2973 }
2974 return error;
2975}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002976
ossue280cde2016-10-12 11:04:10 -07002977int Channel::GetRtpTimestampRateHz() const {
2978 const auto format = audio_coding_->ReceiveFormat();
2979 // Default to the playout frequency if we've not gotten any packets yet.
2980 // TODO(ossu): Zero clockrate can only happen if we've added an external
2981 // decoder for a format we don't support internally. Remove once that way of
2982 // adding decoders is gone!
2983 return (format && format->clockrate_hz != 0)
2984 ? format->clockrate_hz
2985 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00002986}
2987
Minyue2013aec2015-05-13 14:14:42 +02002988int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07002989 RtcpMode method = _rtpRtcpModule->RTCP();
2990 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002991 return 0;
2992 }
2993 std::vector<RTCPReportBlock> report_blocks;
2994 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02002995
2996 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00002997 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02002998 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08002999 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003000 Channel* channel = associate_send_channel_.channel();
3001 // Tries to get RTT from an associated channel. This is important for
3002 // receive-only channels.
3003 if (channel) {
3004 // To prevent infinite recursion and deadlock, calling GetRTT of
3005 // associate channel should always use "false" for argument:
3006 // |allow_associate_channel|.
3007 rtt = channel->GetRTT(false);
3008 }
3009 }
3010 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003011 }
3012
3013 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3014 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3015 for (; it != report_blocks.end(); ++it) {
3016 if (it->remoteSSRC == remoteSSRC)
3017 break;
3018 }
3019 if (it == report_blocks.end()) {
3020 // We have not received packets with SSRC matching the report blocks.
3021 // To calculate RTT we try with the SSRC of the first report block.
3022 // This is very important for send-only channels where we don't know
3023 // the SSRC of the other end.
3024 remoteSSRC = report_blocks[0].remoteSSRC;
3025 }
Minyue2013aec2015-05-13 14:14:42 +02003026
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003027 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003028 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003029 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003030 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3031 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003032 return 0;
3033 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003034 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003035}
3036
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003037} // namespace voe
3038} // namespace webrtc